diff --git a/bench/tree-fold-cpu-worker/fold-step.test.ts b/bench/tree-fold-cpu-worker/fold-step.test.ts index f12c8925..8b10cb0c 100644 --- a/bench/tree-fold-cpu-worker/fold-step.test.ts +++ b/bench/tree-fold-cpu-worker/fold-step.test.ts @@ -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"; @@ -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); @@ -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 => { + 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/, diff --git a/bench/tree-fold-cpu-worker/fold-step.ts b/bench/tree-fold-cpu-worker/fold-step.ts index bff941c8..791cc41c 100644 --- a/bench/tree-fold-cpu-worker/fold-step.ts +++ b/bench/tree-fold-cpu-worker/fold-step.ts @@ -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/` 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. @@ -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"; @@ -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; + /** 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 => { +export const runFoldStep = async ( + storage: Storage, + cell: Cell, + host: FoldHost, +): Promise => { const prefix = collectionPrefix(cell.fixture.tenant); const end = cell.cap ?? TAIL_ENTRIES; const ledger = new RequestLedger({ internal: LEDGER_CALLS, external: LEDGER_CALLS }); @@ -109,6 +124,8 @@ export const runFoldStep = async (storage: Storage, cell: Cell): Promise { +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") { @@ -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, @@ -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 => { +const route = async ( + req: Request, + env: BenchEnv, + url: URL, + cold: boolean, + startedAt: number, +): Promise => { const bucket = env.BUCKET; switch (`${req.method} ${url.pathname}`) { case "POST /bench/fold": { @@ -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); @@ -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 { + 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 }); } diff --git a/bench/tree-op-model/crosscheck.ts b/bench/tree-op-model/crosscheck.ts index 2f7beaf2..17716628 100644 --- a/bench/tree-op-model/crosscheck.ts +++ b/bench/tree-op-model/crosscheck.ts @@ -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) { diff --git a/bench/tree-op-model/measure.ts b/bench/tree-op-model/measure.ts index 8d906e2b..0a17080e 100644 --- a/bench/tree-op-model/measure.ts +++ b/bench/tree-op-model/measure.ts @@ -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. @@ -663,6 +663,7 @@ export const measureFold = async ( tailLength: number, mode: FaultMode, budget: number, + parallelCalls: number, depthZero?: TreeDepthZeroLimit, ): Promise => { const m = meter(bucket, mode, Number.MAX_SAFE_INTEGER); @@ -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") { diff --git a/bench/tree-op-model/model.ts b/bench/tree-op-model/model.ts index a1374ba7..665585dc 100644 --- a/bench/tree-op-model/model.ts +++ b/bench/tree-op-model/model.ts @@ -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, @@ -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`). */ @@ -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, @@ -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, diff --git a/packages/protocol/src/constants.ts b/packages/protocol/src/constants.ts index abe736cf..aa9b79da 100644 --- a/packages/protocol/src/constants.ts +++ b/packages/protocol/src/constants.ts @@ -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 @@ -1259,6 +1269,7 @@ type MaintenanceProfileShape = Readonly<{ foldAtTailEntries: number; maxFoldBytes: number; maxFoldRows: number; + foldParallelCalls: number; }>; /** CF-free profile; the absent-context default. */ @@ -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. */ @@ -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, }; /** @@ -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, }; /** diff --git a/packages/server/src/maintenance.ts b/packages/server/src/maintenance.ts index 15bcfce9..47edaba2 100644 --- a/packages/server/src/maintenance.ts +++ b/packages/server/src/maintenance.ts @@ -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 { diff --git a/packages/server/src/tree/constants.ts b/packages/server/src/tree/constants.ts index 96b07974..25ada612 100644 --- a/packages/server/src/tree/constants.ts +++ b/packages/server/src/tree/constants.ts @@ -9,6 +9,7 @@ */ import { + CF_MAX_CONCURRENT_STORAGE_CALLS, MAX_KEY_BYTES, MAX_PARALLEL_LOG_READS, STORAGE_RETRY_MAX_ATTEMPTS, @@ -73,35 +74,38 @@ export const TREE_HEAD_CAS_CHARGE = 1; export const TREE_READ_PARALLEL_GETS: number = MAX_PARALLEL_LOG_READS; /** - * Wall-clock milliseconds a fold tick may spend capturing the head and - * planning before it stops admitting log entries and publishes the - * planned prefix (`prepareTreeFold`, `./fold.ts`). + * Wall-clock milliseconds a fold tick may take in total, from the + * request's arrival to its head CAS and fate re-read (`prepareTreeFold`, + * `./fold.ts`). Planning stops admitting log entries once the time + * elapsed plus the estimated publication time of the plan so far would + * pass it. * * A tick that runs past the response on Cloudflare (`ctx.waitUntil`) - * has about 30 s before the platform may cancel it, and a tick cut off - * before its head CAS makes no progress: the next tick plans the same - * batch, so without a clock folding can stall. Planning wall time is - * almost all storage latency (a few hundred ms per R2 binding GET). - * Publication issues one create per fresh node, and a fold's fresh - * nodes are mostly rewrites of the nodes it read, so publication takes - * roughly as long again as planning, plus the head CAS and its fate - * re-read. Ten seconds of planning leaves the rest of the window for - * that, and for any maintenance the same tick ran before the fold. - * - * The deadline is checked between log entries, so one entry's node - * reads are never cut short, and it never stops a publication. + * has 30 s before the platform cancels it, silently and with no + * remaining-time API, and a tick cut off before its head CAS makes no + * progress: the next tick plans the same batch, so without a clock + * folding can stall. Counting from the request's arrival rather than + * from the response keeps a tick inside 30 s even where the window + * counts from the invocation's start. The 10 s left over absorb what + * the budget check cannot see: the entry admitted after the last check + * (its log batch and node reads), publication calls slower than the + * GETs the estimate is drawn from, and a create conflict's adoption GET. + * They do not bound a fold pinned at its floor, which reads on past the + * budget until something is publishable; its result reports that + * (`pinnedPastTickBudget`). */ -export const TREE_FOLD_PLAN_DEADLINE_MS = 10_000; +export const TREE_FOLD_TICK_BUDGET_MS = 20_000; /** - * Most node GETs a fold planner issues at once when it reads ahead the - * leaf paths of a batch of changes (`FoldPlanner.prefetch`). Planning - * wall time is almost all storage latency, so reading a batch's nodes + * Most storage calls a fold keeps in flight at once when no width is + * passed: its node read-ahead (`FoldPlanner.prefetch`) and each level of + * its publication's creates (`publishTree`). Planning and publication + * wall time is almost all storage latency, so issuing a level's calls * together rather than one after another divides it by about this - * width. Workers may cap simultaneous storage binding calls at about 6 - * (unverified); a deployed measurement tunes this value. + * width. The default is the Workers width, the narrowest first-class + * host; a host passes its maintenance profile's `foldParallelCalls`. */ -export const TREE_FOLD_PARALLEL_GETS = 6; +export const TREE_FOLD_PARALLEL_CALLS: number = CF_MAX_CONCURRENT_STORAGE_CALLS; /** Most child entries one branch may hold. */ export const BRANCH_MAX_ENTRIES = 256; diff --git a/packages/server/src/tree/fold.test.ts b/packages/server/src/tree/fold.test.ts index dd4cf09a..34eed71d 100644 --- a/packages/server/src/tree/fold.test.ts +++ b/packages/server/src/tree/fold.test.ts @@ -27,19 +27,29 @@ * - An entry no fresh tick can fold is refused with a counted warning. * - A tick reads the nodes of a batch of entries concurrently and makes * the same storage calls as reading them one at a time. - * - A tick past its planning deadline publishes the prefix it planned, - * at least one entry, and the next tick continues from there. + * - A tick past its tick budget publishes the prefix it planned, at + * least one entry, and the next tick continues from there. The budget + * counts the plan's publication, at the call latency the tick + * observed, and the time since the injected start, so the whole tick + * fits its budget; publication creates at most the host's width of + * nodes at once, and read-ahead reads only what still fits. A fold + * pinned at its floor reads on past the budget and its result says + * so, counted. */ import { fc, test as fcTest } from "@fast-check/vitest"; import { describe, expect, test } from "vitest"; import { BaerlyError, + CF_MAX_CONCURRENT_STORAGE_CALLS, casUpdateCurrentJson, type DocumentData, decodeJsonBytes, encodeJsonBytes, type LogEntry, logObjectKey, + MAINTENANCE_PROFILE_CF_FREE, + MAINTENANCE_PROFILE_CF_PAID, + MAINTENANCE_PROFILE_NODE, MemoryStorage, RequestLedger, retryStorageCall, @@ -58,9 +68,12 @@ import { TreeWriter, type TreeWrite } from "../../../../tests/fixtures/tree-writ import { foldLogEntriesOnto } from "../log-walk.ts"; import { createObservabilityContext, runWithContext } from "../observability/context.ts"; import { RequestScopedMetricsRecorder } from "../observability/recorder.ts"; +import { sealTree } from "./build.ts"; +import { TREE_FOLD_PARALLEL_CALLS } from "./constants.ts"; import { foldTree, prepareTreeFold, type TreeFoldInput, type TreeFoldOutcome } from "./fold.ts"; import { readTreeHead, treeHeadKey } from "./head.ts"; import { createTreeConfig, TREE_LAYOUT, type TreeConfig, type TreeLayout } from "./layout.ts"; +import type { TreeFoldPlan } from "./plan.ts"; const PREFIX = "app/helpdesk/tenant/acme/manifests/tickets"; const COLLECTION = "tickets"; @@ -652,13 +665,13 @@ describe("invalid survivors and the look-ahead fallback", () => { let published = 0; for (let budget = 20; budget <= 260; budget += 6) { const ends: string[] = []; - for (const parallelGets of [1, undefined]) { + for (const parallelCalls of [1, undefined]) { const b = await open(); const before = b.counted.calls.get + b.counted.calls.put; const outcome = await fold(b, SMALL, { budget, knownTail: 134, - ...(parallelGets !== undefined && { parallelGets }), + ...(parallelCalls !== undefined && { parallelCalls }), }); expect(b.counted.calls.get + b.counted.calls.put - before).toBeLessThanOrEqual(budget); ends.push(outcome.kind); @@ -881,7 +894,7 @@ describe("stuck entry", () => { }); }); -describe("deadline", () => { +describe("tick-budget stop", () => { /** A fake wall clock that every GET of the fold advances by `getMs`. */ const slowClock = (b: Bucket, getMs: number) => { const clock = { t: 0 }; @@ -895,7 +908,7 @@ describe("deadline", () => { return { storage, now: () => clock.t }; }; - test("a tick past its deadline publishes the planned prefix, and later ticks continue to the same root", async () => { + test("a tick past its budget publishes the planned prefix, and later ticks continue to the same root", async () => { const log = changes(20); const whole = openBucket(); await whole.writer.commit(log); @@ -909,14 +922,14 @@ describe("deadline", () => { let stoppedByDeadline = 0; for (let tick = 0; floor < 20; tick++) { expect(tick).toBeLessThan(40); - const outcome = await fold(split, SMALL, { ...slow, planDeadlineMs: 1000 }); + const outcome = await fold(split, SMALL, { ...slow, tickBudgetMs: 1000 }); expect(outcome.kind).toBe("published"); if (outcome.kind !== "published") { break; } expect(outcome.foldEnd).toBeGreaterThan(floor); if (outcome.foldEnd < 20) { - expect(outcome.stop).toEqual({ reason: "deadline", seq: outcome.foldEnd }); + expect(outcome.stop).toEqual({ reason: "tick-budget", seq: outcome.foldEnd }); stoppedByDeadline += 1; } floor = outcome.foldEnd; @@ -928,21 +941,21 @@ describe("deadline", () => { ); }); - test("a deadline that elapsed before the first entry still folds one entry", async () => { + test("a budget spent before the first entry still folds one entry", async () => { const b = openBucket(); await b.writer.commit(changes(5)); for (const floor of [0, 1, 2]) { - await expect(fold(b, SMALL, { planDeadlineMs: 0 })).resolves.toMatchObject({ + await expect(fold(b, SMALL, { tickBudgetMs: 0 })).resolves.toMatchObject({ kind: "published", floor, foldEnd: floor + 1, - stop: { reason: "deadline", seq: floor + 1 }, + stop: { reason: "tick-budget", seq: floor + 1 }, }); await judge(b.storage, SMALL_LAYOUT, floor + 1); } }); - test("a deadline that elapses during a log read stops the fold before it reads that batch's nodes", async () => { + test("a budget that runs out during a log read stops the fold before it reads that batch's nodes", async () => { const id = (i: number) => `r${String(i).padStart(3, "0")}`; const b = openBucket(); await b.writer.commit(Array.from({ length: 120 }, (_, i) => row(id(i), i))); @@ -956,7 +969,7 @@ describe("deadline", () => { const isLog = key.startsWith(LOG_PREFIX); reads.push(isLog ? "log" : "other"); if (isLog) { - // The first entry's read stays inside the deadline; the next batch's does not. + // The first entry's read stays inside the budget; the next batch's does not. clock.t += 600; } return b.storage.get(key, opts); @@ -965,13 +978,13 @@ describe("deadline", () => { const outcome = await fold(b, SMALL, { storage, now: () => clock.t, - planDeadlineMs: 1000, + tickBudgetMs: 1000, knownTail: 140, }); expect(outcome).toMatchObject({ kind: "published", foldEnd: 121, - stop: { reason: "deadline", seq: 121 }, + stop: { reason: "tick-budget", seq: 121 }, }); const lastLog = reads.lastIndexOf("log"); expect(lastLog).toBeGreaterThan(reads.indexOf("log")); @@ -979,19 +992,438 @@ describe("deadline", () => { await judge(b.storage, SMALL_LAYOUT, 121); }); - test("past the deadline, a fold pinned at its floor reads on until the pin releases", async () => { + /** Fold `b` under a fresh metrics recorder; returns the outcome and the pinned-overrun count. */ + const foldCounting = async (b: Bucket, extra: Partial) => { + const recorder = new RequestScopedMetricsRecorder(); + const outcome = await runWithContext(createObservabilityContext({ recorder }), () => + fold(b, SMALL, extra), + ); + const overruns = recorder + .snapshot() + .counters.filter((c) => c.name === "db.compact.pinned_past_tick_budget_total") + .reduce((sum, c) => sum + c.value, 0); + return { outcome, overruns }; + }; + + test("past the budget, a fold pinned at its floor reads on until the pin releases, and says so, counted once", async () => { const b = openBucket(); await b.writer.appendRaw({ op: "I", doc_id: "c", after: { _id: "x", n: 0 } }); await b.writer.commit([row("a", 1), row("c", 2), row("d", 3)]); // Seq 0 is an invalid survivor that seq 2 supersedes: only a prefix - // through seq 2 publishes, so the deadline waits for it. - await expect(fold(b, SMALL, { planDeadlineMs: 0 })).resolves.toMatchObject({ + // through seq 2 publishes, so the budget check waits for it. + const { outcome, overruns } = await foldCounting(b, { tickBudgetMs: 0 }); + expect(outcome).toMatchObject({ kind: "published", foldEnd: 3, - stop: { reason: "deadline", seq: 3 }, + stop: { reason: "tick-budget", seq: 3 }, + pinnedPastTickBudget: true, }); + expect(overruns).toBe(1); await judge(b.storage, SMALL_LAYOUT, 3); }); + + test("a fold pinned at its floor past the budget, whose pin never releases, is refused for the invalid entry and says it passed the budget", async () => { + const b = openBucket(); + await b.writer.appendRaw({ op: "I", doc_id: "c", after: { _id: "x", n: 0 } }); + await b.writer.commit([row("a", 1), row("d", 3)]); + const { outcome, overruns } = await foldCounting(b, { tickBudgetMs: 0 }); + expect(outcome).toMatchObject({ + kind: "refused", + floor: 0, + stop: { reason: "invalid-entry", seq: 0 }, + pinnedPastTickBudget: true, + }); + expect(overruns).toBe(1); + }); + + test("a tick past its budget with nothing pinned, or pinned past its floor, neither reads on nor says so", async () => { + const atFloor = openBucket(); + await atFloor.writer.commit(changes(5)); + const unpinned = await foldCounting(atFloor, { tickBudgetMs: 0 }); + expect(unpinned.outcome).toMatchObject({ kind: "published", foldEnd: 1 }); + expect(unpinned.outcome).not.toHaveProperty("pinnedPastTickBudget"); + expect(unpinned.overruns).toBe(0); + + // Seq 1 is an invalid survivor no later entry supersedes, so the fold + // pins after seq 0. Each log read takes 100 ms: the budget runs out + // at seq 2, with seq 0 publishable, so the fold stops there. + const pastFloor = openBucket(); + await pastFloor.writer.commit([row("a", 1)]); + await pastFloor.writer.appendRaw({ op: "I", doc_id: "c", after: { _id: "x", n: 0 } }); + await pastFloor.writer.commit([row("d", 3), row("e", 4)]); + const clock = { t: 0 }; + const storage: Storage = { + ...pastFloor.storage, + get: (key, opts) => { + clock.t += key.startsWith(LOG_PREFIX) ? 100 : 0; + return pastFloor.storage.get(key, opts); + }, + }; + const pinned = await foldCounting(pastFloor, { + storage, + now: () => clock.t, + tickBudgetMs: 250, + }); + expect(pinned.outcome).toMatchObject({ + kind: "published", + foldEnd: 1, + stop: { reason: "invalid-entry", seq: 1 }, + }); + expect(pinned.outcome).not.toHaveProperty("pinnedPastTickBudget"); + expect(pinned.overruns).toBe(0); + }); +}); + +describe("tick budget", () => { + const id = (i: number) => `r${String(i).padStart(3, "0")}`; + /** Rows the base tree holds, then rows appended past them. */ + const BASE = 24; + const APPENDED = 200; + const TAIL = BASE + APPENDED; + + /** + * A folded base of {@link BASE} rows, then {@link APPENDED} appended + * rows: the appends route to the tree's right edge, so the fold reads a + * few nodes and writes a fresh leaf per row under the small layout. + */ + const appendHeavy = async (): Promise => { + const b = openBucket(); + await b.writer.commit(Array.from({ length: BASE }, (_, i) => row(id(i), i))); + expectPublished(await fold(b, SMALL), BASE); + await b.writer.commit(Array.from({ length: APPENDED }, (_, i) => row(id(BASE + i), i))); + return b; + }; + + /** + * A virtual wall clock over `inner`: a call starts at the current time + * and ends `latency(op, key)` later, so calls in flight together take + * one latency and calls in sequence add up. + */ + const virtualClock = ( + inner: Storage, + latency: (op: "get" | "put", key: string) => number, + ): { storage: Storage; now: () => number } => { + const clock = { t: 0 }; + const take = async (ms: number, call: () => Promise): Promise => { + const start = clock.t; + const result = await call(); + clock.t = Math.max(clock.t, start + ms); + return result; + }; + return { + storage: { + ...inner, + get: (key, opts) => take(latency("get", key), () => inner.get(key, opts)), + put: (key, body, opts) => take(latency("put", key), () => inner.put(key, body, opts)), + }, + now: () => clock.t, + }; + }; + + const isNodeKey = (key: string): boolean => key.includes("/_v99/n/"); + + test("an append-heavy tick stops planning early enough that its publication fits the budget too", async () => { + const b = await appendHeavy(); + const callMs = 100; + const budget = 4_000; + const clock = virtualClock(b.storage, () => callMs); + let planned: number | undefined; + const storage: Storage = { + ...clock.storage, + put: (key, body, opts) => { + if (isNodeKey(key)) { + planned ??= clock.now(); + } + return clock.storage.put(key, body, opts); + }, + }; + const outcome = await fold(b, SMALL, { + storage, + now: clock.now, + tickBudgetMs: budget, + knownTail: TAIL, + }); + expect(outcome).toMatchObject({ kind: "published", stop: { reason: "tick-budget" } }); + if (outcome.kind !== "published") { + return; + } + expect(outcome.foldEnd).toBeLessThan(TAIL); + expect(clock.now()).toBeLessThanOrEqual(budget); + // Publication is a large share of this tick: a deadline on planning + // alone, set at the budget, would plan until the budget and then + // overrun it by all of that publication. + expect(clock.now() - planned!).toBeGreaterThan(budget / 3); + await judge(b.storage, SMALL_LAYOUT, outcome.foldEnd); + }); + + test("the publication estimate scales with the call latency the tick observed", async () => { + const ends: number[] = []; + for (const headMs of [10, 100]) { + const b = await appendHeavy(); + // Only the head GET takes time, so the slowest call timed is it. + const clock = virtualClock(b.storage, (op, key) => + op === "get" && key === treeHeadKey(PREFIX) ? headMs : 0, + ); + const outcome = await fold(b, SMALL, { + ...clock, + tickBudgetMs: 2_000, + knownTail: TAIL, + }); + expect(outcome.kind).toBe("published"); + ends.push(outcome.kind === "published" ? outcome.foldEnd : 0); + await judge(b.storage, SMALL_LAYOUT, ends.at(-1)!); + } + const [fast, slow] = ends as [number, number]; + expect(slow).toBeGreaterThan(BASE + 1); + expect(slow).toBeLessThan(fast); + }); + + test("elapsed time counts from the injected start", async () => { + const ends: number[] = []; + for (const startedAt of [undefined, -1_000, -2_000]) { + const b = await appendHeavy(); + const clock = virtualClock(b.storage, (op, key) => + op === "get" && key === treeHeadKey(PREFIX) ? 100 : 0, + ); + const outcome = await fold(b, SMALL, { + ...clock, + tickBudgetMs: 2_000, + knownTail: TAIL, + ...(startedAt !== undefined && { startedAt }), + }); + expect(outcome).toMatchObject({ kind: "published", stop: { reason: "tick-budget" } }); + ends.push(outcome.kind === "published" ? outcome.foldEnd : 0); + } + const [fromFold, earlier, spent] = ends as [number, number, number]; + expect(earlier).toBeLessThan(fromFold); + // A tick whose budget is gone on arrival still folds one entry. + expect(spent).toBe(BASE + 1); + }); + + test("publication creates at most the host profile's width of nodes at once", async () => { + for (const profile of [ + MAINTENANCE_PROFILE_CF_FREE, + MAINTENANCE_PROFILE_CF_PAID, + MAINTENANCE_PROFILE_NODE, + ]) { + const b = await appendHeavy(); + const seen = { inFlight: 0, max: 0 }; + const storage: Storage = { + ...b.storage, + put: async (key, body, opts) => { + if (!isNodeKey(key)) { + return b.storage.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 b.storage.put(key, body, opts); + } finally { + seen.inFlight -= 1; + } + }, + }; + const width = profile.foldParallelCalls; + expectPublished( + await fold(b, SMALL, { storage, parallelCalls: width, knownTail: TAIL }), + TAIL, + ); + // The leaf level holds more fresh nodes than any width, so it fills every lane. + expect(seen.max).toBe(width); + await judge(b.storage, SMALL_LAYOUT, TAIL); + } + }); + + test("each host profile fixes its fold width: 6 on Workers, where a seventh call queues, and 16 on Node", () => { + expect(CF_MAX_CONCURRENT_STORAGE_CALLS).toBe(6); + expect(MAINTENANCE_PROFILE_CF_FREE.foldParallelCalls).toBe(6); + expect(MAINTENANCE_PROFILE_CF_PAID.foldParallelCalls).toBe(6); + expect(MAINTENANCE_PROFILE_NODE.foldParallelCalls).toBe(16); + expect(MAINTENANCE_PROFILE_CF_FREE.foldParallelCalls).toBe(CF_MAX_CONCURRENT_STORAGE_CALLS); + expect(MAINTENANCE_PROFILE_CF_PAID.foldParallelCalls).toBe(CF_MAX_CONCURRENT_STORAGE_CALLS); + }); + + /** Only the head GET takes `headMs`, so the slowest call the tick times is it. */ + const slowHead = (b: Bucket, headMs: number) => + virtualClock(b.storage, (op, key) => + op === "get" && key === treeHeadKey(PREFIX) ? headMs : 0, + ); + + /** + * Rounds of calls publishing `plan` takes: the fold record, each level + * of fresh nodes `width` at a time as the publication groups them, the + * head CAS and its fate re-read. + */ + const roundsOf = async (plan: TreeFoldPlan, floor: number, width: number): Promise => { + const sealed = await sealTree(plan.tree, { prefix: PREFIX, attempt: "f".repeat(32), floor }); + return sealed.levels.reduce((rounds, level) => rounds + Math.ceil(level.length / width), 3); + }; + + test("a single-leaf plan stops at a budget of exactly its elapsed time plus four rounds: record, leaf, head CAS, re-read", async () => { + const headMs = 100; + for (const [budget, foldEnd] of [ + [headMs + 4 * headMs, 1], + [headMs + 4 * headMs + 1, 5], + ] as const) { + const b = openBucket(); + await b.writer.commit(changes(5)); + const outcome = await fold(b, PRODUCTION, { + ...slowHead(b, headMs), + tickBudgetMs: budget, + knownTail: 5, + }); + expect(outcome, `budget ${budget}`).toMatchObject({ kind: "published", foldEnd }); + if (foldEnd < 5) { + expect(outcome).toMatchObject({ stop: { reason: "tick-budget", seq: foldEnd } }); + } + await judge(b.storage, PRODUCTION.layout, foldEnd); + } + }); + + test("a branch plan stops at a budget of exactly its elapsed time plus its publication's rounds", async () => { + const headMs = 100; + const width = TREE_FOLD_PARALLEL_CALLS; + const probe = await appendHeavy(); + // A spent budget plans exactly one entry: the plan to measure. + const one = await prepareTreeFold({ + storage: probe.storage, + prefix: PREFIX, + config: SMALL, + knownTail: TAIL, + tickBudgetMs: 0, + }); + expect(one).toMatchObject({ kind: "prepared", foldEnd: BASE + 1 }); + if (one.kind !== "prepared") { + return; + } + expect(one.plan.tree?.root.level).toBeGreaterThan(0); + const rounds = await roundsOf(one.plan, BASE + 1, width); + for (const extra of [0, 1]) { + const b = await appendHeavy(); + const outcome = await fold(b, SMALL, { + ...slowHead(b, headMs), + tickBudgetMs: headMs + rounds * headMs + extra, + parallelCalls: width, + knownTail: TAIL, + }); + expect(outcome.kind).toBe("published"); + if (outcome.kind !== "published") { + return; + } + if (extra === 0) { + expect(outcome).toMatchObject({ + foldEnd: BASE + 1, + stop: { reason: "tick-budget", seq: BASE + 1 }, + }); + } else { + expect(outcome.foldEnd).toBeGreaterThan(BASE + 1); + } + await judge(b.storage, SMALL_LAYOUT, outcome.foldEnd); + } + }); + + test("the estimate times the root GET: a slow root under a fast head still stops the tick early", async () => { + const b = await appendHeavy(); + const rootKey = (await readTreeHead(b.storage, PREFIX))!.root; + const clock = virtualClock(b.storage, (op, key) => (op === "get" && key === rootKey ? 100 : 0)); + const outcome = await fold(b, SMALL, { ...clock, tickBudgetMs: 2_000, knownTail: TAIL }); + expect(outcome).toMatchObject({ kind: "published", stop: { reason: "tick-budget" } }); + expect(outcome.kind === "published" && outcome.foldEnd).toBeLessThan(TAIL); + expect(clock.now()).toBeLessThanOrEqual(2_000); + }); + + test("the estimate times node GETs: slow node reads under a fast head and root still stop the tick early", async () => { + const b = await appendHeavy(); + const rootKey = (await readTreeHead(b.storage, PREFIX))!.root; + let slowReads = 0; + const clock = virtualClock(b.storage, (op, key) => { + if (op === "get" && isNodeKey(key) && key !== rootKey) { + slowReads += 1; + return 100; + } + return 0; + }); + const outcome = await fold(b, SMALL, { ...clock, tickBudgetMs: 2_000, knownTail: TAIL }); + expect(slowReads).toBeGreaterThan(0); + expect(outcome).toMatchObject({ kind: "published", stop: { reason: "tick-budget" } }); + expect(outcome.kind === "published" && outcome.foldEnd).toBeLessThan(TAIL); + expect(clock.now()).toBeLessThanOrEqual(2_000); + }); + + test("a tick whose check passes just under its budget reads ahead only what still fits, not the whole batch", async () => { + const updates = Array.from({ length: 40 }, (_, i) => row(id((i * 37) % 120), 500 + i)); + /** A depth-2 tree of 120 rows, then `count` scattered updates. */ + const scattered = async (count: number): Promise => { + const b = openBucket(); + await b.writer.commit(Array.from({ length: 120 }, (_, i) => row(id(i), i))); + expectPublished(await fold(b, SMALL), 120); + await b.writer.commit(updates.slice(0, count)); + return b; + }; + /** `storage` counting the node GETs issued before the first write. */ + const countingPlanReads = (storage: Storage) => { + const seen = { gets: 0, writing: false }; + return { + seen, + storage: { + ...storage, + get: (key, opts) => { + seen.gets += isNodeKey(key) && !seen.writing ? 1 : 0; + return storage.get(key, opts); + }, + put: (key, body, opts) => { + seen.writing = true; + return storage.put(key, body, opts); + }, + } satisfies Storage, + }; + }; + const b = await scattered(updates.length); + // Every call takes 100 ms. The check before seq 121, the first entry + // of a 16-entry log batch, passes with less room than that batch's + // read-ahead takes: several rounds at each of two levels. + const clock = virtualClock(b.storage, () => 100); + const ticked = countingPlanReads(clock.storage); + const outcome = await fold(b, SMALL, { + storage: ticked.storage, + now: clock.now, + tickBudgetMs: 2_500, + knownTail: 120 + updates.length, + }); + expect(outcome).toMatchObject({ kind: "published", stop: { reason: "tick-budget" } }); + if (outcome.kind !== "published") { + return; + } + expect(outcome.foldEnd).toBeGreaterThan(121); + // The same prefix folded with no read-ahead at all reads exactly the + // nodes its entries need; the tick read no node beyond those. + const alone = await scattered(outcome.foldEnd - 120); + const serial = countingPlanReads(alone.storage); + expectPublished( + await fold(alone, SMALL, { storage: serial.storage, parallelCalls: 1 }), + outcome.foldEnd, + ); + expect(ticked.seen.gets).toBe(serial.seen.gets); + }); + + test("a tick past its budget issues no further log reads", async () => { + const b = openBucket(); + await b.writer.commit(changes(5)); + let logReads = 0; + const storage: Storage = { + ...b.storage, + get: (key, opts) => { + logReads += key.startsWith(LOG_PREFIX) ? 1 : 0; + return b.storage.get(key, opts); + }, + }; + await expect(fold(b, SMALL, { storage, tickBudgetMs: 0, knownTail: 5 })).resolves.toMatchObject( + { kind: "published", foldEnd: 1, stop: { reason: "tick-budget" } }, + ); + // The first entry is read before any check can stop the fold; nothing after it is. + expect(logReads).toBe(1); + }); }); describe("node reads", () => { @@ -1023,7 +1455,7 @@ describe("node reads", () => { row(`r${String((i * 37) % 120).padStart(3, "0")}`, 1000 + i), ); const runs = []; - for (const parallelGets of [1, undefined]) { + for (const parallelCalls of [1, undefined]) { const b = openBucket(); await b.writer.commit(base); expectPublished(await fold(b, SMALL), 120); @@ -1033,7 +1465,7 @@ describe("node reads", () => { const outcome = await fold(b, SMALL, { storage: slow.storage, knownTail: 150, - ...(parallelGets !== undefined && { parallelGets }), + ...(parallelCalls !== undefined && { parallelCalls }), }); expectPublished(outcome, 150); const calls = { diff --git a/packages/server/src/tree/fold.ts b/packages/server/src/tree/fold.ts index 162dfaa6..5f4eb972 100644 --- a/packages/server/src/tree/fold.ts +++ b/packages/server/src/tree/fold.ts @@ -55,21 +55,45 @@ * tree already past either ceiling folds nothing. Each refuses as a * `deferred` stop the caller reports. * - * **Deadline.** Planning also stops on the wall clock: once - * `planDeadlineMs` (default `TREE_FOLD_PLAN_DEADLINE_MS`) has elapsed - * since the fold began, it admits no further entry and publishes the - * prefix it planned, as when the budget runs out. It is checked between - * entries, never inside one entry's node reads or a publication. A fold - * keeps planning past the deadline until the prefix it would publish is - * non-empty, so every tick that can fold an entry makes progress. + * **Tick budget.** Planning also stops on the wall clock, so the + * whole tick, publication included, fits `tickBudgetMs` (default + * `TREE_FOLD_TICK_BUDGET_MS`) counted from `startedAt`, the request's + * arrival. Before each log batch and each entry the fold adds the time + * elapsed since then to an estimate of publishing the plan so far, and + * once that reaches the budget it admits no further entry and publishes + * the prefix it planned (stop `tick-budget`), as when the call budget + * runs out. The estimate is the publication's rounds of calls + * (`publicationStages`: the fold record, each level of fresh nodes + * `parallelCalls` at a time, then the head CAS and its re-read) times + * the slowest call the tick has timed so far: its head GET, its root + * GET and its node GETs, issued at most `parallelCalls` at once so none + * waits behind a host's cap. A round lasts as long as its slowest call, + * and erring high only ends a tick early, while erring low can lose the + * tick. Log reads are not timed, as they may queue behind a host's + * concurrency cap. The check never interrupts one entry's node reads or + * a publication, so a tick overshoots its last passing check by at most + * one entry: its log batch, its node reads and the publication rounds + * it adds. A fold keeps planning past the budget until the prefix it + * would publish is non-empty, so every tick that can fold an entry + * makes progress. A fold pinned at its floor (behind an invalid + * survivor or a depth-0 byte overrun) so reads on past the budget until + * the pin releases or the window or call budget ends; its result then + * carries `pinnedPastTickBudget`, whatever its `stop` names, and the + * tick is counted as `db.compact.pinned_past_tick_budget_total`. * - * **Node reads.** Before adding a batch of entries, the fold has the + * **Node reads.** Before adding entries of a log batch, the fold has the * planner read ahead, concurrently, the nodes their leaf paths route to - * (`FoldPlanner.prefetch`), each GET charged as it is issued. A stop - * inside the batch may leave some of those GETs unused. While the prefix - * the fold would publish is empty (at the floor, or pinned there), it - * reads ahead one entry at a time, so read-ahead never charges the GETs - * that would keep the first publishable entry from fitting. + * (`FoldPlanner.prefetch`), at most `parallelCalls` at a time, each GET + * charged as it is issued. It reads ahead as many of the batch's + * entries as still fit the tick budget, the read-ahead's own rounds + * (one per `parallelCalls` entries at each level below the root, at the + * slowest call timed) counted with the elapsed time and the publication + * estimate, and at least one entry; the rest of the batch is read ahead + * the same way when the fold reaches it. A stop inside a read-ahead may + * leave some of its GETs unused. While the prefix the fold would publish + * is empty (at the floor, or pinned there), it reads ahead one entry at + * a time, so read-ahead never charges the GETs that would keep the first + * publishable entry from fitting. * * **Stuck entry.** When not even the first entry fits this tick's * budget, the fold publishes nothing, keeps the floor and emits a @@ -98,7 +122,8 @@ import { singleLeafApplies } from "./build.ts"; import { importChunkKey } from "./chunk.ts"; import { TREE_CHUNK_SALT_BYTES, - TREE_FOLD_PLAN_DEADLINE_MS, + TREE_FOLD_PARALLEL_CALLS, + TREE_FOLD_TICK_BUDGET_MS, TREE_RETRIED_CALL_CHARGE, } from "./constants.ts"; import { importTreeChunkKey, readTreeHead, readTreeRoot, type TreeHead } from "./head.ts"; @@ -106,7 +131,7 @@ import { collectionOfPrefix } from "./key.ts"; import { DEFAULT_TREE_CONFIG, type TreeConfig } from "./layout.ts"; import { type CanonicalDocument, canonicalDocument, type DecodedTreeNode } from "./node-codec.ts"; import { FoldPlanner, type TreeFoldPlan, type TreeMutation } from "./plan.ts"; -import { publishTree, type TreePublishOutcome } from "./publish.ts"; +import { publicationStages, publishTree, type TreePublishOutcome } from "./publish.ts"; /** * A depth-0 write limit: the fold publishes only a root leaf holding at @@ -142,16 +167,24 @@ export interface TreeFoldInput { /** Mints the chunk salt of a head that has none yet. Default: 16 random bytes. */ readonly mintChunkSalt?: () => string; /** - * Wall-clock milliseconds the fold may plan for. Default - * `TREE_FOLD_PLAN_DEADLINE_MS`. + * Wall-clock milliseconds the whole tick may take, counted from + * `startedAt`. Default `TREE_FOLD_TICK_BUDGET_MS`. */ - readonly planDeadlineMs?: number; + readonly tickBudgetMs?: number; /** - * Most node GETs the planner issues at once. Default - * `TREE_FOLD_PARALLEL_GETS`; `1` reads each node only when a change - * needs it. + * When the tick began on the `now` clock: the request's arrival, so + * that work the invocation did before the fold counts against the + * tick budget. Default: when the fold starts. */ - readonly parallelGets?: number; + readonly startedAt?: number; + /** + * Most storage calls the fold keeps in flight at once: node GETs read + * ahead, and node creates in each level of the publication. The host + * passes its maintenance profile's `foldParallelCalls`. Default + * `TREE_FOLD_PARALLEL_CALLS`; `1` reads each node only when a change + * needs it and creates nodes one at a time. + */ + readonly parallelCalls?: number; /** * The wall clock, in milliseconds; tests pass a fake one. Default * `Date.now`. On Workers it advances only across I/O, which is where a @@ -165,8 +198,8 @@ export interface TreeFoldInput { export type TreeFoldStop = /** The budget ran out before the entry at `seq` (or before reading it). */ | { readonly reason: "budget"; readonly seq: number } - /** The planning deadline elapsed before the entry at `seq` (or before reading it). */ - | { readonly reason: "deadline"; readonly seq: number } + /** The tick budget would run out before the entry at `seq` (or before reading it) could publish. */ + | { readonly reason: "tick-budget"; readonly seq: number } /** * A depth-0 ceiling: the captured tree is past it (`gate: "pre-fold"`), * or the entry at `seq` would take the totals past it and no later @@ -186,23 +219,39 @@ export type TreeFoldStop = /** Not even the first entry, at `seq`, fits this tick's budget. */ | { readonly reason: "stuck-entry"; readonly seq: number }; +/** + * Set on a fold's result when its tick budget ran out while the fold was + * pinned at its floor, so nothing was publishable yet, and it read on + * past the budget toward the entry that releases the pin. Such a tick + * may overrun its budget by as long as that reading takes; its `stop` + * may name another reason, or none. Counted as + * `db.compact.pinned_past_tick_budget_total`. + */ +export interface PinnedPastTickBudget { + readonly pinnedPastTickBudget?: true; +} + /** What a fold tick did. */ export type TreeFoldOutcome = /** The collection has no head, or the log has nothing past the floor. */ | { readonly kind: "nothing-to-fold"; readonly floor: number } /** Nothing was published: `stop` held the fold end at the floor. */ - | { readonly kind: "refused"; readonly floor: number; readonly stop: TreeFoldStop } + | ({ + readonly kind: "refused"; + readonly floor: number; + readonly stop: TreeFoldStop; + } & PinnedPastTickBudget) /** A publication attempt over `[floor, foldEnd)`; `stop` says why it ended early, if it did. */ - | { + | ({ readonly kind: "published" | "cas-lost"; readonly floor: number; readonly foldEnd: number; readonly publication: TreePublishOutcome; readonly stop?: TreeFoldStop; - }; + } & PinnedPastTickBudget); /** A fold that has captured the head and planned, and has not published. */ -export interface TreePreparedFold { +export interface TreePreparedFold extends PinnedPastTickBudget { readonly kind: "prepared"; readonly floor: number; readonly foldEnd: number; @@ -437,9 +486,26 @@ export const prepareTreeFold = async ( const collection = collectionOfPrefix(prefix); const opts = signal === undefined ? undefined : { signal }; const now = input.now ?? Date.now; - const deadline = now() + (input.planDeadlineMs ?? TREE_FOLD_PLAN_DEADLINE_MS); + const startedAt = input.startedAt ?? now(); + const tickBudgetMs = input.tickBudgetMs ?? TREE_FOLD_TICK_BUDGET_MS; + const width = Math.max(1, input.parallelCalls ?? TREE_FOLD_PARALLEL_CALLS); + /** + * The slowest storage call timed so far this tick, in milliseconds. + * The head GET is timed before anything is planned, so every estimate + * has a measurement. + */ + let slowestCallMs = 0; + /** Run one storage call, timing it for the publication estimate. */ + const timed = async (call: () => Promise): Promise => { + const begun = now(); + try { + return await call(); + } finally { + slowestCallMs = Math.max(slowestCallMs, now() - begun); + } + }; - const head: TreeHead | null = await readTreeHead(storage, prefix, opts); + const head: TreeHead | null = await timed(() => readTreeHead(storage, prefix, opts)); if (head === null) { return { kind: "nothing-to-fold", floor: 0 }; } @@ -455,7 +521,8 @@ export const prepareTreeFold = async ( if (head.root !== null && headCharge + GET_CHARGE > budget) { return refused({ reason: "budget", seq: floor }); } - const root = await readTreeRoot(storage, head, config, opts); + const root = + head.root === null ? null : await timed(() => readTreeRoot(storage, head, config, opts)); if (input.depthZero !== undefined) { const totals = new DepthZeroTotals(root); @@ -486,13 +553,13 @@ export const prepareTreeFold = async ( root, chunkKey, get: async (key) => { - const got = await storage.get(key, opts); + const got = await timed(() => storage.get(key, opts)); return got?.body ?? null; }, config, budget, spent: headCharge + (root === null ? 0 : GET_CHARGE), - ...(input.parallelGets !== undefined && { parallelGets: input.parallelGets }), + parallelGets: width, }); const totals = input.depthZero === undefined ? null : new DepthZeroTotals(root); @@ -507,6 +574,8 @@ export const prepareTreeFold = async ( /** While a checkpoint is pinned, how many entries it accepted. */ let pinnedAt = 0; let stop: TreeFoldStop | undefined; + /** Whether the tick budget ran out while the fold was pinned at its floor. */ + let pinnedPastTickBudget = false; let next = floor; let atTail = false; @@ -524,17 +593,63 @@ export const prepareTreeFold = async ( pinned = null; } }; - /** - * Whether the deadline stops the fold before the entry at `seq`: it - * has elapsed and the prefix the fold would publish is non-empty. - */ /** How many entries the fold would publish if it stopped now. */ const publishable = (): number => (pinned === null ? planner.accepted : pinnedAt); - const pastDeadline = (seq: number): boolean => { - if (publishable() === 0 || now() < deadline) { + /** Estimated milliseconds to publish the plan so far. */ + const publishMs = (): number => + slowestCallMs * + publicationStages(planner.publicationNodes).reduce( + (rounds, calls) => rounds + Math.ceil(calls / width), + 0, + ); + /** + * Estimated milliseconds to read ahead the nodes of `changes`: at the + * slowest call timed, one round per `width` changes at each level the + * read-ahead descends. An upper bound: a level may hold fewer distinct + * nodes than changes, and nodes already read are not read again. + */ + const readAheadMs = (changes: readonly EntryChange[]): number => + slowestCallMs * + planner.prefetchLevels * + Math.ceil(changes.filter((change) => change.kind === "change").length / width); + /** + * How many entries of `changes`, from index `i`, to read ahead. While + * nothing could publish, one: GETs charged for later entries could + * otherwise starve the entry that makes the prefix publishable, every + * tick. Otherwise the most whose read-ahead still fits the tick budget + * with the time elapsed and the publication estimate, and at least + * one, so a check that passed is overshot by at most one entry's reads. + */ + const readAheadSize = (changes: readonly EntryChange[], i: number): number => { + if (publishable() === 0) { + return 1; + } + const room = tickBudgetMs - (now() - startedAt) - publishMs(); + let size = changes.length - i; + while (size > 1 && readAheadMs(changes.slice(i, i + size)) >= room) { + size -= 1; + } + return size; + }; + /** + * Whether the tick budget stops the fold before the entry at `seq`: + * the time elapsed plus the time to publish the plan reaches the tick + * budget, and the prefix the fold would publish is non-empty. A fold + * pinned at its floor reads on instead; the first time that happens + * the tick is marked and counted. + */ + const pastTickBudget = (seq: number): boolean => { + if (now() - startedAt + publishMs() < tickBudgetMs) { + return false; + } + if (publishable() === 0) { + if (pinned !== null && !pinnedPastTickBudget) { + pinnedPastTickBudget = true; + ctxMetrics().counter("db.compact.pinned_past_tick_budget_total", 1, { collection }); + } return false; } - stop = { reason: "deadline", seq }; + stop = { reason: "tick-budget", seq }; return true; }; /** Accept an entry that changes no row; returns whether the fold reads on. */ @@ -595,7 +710,7 @@ export const prepareTreeFold = async ( }; reading: while (!atTail) { - if (pastDeadline(next)) { + if (pastTickBudget(next)) { break; } const first = next === floor; @@ -630,14 +745,11 @@ export const prepareTreeFold = async ( /** Entries of the batch whose nodes have been read ahead. */ let readAhead = 0; for (const [i, item] of batch.entries()) { - if (pastDeadline(item.seq)) { + if (pastTickBudget(item.seq)) { break reading; } if (i >= readAhead) { - // While nothing could publish, read ahead one entry at a time: - // GETs charged for later entries could otherwise starve the - // entry that makes the prefix publishable, every tick. - readAhead = publishable() === 0 ? i + 1 : batch.length; + readAhead = i + readAheadSize(changes, i); await planner.prefetch( changes .slice(i, readAhead) @@ -660,6 +772,7 @@ export const prepareTreeFold = async ( } const foldEnd = floor + planner.accepted; const plan = planner.plan; + const overrun = pinnedPastTickBudget ? ({ pinnedPastTickBudget: true } as const) : {}; if (foldEnd === floor || plan === null) { if (stop === undefined) { return { kind: "nothing-to-fold", floor }; @@ -667,7 +780,7 @@ export const prepareTreeFold = async ( if (stop.reason === "stuck-entry") { warnStuckEntry(collection, stop.seq); } - return refused(stop); + return { ...refused(stop), ...overrun }; } if (input.depthZero !== undefined && (plan.tree?.root.level ?? 0) !== 0) { throw new BaerlyError( @@ -683,6 +796,7 @@ export const prepareTreeFold = async ( foldEnd, plan, ...(stop !== undefined && { stop }), + ...overrun, publish: async () => { const publication = await publishTree({ storage, @@ -694,6 +808,7 @@ export const prepareTreeFold = async ( chunkSalt, meanEntryBytes, config, + parallelCalls: width, ...(signal !== undefined && { signal }), }); return { @@ -702,6 +817,7 @@ export const prepareTreeFold = async ( foldEnd, publication, ...(stop !== undefined && { stop }), + ...overrun, }; }, }; diff --git a/packages/server/src/tree/plan.ts b/packages/server/src/tree/plan.ts index a4efdd5b..0fc7487e 100644 --- a/packages/server/src/tree/plan.ts +++ b/packages/server/src/tree/plan.ts @@ -67,7 +67,7 @@ import { } from "./build.ts"; import type { ChunkKey } from "./chunk.ts"; import { - TREE_FOLD_PARALLEL_GETS, + TREE_FOLD_PARALLEL_CALLS, TREE_GC_RECORD_MAX_KEYS, TREE_HEAD_CAS_CHARGE, TREE_RETRIED_CALL_CHARGE, @@ -960,6 +960,14 @@ export const publicationReserve = (tree: PlannedTree | null): number => */ export const recordKeysFit = (keys: number): boolean => keys <= TREE_GC_RECORD_MAX_KEYS; +/** Fresh nodes publishing `state` creates, by level from the leaves up. */ +const freshByLevel = (state: PlannerState): readonly number[] => { + if (state.kind === "single") { + return state.rows === 0 ? [] : [1]; + } + return [...state.fresh, 1]; +}; + /** Input to {@link FoldPlanner}. */ export interface FoldPlannerInput extends Omit { /** Calls the request ledger allows this fold tick in total. */ @@ -968,7 +976,7 @@ export interface FoldPlannerInput extends Omit { readonly spent: number; /** * Most node GETs {@link FoldPlanner.prefetch} issues at once. Default - * `TREE_FOLD_PARALLEL_GETS`; `1` turns prefetching off, so every node + * `TREE_FOLD_PARALLEL_CALLS`; `1` turns prefetching off, so every node * is read as a change first needs it. */ readonly parallelGets?: number; @@ -1185,6 +1193,42 @@ export class FoldPlanner { return this.#gets; } + /** + * Levels of nodes {@link FoldPlanner.prefetch} would read for the next + * changes: every level below a root branch of the tree of the changes + * accepted so far, from the root's children down to the leaves. Zero + * when the root is a leaf, the tree is one leaf, a change has been + * rejected, or prefetching is off. + */ + get prefetchLevels(): number { + const width = this.#input.parallelGets ?? TREE_FOLD_PARALLEL_CALLS; + const { state } = this.#current; + if (width <= 1 || this.#rejected || state.kind !== "tree" || state.root.kind !== "branch") { + return 0; + } + return state.root.level; + } + + /** + * Fresh nodes publishing the last accepted plan creates, by level from + * the leaves up, the root's level last. While a checkpoint is pinned, + * each level holds the larger of that plan's count and the pinned + * plan's, as the charge holds the larger reserve: the fold publishes + * one or the other. Empty when the plan empties the tree. Before any + * change is accepted it counts a fresh root over the captured tree, + * though a fold with nothing accepted publishes nothing. + */ + get publicationNodes(): readonly number[] { + const current = freshByLevel(this.#current.state); + if (this.#pinned === null) { + return current; + } + const pinned = freshByLevel(this.#checkpoints[this.#pinned]!.state); + return Array.from({ length: Math.max(current.length, pinned.length) }, (_, level) => + Math.max(current[level] ?? 0, pinned[level] ?? 0), + ); + } + /** * Add the next change in seq order; a change to an `_id` already added * replaces that change. Returns whether it was accepted. After the @@ -1292,7 +1336,7 @@ export class FoldPlanner { * Adds no change. After a rejection it reads nothing. */ async prefetch(mutations: readonly TreeMutation[]): Promise { - const width = this.#input.parallelGets ?? TREE_FOLD_PARALLEL_GETS; + const width = this.#input.parallelGets ?? TREE_FOLD_PARALLEL_CALLS; const { state } = this.#current; if (width <= 1 || this.#rejected || state.kind !== "tree" || state.root.kind !== "branch") { return; diff --git a/packages/server/src/tree/publish.test.ts b/packages/server/src/tree/publish.test.ts index 2732b9f8..112bb113 100644 --- a/packages/server/src/tree/publish.test.ts +++ b/packages/server/src/tree/publish.test.ts @@ -815,6 +815,35 @@ describe("create-conflict adoption", () => { expect(sent).not.toContain(HEAD); await expect(bucket.head()).resolves.toMatchObject({ etag: fold.head.etag }); }); + + test("a level with several failed creates throws the failure of the first node in write order", async () => { + const bucket = await Bucket.seeded(); + const fold = await bucket.prepare(MIXED); + const attempt = attemptOf(0xfa11); + const sealed = await sealTree(fold.plan.tree, { + prefix: PREFIX, + attempt, + floor: fold.floor, + }); + const leaves = sealed.levels[0]!.map((node) => node.key); + expect(leaves.length).toBeGreaterThan(2); + const storage: Storage = { + ...bucket.storage, + put: async (key, body, opts) => { + const at = leaves.indexOf(key); + if (at === -1) { + return bucket.storage.put(key, body, opts); + } + // Later leaves fail first, so completion order is the reverse of write order. + await new Promise((resolve) => setTimeout(resolve, 2 * (leaves.length - at))); + throw new BaerlyError("AccessDenied", `injected: leaf ${at} denied`); + }, + }; + await expect(bucket.publish(fold, { storage, attempt })).rejects.toMatchObject({ + code: "AccessDenied", + message: "injected: leaf 0 denied", + }); + }); }); // --------------------------------------------------------------------- diff --git a/packages/server/src/tree/publish.ts b/packages/server/src/tree/publish.ts index 9ed4beb4..343e3efb 100644 --- a/packages/server/src/tree/publish.ts +++ b/packages/server/src/tree/publish.ts @@ -12,7 +12,8 @@ * 2. every fresh leaf, create-only; * 3. each level of fresh branches only after every fresh child it * references has completed, level by level up to the root; the - * creates of one level run concurrently; + * creates of one level run concurrently, at most `parallelCalls` at + * once; * 4. the head, `If-Match` the captured ETag. * * Exactly one record write comes first and exactly one head write last; @@ -87,6 +88,7 @@ import { } from "@baerly/protocol"; import { type PlannedTree, type SealedTree, sealTree } from "./build.ts"; import { chunkKeyIsOf } from "./chunk.ts"; +import { TREE_FOLD_PARALLEL_CALLS } from "./constants.ts"; import { assertRootMatchesHead, isTreeChunkSalt, @@ -144,9 +146,32 @@ export interface PublishTreeInput { readonly meanEntryBytes?: number; /** The tree configuration; tests pass a mutant here. */ readonly config?: TreeConfig; + /** + * Most node creates in flight at once. Default + * `TREE_FOLD_PARALLEL_CALLS`. + */ + readonly parallelCalls?: number; readonly signal?: AbortSignal; } +/** + * The storage calls publishing a plan issues, stage by stage in order: + * the fold record create, the fresh nodes of each level from the leaves + * up (`freshByLevel`, as `FoldPlanner.publicationNodes` gives them), + * then the head CAS and its fate re-read. The calls of one stage run + * concurrently and a stage starts once the one before has completed, so + * a stage of `n` calls takes `ceil(n / parallelCalls)` rounds. The + * re-read is counted though it follows only a CAS that throws; a create + * conflict's adoption GET is not, since it doubles a stage only on that + * failure path. + */ +export const publicationStages = (freshByLevel: readonly number[]): readonly number[] => [ + 1, // the fold record + ...freshByLevel, + 1, // the head CAS + 1, // its fate re-read +]; + /** What one publication attempt did. */ export type TreePublishOutcome = { /** This attempt's identity, carried by every node it created. */ @@ -544,12 +569,24 @@ export const publishTree = async (input: PublishTreeInput): Promise => { - const results = await Promise.allSettled(nodes.map(create)); - for (const result of results) { - if (result.status === "rejected") { - throw result.reason; + const failures: { readonly at: number; readonly error: unknown }[] = []; + let next = 0; + const lane = async (): Promise => { + while (next < nodes.length) { + const at = next++; + try { + await create(nodes[at]!); + } catch (error) { + failures.push({ at, error }); + } } + }; + await Promise.all(Array.from({ length: Math.min(width, nodes.length) }, lane)); + if (failures.length > 0) { + throw failures.reduce((first, failure) => (failure.at < first.at ? failure : first)).error; } }; diff --git a/tests/unit/tree-fold-planner.test.ts b/tests/unit/tree-fold-planner.test.ts index d0abd3f3..3003b4b3 100644 --- a/tests/unit/tree-fold-planner.test.ts +++ b/tests/unit/tree-fold-planner.test.ts @@ -640,6 +640,91 @@ describe("checkpoints and the look-ahead fallback", () => { // Prefix split // --------------------------------------------------------------------- +describe("the publication's fresh nodes by level", () => { + /** Fresh nodes publishing `plan` creates, by level from the leaves up, as the publication groups them. */ + const levelsOf = async (plan: TreeFoldPlan | null, floor: number): Promise => { + if (plan === null) { + return []; + } + const sealed = await sealTree(plan.tree, { + prefix: FOLD_PREFIX, + attempt: "f".repeat(32), + floor, + }); + return sealed.levels.map((level) => level.length); + }; + + fcTest.prop( + { + layout: fc.constantFrom(SMALL_LAYOUT, SMALL_DEPTH_ZERO), + base: fc.uniqueArray(smallIds, { maxLength: 80 }), + ticks: ticksOver(smallIds, fc.integer({ min: 11, max: 60 }), { ticks: 1, perTick: 30 }), + }, + { numRuns: 60 }, + )( + "after every change, the planner counts each level's fresh nodes as the publication creates them, root included", + async ({ layout, base, ticks }) => { + const config = configOf(layout); + const run = await FoldRun.open(config); + if (base.length > 0) { + await run.fold(base.map((id) => ({ id, value: sizedRow(id, 30, "a") }))); + } + const planner = new FoldPlanner({ + prefix: FOLD_PREFIX, + root: await run.captured(), + chunkKey, + get: (key) => Promise.resolve(run.store.get(key) ?? null), + config, + budget: UNBOUNDED, + spent: FOLD_SPENT_BEFORE_PLANNING, + }); + for (const { id, value } of ticks[0]!) { + await expect( + planner.add({ id, doc: value === null ? null : canonicalDocument(value, "row") }), + ).resolves.toBe(true); + expect(planner.publicationNodes).toEqual( + await levelsOf(planner.plan, run.floor + planner.accepted), + ); + } + }, + ); + + test("while pinned, each level counts the larger of the pinned plan and the current one", async () => { + const config = configOf(SMALL_LAYOUT); + const ids = Array.from({ length: 120 }, (_, i) => `r${String(i).padStart(3, "0")}`); + const run = await FoldRun.open(config); + await run.fold(ids.map((id) => ({ id, value: sizedRow(id, 30, "a") }))); + const planner = new FoldPlanner({ + prefix: FOLD_PREFIX, + root: await run.captured(), + chunkKey, + get: (key) => Promise.resolve(run.store.get(key) ?? null), + config, + budget: UNBOUNDED, + spent: FOLD_SPENT_BEFORE_PLANNING, + }); + // Scattered updates rewrite many leaves; the pin holds that plan. + for (let i = 0; i < 30; i++) { + const id = ids[(i * 37) % ids.length]!; + await expect( + planner.add({ id, doc: canonicalDocument(sizedRow(id, 30, "b"), "row") }), + ).resolves.toBe(true); + } + const pinned = await levelsOf(planner.plan, run.floor + planner.accepted); + expect(pinned[0]).toBeGreaterThan(1); + planner.pin(); + // Deleting every row leaves a current plan with no fresh node at all. + for (const id of ids) { + await expect(planner.add({ id, doc: null })).resolves.toBe(true); + } + const current = await levelsOf(planner.plan, run.floor + planner.accepted); + expect(current).toEqual([]); + expect(planner.publicationNodes).toEqual(pinned); + planner.rollback(); + expect(planner.publicationNodes).toEqual(pinned); + }); +}); + describe("the fold record's key cap", () => { const base: RowChange[] = Array.from({ length: 20 }, (_, i) => ({ id: `k${i}`, diff --git a/tests/unit/tree-fold-prefetch.test.ts b/tests/unit/tree-fold-prefetch.test.ts index 788b47d3..b4b87d90 100644 --- a/tests/unit/tree-fold-prefetch.test.ts +++ b/tests/unit/tree-fold-prefetch.test.ts @@ -12,7 +12,7 @@ * one it charged, its charge never passes the budget, and the plan it * stops at is the canonical plan of its accepted prefix. * - **Concurrency.** Prefetched GETs overlap, never more than - * `TREE_FOLD_PARALLEL_GETS` at once; `parallelGets: 1` reads one node + * `TREE_FOLD_PARALLEL_CALLS` at once; `parallelGets: 1` reads one node * at a time. */ import { fc, test as fcTest } from "@fast-check/vitest"; @@ -20,7 +20,7 @@ import { describe, expect, test } from "vitest"; import type { DocumentData } from "@baerly/protocol"; import { sealTree } from "../../packages/server/src/tree/build.ts"; import { - TREE_FOLD_PARALLEL_GETS, + TREE_FOLD_PARALLEL_CALLS, TREE_RETRIED_CALL_CHARGE, } from "../../packages/server/src/tree/constants.ts"; import type { TreeConfig } from "../../packages/server/src/tree/layout.ts"; @@ -229,13 +229,13 @@ describe("prefetched GETs run concurrently, within the width", () => { /** 48 updates scattered over the rows. */ const scattered = Array.from({ length: 48 }, (_, i) => base[(i * 97) % base.length]!); - test("the reads of a window overlap, at most TREE_FOLD_PARALLEL_GETS at once", async () => { + test("the reads of a window overlap, at most TREE_FOLD_PARALLEL_CALLS at once", async () => { const run = await runOver(rowsOf(base, 30), []); expect((await run.captured())!.node.level).toBeGreaterThanOrEqual(2); const mutations = mutationsOf(rowsOf(scattered, 31, "z")); const parallel = await drive(run, config, mutations, { budget: UNBOUNDED, delay: true }); expect(parallel.maxInFlight).toBeGreaterThan(1); - expect(parallel.maxInFlight).toBeLessThanOrEqual(TREE_FOLD_PARALLEL_GETS); + expect(parallel.maxInFlight).toBeLessThanOrEqual(TREE_FOLD_PARALLEL_CALLS); const serial = await drive(run, config, mutations, { budget: UNBOUNDED, parallelGets: 1,