Skip to content
74 changes: 72 additions & 2 deletions bench/tree-fold-cpu-worker/fold-step.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { MemoryStorage } from "@baerly/protocol";
import {
MAINTENANCE_PROFILE_CF_PAID,
MAINTENANCE_PROFILE_NODE,
MemoryStorage,
type Storage,
} from "@baerly/protocol";
import { TREE_FOLD_TICK_BUDGET_MS } from "../../packages/server/src/tree/constants.ts";
import { describe, expect, test, vi } from "vitest";
import { cellByName, CELLS, FIXTURES, headKey, savedHeadKey, selectCells } from "./cells.ts";
import { buildFixture, fixtureText } from "./fixtures.ts";
Expand Down Expand Up @@ -137,7 +143,10 @@ describe("fold tick and reset", () => {
const cell = cellByName("d1b256-100-memory")!;

for (let sample = 0; sample < 2; sample++) {
const result = await runFoldStep(retrying(storage), cell);
const result = await runFoldStep(retrying(storage), cell, {
profile: MAINTENANCE_PROFILE_CF_PAID,
startedAt: Date.now(),
});
expect(sampleProblem(cell, result)).toBeNull();
expect(result).toMatchObject({ outcome: "published", floor: 0, foldEnd: 100, folded: 100 });
expect(result.nodesWritten).toBeGreaterThan(1);
Expand All @@ -153,6 +162,67 @@ describe("fold tick and reset", () => {
}
});

/** A fresh bucket holding the d1b256 fixture with a `tail`-entry log. */
const fixtureBucket = async (tail: number): Promise<MemoryStorage> => {
const built = await buildFixture(
FIXTURES.find((f) => f.tenant === "d1b256")!,
tail,
);
const storage = new MemoryStorage();
const enc = new TextEncoder();
for (const [key, text] of built.objects) {
await storage.put(key, enc.encode(text));
}
return storage;
};

test("a tick creates nodes at most its host profile's fold width at once", async () => {
const cell = cellByName("d1b256-500-memory")!;
const widest: number[] = [];
for (const profile of [MAINTENANCE_PROFILE_CF_PAID, MAINTENANCE_PROFILE_NODE]) {
const inner = await fixtureBucket(500);
const seen = { inFlight: 0, max: 0 };
const storage: Storage = {
...inner,
get: (key, opts) => inner.get(key, opts),
list: (prefix, opts) => inner.list(prefix, opts),
delete: (key, opts) => inner.delete(key, opts),
put: async (key, body, opts) => {
if (!key.includes("/_v99/n/")) {
return inner.put(key, body, opts);
}
seen.inFlight += 1;
seen.max = Math.max(seen.max, seen.inFlight);
try {
await new Promise((resolve) => setTimeout(resolve, 1));
return await inner.put(key, body, opts);
} finally {
seen.inFlight -= 1;
}
},
};
const result = await runFoldStep(retrying(storage), cell, {
profile,
startedAt: Date.now(),
});
expect(sampleProblem(cell, result)).toBeNull();
widest.push(seen.max);
}
expect(widest).toEqual([
MAINTENANCE_PROFILE_CF_PAID.foldParallelCalls,
MAINTENANCE_PROFILE_NODE.foldParallelCalls,
]);
});

test("a tick whose request arrived a whole tick budget ago folds one entry and stops on the tick budget", async () => {
const cell = cellByName("d1b256-100-memory")!;
const result = await runFoldStep(retrying(await fixtureBucket(300)), cell, {
profile: MAINTENANCE_PROFILE_CF_PAID,
startedAt: Date.now() - TREE_FOLD_TICK_BUDGET_MS,
});
expect(result).toMatchObject({ outcome: "published", folded: 1, stop: "tick-budget" });
});

test("reset refuses a tenant with no saved head", async () => {
await expect(resetTenant(bucketOver(new MemoryStorage()), "d1b256")).rejects.toThrow(
/no saved fixture head/,
Expand Down
23 changes: 20 additions & 3 deletions bench/tree-fold-cpu-worker/fold-step.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
* the Worker and the Node baseline run the identical call.
*
* The tick passes the writer's committed tail as `knownTail`, as the write
* tick would. A capped cell cuts the log at `cap` entries: every
* tick would, its host's fold width from the maintenance profile it runs
* under (`foldParallelCalls`), and the request's arrival as `startedAt`, so
* the tick budget counts what the invocation did before the fold. A capped cell cuts the log at `cap` entries: every
* `log/<seq>` GET at or past `floor + cap` is sent for a key that does not
* exist, so the fold reads the cut, probes one missing slot and stops at the
* tail, with the same storage calls as a log that really ends there.
Expand All @@ -20,6 +22,7 @@ import {
createObservabilityContext,
runWithContext,
} from "../../packages/server/src/observability/context.ts";
import type { MaintenanceProfile } from "../../packages/server/src/maintenance.ts";
import { foldTree } from "../../packages/server/src/tree/fold.ts";
import { type Cell, collectionPrefix, LEDGER_CALLS, TAIL_ENTRIES } from "./cells.ts";

Expand Down Expand Up @@ -95,11 +98,23 @@ export interface FoldStepResult {
readonly ms: number;
}

/** The host a tick runs on. */
export interface FoldHost {
/** The maintenance profile the host runs under; the fold takes its width from it. */
readonly profile: Pick<MaintenanceProfile, "foldParallelCalls">;
/** When the tick's request arrived, on the `Date.now` clock. */
readonly startedAt: number;
}

/**
* One fold tick of `cell` on `storage` (the fixture, behind the adapter
* retry), under a fresh {@link LEDGER_CALLS}-call ledger.
* retry), under a fresh {@link LEDGER_CALLS}-call ledger, on `host`.
*/
export const runFoldStep = async (storage: Storage, cell: Cell): Promise<FoldStepResult> => {
export const runFoldStep = async (
storage: Storage,
cell: Cell,
host: FoldHost,
): Promise<FoldStepResult> => {
const prefix = collectionPrefix(cell.fixture.tenant);
const end = cell.cap ?? TAIL_ENTRIES;
const ledger = new RequestLedger({ internal: LEDGER_CALLS, external: LEDGER_CALLS });
Expand All @@ -109,6 +124,8 @@ export const runFoldStep = async (storage: Storage, cell: Cell): Promise<FoldSte
storage: cell.cap === null ? storage : cutLog(storage, prefix, end),
prefix,
knownTail: end,
parallelCalls: host.profile.foldParallelCalls,
startedAt: host.startedAt,
}),
);
const ms = performance.now() - t0;
Expand Down
8 changes: 7 additions & 1 deletion bench/tree-fold-cpu-worker/node-baseline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { readFileSync, writeFileSync } from "node:fs";
import { cpus, loadavg } from "node:os";
import { join } from "node:path";
import { parseArgs } from "node:util";
import { MAINTENANCE_PROFILE_NODE } from "@baerly/protocol";
import { runAsCliEntrypoint } from "../measurement/cli-entrypoint.ts";
import { type Cell, CELLS, type FixtureManifest, selectCells } from "./cells.ts";
import { OUT_DIR } from "./fixtures.ts";
Expand Down Expand Up @@ -98,7 +99,12 @@ const runCell = async (
let last: FoldStepResult | undefined;
for (let i = 0; i < warmup + samples; i++) {
const t0 = threadCpuMs();
const result = await runFoldStep(await memoryStorageOf(objects), cell);
// As in the Worker, the tick's request arrives before its bucket is loaded.
const startedAt = Date.now();
const result = await runFoldStep(await memoryStorageOf(objects), cell, {
profile: MAINTENANCE_PROFILE_NODE,
startedAt,
});
const t1 = threadCpuMs();
const problem = sampleProblem(cell, result);
if (problem !== null) {
Expand Down
29 changes: 23 additions & 6 deletions bench/tree-fold-cpu-worker/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* Synthetic fixtures only.
*/
import { r2BindingStorage } from "@baerly/adapter-cloudflare";
import type { Storage } from "@baerly/protocol";
import { MAINTENANCE_PROFILE_CF_PAID, type Storage } from "@baerly/protocol";
import { type Cell, cellByName, collectionPrefix, fixtureByTenant, tenantRoot } from "../cells.ts";
import { memoryStorageOf, runFoldStep, sampleProblem } from "../fold-step.ts";
import { resetTenant } from "../reset.ts";
Expand Down Expand Up @@ -104,7 +104,13 @@ const readAll = async (bucket: R2Bucket, prefix: string): Promise<Map<string, Ui
return objects;
};

const fold = async (cell: Cell, env: BenchEnv, tag: string | null, cold: boolean) => {
const fold = async (
cell: Cell,
env: BenchEnv,
tag: string | null,
cold: boolean,
startedAt: number,
) => {
const calls: Calls = { get: 0, put: 0, delete: 0, list: 0 };
let storage: Storage;
if (cell.storage === "r2") {
Expand All @@ -118,7 +124,11 @@ const fold = async (cell: Cell, env: BenchEnv, tag: string | null, cold: boolean
}
storage = await memoryStorageOf(cached.objects);
}
const result = await runFoldStep(storage, cell);
// Every cell runs under the Workers Paid ledger, so under its profile.
const result = await runFoldStep(storage, cell, {
profile: MAINTENANCE_PROFILE_CF_PAID,
startedAt,
});
const line = {
cell: cell.name,
tag,
Expand All @@ -132,7 +142,13 @@ const fold = async (cell: Cell, env: BenchEnv, tag: string | null, cold: boolean
return Response.json(line);
};

const route = async (req: Request, env: BenchEnv, url: URL, cold: boolean): Promise<Response> => {
const route = async (
req: Request,
env: BenchEnv,
url: URL,
cold: boolean,
startedAt: number,
): Promise<Response> => {
const bucket = env.BUCKET;
switch (`${req.method} ${url.pathname}`) {
case "POST /bench/fold": {
Expand All @@ -141,7 +157,7 @@ const route = async (req: Request, env: BenchEnv, url: URL, cold: boolean): Prom
if (cell === undefined) {
return Response.json({ error: `unknown cell ${JSON.stringify(name)}` }, { status: 404 });
}
return await fold(cell, env, url.searchParams.get("tag"), cold);
return await fold(cell, env, url.searchParams.get("tag"), cold, startedAt);
}
case "POST /bench/objects": {
const objects = Object.entries((await req.json()) as Record<string, string>);
Expand Down Expand Up @@ -207,13 +223,14 @@ const route = async (req: Request, env: BenchEnv, url: URL, cold: boolean): Prom

export default {
async fetch(req: Request, env: BenchEnv): Promise<Response> {
const startedAt = Date.now();
const cold = coldIsolate;
coldIsolate = false;
if (!authorized(req, env)) {
return Response.json({ error: "unauthorized" }, { status: 401 });
}
try {
return await route(req, env, new URL(req.url), cold);
return await route(req, env, new URL(req.url), cold, startedAt);
} catch (error) {
return Response.json({ error: String(error), cold }, { status: 500 });
}
Expand Down
1 change: 1 addition & 0 deletions bench/tree-op-model/crosscheck.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ const tickCells = async (
length,
mode,
foldBudget,
host.foldParallelCalls,
depthZero ? { maxBytes: host.collection.bytes, maxRows: host.collection.rows } : undefined,
);
if (op === "tick-pass" && m.folded !== length) {
Expand Down
8 changes: 5 additions & 3 deletions bench/tree-op-model/measure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,7 @@ export interface MeasuredFold extends Measured {
/**
* One fold step on a bucket whose unfolded tail is `tailLength` entries,
* with the writer's committed tail as `knownTail` (the write tick passes
* it), against `budget`. A concurrent `tail_hint` refresh lands between
* it), against `budget`, at the host's fold width `parallelCalls`. A concurrent `tail_hint` refresh lands between
* planning and publication, so the head CAS is lost and the fold pays
* its fate re-read: the worst case the model's tick assumes. That
* refresh goes to the bucket directly and is not counted.
Expand All @@ -663,6 +663,7 @@ export const measureFold = async (
tailLength: number,
mode: FaultMode,
budget: number,
parallelCalls: number,
depthZero?: TreeDepthZeroLimit,
): Promise<MeasuredFold> => {
const m = meter(bucket, mode, Number.MAX_SAFE_INTEGER);
Expand All @@ -673,9 +674,10 @@ export const measureFold = async (
budget,
knownTail: tailLength,
config: DEFAULT_TREE_CONFIG,
parallelCalls,
// Counts must not depend on how fast this host plans, so the
// wall-clock deadline never stops a measured fold.
planDeadlineMs: Number.POSITIVE_INFINITY,
// tick budget never stops a measured fold.
tickBudgetMs: Number.POSITIVE_INFINITY,
...(depthZero !== undefined && { depthZero }),
});
if (prepared.kind !== "prepared") {
Expand Down
5 changes: 5 additions & 0 deletions bench/tree-op-model/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
LOG_RETENTION_MAX_DELETES_PER_TICK,
MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,
MAINTENANCE_MAX_FOLD_ROWS,
MAINTENANCE_PROFILE_CF_FREE,
MAINTENANCE_PROFILE_CF_PAID,
STORAGE_RETRY_MAX_ATTEMPTS,
WRITE_TICK_MIN_ENTRIES_TO_COMPACT,
Expand Down Expand Up @@ -726,6 +727,8 @@ export interface HostProfile {
readonly collection: CollectionSize;
/** Log entries one fold pass takes (`maxFoldEntriesPerPass`). */
readonly entriesPerPass: number;
/** Storage calls a fold keeps in flight at once (`foldParallelCalls`). */
readonly foldParallelCalls: number;
/** GC deletes per tick (`gcMaxSweeps`). */
readonly gcSweeps: number;
/** Log objects one retirement pass deletes (`LOG_RETENTION_MAX_DELETES_PER_TICK`). */
Expand All @@ -746,6 +749,7 @@ export const FREE_R2_HOST: HostProfile = {
ledger: FREE_LEDGER,
collection: FLOOR_COLLECTION,
entriesPerPass: WRITE_TICK_FOLD_ENTRIES_PER_PASS,
foldParallelCalls: MAINTENANCE_PROFILE_CF_FREE.foldParallelCalls,
gcSweeps: WRITE_TICK_GC_MAX_SWEEPS,
retirementDeletes: LOG_RETENTION_MAX_DELETES_PER_TICK,
listPageKeys: GC_MARK_LIST_PAGE_KEYS,
Expand All @@ -758,6 +762,7 @@ export const PAID_HOST: HostProfile = {
ledger: PAID_LEDGER,
collection: PAID_COLLECTION,
entriesPerPass: MAINTENANCE_PROFILE_CF_PAID.maxFoldEntriesPerPass,
foldParallelCalls: MAINTENANCE_PROFILE_CF_PAID.foldParallelCalls,
gcSweeps: MAINTENANCE_PROFILE_CF_PAID.gcMaxSweeps,
retirementDeletes: LOG_RETENTION_MAX_DELETES_PER_TICK,
listPageKeys: GC_MARK_LIST_PAGE_KEYS,
Expand Down
14 changes: 14 additions & 0 deletions packages/protocol/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,16 @@ export const CF_FREE_EXTERNAL_REQUEST_LIMIT: number = 45;
*/
export const CF_PAID_REQUEST_LIMIT: number = 9000;

/**
* Most storage calls a Workers invocation has waiting on response
* headers at once, on Free and Paid alike. Cloudflare documents six
* simultaneous open connections per invocation, R2 binding calls
* included; a seventh call queues until one of them answers. Work sized
* as rounds of concurrent calls uses this width on Workers, so a round
* never silently becomes two.
*/
export const CF_MAX_CONCURRENT_STORAGE_CALLS: number = 6;

/**
* Legacy internal Cache API accounting cap. The production Worker never
* calls the Cache API; point reads always reach storage. Retained with
Expand Down Expand Up @@ -1259,6 +1269,7 @@ type MaintenanceProfileShape = Readonly<{
foldAtTailEntries: number;
maxFoldBytes: number;
maxFoldRows: number;
foldParallelCalls: number;
}>;

/** CF-free profile; the absent-context default. */
Expand All @@ -1270,6 +1281,7 @@ export const MAINTENANCE_PROFILE_CF_FREE: MaintenanceProfileShape = {
foldAtTailEntries: WRITE_TICK_FOLD_AT_TAIL_ENTRIES,
maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,
maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS,
foldParallelCalls: CF_MAX_CONCURRENT_STORAGE_CALLS,
};

/** Node profile; 10× CF-free per-pass caps, and its own measured snapshot ceilings. */
Expand All @@ -1281,6 +1293,7 @@ export const MAINTENANCE_PROFILE_NODE: MaintenanceProfileShape = {
foldAtTailEntries: MAINTENANCE_FOLD_AT_TAIL_ENTRIES,
maxFoldBytes: NODE_MAINTENANCE_MAX_FOLD_BYTES,
maxFoldRows: NODE_MAINTENANCE_MAX_FOLD_ROWS,
foldParallelCalls: MAX_PARALLEL_LOG_READS,
};

/**
Expand Down Expand Up @@ -1308,6 +1321,7 @@ export const MAINTENANCE_PROFILE_CF_PAID: MaintenanceProfileShape = {
foldAtTailEntries: MAINTENANCE_FOLD_AT_TAIL_ENTRIES,
maxFoldBytes: CF_PAID_MAINTENANCE_MAX_FOLD_BYTES,
maxFoldRows: CF_PAID_MAINTENANCE_MAX_FOLD_ROWS,
foldParallelCalls: CF_MAX_CONCURRENT_STORAGE_CALLS,
};

/**
Expand Down
8 changes: 8 additions & 0 deletions packages/server/src/maintenance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,14 @@ export interface MaintenanceProfile {
readonly foldAtTailEntries: number;
readonly maxFoldBytes: number;
readonly maxFoldRows: number;
/**
* Most storage calls a tree fold keeps in flight at once: its node
* read-ahead and each level of its publication's creates. Fixed per
* host, not adaptive: `CF_MAX_CONCURRENT_STORAGE_CALLS` (6) on Workers,
* where a seventh call queues, and `MAX_PARALLEL_LOG_READS` (16) on
* Node, the width the log walk already uses there.
*/
readonly foldParallelCalls: number;
}

export {
Expand Down
Loading