From c5b50ae50a1d0ffe2a9602c8c53f8a14c742613c Mon Sep 17 00:00:00 2001 From: Eric Baer Date: Tue, 24 Nov 2026 11:16:30 -0800 Subject: [PATCH 01/15] feat(tree): decode fold records strictly GC reads fold records to nominate deletions, so it needs a decoder that accepts only what a publication sealed at that key: the body ceiling, the key's hash against the exact bytes, fatal UTF-8, JSON, every rule the sealer enforces (re-run through sealFoldRecord), and byte equality with the canonical re-encoding. Any failure is InvalidResponse naming the key and the check. --- packages/server/src/tree/record.test.ts | 57 ++++++++++- packages/server/src/tree/record.ts | 123 +++++++++++++++++++++++- 2 files changed, 177 insertions(+), 3 deletions(-) diff --git a/packages/server/src/tree/record.test.ts b/packages/server/src/tree/record.test.ts index 17db1488..ff6c87aa 100644 --- a/packages/server/src/tree/record.test.ts +++ b/packages/server/src/tree/record.test.ts @@ -7,7 +7,7 @@ import { describe, expect, test } from "vitest"; import { sha256Hex } from "@baerly/protocol"; import { TREE_GC_RECORD_MAX_KEYS } from "./constants.ts"; import { parseTreeRecordKey } from "./key.ts"; -import { type FoldRecord, sealFoldRecord } from "./record.ts"; +import { decodeFoldRecord, type FoldRecord, sealFoldRecord } from "./record.ts"; const P = "app/helpdesk/tenant/acme/manifests/tickets"; const A1 = "00112233445566778899aabbccddeeff"; @@ -95,3 +95,58 @@ describe("sealFoldRecord", () => { expect(sealed.bytes.byteLength).toBeGreaterThan(TREE_GC_RECORD_MAX_KEYS * 60); }); }); + +describe("decodeFoldRecord", () => { + const reseal = async (body: Uint8Array): Promise => + `${P}/_v99/r/0000000000000007/${A1}/${await sha256Hex(body)}`; + + test("decodes exactly what sealFoldRecord sealed", async () => { + const sealed = await sealFoldRecord(P, RECORD); + await expect(decodeFoldRecord(P, sealed.key, sealed.bytes)).resolves.toEqual(RECORD); + }); + + test.each<[string, (text: string) => string]>([ + ["whitespace", (text) => text.replace(",", ", ")], + [ + "reordered fields", + (text) => + text.replace( + '"format":"baerly-tree-fold-record-proto","schema_version":1', + '"schema_version":1,"format":"baerly-tree-fold-record-proto"', + ), + ], + ["an extra field", (text) => text.replace(/}$/, ',"extra":1}')], + ["another format", (text) => text.replace("fold-record-proto", "fold-record-other")], + ["a newer schema", (text) => text.replace('"schema_version":1', '"schema_version":2')], + [ + "unsorted fresh", + (text) => text.replace(`"${sha(1)}","${sha(2)}"`, `"${sha(2)}","${sha(1)}"`), + ], + ["a string floor", (text) => text.replace('"floor":7', '"floor":"7"')], + ["not JSON", () => "{"], + ])("a body with %s is InvalidResponse, even keyed by its own hash", async (_name, edit) => { + const sealed = await sealFoldRecord(P, RECORD); + const body = new TextEncoder().encode(edit(new TextDecoder().decode(sealed.bytes))); + await expect(decodeFoldRecord(P, await reseal(body), body)).rejects.toMatchObject({ + code: "InvalidResponse", + }); + }); + + test("a body that does not hash to its key, or a key of another floor or attempt, is InvalidResponse", async () => { + const sealed = await sealFoldRecord(P, RECORD); + const other = sealed.bytes.slice(); + other[other.length - 2] = other[other.length - 2]! ^ 1; + await expect(decodeFoldRecord(P, sealed.key, other)).rejects.toMatchObject({ + code: "InvalidResponse", + }); + for (const key of [ + sealed.key.replace("/0000000000000007/", "/0000000000000008/"), + sealed.key.replace(`/${A1}/`, `/${A2}/`), + sealed.key.replace("/_v99/r/", "/_v99/n/"), + ]) { + await expect(decodeFoldRecord(P, key, sealed.bytes)).rejects.toMatchObject({ + code: "InvalidResponse", + }); + } + }); +}); diff --git a/packages/server/src/tree/record.ts b/packages/server/src/tree/record.ts index 4d40b166..475e9d30 100644 --- a/packages/server/src/tree/record.ts +++ b/packages/server/src/tree/record.ts @@ -31,7 +31,12 @@ * record can name only its own attempt's fresh nodes; no `superseded` * entry carries the record's attempt. */ -import { BaerlyError, encodeJsonBytes, sha256Hex } from "@baerly/protocol"; +import { + BaerlyError, + encodeJsonBytes, + sha256Hex, + unsupportedSchemaVersionMessage, +} from "@baerly/protocol"; import { TREE_FOLD_RECORD_FORMAT, TREE_FOLD_RECORD_SCHEMA_VERSION, @@ -39,7 +44,13 @@ import { TREE_GC_RECORD_MAX_KEYS, } from "./constants.ts"; import type { TreeHead } from "./head.ts"; -import { isTreeAttempt, isTreeSha256, parseTreeNodeKey, treeRecordKey } from "./key.ts"; +import { + isTreeAttempt, + isTreeSha256, + parseTreeNodeKey, + parseTreeRecordKey, + treeRecordKey, +} from "./key.ts"; import type { DecodedTreeNode, TreeChildEntry } from "./node-codec.ts"; /** The head a fold record's attempt captured, and will CAS against. */ @@ -263,3 +274,111 @@ export const sealFoldRecord = async ( const sha256 = await sha256Hex(bytes); return { key: treeRecordKey(prefix, base.floor, attempt, sha256), bytes, sha256 }; }; + +const fatalUtf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + +const isPlainObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +const isStringOrNull = (value: unknown): value is string | null => + value === null || typeof value === "string"; + +/** + * Strictly decode the fold record `bytes` read from `key`, a record key + * under `prefix`: the body ceiling, the key's hash against the exact + * bytes, fatal UTF-8, JSON, every field and rule `sealFoldRecord` + * enforces, and byte equality with the canonical re-encoding. So a + * decoded record is exactly what some publication sealed at that key. + * + * @throws BaerlyError code="InvalidResponse" — any check fails; the + * message names the key and the failed check. + */ +export const decodeFoldRecord = async ( + prefix: string, + key: string, + bytes: Uint8Array, +): Promise => { + const fail: (detail: string) => never = (detail) => { + throw new BaerlyError("InvalidResponse", `tree fold record ${JSON.stringify(key)}: ${detail}`); + }; + const parts = parseTreeRecordKey(prefix, key); + if (parts === null) { + fail("the key is not a fold-record key of this collection"); + } + if (bytes.byteLength > TREE_GC_RECORD_MAX_BODY_BYTES) { + fail(`the body is ${bytes.byteLength} bytes, over its ceiling`); + } + if ((await sha256Hex(bytes)) !== parts.sha256) { + fail("the body does not hash to the key"); + } + let value: unknown; + try { + value = JSON.parse(fatalUtf8.decode(bytes)); + } catch { + fail("the body is not UTF-8 JSON"); + } + if (!isPlainObject(value)) { + fail("the body is not an object"); + } + if (value["format"] !== TREE_FOLD_RECORD_FORMAT) { + fail("the format tag is not a fold record's"); + } + if (value["schema_version"] !== TREE_FOLD_RECORD_SCHEMA_VERSION) { + fail( + unsupportedSchemaVersionMessage( + "fold record", + typeof value["schema_version"] === "number" ? value["schema_version"] : "a non-number", + TREE_FOLD_RECORD_SCHEMA_VERSION, + ), + ); + } + const base = value["base"]; + const result = value["result"]; + const fresh = value["fresh"]; + const superseded = value["superseded"]; + if ( + typeof value["attempt"] !== "string" || + !isPlainObject(base) || + typeof base["floor"] !== "number" || + !isStringOrNull(base["root"]) || + !isStringOrNull(base["attempt"]) || + !isStringOrNull(base["generation"]) || + !isPlainObject(result) || + typeof result["floor"] !== "number" || + !isStringOrNull(result["root"]) || + !Array.isArray(fresh) || + !fresh.every((entry) => typeof entry === "string") || + !Array.isArray(superseded) || + !superseded.every((entry) => typeof entry === "string") + ) { + fail("the body does not have the fields of a fold record"); + } + const record: FoldRecord = { + attempt: value["attempt"], + base: { + floor: base["floor"], + root: base["root"], + attempt: base["attempt"], + generation: base["generation"], + }, + result: { floor: result["floor"], root: result["root"] }, + fresh: fresh as string[], + superseded: superseded as string[], + }; + let sealed: SealedFoldRecord; + try { + sealed = await sealFoldRecord(prefix, record); + } catch (error) { + return fail(`the record breaks a record rule: ${(error as Error).message}`); + } + if (sealed.key !== key) { + fail("the body's attempt or base floor is not the key's"); + } + if ( + sealed.bytes.byteLength !== bytes.byteLength || + !sealed.bytes.every((b, i) => b === bytes[i]) + ) { + fail("the body is not the canonical encoding of its value"); + } + return record; +}; From a22140f39ad6c9e200149e5c431686961ebcecaf Mon Sep 17 00:00:00 2001 From: Eric Baer Date: Tue, 24 Nov 2026 11:16:53 -0800 Subject: [PATCH 02/15] feat(tree): add the tree GC state codec and tick constants Tree GC keeps its progress at

/_v99/gc-pending.json: the head generation and floor it is bound to, a write counter, the last probe's server time and the local time of that probe, the resolved floors, a stuck floor, one work entry per resolved floor and the leak sweep's cursor and marks. The state schedules and never authorizes a deletion, so a stale or lost one can only leak. The encoder refuses a state the decoder would refuse. The decoder returns a malformed state as a value, since GC replaces it leak-only, and throws InvalidResponse only for this format at another schema version, saying GC for the collection is paused. Constants: the state format tag, schema version and body ceiling, the larger per-tick candidate ceiling a roomy ledger allows (512), and the calls a tick reserves besides its candidate checks. --- packages/server/src/tree/constants.ts | 34 +++ packages/server/src/tree/gc-state.test.ts | 117 ++++++++ packages/server/src/tree/gc-state.ts | 310 ++++++++++++++++++++++ packages/server/src/tree/key.ts | 3 + 4 files changed, 464 insertions(+) create mode 100644 packages/server/src/tree/gc-state.test.ts create mode 100644 packages/server/src/tree/gc-state.ts diff --git a/packages/server/src/tree/constants.ts b/packages/server/src/tree/constants.ts index 25ada612..b124cca5 100644 --- a/packages/server/src/tree/constants.ts +++ b/packages/server/src/tree/constants.ts @@ -262,3 +262,37 @@ export const TREE_GC_MAX_WORK_ENTRIES = 256; * key left unmarked is examined again on the next sweep pass. */ export const TREE_GC_MAX_SWEEP_MARKS = 256; + +/** + * Most candidate checks one GC tick makes when its request ledger has + * room: on the Workers Paid ledger a tick of this many checks at depth 2 + * costs about 4,700 calls with log retirement, about half the ledger, + * and drains a whole-tree rewrite's record in a few ticks instead of + * dozens. A ledger with less room gets {@link TREE_GC_TICK_CANDIDATES}. + */ +export const TREE_GC_TICK_MAX_CANDIDATES = 512; + +/** + * Calls a GC tick may make besides its candidate checks, each charged + * at every attempt: the state GET, two LISTs, the head and root GETs, + * {@link TREE_GC_TICK_RECORD_CALLS} record GETs and as many record + * DELETEs (3 each), one state create (3) and one state CAS (1), plus 69 + * for a log-retirement pass that finds work (its gate GET, CAS GET and + * PUT, and 20 DELETEs). The tick sizes its candidate count from what + * the ledger has left after these. + */ +export const TREE_GC_TICK_RESERVED_CALLS = 43 + 69; + +/** The `format` tag of the tree GC state. */ +export const TREE_GC_STATE_FORMAT = "baerly-tree-gc-state-proto"; + +/** The `schema_version` of the tree GC state. */ +export const TREE_GC_STATE_SCHEMA_VERSION = 1; + +/** + * Decoder ceiling on the tree GC state body, in bytes. A state at its + * caps ({@link TREE_GC_MAX_WORK_ENTRIES} work entries and + * {@link TREE_GC_MAX_SWEEP_MARKS} marks, a few hundred bytes each) is + * well under it. + */ +export const TREE_GC_STATE_MAX_BODY_BYTES = 524_288; diff --git a/packages/server/src/tree/gc-state.test.ts b/packages/server/src/tree/gc-state.test.ts new file mode 100644 index 00000000..a409ec0c --- /dev/null +++ b/packages/server/src/tree/gc-state.test.ts @@ -0,0 +1,117 @@ +/** The tree GC state codec (`./gc-state.ts`). */ +import { describe, expect, test } from "vitest"; +import { encodeJsonBytes } from "@baerly/protocol"; +import { TREE_GC_MAX_SWEEP_MARKS, TREE_GC_MAX_WORK_ENTRIES } from "./constants.ts"; +import { + decodeTreeGcState, + emptyTreeGcState, + encodeTreeGcState, + type TreeGcState, +} from "./gc-state.ts"; + +const KEY = "app/a/tenant/t/manifests/c/_v99/gc-pending.json"; +const REF = `${"0".repeat(31)}1/${"f".repeat(64)}`; +const AT = "2026-01-05T00:15:00.000Z"; + +const FULL: TreeGcState = { + generation: "0a", + floor_seen: 23, + ticks: 7, + clock: "2026-01-05T00:00:00.000Z", + probed_local_at: "2026-01-05T00:00:01.000Z", + resolved_through: 20, + stuck: { floor: 21, since: null }, + work: [ + { floor: 0, winner: REF, quarantined: false, due_at: AT, next: 3, loser: null }, + { + floor: 20, + winner: REF, + quarantined: true, + due_at: null, + next: 0, + loser: { record: REF, next: 2 }, + }, + ], + sweep: { + cursor: "app/a/tenant/t/manifests/c/_v99/n/x", + marks: [{ key: REF, floor: 20, due_at: AT }], + }, +}; + +describe("tree GC state", () => { + test("a state round-trips through its canonical body", () => { + for (const state of [FULL, emptyTreeGcState(null, 0)]) { + expect(decodeTreeGcState(KEY, encodeTreeGcState(state))).toEqual({ kind: "state", state }); + } + }); + + test.each<[string, (state: TreeGcState) => unknown]>([ + ["a non-instant clock", (s) => ({ ...s, clock: "yesterday" })], + ["a fractional floor", (s) => ({ ...s, floor_seen: 1.5 })], + ["a malformed winner", (s) => ({ ...s, work: [{ ...s.work[0]!, winner: "x" }] })], + ["work out of floor order", (s) => ({ ...s, work: s.work.toReversed() })], + [ + "a repeated mark", + (s) => ({ ...s, sweep: { ...s.sweep, marks: [s.sweep.marks[0]!, s.sweep.marks[0]!] } }), + ], + [ + "too many work entries", + (s) => ({ + ...s, + work: Array.from({ length: TREE_GC_MAX_WORK_ENTRIES + 1 }, (_, i) => ({ + ...s.work[0]!, + floor: i, + })), + }), + ], + [ + "too many marks", + (s) => ({ + ...s, + sweep: { + ...s.sweep, + marks: Array.from({ length: TREE_GC_MAX_SWEEP_MARKS + 1 }, (_, i) => ({ + key: `${String(i).padStart(32, "0")}/${"f".repeat(64)}`, + floor: 0, + due_at: null, + })), + }, + }), + ], + ])("%s is refused by the encoder and malformed to the decoder", (_name, edit) => { + const state = edit(FULL) as TreeGcState; + expect(() => encodeTreeGcState(state)).toThrow(expect.objectContaining({ code: "Internal" })); + const body = encodeJsonBytes({ + format: "baerly-tree-gc-state-proto", + schema_version: 1, + ...state, + }); + expect(decodeTreeGcState(KEY, body).kind).toBe("malformed"); + }); + + test("a non-canonical body, another format or a non-number schema is malformed", () => { + const text = new TextDecoder().decode(encodeTreeGcState(FULL)); + for (const body of [ + text.replace(",", ", "), + text.replace('"ticks":7', '"ticks":7,"extra":1'), + text.replace("gc-state-proto", "gc-state-other"), + text.replace('"schema_version":1', '"schema_version":"1"'), + "[]", + "{", + ]) { + expect(decodeTreeGcState(KEY, new TextEncoder().encode(body)).kind).toBe("malformed"); + } + }); + + test("a state of another schema version is InvalidResponse that says GC is paused", () => { + const body = new TextDecoder() + .decode(encodeTreeGcState(FULL)) + .replace('"schema_version":1', '"schema_version":2'); + expect(() => decodeTreeGcState(KEY, new TextEncoder().encode(body))).toThrow( + expect.objectContaining({ + code: "InvalidResponse", + message: expect.stringContaining("paused"), + }), + ); + }); +}); diff --git a/packages/server/src/tree/gc-state.ts b/packages/server/src/tree/gc-state.ts new file mode 100644 index 00000000..625aef2e --- /dev/null +++ b/packages/server/src/tree/gc-state.ts @@ -0,0 +1,310 @@ +/** + * The tree GC state at `

/_v99/gc-pending.json`: what GC has resolved, + * what it still has to drain, its last reading of the storage server's + * clock and the leak sweep's progress. + * + * The state records progress only. It names candidates and schedules, + * and never authorizes a DELETE: every deletion is proven in its own + * tick against the root that tick read (`./gc.ts`). A stale, replaced or + * lost state can therefore leak, never delete. + * + * The body is the `encodeJsonBytes` of exactly this object, in this + * field order, and is strictly decoded (fatal UTF-8, JSON, structure, + * canonical bytes): + * + * ```text + * {"format":"baerly-tree-gc-state-proto","schema_version":1, + * "generation":""|null, "floor_seen":h, "ticks":N, + * "clock":""|null, "probed_local_at":""|null, + * "resolved_through":f|null, + * "stuck":{"floor":f,"since":""|null}|null, + * "work":[{"floor":f,"winner":"/","quarantined":bool, + * "due_at":""|null,"next":i, + * "loser":{"record":"/","next":j}|null},...], + * "sweep":{"cursor":""|null, + * "marks":[{"key":"/","floor":h,"due_at":""|null},...]}} + * ``` + * + * - `generation` and `floor_seen` bind the state to one head history. + * - `ticks` grows on every write, so no two written bodies are equal. + * - `clock` is the server time of the latest probe, a lower bound on + * server now. `probed_local_at` is the prober's local clock at that + * probe; it paces the next probe and is never compared with a server + * time. + * - `resolved_through`: every floor at or below it is resolved or + * retired. `stuck` is the lowest closed floor without a unique winner. + * - `work` holds one entry per resolved floor: the winner record's key + * tail, whether its list is quarantined, when its superseded nodes are + * due, how far it is drained, and the one loser record being drained. + * - `sweep` holds the leak sweep's cursor and marks (noted, then + * stamped). + */ +import { BaerlyError, encodeJsonBytes, unsupportedSchemaVersionMessage } from "@baerly/protocol"; +import { + TREE_GC_MAX_SWEEP_MARKS, + TREE_GC_MAX_WORK_ENTRIES, + TREE_GC_STATE_FORMAT, + TREE_GC_STATE_MAX_BODY_BYTES, + TREE_GC_STATE_SCHEMA_VERSION, +} from "./constants.ts"; + +/** A floor GC has resolved: its winner and the loser being drained. */ +export interface TreeGcWork { + readonly floor: number; + /** The winner record's key tail, `/`. */ + readonly winner: string; + /** Whether the winner's `superseded` list is blocked from being consumed. */ + readonly quarantined: boolean; + /** When the winner's superseded nodes are due, on the server clock; `null` until stamped. */ + readonly due_at: string | null; + /** How many of the winner's `superseded` entries are done. */ + readonly next: number; + /** The loser record being drained, and how many of its `fresh` entries are done. */ + readonly loser: { readonly record: string; readonly next: number } | null; +} + +/** A node the leak sweep found unreachable. */ +export interface TreeGcMark { + /** The node key tail, `/`. */ + readonly key: string; + /** The head floor read after the LIST that showed it. */ + readonly floor: number; + /** When it may be deleted, on the server clock; `null` while only noted. */ + readonly due_at: string | null; +} + +/** The decoded tree GC state. */ +export interface TreeGcState { + readonly generation: string | null; + readonly floor_seen: number; + readonly ticks: number; + readonly clock: string | null; + readonly probed_local_at: string | null; + readonly resolved_through: number | null; + readonly stuck: { readonly floor: number; readonly since: string | null } | null; + readonly work: readonly TreeGcWork[]; + readonly sweep: { readonly cursor: string | null; readonly marks: readonly TreeGcMark[] }; +} + +/** The empty state bound to a head of `generation` at floor `floor`. */ +export const emptyTreeGcState = (generation: string | null, floor: number): TreeGcState => ({ + generation, + floor_seen: floor, + ticks: 0, + clock: null, + probed_local_at: null, + resolved_through: null, + stuck: null, + work: [], + sweep: { cursor: null, marks: [] }, +}); + +const REF_PATTERN = /^[0-9a-f]{32}\/[0-9a-f]{64}$/; + +const isFloor = (value: unknown): value is number => + typeof value === "number" && Number.isSafeInteger(value) && value >= 0; + +/** Whether `value` is an ISO-8601 instant as `Date.prototype.toISOString` writes it. */ +const isInstant = (value: unknown): value is string => { + if (typeof value !== "string") { + return false; + } + const date = new Date(value); + return !Number.isNaN(date.getTime()) && date.toISOString() === value; +}; + +const isInstantOrNull = (value: unknown): value is string | null => + value === null || isInstant(value); + +/** Whether `value` is a non-array object, without narrowing its declared type. */ +const isObject = (value: unknown): boolean => + typeof value === "object" && value !== null && !Array.isArray(value); + +const isPlainObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** The first rule `state` breaks, or `undefined`. */ +const stateViolation = (state: TreeGcState): string | undefined => { + if (state.generation !== null && typeof state.generation !== "string") { + return "generation is neither null nor a string"; + } + if (!isFloor(state.floor_seen) || !isFloor(state.ticks)) { + return "floor_seen or ticks is not a non-negative safe integer"; + } + if (!isInstantOrNull(state.clock) || !isInstantOrNull(state.probed_local_at)) { + return "clock or probed_local_at is neither null nor an ISO-8601 instant"; + } + if (state.resolved_through !== null && !isFloor(state.resolved_through)) { + return "resolved_through is neither null nor a floor"; + } + if ( + state.stuck !== null && + (!isObject(state.stuck) || !isFloor(state.stuck.floor) || !isInstantOrNull(state.stuck.since)) + ) { + return "stuck is malformed"; + } + if (!Array.isArray(state.work) || state.work.length > TREE_GC_MAX_WORK_ENTRIES) { + return "work is not a list within its cap"; + } + for (const entry of state.work) { + if ( + !isObject(entry) || + !isFloor(entry.floor) || + typeof entry.winner !== "string" || + !REF_PATTERN.test(entry.winner) || + typeof entry.quarantined !== "boolean" || + !isInstantOrNull(entry.due_at) || + !isFloor(entry.next) || + (entry.loser !== null && + (!isObject(entry.loser) || + typeof entry.loser.record !== "string" || + !REF_PATTERN.test(entry.loser.record) || + !isFloor(entry.loser.next))) + ) { + return "a work entry is malformed"; + } + } + if (!state.work.every((entry, i) => i === 0 || state.work[i - 1]!.floor < entry.floor)) { + return "work entries are not in strictly increasing floor order"; + } + const sweep = state.sweep; + if ( + !isObject(sweep) || + (sweep.cursor !== null && typeof sweep.cursor !== "string") || + !Array.isArray(sweep.marks) || + sweep.marks.length > TREE_GC_MAX_SWEEP_MARKS + ) { + return "sweep is malformed"; + } + for (const mark of sweep.marks) { + if ( + !isObject(mark) || + typeof mark.key !== "string" || + !REF_PATTERN.test(mark.key) || + !isFloor(mark.floor) || + !isInstantOrNull(mark.due_at) + ) { + return "a sweep mark is malformed"; + } + } + if (new Set(sweep.marks.map((mark) => mark.key)).size !== sweep.marks.length) { + return "a sweep mark repeats a key"; + } + return undefined; +}; + +/** The canonical body of `state`, fields in format order. */ +const encodeBody = (state: TreeGcState): Uint8Array => + encodeJsonBytes({ + format: TREE_GC_STATE_FORMAT, + schema_version: TREE_GC_STATE_SCHEMA_VERSION, + generation: state.generation, + floor_seen: state.floor_seen, + ticks: state.ticks, + clock: state.clock, + probed_local_at: state.probed_local_at, + resolved_through: state.resolved_through, + stuck: state.stuck === null ? null : { floor: state.stuck.floor, since: state.stuck.since }, + work: state.work.map((entry) => ({ + floor: entry.floor, + winner: entry.winner, + quarantined: entry.quarantined, + due_at: entry.due_at, + next: entry.next, + loser: entry.loser === null ? null : { record: entry.loser.record, next: entry.loser.next }, + })), + sweep: { + cursor: state.sweep.cursor, + marks: state.sweep.marks.map((mark) => ({ + key: mark.key, + floor: mark.floor, + due_at: mark.due_at, + })), + }, + }); + +/** + * Encode `state`. A state the decoder would refuse is never encoded. + * + * @throws BaerlyError code="Internal" — the state breaks a state rule + * (a GC bug). + */ +export const encodeTreeGcState = (state: TreeGcState): Uint8Array => { + const violation = stateViolation(state); + if (violation !== undefined) { + throw new BaerlyError("Internal", `tree GC state: ${violation}`); + } + const bytes = encodeBody(state); + if (bytes.byteLength > TREE_GC_STATE_MAX_BODY_BYTES) { + throw new BaerlyError("Internal", `tree GC state: the body is over its ceiling`); + } + return bytes; +}; + +/** What a state read decodes to. */ +export type TreeGcStateDecode = + | { readonly kind: "state"; readonly state: TreeGcState } + | { readonly kind: "malformed"; readonly reason: string }; + +const fatalUtf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + +const malformed = (reason: string): TreeGcStateDecode => ({ kind: "malformed", reason }); + +/** + * Strictly decode the state body `bytes` read from `key`. A malformed + * state is a value, because GC replaces it leak-only; only a state of + * this format with a `schema_version` this build does not know throws. + * + * @throws BaerlyError code="InvalidResponse" — the state has this + * format and an unknown `schema_version`: it was written by another + * release, so GC for this collection is paused. + */ +export const decodeTreeGcState = (key: string, bytes: Uint8Array): TreeGcStateDecode => { + if (bytes.byteLength > TREE_GC_STATE_MAX_BODY_BYTES) { + return malformed("the body is over its ceiling"); + } + let value: unknown; + try { + value = JSON.parse(fatalUtf8.decode(bytes)); + } catch { + return malformed("the body is not UTF-8 JSON"); + } + if (!isPlainObject(value) || value["format"] !== TREE_GC_STATE_FORMAT) { + return malformed("the body is not a tree GC state"); + } + const version = value["schema_version"]; + if (typeof version !== "number") { + return malformed("schema_version is not a number"); + } + if (version !== TREE_GC_STATE_SCHEMA_VERSION) { + throw new BaerlyError( + "InvalidResponse", + `${unsupportedSchemaVersionMessage( + `tree GC state ${JSON.stringify(key)}`, + version, + TREE_GC_STATE_SCHEMA_VERSION, + )} GC for this collection was written by a newer release and is paused.`, + { resolution: "Run the app or operator CLI at that release or later." }, + ); + } + const state: TreeGcState = { + generation: value["generation"] as TreeGcState["generation"], + floor_seen: value["floor_seen"] as number, + ticks: value["ticks"] as number, + clock: value["clock"] as TreeGcState["clock"], + probed_local_at: value["probed_local_at"] as TreeGcState["probed_local_at"], + resolved_through: value["resolved_through"] as TreeGcState["resolved_through"], + stuck: value["stuck"] as TreeGcState["stuck"], + work: value["work"] as TreeGcState["work"], + sweep: value["sweep"] as TreeGcState["sweep"], + }; + const violation = stateViolation(state); + if (violation !== undefined) { + return malformed(violation); + } + const canonical = encodeBody(state); + if (canonical.byteLength !== bytes.byteLength || !canonical.every((b, i) => b === bytes[i])) { + return malformed("the body is not the canonical encoding of its value"); + } + return { kind: "state", state }; +}; diff --git a/packages/server/src/tree/key.ts b/packages/server/src/tree/key.ts index 9d190ead..3d83be7a 100644 --- a/packages/server/src/tree/key.ts +++ b/packages/server/src/tree/key.ts @@ -181,6 +181,9 @@ export const parseTreeRecordKey = (prefix: string, key: string): TreeRecordKeyPa return { floor, attempt: rest.slice(0, 32), sha256: rest.slice(33) }; }; +/** The key of the collection's tree GC state: `

/_v99/gc-pending.json`. */ +export const treeGcStateKey = (prefix: string): string => `${prefix}/${TREE_NS}/gc-pending.json`; + /** * Mint a fresh attempt identity: 128 random bits as lowercase hex. One * publication attempt (one capture of the head and its root, then at From b0485e23add841f0af5dab9b214630886c6919fb Mon Sep 17 00:00:00 2001 From: Eric Baer Date: Tue, 24 Nov 2026 11:17:20 -0800 Subject: [PATCH 03/15] feat(tree): add the tree GC tick runTreeGcTick reclaims tree nodes no current root reaches, and never writes the head. A record's floor is closed once the head's floor is above it: that attempt's head CAS can no longer land. The winner of a closed floor is named by evidence its CAS created (the head's installer, or the base installer of a record captured on a later floor); every other attempt there is a loser. - Losers' fresh nodes are deleted at once. - Winners' superseded nodes are deleted 15 minutes of server time after a probe first stamps them, so reads through the old root can finish; a read that outlives that meets the reader's backstop. - A leak sweep lists the node prefix a page per probe, notes unreachable nodes with the head floor read after the LIST, stamps them once a later fold moved the floor, and deletes them 60 minutes later. Every DELETE is proven in its own tick by the membership check against the root that tick read (key-only at depth 0 and 1; a body GET and a validated path above). A missing or undecodable path node stops the tick's deletions. Records, the state and the clock only nominate and pace. The only clock is the server time of GC's own state write, probed at most once a minute of local time judged against the local time of the last probe; no server time means nothing is due. A corrupt candidate is counted and warned and left in place, except a known loser's, which is deleted on its key alone. An identity found in two records is never a deletion source. Candidate checks per tick are sized from the request ledger: 512 when it has room, else at most 64. Tests run real folds against a harness with hand-moved local and server clocks and folds paused before their head CAS, judge the tree with the physical oracle and a reader-margin watch, sweep a crash across a tick, and turn 22 GC mutants red, including record path, membership, sweep, classification, clock and identity defects. --- packages/server/src/tree/gc-member.ts | 270 +++++++ packages/server/src/tree/gc.test.ts | 1020 +++++++++++++++++++++++++ packages/server/src/tree/gc.ts | 880 +++++++++++++++++++++ packages/server/src/tree/layout.ts | 46 ++ tests/fixtures/tree-gc-harness.ts | 487 ++++++++++++ tests/fixtures/tree-mutants.ts | 289 +++++++ 6 files changed, 2992 insertions(+) create mode 100644 packages/server/src/tree/gc-member.ts create mode 100644 packages/server/src/tree/gc.test.ts create mode 100644 packages/server/src/tree/gc.ts create mode 100644 tests/fixtures/tree-gc-harness.ts diff --git a/packages/server/src/tree/gc-member.ts b/packages/server/src/tree/gc-member.ts new file mode 100644 index 00000000..d21c99af --- /dev/null +++ b/packages/server/src/tree/gc-member.ts @@ -0,0 +1,270 @@ +/** + * Whether a node key is reachable from the root a GC tick read: the + * per-candidate proof behind every tree GC deletion. + * + * For a node key `x` and the tick's root `ρ` at level `d`: + * + * 1. no root: not a member; `x` is the root's key: a member; + * 2. `d ≤ 1`: a member iff `x` is one of the root's child refs, decided + * from the key alone (every non-root node of such a tree is a child of + * the root); + * 3. `d ≥ 2`: GET `x`. Absent: already gone. A body that fails its strict + * decode is read once more: still failing, it is corrupt; decoding the + * second time, it is deferred to a later tick. An authenticated node + * at level `λ ≥ d` is not a member. Otherwise it is a member iff the + * level-`λ + 1` node on its first `_id`'s path from the root has an + * entry naming both its attempt and its sha256. Each path node is + * validated against its parent entry and cached for the tick; one + * that is missing after a re-GET, or fails to decode, makes the answer + * "path unreadable", which ends the tick's deletions. + * + * A node the current root does not reach is never reachable again, + * except as a fresh node of an attempt that can still publish: a root + * reuses only refs reachable from the head its attempt captured, and + * fresh nodes carry a new identity. The tick excludes that case by + * closure (a later fold moved the floor past the attempt's) or by the + * sweep's floor gate. + */ +import { compareDocIds } from "../snapshot-doc-id.ts"; +import type { Storage } from "@baerly/protocol"; +import { parseTreeNodeKey, treeNodeKeyPrefix, type TreeNodeKeyParts } from "./key.ts"; +import type { TreeConfig } from "./layout.ts"; +import { type DecodedTreeNode, decodeNode, type TreeChildEntry } from "./node-codec.ts"; + +/** What a membership check found. */ +export type TreeGcMembership = + /** The root reaches the node: never delete it. */ + | "member" + /** The root does not reach the node. */ + | "non-member" + /** The node is already absent. */ + | "gone" + /** The node's body failed its strict decode twice. */ + | "corrupt" + /** The node's body failed once and decoded on the re-read: left for later. */ + | "deferred" + /** A node on the path from the root is missing or undecodable: proves nothing. */ + | "path-unreadable"; + +/** The root a GC tick read, and how to fetch what a check needs. */ +export interface TreeGcRootView { + readonly prefix: string; + /** The strictly decoded root of the head the tick read, or `null`. */ + readonly root: DecodedTreeNode | null; + /** The root's level; 0 with no root. */ + readonly depth: number; + readonly config: TreeConfig; + /** GET a candidate's body, uncached; `null` when absent. */ + readonly getBody: (key: string) => Promise; + /** + * The node `entry` of `parent` names, strictly decoded against that + * entry and cached for the tick, or `null` when it is missing after a + * re-GET or fails to decode. + */ + readonly pathNode: ( + parent: DecodedTreeNode, + entry: TreeChildEntry, + ) => Promise; +} + +/** Whether `entry` names the node `parts` by both attempt and sha256. */ +export const entryNamesNode = (entry: TreeChildEntry, parts: TreeNodeKeyParts): boolean => + entry.attempt === parts.attempt && entry.sha256 === parts.sha256; + +/** + * The key-only rule, valid only for a root at level 0 or 1: `x` is the + * root, or one of its child refs. + */ +export const keyOnlyMember = ( + x: string, + root: DecodedTreeNode | null, + parts: TreeNodeKeyParts, +): boolean => { + if (root === null) { + return false; + } + if (x === root.key) { + return true; + } + return root.node.kind === "branch" && root.node.children.some((e) => entryNamesNode(e, parts)); +}; + +/** + * The node at `level` on `id`'s path from the view's root: the root + * itself when `level` is its level. `null` when some node on the way has + * no entry whose `[lo, hi]` contains `id`; `"unreadable"` when a path + * node is missing or undecodable. + */ +export const routeTo = async ( + view: TreeGcRootView, + id: string, + level: number, +): Promise => { + let node = view.root; + while (node !== null && node.node.level > level) { + if (node.node.kind !== "branch") { + return null; + } + const entry = node.node.children.find( + (e) => compareDocIds(e.lo, id) <= 0 && compareDocIds(id, e.hi) <= 0, + ); + if (entry === undefined) { + return null; + } + const child = await view.pathNode(node, entry); + if (child === null) { + return "unreadable"; + } + node = child; + } + return node; +}; + +/** A candidate's body, authenticated or not. */ +export type TreeGcCandidateRead = + | { readonly kind: "node"; readonly node: DecodedTreeNode } + | { readonly kind: "gone" | "corrupt" | "deferred" }; + +/** + * GET and strictly decode candidate `x` as any node of the collection, + * root or not. A body that fails is read once more when + * `retriesCorrupt`; still failing, the candidate is corrupt. + */ +export const readCandidate = async ( + x: string, + view: TreeGcRootView, + retriesCorrupt: boolean, +): Promise => { + const decode = async (body: Uint8Array): Promise => { + try { + return await decodeNode(x, body, { prefix: view.prefix, root: "either" }, view.config); + } catch { + return null; + } + }; + const body = await view.getBody(x); + if (body === null) { + return { kind: "gone" }; + } + const node = await decode(body); + if (node !== null) { + return { kind: "node", node }; + } + if (!retriesCorrupt) { + return { kind: "corrupt" }; + } + const again = await view.getBody(x); + if (again === null) { + return { kind: "gone" }; + } + return (await decode(again)) === null ? { kind: "corrupt" } : { kind: "deferred" }; +}; + +/** How a check routes an authenticated candidate; production uses {@link TREE_GC_ROUTING}. */ +export interface TreeGcRouting { + /** The level of the node whose entries must name a candidate at `level`. */ + readonly parentLevel: (level: number) => number; + /** Whether `entry` names the candidate `parts`. */ + readonly names: (entry: TreeChildEntry, parts: TreeNodeKeyParts) => boolean; +} + +/** The routing every production check uses: the parent one level up, matched by attempt and sha256. */ +export const TREE_GC_ROUTING: TreeGcRouting = Object.freeze({ + parentLevel: (level: number) => level + 1, + names: entryNamesNode, +}); + +/** + * Whether node key `x` is reachable from the view's root; see the module + * comment. `routing` and `retriesCorrupt` are what tests vary. + */ +export const treeGcMembershipVia = async ( + x: string, + view: TreeGcRootView, + routing: TreeGcRouting, + retriesCorrupt: boolean, +): Promise => { + const parts = parseTreeNodeKey(view.prefix, x); + if (parts === null || view.root === null) { + return "non-member"; + } + if (x === view.root.key) { + return "member"; + } + if (view.depth <= 1) { + return keyOnlyMember(x, view.root, parts) ? "member" : "non-member"; + } + const read = await readCandidate(x, view, retriesCorrupt); + if (read.kind !== "node") { + return read.kind; + } + const level = read.node.node.level; + if (level >= view.depth) { + return "non-member"; + } + const parent = await routeTo(view, read.node.summary.lo, routing.parentLevel(level)); + if (parent === "unreadable") { + return "path-unreadable"; + } + if (parent === null || parent.node.kind !== "branch") { + return "non-member"; + } + return parent.node.children.some((entry) => routing.names(entry, parts)) + ? "member" + : "non-member"; +}; + +/** The production membership check. */ +export const treeGcMembership = (x: string, view: TreeGcRootView): Promise => + treeGcMembershipVia(x, view, TREE_GC_ROUTING, view.config.steps.gcRetriesCorrupt?.() ?? true); + +/** + * The view a tick checks candidates against: `root` as read, candidate + * GETs straight from `storage`, and path nodes read once per tick, each + * re-read once when missing and strictly decoded against its parent + * entry. + */ +export const createTreeGcRootView = ( + storage: Storage, + prefix: string, + root: DecodedTreeNode | null, + config: TreeConfig, + signal?: AbortSignal, +): TreeGcRootView => { + const opts = signal === undefined ? undefined : { signal }; + const nodePrefix = treeNodeKeyPrefix(prefix); + const cache = new Map(); + const getBody = async (key: string): Promise => { + const got = await storage.get(key, opts); + return got?.body ?? null; + }; + return { + prefix, + root, + depth: root?.node.level ?? 0, + config, + getBody, + pathNode: async (parent, entry) => { + const key = `${nodePrefix}${entry.attempt}/${entry.sha256}`; + if (cache.has(key)) { + return cache.get(key)!; + } + const body = (await getBody(key)) ?? (await getBody(key)); + let node: DecodedTreeNode | null = null; + if (body !== null) { + try { + node = await decodeNode( + key, + body, + { prefix, root: false, level: parent.node.level - 1, entry }, + config, + ); + } catch { + node = null; + } + } + cache.set(key, node); + return node; + }, + }; +}; diff --git a/packages/server/src/tree/gc.test.ts b/packages/server/src/tree/gc.test.ts new file mode 100644 index 00000000..02eb10b4 --- /dev/null +++ b/packages/server/src/tree/gc.test.ts @@ -0,0 +1,1020 @@ +/** + * Tree GC (`./gc.ts`): the record path (losers at once, winners after + * the server-clock delay), the leak sweep, the membership check every + * DELETE rests on, the state's binding and malformed-state rules, the + * probe clock, the per-tick budget and crashes inside a tick. + * + * Buckets come from `tests/fixtures/tree-gc-harness.ts`: real folds at + * the small-scope layout, hand-moved local and server clocks, folds + * paused before their head CAS, and the physical oracle judging the + * current tree. `MarginWatch` flags a deletion of a node the root + * reaches, or one sooner than the superseded delay after the node + * became unreachable. The `mutation` block requires each GC mutant in + * `tests/fixtures/tree-mutants.ts` to turn its checks red. + */ +import { describe, expect, test } from "vitest"; +import { BaerlyError, encodeJsonBytes, RequestLedger, type Storage } from "@baerly/protocol"; +import { ledgeredStorage } from "../../../../tests/fixtures/ledgered-storage.ts"; +import { + freshGcHead, + GC_HEAD, + GC_NODES, + GC_PREFIX, + GC_RECORDS, + GC_SEED, + GC_STATE, + gcAttemptOf, + GcBucket, + type GcChange, + gcConfig, + MarginWatch, +} from "../../../../tests/fixtures/tree-gc-harness.ts"; +import { + GC_CORRUPT_NO_RETRY, + GC_DELETES_CORRUPT_CANDIDATE, + GC_DELETES_UNPARSEABLE_KEY, + GC_IGNORES_DUE_AT, + GC_IGNORES_DUPLICATE_IDENTITY, + GC_IGNORES_GENERATION, + GC_IGNORES_LIVE_ROOT, + GC_KEY_ONLY_MEMBERSHIP_AT_DEPTH_2, + GC_LOCAL_CLOCK, + GC_LOSER_AS_WINNER, + GC_MEMBER_ATTEMPT_ONLY, + GC_MEMBER_WRONG_LEVEL, + GC_MUTANTS, + GC_PATH_MISS_AS_NONMEMBER, + GC_PROCESSES_OPEN_FLOOR, + GC_SKIPS_MEMBERSHIP_CHECK, + GC_WINNER_AS_LOSER, + GC_WINNER_BY_KEY_ORDER, + PUBLISH_REUSES_ATTEMPT, + RECORD_NAMES_REUSED_NODE, + SWEEP_AGE_FROM_NOTE, + SWEEP_FLOOR_BEFORE_LIST, + SWEEP_MEMBER_AGAINST_MARK_ROOT, + SWEEP_NO_FLOOR_GATE, + type TreeMutant, +} from "../../../../tests/fixtures/tree-mutants.ts"; +import { createObservabilityContext, runWithContext } from "../observability/context.ts"; +import { + TREE_GC_SUPERSEDED_DELAY_MINUTES, + TREE_GC_SWEEP_AGE_MINUTES, + TREE_GC_TICK_CANDIDATES, + TREE_GC_TICK_MAX_CANDIDATES, + TREE_GC_TICK_RESERVED_CALLS, +} from "./constants.ts"; +import { runTreeGcTick, treeGcCandidateCharge, treeGcCandidates } from "./gc.ts"; +import { createTreeGcRootView, type TreeGcMembership, treeGcMembership } from "./gc-member.ts"; +import { emptyTreeGcState, encodeTreeGcState } from "./gc-state.ts"; +import { readTreeHead, readTreeRoot } from "./head.ts"; +import { openTreeView } from "./read.ts"; + +const MIXED: readonly GcChange[] = [ + ["k03", 103], + ["k10a", 7], + ["k16", null], +]; + +const DELAY = TREE_GC_SUPERSEDED_DELAY_MINUTES; +const AGE = TREE_GC_SWEEP_AGE_MINUTES; +const LONG = 60_000; + +/** Run `check`, turning a throw into a failure message. */ +const guarded = async (check: () => Promise): Promise => { + try { + return await check(); + } catch (error) { + return `threw ${String(error)}`; + } +}; + +const joined = (problems: readonly string[]): string | undefined => + problems.length === 0 ? undefined : problems.join("; "); + +/** Resolve, wait out the delay, and tick until the records are drained. */ +const reclaim = async (bucket: GcBucket, config = gcConfig()): Promise => { + const deleted: string[] = []; + for (const minutes of [0, DELAY + 1, 1, 1]) { + bucket.advance(minutes); + const { result } = await bucket.tick(config); + deleted.push(...result.deleted); + } + return deleted; +}; + +/** What is wrong with the bucket once GC should have reclaimed everything recorded. */ +const reclaimedProblems = async (bucket: GcBucket): Promise => { + const problems = [...(await bucket.violations())]; + const unreachable = await bucket.unreachable(); + if (unreachable.length > 0) { + problems.push(`unreachable nodes remain: ${unreachable.join(", ")}`); + } + const records = await bucket.keys(GC_RECORDS); + if (records.length > 0) { + problems.push(`records remain: ${records.join(", ")}`); + } + return joined(problems); +}; + +/** The nodes the last fold of `bucket` superseded, given the reachable set before it. */ +const supersededSince = async ( + bucket: GcBucket, + before: ReadonlySet, +): Promise => { + const live = await bucket.reachable(); + return [...before].filter((key) => !live.has(key)); +}; + +// --------------------------------------------------------------------- +// Checks shared with the mutation block. Each returns the first +// failure, or `undefined`. +// --------------------------------------------------------------------- + +/** A fold's superseded nodes and its record are all reclaimed, and nothing live is lost. */ +const reclaimFailure = (...mutants: (TreeMutant | undefined)[]) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + await bucket.fold(MIXED, { config: gcConfig(...mutants) }); + await reclaim(bucket, gcConfig(...mutants)); + return reclaimedProblems(bucket); + }); + +/** + * Every node of the current depth-3 root is a member, every node the + * last fold superseded is not, and a deep node whose path from the root + * cannot be read is path-unreadable. + */ +const membershipFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const before = await bucket.reachable(); + await bucket.fold(MIXED); + const live = await bucket.reachable(); + const superseded = [...before].filter((key) => !live.has(key)); + const config = gcConfig(mutant); + const head = (await readTreeHead(bucket.storage, GC_PREFIX))!; + const root = (await readTreeRoot(bucket.storage, head, config))!; + const check = config.steps.gcIsMember ?? treeGcMembership; + const ask = (x: string, storage: Storage = bucket.storage): Promise => + check(x, createTreeGcRootView(storage, GC_PREFIX, root, config)); + const problems: string[] = []; + for (const key of live) { + const found = await ask(key); + if (found !== "member") { + problems.push(`live ${key}: ${found}`); + } + } + for (const key of superseded) { + const found = await ask(key); + if (found !== "non-member") { + problems.push(`superseded ${key}: ${found}`); + } + } + // Below the root's children, every path runs through one of them. + const hidden = new Set( + root.node.kind === "branch" + ? root.node.children.map((e) => `${GC_NODES}${e.attempt}/${e.sha256}`) + : [], + ); + const blind: Storage = { + ...bucket.storage, + get: (key, opts) => (hidden.has(key) ? Promise.resolve(null) : bucket.storage.get(key, opts)), + }; + const deep = [...live].filter((key) => !hidden.has(key) && key !== root.key); + if (root.node.level < 3 || deep.length === 0) { + problems.push("setup: no node below the root's children"); + } + for (const key of deep) { + const found = await ask(key, blind); + if (found !== "path-unreadable") { + problems.push(`live ${key} under an unreadable path: ${found}`); + } + } + return joined(problems); + }); + +/** + * Two attempts race on one floor and the one whose id sorts last wins: + * the loser's fresh nodes and the winner's superseded nodes are all + * reclaimed, and nothing live is lost. + */ +const raceFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const loser = await bucket.prepare([["k04", 44]]); + const winner = await bucket.prepare([["k15", 55]]); + const won = await bucket.publish(winner, { attempt: "f".repeat(32) }); + const lost = await bucket.publish(loser, { attempt: "1".repeat(32) }); + if (won.kind !== "published" || lost.kind !== "cas-lost") { + return `setup: ${won.kind}, ${lost.kind}`; + } + await reclaim(bucket, gcConfig(mutant)); + return reclaimedProblems(bucket); + }); + +/** + * A read that opened the root before a fold, and reads after GC has + * resolved the fold and ticked inside the delay, meets no missing node. + */ +const readDuringGcFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + let misses = 0; + const tapped: Storage = { + ...bucket.storage, + get: async (key, opts) => { + const got = await bucket.storage.get(key, opts); + if (got === null && key.startsWith(GC_NODES)) { + misses += 1; + } + return got; + }, + }; + const view = await openTreeView({ storage: tapped, prefix: GC_PREFIX, config: gcConfig() }); + const rows = bucket.rows.size; + await bucket.fold(MIXED); + for (const minutes of [0, 2, DELAY - 3]) { + bucket.advance(minutes); + await bucket.tick(gcConfig(mutant)); + } + const read = await view.scan(); + if (misses > 0) { + return `the read met ${misses} missing nodes inside the delay`; + } + return read.length === rows ? undefined : `read ${read.length} rows of ${rows}`; + }); + +/** The local clock runs far ahead of the server's: superseded nodes still wait out the delay on the server clock. */ +const skewFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const watch = new MarginWatch(bucket); + await watch.observe(); + await bucket.fold(MIXED); + await watch.observe(); + for (let i = 0; i < 6; i++) { + // Twenty local minutes, two on the server. + bucket.advance(20, 2); + const { result } = await bucket.tick(gcConfig(mutant)); + await watch.afterTick(result.deleted); + } + return joined(watch.problems); + }); + +/** + * An attempt that lost reuses its identity for a publication still in + * flight: GC must not drain the first publication's nodes, which the + * second one adopted. + */ +const reuseFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const reused = "a".repeat(32); + const loser = await bucket.prepare([["k03", 5]]); + const winner = await bucket.prepare([["k19", 119]]); + await bucket.publish(winner, { attempt: "b".repeat(32) }); + const lost = await bucket.publish(loser, { attempt: reused }); + if (lost.kind !== "cas-lost") { + return `setup: ${lost.kind}`; + } + const retry = await bucket.startFold([["k03", 5]], { attempt: reused }); + await bucket.tick(gcConfig(mutant)); + const outcome = await retry.release(); + if (outcome.kind !== "published") { + return `the retry was ${outcome.kind}`; + } + return joined(await bucket.violations()); + }); + +/** + * A lost attempt the publisher retries shows up in GC's + * duplicate-identity counter only if the retry reused its identity. + */ +const reuseCounterFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const options = mutant === undefined ? {} : { config: gcConfig(mutant) }; + const loser = await bucket.prepare([["k03", 5]]); + await bucket.fold([["k19", 119]]); + await bucket.publish(loser, options); + await bucket.fold([["k03", 5]], options); + const { counters } = await bucket.tick(); + const duplicates = counters.get("db.tree_gc.duplicate_attempt_total") ?? 0; + return duplicates === 0 ? undefined : `${duplicates} duplicate identities`; + }); + +/** An attempt in flight at the head's floor is neither resolved nor stuck, and its nodes survive. */ +const openFloorFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const flight = await bucket.startFold([["k05", 55]]); + const problems: string[] = []; + for (let i = 0; i < 3; i++) { + bucket.advance(1); + await bucket.tick(gcConfig(mutant)); + const state = await bucket.state(); + const stuck = state?.stuck ?? null; + if (stuck !== null) { + problems.push(`floor ${stuck.floor} marked stuck`); + } + } + await flight.release(); + problems.push(...(await bucket.violations())); + return joined(problems); + }); + +/** + * After the head is re-seeded with a new generation and a lower floor, + * the new history's superseded nodes are reclaimed: the old state's + * progress never applies to it. + */ +const regenerationFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded("0a"); + await bucket.fold(MIXED); + await reclaim(bucket, gcConfig(mutant)); + // A restore-like re-seed: a fresh head of a new history. + await bucket.memory.put(GC_HEAD, encodeJsonBytes(freshGcHead("0b"))); + bucket.rows.clear(); + await bucket.fold(GC_SEED); + const before = await bucket.reachable(); + await bucket.fold(MIXED); + const superseded = await supersededSince(bucket, before); + bucket.advance(1); + await bucket.tick(gcConfig(mutant)); + await reclaim(bucket, gcConfig(mutant)); + const left = new Set(await bucket.keys(GC_NODES)); + const problems = [...(await bucket.violations())]; + const kept = superseded.filter((key) => left.has(key)); + if (kept.length > 0) { + problems.push(`the new history's superseded nodes remain: ${kept.join(", ")}`); + } + return joined(problems); + }); + +/** + * The sweep reclaims nodes no record names (a lost attempt whose record + * is gone), leaves keys that do not parse, counting them, and never + * deletes a node the root reaches or one sooner than the delay after it + * became unreachable. + */ +const sweepFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const loser = await bucket.prepare([["k07", 77]]); + await bucket.fold([["k12", 12]]); + const lost = await bucket.publish(loser); + if (lost.kind !== "cas-lost") { + return `setup: ${lost.kind}`; + } + await bucket.memory.delete(lost.record); + const unreachable = await bucket.unreachable(); + const orphans = unreachable.filter((key) => key.startsWith(`${GC_NODES}${lost.attempt}/`)); + const sha = "0".repeat(64); + const strays = [ + `${GC_NODES}${lost.attempt}/${sha}.json`, + `${GC_NODES}${"A".repeat(32)}/${sha}`, + ]; + for (const key of strays) { + await bucket.memory.put(key, new TextEncoder().encode("{}")); + } + const watch = new MarginWatch(bucket); + await watch.observe(); + let unknown = 0; + for (let minute = 0; minute < 3 * AGE; minute++) { + if (minute % 20 === 10) { + await bucket.fold([["k00", minute]]); + await watch.observe(); + } + bucket.advance(1); + const { result, counters } = await bucket.tick(gcConfig(mutant)); + unknown += counters.get("db.tree_gc.unknown_key_total") ?? 0; + await watch.afterTick(result.deleted); + } + const left = new Set(await bucket.keys(GC_NODES)); + const problems = [...watch.problems]; + if (orphans.length === 0) { + problems.push("setup: no orphan nodes"); + } + problems.push( + ...orphans.filter((key) => left.has(key)).map((key) => `orphan ${key} not swept`), + ...strays.filter((key) => !left.has(key)).map((key) => `stray ${key} deleted`), + ); + if (unknown === 0) { + problems.push("no unknown key counted"); + } + return joined(problems); + }); + +/** + * An attempt stays in flight past the sweep age, then lands; an + * unrelated fold follows. Its nodes are never deleted while it can + * still publish, nor once its root reaches them. + */ +const sweepInFlightFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const watch = new MarginWatch(bucket); + await watch.observe(); + const flight = await bucket.startFold([["k08", 88]], { attempt: "0".repeat(32) }); + await bucket.tickFor(AGE + 10, gcConfig(mutant), watch); + await flight.release(); + const problems = [...(await bucket.violations())]; + await watch.observe(); + await bucket.fold([["k12", 12]]); + await watch.observe(); + await bucket.tickFor(AGE + 20, gcConfig(mutant), watch); + problems.push(...watch.problems); + return joined(problems); + }); + +/** + * An attempt's node is noted while the attempt is in flight, the + * attempt lands, and a later fold supersedes the node: the node still + * waits out the delay after that fold. + */ +const supersededAfterNoteFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const watch = new MarginWatch(bucket); + await watch.observe(); + const flight = await bucket.startFold([["k08", 88]], { attempt: "0".repeat(32) }); + await bucket.tickFor(30, gcConfig(mutant), watch); + await flight.release(); + await watch.observe(); + await bucket.tickFor(28, gcConfig(mutant), watch); + await bucket.fold([["k08", 89]]); + await watch.observe(); + await bucket.tickFor(AGE + 30, gcConfig(mutant), watch); + return joined(watch.problems); + }); + +/** + * A fold lands and another attempt starts around the probe tick's head + * GET and sweep LIST: the attempt's nodes are never deleted while it is + * in flight. + */ +const floorBeforeListFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + let flight: Awaited> | undefined; + bucket.onList.set(GC_NODES, async () => { + await bucket.fold([["k19", 1]]); + flight = await bucket.startFold([["k02", 2]], { attempt: "0".repeat(32) }); + }); + const watch = new MarginWatch(bucket); + await watch.observe(); + await bucket.tickFor(AGE + 10, gcConfig(mutant), watch); + if (flight === undefined) { + return "setup: the LIST hook never ran"; + } + await flight.release(); + return joined([...watch.problems, ...(await bucket.violations())]); + }); + +/** A superseded node below the root, at depth 3, picked from the last fold of `bucket`. */ +const supersededBelowRoot = async (bucket: GcBucket): Promise => { + const head = await bucket.head(); + const before = await bucket.reachable(); + await bucket.fold(MIXED); + const superseded = await supersededSince(bucket, before); + return superseded.find((key) => key !== head.root)!; +}; + +/** A superseded node corrupt at rest at depth 3 is counted and left in place; the rest is reclaimed. */ +const corruptFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const target = await supersededBelowRoot(bucket); + await bucket.memory.put(target, new TextEncoder().encode("not a node")); + let corrupt = 0; + for (const minutes of [0, DELAY + 1, 1, 1]) { + bucket.advance(minutes); + const { counters } = await bucket.tick(gcConfig(mutant)); + corrupt += counters.get("db.tree_gc.corrupt_node_total") ?? 0; + } + const problems = [...(await bucket.violations())]; + const unreachable = await bucket.unreachable(); + if (!unreachable.includes(target)) { + problems.push(`the corrupt node ${target} was deleted`); + } + if (unreachable.length !== 1) { + problems.push(`unreachable: ${unreachable.join(", ")}`); + } + if (corrupt === 0) { + problems.push("the corrupt node was not counted"); + } + return joined(problems); + }); + +/** A one-time misread of a superseded node is read again: no corruption is counted or warned. */ +const misreadFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const target = await supersededBelowRoot(bucket); + let misread = false; + bucket.getOverride = (key) => { + if (key === target && !misread) { + misread = true; + return new TextEncoder().encode("torn read"); + } + return undefined; + }; + const problems: string[] = []; + for (const minutes of [0, DELAY + 1, 1, 1]) { + bucket.advance(minutes); + const { counters, warnings } = await bucket.tick(gcConfig(mutant)); + if ((counters.get("db.tree_gc.corrupt_node_total") ?? 0) > 0) { + problems.push("a misread was counted as corruption"); + } + if (warnings.includes("tree_gc_corrupt_node")) { + problems.push("a misread was warned as corruption"); + } + } + if (!misread) { + problems.push("setup: the target was never read"); + } + return joined(problems); + }); + +/** Overwrite the head's installer, keeping everything else (test-only damage). */ +const overwriteInstaller = async (bucket: GcBucket, attempt: string): Promise => { + const head = await bucket.head(); + await bucket.memory.put( + GC_HEAD, + encodeJsonBytes({ ...head.json, proto_tree: { ...head.json.proto_tree!, attempt } }), + ); +}; + +/** The fresh node keys of attempt `attempt` in `bucket`. */ +const freshOf = async (bucket: GcBucket, attempt: string): Promise => { + const keys = await bucket.keys(GC_NODES); + return keys.filter((key) => key.startsWith(`${GC_NODES}${attempt}/`)); +}; + +// --------------------------------------------------------------------- +// Record path +// --------------------------------------------------------------------- + +describe("record path", () => { + test("a fold's superseded nodes and its record are reclaimed after the delay, and nothing live is lost", async () => { + await expect(reclaimFailure()).resolves.toBeUndefined(); + }); + + test("superseded nodes wait out the delay on the server clock", async () => { + const bucket = await GcBucket.seeded(); + await bucket.fold(MIXED); + const unreachable = await bucket.unreachable(); + await bucket.tick(); + bucket.advance(DELAY - 1); + const early = await bucket.tick(); + expect(early.result.deleted.filter((key) => key.startsWith(GC_NODES))).toEqual([]); + bucket.advance(2); + const due = await bucket.tick(); + expect(due.result.deleted.filter((key) => key.startsWith(GC_NODES)).toSorted()).toEqual( + unreachable.toSorted(), + ); + }); + + test("a loser's fresh nodes are deleted in the tick that resolves its floor", async () => { + const bucket = await GcBucket.seeded(); + const loser = await bucket.prepare([["k04", 44]]); + await bucket.fold([["k15", 55]]); + const lost = await bucket.publish(loser); + expect(lost.kind).toBe("cas-lost"); + const fresh = await freshOf(bucket, lost.attempt); + expect(fresh.length).toBeGreaterThan(0); + const { result } = await bucket.tick(); + expect(result.deleted).toEqual(expect.arrayContaining([...fresh, lost.record])); + await expect(bucket.violations()).resolves.toEqual([]); + }); + + test("racing attempts: the loser's fresh and the winner's superseded nodes are all reclaimed", async () => { + await expect(raceFailure()).resolves.toBeUndefined(); + }); + + test("a loser's corrupt node at depth 3 is deleted on its key alone, counted and warned", async () => { + const bucket = await GcBucket.seeded(); + const loser = await bucket.prepare([["k04", 44]]); + await bucket.fold([["k15", 55]]); + const lost = await bucket.publish(loser); + const [target] = await freshOf(bucket, lost.attempt); + await bucket.memory.put(target!, new TextEncoder().encode("not a node")); + const { result, counters, warnings } = await bucket.tick(); + expect(result.deleted).toContain(target); + expect(counters.get("db.tree_gc.corrupt_node_total")).toBe(1); + expect(warnings).toContain("tree_gc_corrupt_node"); + }); + + test("a superseded node corrupt at rest is counted and left in place", async () => { + await expect(corruptFailure()).resolves.toBeUndefined(); + }); + + test("a one-time misread is read again, not counted as corruption", async () => { + await expect(misreadFailure()).resolves.toBeUndefined(); + }); + + test("a read through the replaced root meets no missing node inside the delay", async () => { + await expect(readDuringGcFailure()).resolves.toBeUndefined(); + }); + + test("a local clock far ahead of the server's does not shorten the delay", async () => { + await expect(skewFailure()).resolves.toBeUndefined(); + }); + + test("a probe whose write reports no server time stamps nothing, counts and warns; losers still drain", async () => { + const bucket = await GcBucket.seeded(); + const loser = await bucket.prepare([["k04", 44]]); + await bucket.fold([["k15", 55]]); + const lost = await bucket.publish(loser); + bucket.serverTime = false; + const { result, counters, warnings } = await bucket.tick(); + expect(counters.get("db.tree_gc.no_server_time_total")).toBe(1); + expect(warnings).toContain("tree_gc_no_server_time"); + expect(result.deleted).toEqual(expect.arrayContaining(await freshOf(bucket, lost.attempt))); + bucket.advance(3 * DELAY); + const later = await bucket.tick(); + expect(later.result.deleted.filter((key) => key.startsWith(GC_NODES))).toEqual([]); + const state = await bucket.state(); + expect(state?.work.every((entry) => entry.due_at === null)).toBe(true); + }); + + test("a path node GC cannot read stops the tick's deletions, counted; the state is still written", async () => { + const bucket = await GcBucket.seeded(); + await bucket.fold(MIXED); + await bucket.tick(); + bucket.advance(DELAY + 1); + const root = (await readTreeRoot(bucket.memory, await bucket.head()))!; + const children = new Set( + root.node.kind === "branch" + ? root.node.children.map((e) => `${GC_NODES}${e.attempt}/${e.sha256}`) + : [], + ); + bucket.getOverride = (key) => (children.has(key) ? null : undefined); + const before = await bucket.state(); + const { counters } = await bucket.tick(); + expect(counters.get("db.tree_gc.path_unreadable_total")).toBe(1); + bucket.getOverride = undefined; + await expect(bucket.unreachable()).resolves.not.toEqual([]); + const after = await bucket.state(); + expect(after!.ticks).toBeGreaterThan(before!.ticks); + await reclaim(bucket); + await expect(reclaimedProblems(bucket)).resolves.toBeUndefined(); + }); + + test("a floor with no evidence of its winner is stuck, then retired leak-only after the sweep age", async () => { + const bucket = await GcBucket.seeded(); + await bucket.fold(MIXED); + await bucket.fold([["k01", 1]]); + const [, mixedRecord, lastRecord] = await bucket.keys(GC_RECORDS); + // Hide the evidence of the mixed fold's win: the next record, and the installer. + await bucket.memory.delete(lastRecord!); + await overwriteInstaller(bucket, "e".repeat(32)); + await bucket.tick(); + const stuck = await bucket.state(); + expect(stuck?.stuck).toMatchObject({ floor: 20 }); + await bucket.tickFor(AGE + 2); + await expect(bucket.keys(GC_RECORDS)).resolves.not.toContain(mixedRecord); + const state = await bucket.state(); + expect(state?.stuck).toBeNull(); + expect(state?.resolved_through).toBeGreaterThanOrEqual(20); + await expect(bucket.violations()).resolves.toEqual([]); + }); +}); + +// --------------------------------------------------------------------- +// Membership +// --------------------------------------------------------------------- + +describe("membership", () => { + test("live nodes are members, superseded ones are not, and an unreadable path proves nothing", async () => { + await expect(membershipFailure()).resolves.toBeUndefined(); + }); + + test("at depth 0 and 1 membership reads no body", async () => { + const bucket = await GcBucket.open(); + await bucket.fold([ + ["a", 1], + ["b", 2], + ]); + const config = gcConfig(); + const head = (await readTreeHead(bucket.storage, GC_PREFIX))!; + const root = (await readTreeRoot(bucket.storage, head, config))!; + expect(root.node.level).toBeLessThanOrEqual(1); + let gets = 0; + const counting: Storage = { + ...bucket.storage, + get: (key, opts) => { + gets += 1; + return bucket.storage.get(key, opts); + }, + }; + const view = createTreeGcRootView(counting, GC_PREFIX, root, config); + await expect(treeGcMembership(root.key, view)).resolves.toBe("member"); + await expect( + treeGcMembership(`${GC_NODES}${gcAttemptOf(9)}/${"0".repeat(64)}`, view), + ).resolves.toBe("non-member"); + expect(gets).toBe(0); + }); +}); + +// --------------------------------------------------------------------- +// Attempt identity and closure +// --------------------------------------------------------------------- + +describe("attempt identity and closure", () => { + test("a reused identity is never a deletion source, from either list", async () => { + await expect(reuseFailure()).resolves.toBeUndefined(); + }); + + test("an identity in two records is counted, warned and its records retired leak-only", async () => { + const bucket = await GcBucket.seeded(); + const reused = "a".repeat(32); + const loser = await bucket.prepare([["k03", 5]]); + await bucket.fold([["k19", 119]]); + await bucket.publish(loser, { attempt: reused }); + await bucket.fold([["k03", 5]], { attempt: reused }); + const { result, counters, warnings } = await bucket.tick(); + expect(counters.get("db.tree_gc.duplicate_attempt_total")).toBe(1); + expect(warnings).toContain("tree_gc_duplicate_attempt"); + const retired = result.deleted.filter((key) => key.startsWith(GC_RECORDS)); + expect(retired.filter((key) => key.includes(`/${reused}/`))).toHaveLength(2); + expect(result.deleted.filter((key) => key.includes(`/n/${reused}/`))).toEqual([]); + await expect(bucket.violations()).resolves.toEqual([]); + }); + + test("publications that mint fresh identities never trip the duplicate-identity counter", async () => { + await expect(reuseCounterFailure()).resolves.toBeUndefined(); + }); + + test("an attempt in flight at the head's floor is left alone", async () => { + await expect(openFloorFailure()).resolves.toBeUndefined(); + }); + + test("a new head history resets the state, and its superseded nodes are reclaimed", async () => { + await expect(regenerationFailure()).resolves.toBeUndefined(); + }); + + test("a head writer that keeps proto_tree keeps GC running; one that drops the installer stops it loudly", async () => { + const kept = await GcBucket.seeded(); + await kept.fold(MIXED); + await kept.refreshTailHint(); + await expect(kept.tick()).resolves.toMatchObject({ result: { outcome: "collected" } }); + + const dropped = await GcBucket.seeded(); + await dropped.fold(MIXED); + const nodes = await dropped.keys(GC_NODES); + const head = await dropped.head(); + const { attempt: _installer, ...withoutInstaller } = head.json.proto_tree!; + await dropped.memory.put( + GC_HEAD, + encodeJsonBytes({ ...head.json, proto_tree: withoutInstaller }), + ); + await expect(dropped.tick()).rejects.toMatchObject({ code: "InvalidResponse" }); + await expect(dropped.keys(GC_NODES)).resolves.toEqual(nodes); + }); +}); + +// --------------------------------------------------------------------- +// Leak sweep +// --------------------------------------------------------------------- + +describe("leak sweep", () => { + test( + "orphan nodes are swept, stray keys left and counted, and no live node is lost", + async () => { + await expect(sweepFailure()).resolves.toBeUndefined(); + }, + LONG, + ); + + test( + "an attempt in flight past the sweep age keeps its nodes, before and after it lands", + async () => { + await expect(sweepInFlightFailure()).resolves.toBeUndefined(); + }, + LONG, + ); + + test( + "a node noted while its attempt was in flight waits out the delay after a later fold supersedes it", + async () => { + await expect(supersededAfterNoteFailure()).resolves.toBeUndefined(); + }, + LONG, + ); + + test( + "a fold that lands around a probe's LIST and head GET cannot expose an attempt in flight", + async () => { + await expect(floorBeforeListFailure()).resolves.toBeUndefined(); + }, + LONG, + ); +}); + +// --------------------------------------------------------------------- +// State, clock and budget +// --------------------------------------------------------------------- + +describe("state and clock", () => { + test("a tick with nothing to do and no probe due writes nothing", async () => { + const bucket = await GcBucket.seeded(); + await bucket.tick(); + const before = await bucket.memory.get(GC_STATE); + bucket.advance(0.5); + await bucket.tick(); + const after = await bucket.memory.get(GC_STATE); + expect(after?.etag).toBe(before?.etag); + }); + + test("probes are paced by local time against the local time of the last probe", async () => { + const bucket = await GcBucket.seeded(); + await expect(bucket.tick()).resolves.toMatchObject({ result: { probed: true } }); + bucket.advance(0.5, 30); + await expect(bucket.tick()).resolves.toMatchObject({ result: { probed: false } }); + bucket.advance(0.6, 0); + await expect(bucket.tick()).resolves.toMatchObject({ result: { probed: true } }); + // A local clock that went backwards probes at once. + bucket.advance(-10, 0); + await expect(bucket.tick()).resolves.toMatchObject({ result: { probed: true } }); + }); + + test("a malformed state is replaced by the empty state, and that is the tick's only write", async () => { + const bucket = await GcBucket.seeded(); + await bucket.fold(MIXED); + const nodes = await bucket.keys(GC_NODES); + await bucket.memory.put(GC_STATE, encodeJsonBytes({ format: "baerly-tree-gc-state-proto" })); + await expect(bucket.tick()).resolves.toMatchObject({ + result: { outcome: "reset", deleted: [] }, + }); + await expect(bucket.state()).resolves.toEqual(emptyTreeGcState(null, 23)); + await expect(bucket.keys(GC_NODES)).resolves.toEqual(nodes); + }); + + test("a state of a newer schema stops the tick with InvalidResponse and no write", async () => { + const bucket = await GcBucket.seeded(); + await bucket.memory.put( + GC_STATE, + encodeJsonBytes({ format: "baerly-tree-gc-state-proto", schema_version: 2 }), + ); + const before = await bucket.memory.get(GC_STATE); + const error = await bucket.tick().catch((error_: unknown) => error_); + expect(error).toBeInstanceOf(BaerlyError); + expect(error).toMatchObject({ code: "InvalidResponse" }); + expect((error as BaerlyError).message).toContain("paused"); + const after = await bucket.memory.get(GC_STATE); + expect(after?.etag).toBe(before?.etag); + }); + + test("a state bound to a higher floor is replaced", async () => { + const bucket = await GcBucket.seeded(); + await bucket.memory.put( + GC_STATE, + encodeTreeGcState({ ...emptyTreeGcState(null, 99), ticks: 4 }), + ); + await expect(bucket.tick()).resolves.toMatchObject({ result: { outcome: "reset" } }); + await expect(bucket.state()).resolves.toEqual(emptyTreeGcState(null, 20)); + }); + + test("a collection with no head ends the tick with no write", async () => { + const bucket = new GcBucket(); + await expect(bucket.tick()).resolves.toMatchObject({ result: { outcome: "no-head" } }); + await expect(bucket.keys(GC_PREFIX)).resolves.toEqual([]); + }); +}); + +describe("budget", () => { + test("the candidate count follows the ledger: the static floor, the larger ceiling, or what fits", () => { + expect(treeGcCandidateCharge(1)).toBe(3); + expect(treeGcCandidateCharge(2)).toBe(9); + expect(treeGcCandidates(0, Number.POSITIVE_INFINITY)).toBe(TREE_GC_TICK_MAX_CANDIDATES); + expect(treeGcCandidates(2, 9000)).toBe(TREE_GC_TICK_MAX_CANDIDATES); + expect(treeGcCandidates(0, 900)).toBe(TREE_GC_TICK_CANDIDATES); + expect(treeGcCandidates(2, TREE_GC_TICK_RESERVED_CALLS + 9 * 10)).toBe(10); + expect(treeGcCandidates(0, TREE_GC_TICK_RESERVED_CALLS + 2)).toBe(0); + }); + + test("a ledger with no room for one candidate check skips the tick, counted", async () => { + const bucket = await GcBucket.seeded(); + const ledger = new RequestLedger({ internal: 30, external: 30 }); + const storage = ledgeredStorage(bucket.memory, "internal"); + const result = await runWithContext(createObservabilityContext({ ledger }), () => + runTreeGcTick({ storage, prefix: GC_PREFIX, config: gcConfig() }), + ); + expect(result.outcome).toBe("budget"); + }); + + test("a deleting tick's charged calls stay within the static bound for its candidate count", async () => { + const bucket = await GcBucket.seeded(); + await bucket.fold(MIXED); + await bucket.tick(); + bucket.advance(DELAY + 1); + const ledger = new RequestLedger({ internal: 1_000, external: 1_000 }); + const storage = ledgeredStorage(bucket.memory, "internal"); + const result = await runWithContext(createObservabilityContext({ ledger }), () => + runTreeGcTick({ + storage, + prefix: GC_PREFIX, + config: gcConfig(), + now: () => new Date(bucket.local), + }), + ); + expect(result.deleted.length).toBeGreaterThan(0); + const charged = 1_000 - ledger.storageRemaining(); + expect(result.candidates).toBeGreaterThan(0); + expect(charged).toBeLessThanOrEqual( + TREE_GC_TICK_RESERVED_CALLS + result.candidates * treeGcCandidateCharge(3), + ); + }); +}); + +describe("crashes", () => { + test( + "a crash before any storage call of a tick loses nothing live, and later ticks finish the work", + async () => { + for (let k = 1; ; k++) { + const bucket = await GcBucket.seeded(); + await bucket.fold(MIXED); + await bucket.tick(); + bucket.advance(DELAY + 1); + bucket.faults.armAt(k); + let crashed = false; + try { + await bucket.tick(); + bucket.faults.armAt(undefined); + } catch (error) { + if ((error as Error).name !== "AbortError") { + throw error; + } + crashed = true; + } + await expect(bucket.violations(), `crash at call ${k}`).resolves.toEqual([]); + await reclaim(bucket); + await expect(reclaimedProblems(bucket), `crash at call ${k}`).resolves.toBeUndefined(); + if (!crashed) { + break; + } + } + }, + LONG, + ); +}); + +// --------------------------------------------------------------------- +// Mutation +// --------------------------------------------------------------------- + +type Check = (mutant?: TreeMutant) => Promise; + +/** `check` with `record-names-reused-node` alongside: the record nominates a live node. */ +const withReusedNode = + (check: (...mutants: (TreeMutant | undefined)[]) => Promise): Check => + (mutant) => + check(RECORD_NAMES_REUSED_NODE, mutant); + +describe("mutation", () => { + const checks = new Map([ + [GC_IGNORES_LIVE_ROOT, [membershipFailure]], + [GC_DELETES_UNPARSEABLE_KEY, [sweepFailure]], + [GC_DELETES_CORRUPT_CANDIDATE, [corruptFailure]], + [GC_KEY_ONLY_MEMBERSHIP_AT_DEPTH_2, [membershipFailure, sweepFailure]], + [GC_MEMBER_WRONG_LEVEL, [membershipFailure, sweepFailure]], + [GC_MEMBER_ATTEMPT_ONLY, [membershipFailure, reclaimFailure]], + [GC_PATH_MISS_AS_NONMEMBER, [membershipFailure]], + [SWEEP_MEMBER_AGAINST_MARK_ROOT, [sweepInFlightFailure]], + [GC_SKIPS_MEMBERSHIP_CHECK, [membershipFailure, withReusedNode(reclaimFailure)]], + [PUBLISH_REUSES_ATTEMPT, [reuseCounterFailure]], + [GC_IGNORES_DUPLICATE_IDENTITY, [reuseFailure]], + [GC_PROCESSES_OPEN_FLOOR, [openFloorFailure]], + [GC_IGNORES_GENERATION, [regenerationFailure]], + [GC_WINNER_AS_LOSER, [raceFailure]], + [GC_LOSER_AS_WINNER, [raceFailure]], + [GC_WINNER_BY_KEY_ORDER, [raceFailure]], + [GC_IGNORES_DUE_AT, [readDuringGcFailure]], + [GC_LOCAL_CLOCK, [skewFailure]], + [SWEEP_NO_FLOOR_GATE, [sweepInFlightFailure]], + [SWEEP_FLOOR_BEFORE_LIST, [floorBeforeListFailure]], + [SWEEP_AGE_FROM_NOTE, [supersededAfterNoteFailure]], + [GC_CORRUPT_NO_RETRY, [misreadFailure]], + ]); + + test("every GC mutant has checks", () => { + expect([...checks.keys()]).toEqual(GC_MUTANTS); + }); + + test("a record that names a reused node loses nothing while the membership check holds", async () => { + await expect(withReusedNode(reclaimFailure)()).resolves.toBeUndefined(); + }); + + test.each(GC_MUTANTS.map((mutant) => [mutant.name, mutant] as const))( + "%s turns its checks red", + async (_name, mutant) => { + for (const check of checks.get(mutant)!) { + await expect(check(mutant)).resolves.toBeDefined(); + } + }, + 2 * LONG, + ); +}); diff --git a/packages/server/src/tree/gc.ts b/packages/server/src/tree/gc.ts new file mode 100644 index 00000000..9631a089 --- /dev/null +++ b/packages/server/src/tree/gc.ts @@ -0,0 +1,880 @@ +/** + * The tree GC tick: reclaim the tree nodes no current root reaches, + * without ever writing the head. + * + * Every publication attempt writes a fold record before its first node + * (`./record.ts`), keyed by the floor of the head it captured. A + * record's floor is **closed** once the head's `log_seq_start` is above + * it: floors never decrease within one head history, so the head that + * attempt captured never returns and its head CAS can no longer land. + * At most one attempt per floor published; GC names it from storage + * evidence the winning CAS created (the head's `proto_tree.attempt`, or + * the `base.attempt` of a record captured on a later floor), and every + * other attempt recorded at that floor is a loser. + * + * - A loser's fresh nodes are deleted at once: its root was never + * installed, so nothing ever read them. + * - A winner's superseded nodes are deleted + * `TREE_GC_SUPERSEDED_DELAY_MINUTES` after a probe of the storage + * server's clock first stamps them, so reads through the replaced + * root can finish. The delay is a margin, not a proof: a read that + * outlives it meets the reader's missing-node backstop. + * - A slow leak sweep lists the node prefix a page per probe and + * deletes nodes that are unreachable, whose attempt can no longer + * publish (a later fold moved the floor past the one read after the + * listing), and that stayed so for `TREE_GC_SWEEP_AGE_MINUTES`. + * + * Every DELETE is proven in its own tick by the membership check of + * `./gc-member.ts` against the root of the head that tick read. Records, + * the state and the clock only nominate and pace; none authorizes a + * deletion, so a stale or lost state can leak and never delete. + * + * **State.** `

/_v99/gc-pending.json` (`./gc-state.ts`) holds + * progress, bound to the head's `generation` and floor. A state of + * another history, or a malformed one, is replaced leak-only by the + * empty state; one of an unknown schema version stops the tick with + * `InvalidResponse`. + * + * **Clock.** The only clock is the `serverDate` of GC's own state write. + * A tick probes it (a state CAS) at most once per + * `TREE_GC_CLOCK_PROBE_MINUTES` of local time, judged only against the + * local time of the previous probe. Due tests use that probe's server + * time, or the last one between probes. A probe that reports no server + * time stamps nothing and makes nothing due. + * + * **Tick.** State GET; in a probe tick, the sweep LIST; head GET; root + * GET; record LIST; resolve closed floors; the probe write; checks and + * DELETEs (active losers' fresh nodes, due winners' superseded nodes, + * due sweep marks); the sweep's notes and stamps; the state write, only + * when something changed; then `retireLogRange`. Candidate checks per + * tick are sized from the request ledger. + */ +import { + BaerlyError, + currentRequestLedger, + GC_MARK_LIST_PAGE_KEYS, + isWriteConflict, + type Storage, +} from "@baerly/protocol"; +import { retireLogRange } from "../log-retention.ts"; +import { ctxMetrics, getCurrentContext } from "../observability/context.ts"; +import { + TREE_GC_CLOCK_PROBE_MINUTES, + TREE_GC_MAX_SWEEP_MARKS, + TREE_GC_MAX_WORK_ENTRIES, + TREE_GC_SUPERSEDED_DELAY_MINUTES, + TREE_GC_SWEEP_AGE_MINUTES, + TREE_GC_SWEEP_LIST_KEYS, + TREE_GC_TICK_CANDIDATES, + TREE_GC_TICK_MAX_CANDIDATES, + TREE_GC_TICK_RECORD_CALLS, + TREE_GC_TICK_RESERVED_CALLS, + TREE_RETRIED_CALL_CHARGE, +} from "./constants.ts"; +import { createTreeGcRootView, type TreeGcMembership, treeGcMembership } from "./gc-member.ts"; +import { + decodeTreeGcState, + emptyTreeGcState, + encodeTreeGcState, + type TreeGcMark, + type TreeGcState, + type TreeGcWork, +} from "./gc-state.ts"; +import { readTreeHead, readTreeRoot, type TreeHead } from "./head.ts"; +import { + collectionOfPrefix, + parseTreeNodeKey, + parseTreeRecordKey, + treeGcStateKey, + treeNodeKeyPrefix, + treeRecordKey, + treeRecordKeyPrefix, +} from "./key.ts"; +import { bytesEqual, DEFAULT_TREE_CONFIG, type TreeConfig } from "./layout.ts"; +import { decodeFoldRecord, type FoldRecord } from "./record.ts"; + +const STATE_CONTENT_TYPE = "application/json"; +const MINUTE_MS = 60_000; + +/** The winner and losers among the attempts recorded at one closed floor. */ +export interface TreeGcClassification { + /** The winning attempt, or `null` when the evidence names no unique one. */ + readonly winner: string | null; + /** Attempts whose fresh nodes are deleted; empty without a winner. */ + readonly losers: readonly string[]; + /** The evidence named more than one member. */ + readonly ambiguous: boolean; +} + +/** + * Classify the attempts recorded at one closed floor: the winner is the + * unique member the evidence names, every other member a loser. An + * attempt that appears in more than one listed record is neither. + */ +export const classifyFloor = ( + members: readonly string[], + evidence: ReadonlySet, + duplicates: ReadonlySet, +): TreeGcClassification => { + const eligible = members.filter((attempt) => !duplicates.has(attempt)); + const named = eligible.filter((attempt) => evidence.has(attempt)); + if (named.length !== 1) { + return { winner: null, losers: [], ambiguous: named.length > 1 }; + } + const winner = named[0]!; + return { winner, losers: eligible.filter((attempt) => attempt !== winner), ambiguous: false }; +}; + +/** Whether `dueAt` is at or before server time `now`; nothing is due without both. */ +export const isDueAt = (dueAt: string | null, now: Date | undefined): boolean => + dueAt !== null && now !== undefined && Date.parse(dueAt) <= now.getTime(); + +/** Whether the state as read belongs to `head`'s history: same generation, no floor regression. */ +export const stateBindsHead = (state: TreeGcState, head: TreeHead): boolean => + state.generation === (head.json.generation ?? null) && + state.floor_seen <= head.json.log_seq_start; + +/** + * Whether a tick probes the server clock, by local time alone: the + * first probe, at least `TREE_GC_CLOCK_PROBE_MINUTES` after the last, + * or when the local clock reads earlier than the last probe's. + */ +export const probeIsDue = (probedLocalAt: string | null, local: Date): boolean => { + if (probedLocalAt === null) { + return true; + } + const last = Date.parse(probedLocalAt); + return ( + local.getTime() < last || local.getTime() - last >= TREE_GC_CLOCK_PROBE_MINUTES * MINUTE_MS + ); +}; + +interface GcSteps { + readonly isMember: NonNullable; + readonly onCorrupt: NonNullable; + readonly parsesKey: NonNullable; + readonly classify: NonNullable; + readonly isClosed: NonNullable; + readonly isDue: NonNullable; + readonly now: NonNullable; + readonly bindsHead: NonNullable; + readonly sweepIsMember: NonNullable; + readonly passesFloorGate: NonNullable; + readonly startsAge: NonNullable; + readonly listsBeforeHead: NonNullable; +} + +const gcSteps = (config: TreeConfig): GcSteps => { + const s = config.steps; + const isMember = s.gcIsMember ?? treeGcMembership; + return { + isMember, + onCorrupt: s.gcOnCorrupt ?? ((role, guardHolds) => role === "loser" && guardHolds), + parsesKey: s.gcParsesKey ?? parseTreeNodeKey, + classify: s.gcClassify ?? classifyFloor, + isClosed: s.gcIsClosed ?? ((floor, headFloor) => floor < headFloor), + isDue: s.gcIsDue ?? isDueAt, + now: s.gcNow ?? ((serverDate) => serverDate), + bindsHead: s.gcBindsHead ?? stateBindsHead, + sweepIsMember: s.sweepIsMember ?? ((x, view) => isMember(x, view)), + passesFloorGate: s.sweepPassesFloorGate ?? ((markFloor, headFloor) => headFloor > markFloor), + startsAge: s.sweepStartsAge ?? ((phase) => phase === "stamp"), + listsBeforeHead: s.sweepListsBeforeHead ?? (() => true), + }; +}; + +/** Input to {@link runTreeGcTick}. */ +export interface TreeGcInput { + /** Storage behind the adapter retry (`retryStorageCall`). */ + readonly storage: Storage; + /** The collection prefix `P`. */ + readonly prefix: string; + /** The tree configuration; tests pass a mutant here. */ + readonly config?: TreeConfig; + /** The local clock; it only paces probes. Default `new Date()`. */ + readonly now?: () => Date; + /** Test seam for `retireLogRange`'s sequence window; production omits it. */ + readonly retireWindow?: number; + readonly signal?: AbortSignal; +} + +/** What one GC tick did. */ +export interface TreeGcTickResult { + /** + * - `collected`: the tick ran to its end; + * - `no-head`: the collection has no head yet; + * - `reset`: the state was malformed or of another head history, and + * was replaced by the empty state; + * - `budget`: the request ledger had no room for one candidate check; + * - `conflict`: the probe write lost, so the tick deleted nothing. + */ + readonly outcome: "collected" | "no-head" | "reset" | "budget" | "conflict"; + /** Every key the tick deleted, nodes and records, in order. */ + readonly deleted: readonly string[]; + /** The probe's server time, when the tick probed and storage reported one. */ + readonly serverTime: Date | undefined; + /** Whether the tick probed. */ + readonly probed: boolean; + /** Candidate checks the tick could make. */ + readonly candidates: number; +} + +/** A record key the tick listed. */ +interface ListedRecord { + readonly key: string; + readonly floor: number; + readonly attempt: string; + /** `/`. */ + readonly tail: string; +} + +const addMinutes = (instant: Date, minutes: number): string => + new Date(instant.getTime() + minutes * MINUTE_MS).toISOString(); + +/** Calls one candidate check may cost at root level `depth`: its DELETE and membership GETs. */ +export const treeGcCandidateCharge = (depth: number): number => + depth <= 1 ? TREE_RETRIED_CALL_CHARGE : TREE_RETRIED_CALL_CHARGE * (depth + 1); + +/** + * Candidate checks a tick may make at root level `depth` with `left` + * ledger calls remaining: `TREE_GC_TICK_MAX_CANDIDATES` when the ledger + * has room for that many, else at most `TREE_GC_TICK_CANDIDATES`, and + * never more than fit after the tick's other calls. + */ +export const treeGcCandidates = (depth: number, left: number): number => { + const room = Math.floor((left - TREE_GC_TICK_RESERVED_CALLS) / treeGcCandidateCharge(depth)); + const max = + room >= TREE_GC_TICK_MAX_CANDIDATES ? TREE_GC_TICK_MAX_CANDIDATES : TREE_GC_TICK_CANDIDATES; + return Math.max(0, Math.min(max, room)); +}; + +const warn = (code: string, fields: Record, detail: string): void => { + const sink = getCurrentContext()?.maintenance?.warn; + if (sink !== undefined) { + try { + sink(code, { ...fields, detail }); + return; + } catch { + // Fall through to the console line. + } + } + console.warn(detail); +}; + +/** Whether two states are equal apart from `floor_seen`, which alone is no reason to write. */ +const sameState = (a: TreeGcState, b: TreeGcState): boolean => + bytesEqual( + encodeTreeGcState({ ...a, floor_seen: 0 }), + encodeTreeGcState({ ...b, floor_seen: 0 }), + ); + +const isUnknownFate = (error: unknown): boolean => + isWriteConflict(error) || (error instanceof BaerlyError && error.code === "NetworkError"); + +/** + * Run one tree GC tick over the collection at `input.prefix`. See the + * module comment. + * + * @throws BaerlyError code="InvalidResponse" — the head or root is not a + * valid tree, or the GC state was written by a release with a newer + * state schema. + * @throws BaerlyError — a storage call fails, with its code. A lost + * state write is an outcome, not an error. + */ +export const runTreeGcTick = async (input: TreeGcInput): Promise => { + const { storage, prefix, signal } = input; + const config = input.config ?? DEFAULT_TREE_CONFIG; + const steps = gcSteps(config); + const collection = collectionOfPrefix(prefix); + const local = (input.now ?? (() => new Date()))(); + const opts = signal === undefined ? undefined : { signal }; + const stateKey = treeGcStateKey(prefix); + const nodePrefix = treeNodeKeyPrefix(prefix); + const counter = (name: string, value = 1): void => { + if (value > 0) { + ctxMetrics().counter(`db.tree_gc.${name}`, value, { collection }); + } + }; + const deleted: string[] = []; + const end = ( + outcome: TreeGcTickResult["outcome"], + extra: Partial = {}, + ): TreeGcTickResult => ({ + outcome, + deleted, + serverTime: undefined, + probed: false, + candidates: 0, + ...extra, + }); + + const putState = async (state: TreeGcState, etag: string | null) => + storage.put(stateKey, encodeTreeGcState(state), { + ...(etag === null ? { ifNoneMatch: "*" as const } : { ifMatch: etag }), + contentType: STATE_CONTENT_TYPE, + ...(signal !== undefined && { signal }), + }); + + // 1. The state. + const got = await storage.get(stateKey, opts); + const decoded = got === null ? null : decodeTreeGcState(stateKey, got.body); + const e0 = got?.etag ?? null; + const read = decoded?.kind === "state" ? decoded.state : null; + + // 2. The sweep page, listed before the head in a probe tick. + const probe = decoded?.kind !== "malformed" && probeIsDue(read?.probed_local_at ?? null, local); + const listed: string[] = []; + const listSweep = async (cursor: string | null): Promise => { + for await (const entry of storage.list(nodePrefix, { + ...(cursor !== null && { startAfter: cursor }), + maxKeys: TREE_GC_SWEEP_LIST_KEYS, + ...(signal !== undefined && { signal }), + })) { + listed.push(entry.key); + } + }; + if (probe && steps.listsBeforeHead()) { + await listSweep(read?.sweep.cursor ?? null); + } + + // 3. The head. + const head = await readTreeHead(storage, prefix, opts); + if (head === null) { + return end("no-head"); + } + if (probe && !steps.listsBeforeHead()) { + await listSweep(read?.sweep.cursor ?? null); + } + const h = head.json.log_seq_start; + const generation = head.json.generation ?? null; + if (decoded?.kind === "malformed" || (read !== null && !steps.bindsHead(read, head))) { + try { + await putState(emptyTreeGcState(generation, h), e0); + } catch (error) { + if (!isUnknownFate(error)) { + throw error; + } + } + return end("reset"); + } + const base: TreeGcState = read ?? emptyTreeGcState(generation, h); + + // 4. The root, and the candidate budget it implies. + const root = await readTreeRoot(storage, head, config, opts); + const depth = root?.node.level ?? 0; + const candidates = treeGcCandidates( + depth, + currentRequestLedger()?.storageRemaining() ?? Number.POSITIVE_INFINITY, + ); + if (candidates < 1) { + ctxMetrics().counter("db.maintenance.request_budget_skipped_total", 1, { + collection, + phase: "gc", + }); + return end("budget"); + } + + // 5. The record page. + const records: ListedRecord[] = []; + let recordPageFull = false; + for await (const entry of storage.list(treeRecordKeyPrefix(prefix), { + maxKeys: GC_MARK_LIST_PAGE_KEYS, + ...(signal !== undefined && { signal }), + })) { + const parts = parseTreeRecordKey(prefix, entry.key); + if (parts === null) { + counter("unknown_key_total"); + continue; + } + records.push({ + key: entry.key, + floor: parts.floor, + attempt: parts.attempt, + tail: `${parts.attempt}/${parts.sha256}`, + }); + } + recordPageFull = records.length >= GC_MARK_LIST_PAGE_KEYS; + const lastListedFloor = records.at(-1)?.floor ?? -1; + /** Whether the record page shows every record at `floor`. */ + const pageCovers = (floor: number): boolean => !recordPageFull || lastListedFloor > floor; + + const seen = new Map(); + for (const record of records) { + seen.set(record.attempt, (seen.get(record.attempt) ?? 0) + 1); + } + const duplicates = new Set([...seen].filter(([, n]) => n > 1).map(([attempt]) => attempt)); + if (duplicates.size > 0) { + counter("duplicate_attempt_total", duplicates.size); + warn( + "tree_gc_duplicate_attempt", + { collection, attempts: [...duplicates] }, + `tree GC of collection ${JSON.stringify(collection)}: ${duplicates.size} publication identities each appear in more than one fold record; those records are retired without deleting any node they name.`, + ); + } + + // Record GETs and DELETEs share one cap each per tick. + let recordGets = TREE_GC_TICK_RECORD_CALLS; + let recordDeletes = TREE_GC_TICK_RECORD_CALLS; + const retired = new Set(); + const fetched = new Map(); + /** A verified record of this generation, `absent`, `unusable` (retire it) or `budget`. */ + const recordAt = async (key: string): Promise => { + const known = fetched.get(key); + if (known !== undefined) { + return known; + } + if (recordGets <= 0) { + return "budget"; + } + recordGets -= 1; + const body = await storage.get(key, opts); + let result: FoldRecord | "absent" | "unusable"; + if (body === null) { + result = "absent"; + } else { + try { + const record = await decodeFoldRecord(prefix, key, body.body); + result = record.base.generation === base.generation ? record : "unusable"; + } catch (error) { + if (!(error instanceof BaerlyError) || error.code !== "InvalidResponse") { + throw error; + } + counter("corrupt_record_total"); + warn( + "tree_gc_corrupt_record", + { collection, key }, + `tree GC of collection ${JSON.stringify(collection)}: fold record ${key} does not match its key or does not parse; it is retired without deleting any node it names.`, + ); + result = "unusable"; + } + } + fetched.set(key, result); + return result; + }; + /** Delete a record without deleting any node it names; false when the cap is spent. */ + const retireRecord = async (key: string): Promise => { + if (retired.has(key)) { + return true; + } + if (recordDeletes <= 0) { + return false; + } + recordDeletes -= 1; + await storage.delete(key, opts); + deleted.push(key); + retired.add(key); + return true; + }; + const recordKeyOf = (floor: number, tail: string): string => + treeRecordKey(prefix, floor, tail.slice(0, 32), tail.slice(33)); + + // 6. Resolve closed floors in order. + const floors = new Map(); + for (const record of records) { + floors.set(record.floor, [...(floors.get(record.floor) ?? []), record]); + } + const order = [...floors.keys()].toSorted((a, b) => a - b); + const evidence = new Set(head.attempt === null ? [] : [head.attempt]); + const work: TreeGcWork[] = base.work.map((entry) => + duplicates.has(entry.winner.slice(0, 32)) ? { ...entry, quarantined: true } : entry, + ); + let resolvedThrough = base.resolved_through; + let stuck = base.stuck; + const lastClock = base.clock === null ? undefined : new Date(base.clock); + for (const [i, floor] of order.entries()) { + if (!steps.isClosed(floor, h)) { + break; + } + const members = floors.get(floor)!.filter((record) => !retired.has(record.key)); + const at = work.findIndex((entry) => entry.floor === floor); + if (at >= 0) { + const entry = work[at]!; + if (entry.loser === null) { + const { losers } = steps.classify( + members.map((record) => record.attempt), + new Set([...evidence, entry.winner.slice(0, 32)]), + duplicates, + ); + const loser = members.find( + (record) => record.tail !== entry.winner && losers.includes(record.attempt), + ); + if (loser !== undefined) { + work[at] = { ...entry, loser: { record: loser.tail, next: 0 } }; + } + } + continue; + } + if (resolvedThrough !== null && floor <= resolvedThrough) { + // Stale: resolved before, and no entry covers it. + for (const record of members) { + await retireRecord(record.key); + } + continue; + } + if (work.length >= TREE_GC_MAX_WORK_ENTRIES) { + break; + } + const next = order[i + 1]; + const witness = next === undefined ? undefined : floors.get(next)![0]; + if (witness !== undefined && !retired.has(witness.key)) { + const record = await recordAt(witness.key); + if (typeof record === "object") { + if (record.base.attempt !== null) { + evidence.add(record.base.attempt); + } + } else if (record === "unusable") { + await retireRecord(witness.key); + } + } + const verdict = steps.classify( + members.map((record) => record.attempt), + evidence, + duplicates, + ); + if (verdict.winner !== null) { + const winner = members.find((record) => record.attempt === verdict.winner)!; + const loser = members.find( + (record) => record !== winner && verdict.losers.includes(record.attempt), + ); + work.push({ + floor, + winner: winner.tail, + quarantined: false, + due_at: null, + next: 0, + loser: loser === undefined ? null : { record: loser.tail, next: 0 }, + }); + resolvedThrough = floor; + if (stuck?.floor === floor) { + stuck = null; + } + continue; + } + if (verdict.ambiguous) { + counter("ambiguous_floor_total"); + } + if (stuck?.floor !== floor) { + stuck = { floor, since: null }; + } else if ( + stuck.since !== null && + steps.isDue(addMinutes(new Date(stuck.since), TREE_GC_SWEEP_AGE_MINUTES), lastClock) + ) { + // Stuck long enough: retire the floor leak-only and move on. + for (const record of members) { + await retireRecord(record.key); + } + resolvedThrough = floor; + stuck = null; + continue; + } + break; + } + // Duplicate identities are never a deletion source, from either list. + for (const record of records) { + const named = work.some( + (entry) => entry.floor === record.floor && entry.loser?.record === record.tail, + ); + if (duplicates.has(record.attempt) && !named) { + await retireRecord(record.key); + } + } + + // 7. The probe. + let etag = e0; + let written: TreeGcState | null = null; + let serverTime: Date | undefined; + if (probe) { + const probed: TreeGcState = { + ...base, + ticks: base.ticks + 1, + probed_local_at: local.toISOString(), + }; + try { + const result = await putState(probed, e0); + etag = result.etag; + serverTime = steps.now(result.serverDate, local); + } catch (error) { + if (!isUnknownFate(error)) { + throw error; + } + return end("conflict", { deleted, probed: true, candidates }); + } + written = probed; + if (serverTime === undefined) { + counter("no_server_time_total"); + warn( + "tree_gc_no_server_time", + { collection }, + `tree GC is not reclaiming replaced nodes of collection ${JSON.stringify(collection)}: storage reported no server time.`, + ); + } + } + const now = probe ? serverTime : lastClock; + if (serverTime !== undefined) { + for (const [i, entry] of work.entries()) { + if (entry.due_at === null) { + work[i] = { ...entry, due_at: addMinutes(serverTime, TREE_GC_SUPERSEDED_DELAY_MINUTES) }; + } + } + if (stuck !== null && stuck.since === null) { + stuck = { ...stuck, since: serverTime.toISOString() }; + } + } + + // 8. Checks and DELETEs. + let budget = Math.max(0, candidates - listed.length); + let halted = false; + const view = createTreeGcRootView(storage, prefix, root, config, signal); + const rootChildAttempts = new Set( + root?.node.kind === "branch" ? root.node.children.map((entry) => entry.attempt) : [], + ); + const deleteNode = async (key: string): Promise => { + await storage.delete(key, opts); + deleted.push(key); + }; + /** Handle what a check found for `x`; false when the tick must stop deleting. */ + const settle = async ( + x: string, + found: TreeGcMembership, + role: "loser" | "superseded" | "sweep", + attempt: string, + ): Promise => { + switch (found) { + case "path-unreadable": { + counter("path_unreadable_total"); + halted = true; + return false; + } + case "non-member": { + await deleteNode(x); + return true; + } + case "corrupt": { + counter("corrupt_node_total"); + const guardHolds = attempt !== head.attempt && !rootChildAttempts.has(attempt); + if (steps.onCorrupt(role, guardHolds)) { + await deleteNode(x); + warn( + "tree_gc_corrupt_node", + { collection, key: x, deleted: true }, + `tree GC deleted node ${x} of collection ${JSON.stringify(collection)}: its stored body did not match its key or did not parse. No current data used it.`, + ); + } else { + warn( + "tree_gc_corrupt_node", + { collection, key: x, deleted: false }, + `tree GC left node ${x} of collection ${JSON.stringify(collection)} in place: its stored body does not match its key or does not parse. If reads of this collection report InvalidResponse, export it with baerly admin dump and load the dump into a new collection.`, + ); + } + return true; + } + default: { + return true; + } + } + }; + + // 8a. Losers' fresh nodes, at once. + for (const [i, entry] of work.entries()) { + if (halted || budget <= 0) { + break; + } + if (entry.loser === null) { + continue; + } + const key = recordKeyOf(entry.floor, entry.loser.record); + const record = retired.has(key) ? "absent" : await recordAt(key); + if (record === "budget") { + break; + } + if (record === "absent" || record === "unusable") { + if (record === "absent" || (await retireRecord(key))) { + work[i] = { ...entry, loser: null }; + } + continue; + } + let next = entry.loser.next; + while (next < record.fresh.length && budget > 0) { + const x = `${nodePrefix}${record.attempt}/${record.fresh[next]}`; + budget -= 1; + if (!(await settle(x, await steps.isMember(x, view), "loser", record.attempt))) { + break; + } + next += 1; + } + if (next >= record.fresh.length && (await retireRecord(key))) { + work[i] = { ...entry, loser: null }; + } else { + work[i] = { ...entry, loser: { record: entry.loser.record, next } }; + } + } + + // 8b. Due winners' superseded nodes. + const dropped = new Set(); + for (const [i, entry] of work.entries()) { + if (halted) { + break; + } + const key = recordKeyOf(entry.floor, entry.winner); + const listedHere = floors.get(entry.floor) ?? []; + if (retired.has(key) || (pageCovers(entry.floor) && !listedHere.some((r) => r.key === key))) { + // Its record is gone: the slot ends. + dropped.add(i); + continue; + } + if (entry.quarantined || !steps.isDue(entry.due_at, now) || budget <= 0) { + continue; + } + const record = await recordAt(key); + if (record === "budget") { + break; + } + if (record === "absent" || record === "unusable") { + if (record === "absent" || (await retireRecord(key))) { + dropped.add(i); + } + continue; + } + let next = entry.next; + while (next < record.superseded.length && budget > 0) { + const ref = record.superseded[next]!; + const x = `${nodePrefix}${ref}`; + budget -= 1; + if (!(await settle(x, await steps.isMember(x, view), "superseded", ref.slice(0, 32)))) { + break; + } + next += 1; + } + work[i] = { ...entry, next }; + const othersListed = listedHere.some((r) => r.key !== key && !retired.has(r.key)); + if ( + next >= record.superseded.length && + work[i]!.loser === null && + !othersListed && + pageCovers(entry.floor) && + (await retireRecord(key)) + ) { + // Retired before the slot is cleared by the state write. + dropped.add(i); + } + } + const remaining = work.filter((_, i) => !dropped.has(i)); + + // 8c. Due sweep marks. + let marks: TreeGcMark[] = [...base.sweep.marks]; + const keep: TreeGcMark[] = []; + for (const mark of marks) { + if (halted || budget <= 0 || mark.due_at === null || !steps.isDue(mark.due_at, now)) { + keep.push(mark); + continue; + } + const x = `${nodePrefix}${mark.key}`; + budget -= 1; + const found = await steps.sweepIsMember(x, view, "delete"); + if (found === "deferred") { + keep.push(mark); + continue; + } + if (!(await settle(x, found, "sweep", mark.key.slice(0, 32)))) { + keep.push(mark); + } + } + marks = keep; + + // 9. The sweep page: note new marks, stamp noted ones a later floor closed. + let cursor = base.sweep.cursor; + if (probe) { + const marked = new Set(marks.map((mark) => mark.key)); + for (const key of listed) { + const parts = steps.parsesKey(prefix, key); + if (parts === null) { + counter("unknown_key_total"); + continue; + } + const tail = key.slice(nodePrefix.length); + if (halted || marked.has(tail) || marks.length >= TREE_GC_MAX_SWEEP_MARKS) { + continue; + } + const found = await steps.sweepIsMember(key, view, "note"); + if (found === "corrupt") { + // Counted and warned; a sweep candidate GC cannot authenticate stays. + await settle(key, found, "sweep", parts.attempt); + } else if (found === "path-unreadable") { + counter("path_unreadable_total"); + halted = true; + } else if (found === "non-member") { + const stamp = steps.startsAge("note") && serverTime !== undefined; + marks.push({ + key: tail, + floor: h, + due_at: stamp ? addMinutes(serverTime!, TREE_GC_SWEEP_AGE_MINUTES) : null, + }); + marked.add(tail); + } + } + const stamped: TreeGcMark[] = []; + for (const mark of marks) { + if ( + halted || + mark.due_at !== null || + serverTime === undefined || + !steps.startsAge("stamp") || + !steps.passesFloorGate(mark.floor, h) || + budget <= 0 + ) { + stamped.push(mark); + continue; + } + budget -= 1; + const found = await steps.sweepIsMember(`${nodePrefix}${mark.key}`, view, "stamp"); + if (found === "non-member") { + stamped.push({ ...mark, due_at: addMinutes(serverTime, TREE_GC_SWEEP_AGE_MINUTES) }); + } else if (found === "path-unreadable") { + counter("path_unreadable_total"); + halted = true; + stamped.push(mark); + } else if (found === "deferred") { + stamped.push(mark); + } else if (found === "corrupt") { + await settle(`${nodePrefix}${mark.key}`, found, "sweep", mark.key.slice(0, 32)); + } + // A member, a gone node or a corrupt one leaves the sweep's list. + } + marks = stamped; + cursor = listed.length < TREE_GC_SWEEP_LIST_KEYS ? null : listed.at(-1)!; + } + + // 10. The state write, when the tick changed anything. + const prior = written ?? base; + const final: TreeGcState = { + ...prior, + floor_seen: h, + clock: probe && serverTime !== undefined ? serverTime.toISOString() : prior.clock, + resolved_through: resolvedThrough, + stuck, + work: remaining, + sweep: { cursor, marks }, + }; + if (!sameState(final, prior)) { + try { + await putState({ ...final, ticks: prior.ticks + 1 }, etag); + } catch (error) { + if (!isUnknownFate(error)) { + throw error; + } + } + } + + // 11. Log retirement, as main's GC phase ends. + try { + await retireLogRange(storage, head.key, { + ...(signal !== undefined && { signal }), + ...(input.retireWindow !== undefined && { window: input.retireWindow }), + }); + } catch (error) { + if (!isWriteConflict(error)) { + throw error; + } + } + return end("collected", { deleted, serverTime, probed: probe, candidates }); +}; diff --git a/packages/server/src/tree/layout.ts b/packages/server/src/tree/layout.ts index 12e0bc0b..5c6a847f 100644 --- a/packages/server/src/tree/layout.ts +++ b/packages/server/src/tree/layout.ts @@ -16,7 +16,11 @@ */ import { BaerlyError } from "@baerly/protocol"; import type { ChunkKey } from "./chunk.ts"; +import type { TreeGcClassification } from "./gc.ts"; +import type { TreeGcMembership, TreeGcRootView } from "./gc-member.ts"; +import type { TreeGcState } from "./gc-state.ts"; import type { TreeHead } from "./head.ts"; +import type { TreeNodeKeyParts } from "./key.ts"; import type { DecodedTreeNode, TreeChildEntry } from "./node-codec.ts"; import type { LiveTreeRef, TreePublicationWrite } from "./publish.ts"; import type { FoldRecordBase } from "./record.ts"; @@ -318,6 +322,48 @@ export interface TreeSteps { ) => readonly string[]; /** The base a fold record names for an attempt that captured `head`. */ readonly recordBase?: (head: TreeHead) => FoldRecordBase; + /** GC's reachability check of node key `x` against the view's root; see `gc-member.ts`. */ + readonly gcIsMember?: (x: string, view: TreeGcRootView) => Promise; + /** Whether GC reads a candidate whose body failed its decode once more before calling it corrupt. */ + readonly gcRetriesCorrupt?: () => boolean; + /** + * Whether GC deletes a corrupt candidate, given its role and whether + * the key-only guard holds (its attempt is neither the head's + * installer nor that of any child ref of the root). + */ + readonly gcOnCorrupt?: (role: "loser" | "superseded" | "sweep", guardHolds: boolean) => boolean; + /** The parts of a key the leak sweep listed, or `null` when it is not a node key. */ + readonly gcParsesKey?: (prefix: string, key: string) => TreeNodeKeyParts | null; + /** + * The winner and losers among the attempts recorded at one closed + * floor, given the attempts the tick's evidence names and the attempts + * that appear in more than one listed record. + */ + readonly gcClassify?: ( + members: readonly string[], + evidence: ReadonlySet, + duplicates: ReadonlySet, + ) => TreeGcClassification; + /** Whether the records at `floor` are closed under a head at `headFloor`. */ + readonly gcIsClosed?: (floor: number, headFloor: number) => boolean; + /** Whether an item due at `dueAt` (server time) is due at server time `now`. */ + readonly gcIsDue?: (dueAt: string | null, now: Date | undefined) => boolean; + /** The server time a probe reads, from the probe write's `serverDate` and the local clock. */ + readonly gcNow?: (serverDate: Date | undefined, local: Date) => Date | undefined; + /** Whether the GC state as read still belongs to the history of `head`. */ + readonly gcBindsHead?: (state: TreeGcState, head: TreeHead) => boolean; + /** The leak sweep's membership check, by phase. */ + readonly sweepIsMember?: ( + x: string, + view: TreeGcRootView, + phase: "note" | "stamp" | "delete", + ) => Promise; + /** Whether a mark noted under a head at `markFloor` may be stamped under a head at `headFloor`. */ + readonly sweepPassesFloorGate?: (markFloor: number, headFloor: number) => boolean; + /** Whether the sweep starts a mark's age in `phase`. */ + readonly sweepStartsAge?: (phase: "note" | "stamp") => boolean; + /** Whether a probe tick lists its sweep page before it reads the head. */ + readonly sweepListsBeforeHead?: () => boolean; /** * The reader's tail step: walk and probe the unfolded log tail of the * head it is given, and fold it into a per-`_id` overlay. diff --git a/tests/fixtures/tree-gc-harness.ts b/tests/fixtures/tree-gc-harness.ts new file mode 100644 index 00000000..efb8c72a --- /dev/null +++ b/tests/fixtures/tree-gc-harness.ts @@ -0,0 +1,487 @@ +/** + * A bucket for tree GC tests: one collection in memory behind the + * adapter retry, with folds published through the real planner and + * publisher, GC ticks through `runTreeGcTick`, and two clocks the test + * moves by hand. + * + * - **Clocks.** `local` is what the GC tick reads as its local clock; + * `server` is what every PUT reports as `serverDate` (the server-clock + * wrapper). They move independently, so a test can skew one against + * the other, and `serverTime = false` makes PUTs report none. + * - **Interleaving.** A fold can be started and left paused before its + * head CAS ({@link GcBucket.startFold}), the way an attempt still in + * flight looks to GC. `onList` runs once before the next LIST of a + * prefix, and `getOverride` can replace what a GET returns, so a test + * can land a fold inside a tick or simulate a misread. + * - **Judging.** {@link GcBucket.violations} runs the physical oracle + * over the current tree and the rows its folds published; a node the + * root reaches that GC deleted shows up there. {@link MarginWatch} + * records when each node became unreachable and flags a deletion that + * came sooner than the reader margin after it. + * + * Storage stack, outermost first: adapter retry → hooks → fault + * injection (`aborting-storage.ts`) → server clock → memory. + */ +import { + type DocumentData, + MemoryStorage, + retryStorageCall, + type Storage, + type CurrentJson, + createCurrentJson, + casUpdateCurrentJson, +} from "@baerly/protocol"; +import { + createObservabilityContext, + runWithContext, +} from "../../packages/server/src/observability/context.ts"; +import { RequestScopedMetricsRecorder } from "../../packages/server/src/observability/recorder.ts"; +import { TREE_GC_SUPERSEDED_DELAY_MINUTES } from "../../packages/server/src/tree/constants.ts"; +import { runTreeGcTick, type TreeGcTickResult } from "../../packages/server/src/tree/gc.ts"; +import { decodeTreeGcState, type TreeGcState } from "../../packages/server/src/tree/gc-state.ts"; +import { + importTreeChunkKey, + readTreeHead, + readTreeRoot, + type TreeHead, + treeHeadKey, +} from "../../packages/server/src/tree/head.ts"; +import { + treeGcStateKey, + treeNodeKeyPrefix, + treeRecordKeyPrefix, +} from "../../packages/server/src/tree/key.ts"; +import { createTreeConfig, type TreeConfig } from "../../packages/server/src/tree/layout.ts"; +import { + canonicalDocument, + type DecodedTreeNode, +} from "../../packages/server/src/tree/node-codec.ts"; +import { planFold, type TreeFoldPlan } from "../../packages/server/src/tree/plan.ts"; +import { publishTree, type TreePublishOutcome } from "../../packages/server/src/tree/publish.ts"; +import { abortingStorage } from "./aborting-storage.ts"; +import { TREE_TEST_CHUNK_SALT, testChunkKey } from "./tree-chunk-salt.ts"; +import { FOLD_PREFIX, SMALL_LAYOUT } from "./tree-fold-harness.ts"; +import type { TreeMutant } from "./tree-mutants.ts"; +import { captureTreeImage, checkTreeImage } from "./tree-oracle-physical.ts"; + +export const GC_PREFIX = FOLD_PREFIX; +export const GC_HEAD = treeHeadKey(GC_PREFIX); +export const GC_NODES = treeNodeKeyPrefix(GC_PREFIX); +export const GC_RECORDS = treeRecordKeyPrefix(GC_PREFIX); +export const GC_STATE = treeGcStateKey(GC_PREFIX); + +/** Both clocks start here. */ +export const GC_T0 = Date.parse("2026-01-05T00:00:00.000Z"); +const MINUTE = 60_000; + +const chunkKey = await testChunkKey(); + +/** A distinct, deterministic attempt identity. */ +export const gcAttemptOf = (n: number): string => n.toString(16).padStart(32, "0"); + +/** The small-scope layout with the steps of every mutant given. */ +export const gcConfig = (...mutants: readonly (TreeMutant | undefined)[]): TreeConfig => + createTreeConfig({ + layout: SMALL_LAYOUT, + steps: Object.assign({}, ...mutants.map((mutant) => mutant?.options.steps ?? {})), + }); + +/** A row change: the row's new value, or `null` to delete it. */ +export type GcChange = readonly [id: string, value: number | null]; + +/** A captured, planned fold that has not published. */ +export interface GcPreparedFold { + readonly head: TreeHead; + readonly root: DecodedTreeNode | null; + readonly plan: TreeFoldPlan; + readonly floor: number; + readonly changes: readonly GcChange[]; +} + +/** A fold paused before its head CAS. */ +export interface GcFoldInFlight { + readonly fold: GcPreparedFold; + /** Let the head CAS go, and resolve with the outcome. */ + release(): Promise; +} + +/** What a tick did, and what it counted and warned. */ +export interface GcTickRun { + readonly result: TreeGcTickResult; + readonly counters: ReadonlyMap; + readonly warnings: readonly string[]; +} + +/** A fresh tree head with no `proto_tree`. */ +export const freshGcHead = (generation?: string): CurrentJson => ({ + schema_version: 3, + snapshot: null, + tail_hint: 0, + log_seq_start: 0, + writer_fence: { epoch: 0, owner: "", claimed_at: "" }, + snapshot_bytes: 0, + snapshot_rows: 0, + ...(generation !== undefined && { generation }), +}); + +/** The rows `k00`..`k19`, a depth-3 tree at the small-scope layout. */ +export const GC_SEED: readonly GcChange[] = Array.from({ length: 20 }, (_, i) => [ + `k${String(i).padStart(2, "0")}`, + i, +]); + +export class GcBucket { + readonly memory = new MemoryStorage(); + /** Local clock, ms. */ + local = GC_T0; + /** Server clock, ms. */ + server = GC_T0; + /** Whether PUTs report `serverDate`. */ + serverTime = true; + /** Runs once before the next LIST of the prefix it is keyed by. */ + readonly onList = new Map Promise>(); + /** Replaces a GET's body: return `undefined` to read the bucket. */ + getOverride: ((key: string) => Uint8Array | null | undefined) | undefined; + /** The rows the head's tree must hold. */ + readonly rows = new Map(); + readonly faults; + readonly storage: Storage; + #attempts = 0; + + constructor() { + const clocked: Storage = { + get: (key, opts) => this.memory.get(key, opts), + put: async (key, body, opts) => { + const { etag } = await this.memory.put(key, body, opts); + return this.serverTime ? { etag, serverDate: new Date(this.server) } : { etag }; + }, + delete: (key, opts) => this.memory.delete(key, opts), + list: (prefix, opts) => this.memory.list(prefix, opts), + }; + this.faults = abortingStorage(clocked); + const inner = this.faults.storage; + const hooked: Storage = { + get: async (key, opts) => { + const override = this.getOverride?.(key); + if (override === null) { + return null; + } + if (override !== undefined) { + return { body: override, etag: '"override"' }; + } + return inner.get(key, opts); + }, + put: (key, body, opts) => inner.put(key, body, opts), + delete: (key, opts) => inner.delete(key, opts), + list: (prefix, opts) => { + const hook = this.onList.get(prefix); + if (hook === undefined) { + return inner.list(prefix, opts); + } + this.onList.delete(prefix); + return (async function* () { + await hook(); + yield* inner.list(prefix, opts); + })(); + }, + }; + const sleep = async (): Promise => {}; + this.storage = { + get: (key, opts) => retryStorageCall(() => hooked.get(key, opts), { sleep }), + put: (key, body, opts) => + retryStorageCall(() => hooked.put(key, body, opts), { + sleep, + conditionalCreate: opts?.ifNoneMatch === "*", + compareAndSwap: opts?.ifMatch !== undefined, + }), + delete: (key, opts) => retryStorageCall(() => hooked.delete(key, opts), { sleep }), + list: (prefix, opts) => hooked.list(prefix, opts), + }; + } + + static async open(generation?: string): Promise { + const bucket = new GcBucket(); + await createCurrentJson(bucket.memory, GC_HEAD, freshGcHead(generation)); + return bucket; + } + + /** A bucket holding the depth-3 tree of {@link GC_SEED}. */ + static async seeded(generation?: string): Promise { + const bucket = await GcBucket.open(generation); + const outcome = await bucket.fold(GC_SEED); + if (outcome.kind !== "published") { + throw new Error("seeding did not publish"); + } + return bucket; + } + + /** Move both clocks on by `minutes`, or the server clock by `server` minutes instead. */ + advance(minutes: number, server = minutes): void { + this.local += minutes * MINUTE; + this.server += server * MINUTE; + } + + async head(): Promise { + const head = await readTreeHead(this.memory, GC_PREFIX); + if (head === null) { + throw new Error("no head"); + } + return head; + } + + /** Capture the head and its root and plan `changes` onto them. */ + async prepare(changes: readonly GcChange[], config = gcConfig()): Promise { + const head = await readTreeHead(this.storage, GC_PREFIX); + if (head === null) { + throw new Error("no head"); + } + const root = await readTreeRoot(this.storage, head, config); + const survivors = new Map(changes.map((change) => [change[0], change])); + const plan = await planFold({ + prefix: GC_PREFIX, + root, + chunkKey: (await importTreeChunkKey(head)) ?? chunkKey, + mutations: [...survivors.values()].map(([id, value]) => ({ + id, + doc: value === null ? null : canonicalDocument({ _id: id, v: value }, id), + })), + get: async (key) => { + const got = await this.storage.get(key); + return got?.body ?? null; + }, + config, + }); + return { head, root, plan, floor: head.json.log_seq_start + changes.length, changes }; + } + + /** + * Publish `fold` with the next attempt identity (or `attempt`), and + * commit its rows when it publishes. + */ + async publish( + fold: GcPreparedFold, + options: { + readonly attempt?: string; + readonly config?: TreeConfig; + readonly storage?: Storage; + } = {}, + ): Promise { + this.#attempts += 1; + const config = + options.config ?? + createTreeConfig({ + layout: SMALL_LAYOUT, + steps: { mintAttempt: () => options.attempt ?? gcAttemptOf(this.#attempts) }, + }); + const outcome = await publishTree({ + storage: options.storage ?? this.storage, + prefix: GC_PREFIX, + head: fold.head, + root: fold.root, + plan: fold.plan, + floor: fold.floor, + chunkSalt: TREE_TEST_CHUNK_SALT, + config, + }); + if (outcome.kind === "published") { + for (const [id, value] of fold.changes) { + if (value === null) { + this.rows.delete(id); + } else { + this.rows.set(id, { _id: id, v: value }); + } + } + } + return outcome; + } + + /** Prepare and publish `changes`. */ + async fold( + changes: readonly GcChange[], + options: Parameters[1] = {}, + ): Promise { + return this.publish(await this.prepare(changes), options); + } + + /** + * Prepare `changes` and publish them until the head CAS, then pause: + * the record and every fresh node are written, the CAS is not sent. + */ + async startFold( + changes: readonly GcChange[], + options: { readonly attempt?: string; readonly config?: TreeConfig } = {}, + ): Promise { + const fold = await this.prepare(changes); + let paused!: () => void; + const reached = new Promise((resolve) => { + paused = resolve; + }); + let go!: () => void; + const gate = new Promise((resolve) => { + go = resolve; + }); + const storage: Storage = { + ...this.storage, + put: async (key, body, opts) => { + if (key === GC_HEAD) { + paused(); + await gate; + } + return this.storage.put(key, body, opts); + }, + }; + const done = this.publish(fold, { ...options, storage }); + await Promise.race([reached, done]); + return { + fold, + release: () => { + go(); + return done; + }, + }; + } + + /** Rewrite the head the way a tail-hint refresh does: `proto_tree` spread through. */ + async refreshTailHint(): Promise { + await casUpdateCurrentJson(this.memory, GC_HEAD, (head) => ({ + ...head, + tail_hint: head.tail_hint + 1, + })); + } + + /** One GC tick under `config`, with its counters and warnings. */ + async tick(config: TreeConfig = gcConfig(), retireWindow?: number): Promise { + const recorder = new RequestScopedMetricsRecorder(); + const warnings: string[] = []; + const ctx = createObservabilityContext({ + recorder, + maintenance: { warn: (event) => warnings.push(event) }, + }); + const result = await runWithContext(ctx, () => + runTreeGcTick({ + storage: this.storage, + prefix: GC_PREFIX, + config, + now: () => new Date(this.local), + ...(retireWindow !== undefined && { retireWindow }), + }), + ); + const counters = new Map(); + for (const c of recorder.snapshot().counters) { + counters.set(c.name, (counters.get(c.name) ?? 0) + c.value); + } + return { result, counters, warnings }; + } + + /** Tick once a minute for `minutes` minutes, both clocks moving together. */ + async tickFor(minutes: number, config = gcConfig(), watch?: MarginWatch): Promise { + const deleted: string[] = []; + for (let i = 0; i < minutes; i++) { + this.advance(1); + const { result } = await this.tick(config); + deleted.push(...result.deleted); + await watch?.afterTick(result.deleted); + } + return deleted; + } + + /** The decoded GC state, or `null`. */ + async state(): Promise { + const got = await this.memory.get(GC_STATE); + if (got === null) { + return null; + } + const decoded = decodeTreeGcState(GC_STATE, got.body); + return decoded.kind === "state" ? decoded.state : null; + } + + /** Every key under `prefix`, sorted. */ + async keys(prefix: string): Promise { + const keys: string[] = []; + for await (const entry of this.memory.list(prefix)) { + keys.push(entry.key); + } + return keys.toSorted(); + } + + /** The physical oracle over the current tree and the published rows. */ + async violations(): Promise { + const head = await this.head(); + const report = checkTreeImage({ + image: await captureTreeImage(this.memory, GC_PREFIX), + prefix: GC_PREFIX, + layout: SMALL_LAYOUT, + expectedRows: this.rows.values(), + expectedFloor: head.json.log_seq_start, + }); + return report.violations.map((v) => `[${v.kind}] ${v.message}`); + } + + /** Node keys the head's root reaches. */ + async reachable(): Promise> { + const report = checkTreeImage({ + image: await captureTreeImage(this.memory, GC_PREFIX), + prefix: GC_PREFIX, + layout: SMALL_LAYOUT, + }); + return new Set(report.reachableKeys); + } + + /** Node keys present that the head's root does not reach. */ + async unreachable(): Promise { + const reachable = await this.reachable(); + const keys = await this.keys(GC_NODES); + return keys.filter((key) => !reachable.has(key)); + } +} + +/** + * Tracks, on the server clock, when each node that was ever reachable + * stopped being reachable, and checks every deletion against it: no + * deletion of a node the root reaches, and none sooner than the + * superseded delay after the node became unreachable. + */ +export class MarginWatch { + readonly #bucket: GcBucket; + readonly #since = new Map(); + readonly #everReachable = new Set(); + readonly problems: string[] = []; + + constructor(bucket: GcBucket) { + this.#bucket = bucket; + } + + /** Record reachability now; call after every fold. */ + async observe(): Promise { + const reachable = await this.#bucket.reachable(); + for (const key of reachable) { + this.#everReachable.add(key); + this.#since.delete(key); + } + for (const key of this.#everReachable) { + if (!reachable.has(key) && !this.#since.has(key)) { + this.#since.set(key, this.#bucket.server); + } + } + } + + /** Check a tick's deletions, then observe. */ + async afterTick(deleted: readonly string[]): Promise { + for (const key of deleted.filter((k) => k.startsWith(GC_NODES))) { + if (!this.#everReachable.has(key)) { + continue; + } + const since = this.#since.get(key); + if (since === undefined) { + this.problems.push(`deleted ${key} while the root reached it`); + } else if (this.#bucket.server - since < TREE_GC_SUPERSEDED_DELAY_MINUTES * MINUTE) { + this.problems.push( + `deleted ${key} ${(this.#bucket.server - since) / MINUTE} min after it became unreachable`, + ); + } + } + const missing = await this.#bucket.violations(); + this.problems.push(...missing); + await this.observe(); + } +} diff --git a/tests/fixtures/tree-mutants.ts b/tests/fixtures/tree-mutants.ts index 091b86b4..986668ef 100644 --- a/tests/fixtures/tree-mutants.ts +++ b/tests/fixtures/tree-mutants.ts @@ -17,6 +17,15 @@ import { import { sortMutationsById } from "../../packages/server/src/tree/plan.ts"; import { readTreeTail } from "../../packages/server/src/tree/read.ts"; import { foldRecordBase, foldRecordSuperseded } from "../../packages/server/src/tree/record.ts"; +import { classifyFloor } from "../../packages/server/src/tree/gc.ts"; +import { + keyOnlyMember, + TREE_GC_ROUTING, + type TreeGcRootView, + treeGcMembership, + treeGcMembershipVia, +} from "../../packages/server/src/tree/gc-member.ts"; +import { parseTreeNodeKey, treeNodeKeyPrefix } from "../../packages/server/src/tree/key.ts"; export interface TreeMutant { /** Stable name for test titles. */ @@ -422,3 +431,283 @@ export const READ_MUTANTS: readonly TreeMutant[] = [ RESTART_SKIPS_LEDGER, MISSING_NODE_SKIPS_LEDGER, ]; + +// --------------------------------------------------------------------- +// Artifact GC +// --------------------------------------------------------------------- + +/** A membership check that calls the current root's own key unreachable. */ +export const GC_IGNORES_LIVE_ROOT: TreeMutant = { + name: "gc-ignores-live-root", + defect: "membership treats the current root's own key as unreachable", + options: { + steps: { + gcIsMember: (x, view) => + x === view.root?.key ? Promise.resolve("non-member") : treeGcMembership(x, view), + }, + }, +}; + +/** A sweep that takes any key under the node prefix for a node key. */ +export const GC_DELETES_UNPARSEABLE_KEY: TreeMutant = { + name: "gc-deletes-unparseable-key", + defect: "the sweep deletes a listed key that does not parse as a node key", + options: { + steps: { + gcParsesKey: (prefix, key) => { + const tail = key.slice(treeNodeKeyPrefix(prefix).length); + return key.startsWith(treeNodeKeyPrefix(prefix)) + ? { attempt: tail.slice(0, 32), sha256: tail.slice(33) } + : null; + }, + }, + }, +}; + +/** GC that deletes any corrupt candidate, not just a known loser's. */ +export const GC_DELETES_CORRUPT_CANDIDATE: TreeMutant = { + name: "gc-deletes-corrupt-candidate", + defect: "a candidate whose body fails its hash or strict decode is deleted at depth 2 or more", + options: { steps: { gcOnCorrupt: () => true } }, +}; + +/** Membership by the root's child refs alone, at any depth. */ +export const GC_KEY_ONLY_MEMBERSHIP_AT_DEPTH_2: TreeMutant = { + name: "gc-key-only-membership-at-depth-2", + defect: "the key-only root-children rule is applied at depth 2", + options: { + steps: { + gcIsMember: async (x, view) => { + const parts = parseTreeNodeKey(view.prefix, x); + return parts !== null && keyOnlyMember(x, view.root, parts) ? "member" : "non-member"; + }, + }, + }, +}; + +/** A descent that stops one level too deep, at the candidate's own level. */ +export const GC_MEMBER_WRONG_LEVEL: TreeMutant = { + name: "gc-member-wrong-level", + defect: "the descent stops one level early or late", + options: { + steps: { + gcIsMember: (x, view) => + treeGcMembershipVia(x, view, { ...TREE_GC_ROUTING, parentLevel: (level) => level }, true), + }, + }, +}; + +/** A parent entry that names a candidate by attempt alone. */ +export const GC_MEMBER_ATTEMPT_ONLY: TreeMutant = { + name: "gc-member-attempt-only", + defect: "a parent entry matches the candidate by attempt alone", + options: { + steps: { + gcIsMember: (x, view) => + treeGcMembershipVia( + x, + view, + { ...TREE_GC_ROUTING, names: (entry, parts) => entry.attempt === parts.attempt }, + true, + ), + }, + }, +}; + +/** A missing or undecodable path node read as non-membership. */ +export const GC_PATH_MISS_AS_NONMEMBER: TreeMutant = { + name: "gc-path-miss-as-nonmember", + defect: "a missing or undecodable path node counts as non-membership", + options: { + steps: { + gcIsMember: async (x, view) => { + const found = await treeGcMembership(x, view); + return found === "path-unreadable" ? "non-member" : found; + }, + }, + }, +}; + +/** A recorded node deleted without any check against the current root. */ +export const GC_SKIPS_MEMBERSHIP_CHECK: TreeMutant = { + name: "gc-skips-membership-check", + defect: "a recorded node is deleted without checking the current root", + options: { steps: { gcIsMember: () => Promise.resolve("non-member") } }, +}; + +/** The root of the tick that noted each mark, remembered by key. */ +const notedViews = new Map(); + +/** A sweep that checks each mark against the root of the tick that noted it. */ +export const SWEEP_MEMBER_AGAINST_MARK_ROOT: TreeMutant = { + name: "sweep-member-against-mark-root", + defect: "the sweep checks membership against the root of the tick that noted the mark", + options: { + steps: { + sweepIsMember: (x, view, phase) => { + if (phase === "note") { + notedViews.set(x, view); + return treeGcMembership(x, view); + } + return treeGcMembership(x, notedViews.get(x) ?? view); + }, + }, + }, +}; + +/** A publisher that mints one identity and reuses it for every publication. */ +export const PUBLISH_REUSES_ATTEMPT: TreeMutant = { + name: "publish-reuses-attempt", + defect: "a publication reuses the identity of an earlier attempt that lost", + options: { steps: { mintAttempt: () => "a".repeat(32) } }, +}; + +/** GC that drains an attempt found in two records as a loser. */ +export const GC_IGNORES_DUPLICATE_IDENTITY: TreeMutant = { + name: "gc-ignores-duplicate-identity", + defect: "an attempt id present in two records is deleted as a loser", + options: { + steps: { + gcClassify: (members, evidence, duplicates) => { + const verdict = classifyFloor(members, evidence, duplicates); + return verdict.winner === null + ? verdict + : { + ...verdict, + losers: [...verdict.losers, ...members.filter((a) => duplicates.has(a))], + }; + }, + }, + }, +}; + +/** GC that treats the records at the head's own floor as closed. */ +export const GC_PROCESSES_OPEN_FLOOR: TreeMutant = { + name: "gc-processes-open-floor", + defect: "records at the head's own floor are treated as closed", + options: { steps: { gcIsClosed: (floor, headFloor) => floor <= headFloor } }, +}; + +/** GC that keeps its state across a generation change or a floor regression. */ +export const GC_IGNORES_GENERATION: TreeMutant = { + name: "gc-ignores-generation", + defect: "the GC state is kept across a generation change or floor regression", + options: { steps: { gcBindsHead: () => true } }, +}; + +/** GC that swaps a floor's winner with one of its losers. */ +export const GC_WINNER_AS_LOSER: TreeMutant = { + name: "gc-winner-as-loser", + defect: + "the winner of a floor is treated as a loser, so its fresh nodes are deleted with no delay", + options: { + steps: { + gcClassify: (members, evidence, duplicates) => { + const verdict = classifyFloor(members, evidence, duplicates); + const [swap, ...rest] = verdict.losers; + return verdict.winner === null || swap === undefined + ? verdict + : { ...verdict, winner: swap, losers: [verdict.winner, ...rest] }; + }, + }, + }, +}; + +/** GC that never drains a floor's losers. */ +export const GC_LOSER_AS_WINNER: TreeMutant = { + name: "gc-loser-as-winner", + defect: "a loser of a floor is treated as the winner, so its fresh nodes are never deleted", + options: { + steps: { + gcClassify: (members, evidence, duplicates) => ({ + ...classifyFloor(members, evidence, duplicates), + losers: [], + }), + }, + }, +}; + +/** GC that takes the first listed record of a floor as its winner. */ +export const GC_WINNER_BY_KEY_ORDER: TreeMutant = { + name: "gc-winner-by-key-order", + defect: "the winner of a floor is the first listed record, not head or successor evidence", + options: { + steps: { + gcClassify: (members, _evidence, duplicates) => { + const eligible = members.filter((a) => !duplicates.has(a)); + const [winner, ...losers] = eligible; + return winner === undefined + ? { winner: null, losers: [], ambiguous: false } + : { winner, losers, ambiguous: false }; + }, + }, + }, +}; + +/** GC that never waits for a due time. */ +export const GC_IGNORES_DUE_AT: TreeMutant = { + name: "gc-ignores-due-at", + defect: "superseded nodes are deleted in the tick that resolves their group", + options: { steps: { gcIsDue: () => true } }, +}; + +/** GC that reads its clock locally instead of from the storage server. */ +export const GC_LOCAL_CLOCK: TreeMutant = { + name: "gc-local-clock", + defect: "due times come from the local clock instead of storage server time", + options: { steps: { gcNow: (_serverDate, local) => local } }, +}; + +/** A sweep that stamps marks without a later fold moving the floor. */ +export const SWEEP_NO_FLOOR_GATE: TreeMutant = { + name: "sweep-no-floor-gate", + defect: "the sweep stamps or deletes a mark without a later fold moving the floor", + options: { steps: { sweepPassesFloorGate: () => true } }, +}; + +/** A probe tick that reads the head before it lists the sweep page. */ +export const SWEEP_FLOOR_BEFORE_LIST: TreeMutant = { + name: "sweep-floor-before-list", + defect: "the sweep notes marks with a head floor read before its LIST", + options: { steps: { sweepListsBeforeHead: () => false } }, +}; + +/** A sweep that starts a mark's age when it notes it. */ +export const SWEEP_AGE_FROM_NOTE: TreeMutant = { + name: "sweep-age-from-note", + defect: "the sweep's age starts when a mark is noted, not when it is stamped", + options: { steps: { sweepStartsAge: (phase) => phase === "note" } }, +}; + +/** GC that calls a candidate corrupt on its first failed read. */ +export const GC_CORRUPT_NO_RETRY: TreeMutant = { + name: "gc-corrupt-no-retry", + defect: "a candidate's failed GET is not retried before it is counted corrupt", + options: { steps: { gcRetriesCorrupt: () => false } }, +}; + +/** The GC mutants the GC suite must catch. */ +export const GC_MUTANTS: readonly TreeMutant[] = [ + GC_IGNORES_LIVE_ROOT, + GC_DELETES_UNPARSEABLE_KEY, + GC_DELETES_CORRUPT_CANDIDATE, + GC_KEY_ONLY_MEMBERSHIP_AT_DEPTH_2, + GC_MEMBER_WRONG_LEVEL, + GC_MEMBER_ATTEMPT_ONLY, + GC_PATH_MISS_AS_NONMEMBER, + SWEEP_MEMBER_AGAINST_MARK_ROOT, + GC_SKIPS_MEMBERSHIP_CHECK, + PUBLISH_REUSES_ATTEMPT, + GC_IGNORES_DUPLICATE_IDENTITY, + GC_PROCESSES_OPEN_FLOOR, + GC_IGNORES_GENERATION, + GC_WINNER_AS_LOSER, + GC_LOSER_AS_WINNER, + GC_WINNER_BY_KEY_ORDER, + GC_IGNORES_DUE_AT, + GC_LOCAL_CLOCK, + SWEEP_NO_FLOOR_GATE, + SWEEP_FLOOR_BEFORE_LIST, + SWEEP_AGE_FROM_NOTE, + GC_CORRUPT_NO_RETRY, +]; From d1ba6b2e08a7ac4b2a3ef4462b37e2162b84a4ae Mon Sep 17 00:00:00 2001 From: Eric Baer Date: Tue, 24 Nov 2026 11:17:32 -0800 Subject: [PATCH 04/15] bench(tree): model the tree GC tick in the op model Add the tree GC tick's static bound, 43 + K x c(d) plus log retirement, with c(d) = 3 at depth 0 and 1 and 3(d + 1) above, and the Class A writes tree GC adds per minute (a record create and at most one resolving state write per fold, at most two state writes per probe minute). Tests pin the bound at 64 checks for depths 0 to 4, 4,720 calls at 512 checks on depth 2, and agreement with the tick's own sizing. --- bench/tree-op-model/model.test.ts | 27 +++++++++++++++++++++ bench/tree-op-model/model.ts | 39 +++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/bench/tree-op-model/model.test.ts b/bench/tree-op-model/model.test.ts index b3736144..0e05b629 100644 --- a/bench/tree-op-model/model.test.ts +++ b/bench/tree-op-model/model.test.ts @@ -9,6 +9,8 @@ import { WRITE_TICK_FOLD_ENTRIES_PER_PASS, WRITE_TICK_GC_MAX_SWEEPS, } from "@baerly/protocol"; +import { TREE_GC_TICK_RESERVED_CALLS } from "../../packages/server/src/tree/constants.ts"; +import { treeGcCandidateCharge } from "../../packages/server/src/tree/gc.ts"; import { loadRequestCountSnapshot, parseCell } from "../../scripts/request-counts.ts"; import { ALL_ATTEMPTS, @@ -22,6 +24,9 @@ import { findLogTailGets, FOLD_RECORD_CREATES, foldTickCalls, + treeGcCandidateCalls, + treeGcClassAPerMinute, + treeGcTickBound, GC_WORST_STATE, gcTickCalls, type GcTickState, @@ -424,3 +429,25 @@ describe("Paid ledger", () => { }, ); }); + +describe("tree GC tick", () => { + test("the static bound at 64 checks, depth 0 to 4, and at 512 checks on depth 2", () => { + expect([0, 1, 2, 3, 4].map((d) => treeGcTickBound(64, d, false) - 3)).toEqual([ + 235, 235, 619, 811, 1003, + ]); + expect(treeGcTickBound(64, 1, true)).toBe(304); + expect(treeGcTickBound(512, 2, true)).toBe(4720); + expect(treeGcTickBound(64, 0, true)).toBeLessThanOrEqual(900); + }); + + test("the model agrees with the tick's own sizing", () => { + for (const depth of [0, 1, 2, 3]) { + expect(treeGcCandidateCalls(depth)).toBe(treeGcCandidateCharge(depth)); + } + expect(treeGcTickBound(0, 0, true)).toBe(TREE_GC_TICK_RESERVED_CALLS); + }); + + test("tree GC adds about four Class A writes a minute at one fold a minute, whatever the write rate", () => { + expect(treeGcClassAPerMinute(1)).toBe(4); + }); +}); diff --git a/bench/tree-op-model/model.ts b/bench/tree-op-model/model.ts index 665585dc..4bad4049 100644 --- a/bench/tree-op-model/model.ts +++ b/bench/tree-op-model/model.ts @@ -580,6 +580,45 @@ export const gcTickCalls = (input: GcTickInput): Calls => { ); }; +// ── Tree GC tick ───────────────────────────────────────────────────────── + +/** + * Charged calls of one tree GC candidate check at root level `depth`: + * its DELETE plus its membership GETs, each charged at every attempt. + * At depth 0 or 1 membership is decided from the key alone; above, a + * check GETs the candidate and at most `depth − 1` path nodes + * (`packages/server/src/tree/gc-member.ts`). + */ +export const treeGcCandidateCalls = (depth: number): number => + depth <= 1 ? STORAGE_RETRY_MAX_ATTEMPTS : STORAGE_RETRY_MAX_ATTEMPTS * (depth + 1); + +/** + * The static bound on one tree GC tick's charged calls with `candidates` + * checks at root level `depth` (`packages/server/src/tree/gc.ts`): the + * state GET, the sweep and record LISTs, the head and root GETs, 4 + * record GETs and 4 record DELETEs (each charged at every attempt), one + * state create (retried) and one state CAS (sent once), the checks, and + * log retirement (its gate GET alone, or 69 when it finds work). + */ +export const treeGcTickBound = ( + candidates: number, + depth: number, + retirementFindsWork: boolean, +): number => { + const a = STORAGE_RETRY_MAX_ATTEMPTS; + const fixed = 5 * a + 4 * a + 4 * a + a + 1; + const retire = retirementFindsWork ? 3 * a + 20 * a : a; + return fixed + candidates * treeGcCandidateCalls(depth) + retire; +}; + +/** + * Class A writes per minute that tree GC adds, at `foldsPerMinute` folds + * a minute: each fold attempt's record create, at most one state write + * to resolve its floor, and at most two state writes per clock probe, + * one probe a minute. Independent of the app's write rate. + */ +export const treeGcClassAPerMinute = (foldsPerMinute: number): number => foldsPerMinute * 2 + 2; + // ── Reads ──────────────────────────────────────────────────────────────── export interface ReadInput { From 7f7e4f0978c9b939ee6956c821f9e0068852fb2e Mon Sep 17 00:00:00 2001 From: Eric Baer Date: Tue, 24 Nov 2026 11:58:01 -0800 Subject: [PATCH 05/15] fix(tree): close the tree GC identity, budget and state gaps - An identity that appears in two records, or has a record on an open floor, is never a deletion source: a loser entry naming one is cleared before it drains, every record of a duplicated identity is retired leak-only (a named loser no longer exempts it), a winner of one is quarantined, and the sweep neither notes, stamps nor deletes its nodes. Before, a duplicate found after a loser entry was assigned still drained it, and a stamped mark could be deleted after an attempt reusing its identity adopted the key. - The sweep page's notes count toward the tick's candidate checks: a short ledger shortens the page, and the cursor moves past only the keys examined. Before, a probe tick with room for one check made sixteen. - A state naming another format, or this format at any schema version but 1, pauses GC with InvalidResponse instead of being replaced, so no build wipes a state it cannot read. - The membership check answers "not-a-node", never "non-member", for a key that does not parse. Tests cover each schedule (red against the previous tick), plus record generations as evidence, a late supersession of a dropped mark and winner quarantine when the record DELETE cap runs out. The mutation block now rejects a red that is only an unexplained throw, and the open-floor check asserts the leak it causes. Sweep scenarios hide the in-flight record from LIST, so they test the floor gate rather than the open-floor guard. --- packages/server/src/tree/gc-member.ts | 9 +- packages/server/src/tree/gc-state.test.ts | 15 +- packages/server/src/tree/gc-state.ts | 36 ++- packages/server/src/tree/gc.test.ts | 322 +++++++++++++++++++++- packages/server/src/tree/gc.ts | 86 ++++-- packages/server/src/tree/layout.ts | 10 + tests/fixtures/tree-gc-harness.ts | 37 ++- tests/fixtures/tree-mutants.ts | 18 +- 8 files changed, 457 insertions(+), 76 deletions(-) diff --git a/packages/server/src/tree/gc-member.ts b/packages/server/src/tree/gc-member.ts index d21c99af..97eaf0de 100644 --- a/packages/server/src/tree/gc-member.ts +++ b/packages/server/src/tree/gc-member.ts @@ -44,7 +44,9 @@ export type TreeGcMembership = /** The node's body failed once and decoded on the re-read: left for later. */ | "deferred" /** A node on the path from the root is missing or undecodable: proves nothing. */ - | "path-unreadable"; + | "path-unreadable" + /** The key is not a node key of the collection: never deleted. */ + | "not-a-node"; /** The root a GC tick read, and how to fetch what a check needs. */ export interface TreeGcRootView { @@ -185,7 +187,10 @@ export const treeGcMembershipVia = async ( retriesCorrupt: boolean, ): Promise => { const parts = parseTreeNodeKey(view.prefix, x); - if (parts === null || view.root === null) { + if (parts === null) { + return "not-a-node"; + } + if (view.root === null) { return "non-member"; } if (x === view.root.key) { diff --git a/packages/server/src/tree/gc-state.test.ts b/packages/server/src/tree/gc-state.test.ts index a409ec0c..85aeb29b 100644 --- a/packages/server/src/tree/gc-state.test.ts +++ b/packages/server/src/tree/gc-state.test.ts @@ -89,13 +89,12 @@ describe("tree GC state", () => { expect(decodeTreeGcState(KEY, body).kind).toBe("malformed"); }); - test("a non-canonical body, another format or a non-number schema is malformed", () => { + test("a non-canonical body, an unknown field or a body with no format is malformed", () => { const text = new TextDecoder().decode(encodeTreeGcState(FULL)); for (const body of [ text.replace(",", ", "), text.replace('"ticks":7', '"ticks":7,"extra":1'), - text.replace("gc-state-proto", "gc-state-other"), - text.replace('"schema_version":1', '"schema_version":"1"'), + '{"schema_version":1}', "[]", "{", ]) { @@ -103,10 +102,12 @@ describe("tree GC state", () => { } }); - test("a state of another schema version is InvalidResponse that says GC is paused", () => { - const body = new TextDecoder() - .decode(encodeTreeGcState(FULL)) - .replace('"schema_version":1', '"schema_version":2'); + test.each([ + ['"schema_version":2', '"schema_version":1'], + ['"schema_version":"1"', '"schema_version":1'], + ["gc-state-other", "gc-state-proto"], + ])("a state with %s is InvalidResponse that says GC is paused, never replaced", (to, from) => { + const body = new TextDecoder().decode(encodeTreeGcState(FULL)).replace(from, to); expect(() => decodeTreeGcState(KEY, new TextEncoder().encode(body))).toThrow( expect.objectContaining({ code: "InvalidResponse", diff --git a/packages/server/src/tree/gc-state.ts b/packages/server/src/tree/gc-state.ts index 625aef2e..481829e8 100644 --- a/packages/server/src/tree/gc-state.ts +++ b/packages/server/src/tree/gc-state.ts @@ -252,12 +252,13 @@ const malformed = (reason: string): TreeGcStateDecode => ({ kind: "malformed", r /** * Strictly decode the state body `bytes` read from `key`. A malformed - * state is a value, because GC replaces it leak-only; only a state of - * this format with a `schema_version` this build does not know throws. + * state is a value, because GC replaces it leak-only. A state that names + * a format this build does not read, or this format at another + * `schema_version`, throws instead: it may be a newer release's, and GC + * pauses rather than wipe it. * - * @throws BaerlyError code="InvalidResponse" — the state has this - * format and an unknown `schema_version`: it was written by another - * release, so GC for this collection is paused. + * @throws BaerlyError code="InvalidResponse" — the state names another + * format or schema version, so GC for this collection is paused. */ export const decodeTreeGcState = (key: string, bytes: Uint8Array): TreeGcStateDecode => { if (bytes.byteLength > TREE_GC_STATE_MAX_BODY_BYTES) { @@ -269,21 +270,26 @@ export const decodeTreeGcState = (key: string, bytes: Uint8Array): TreeGcStateDe } catch { return malformed("the body is not UTF-8 JSON"); } - if (!isPlainObject(value) || value["format"] !== TREE_GC_STATE_FORMAT) { + if (!isPlainObject(value) || typeof value["format"] !== "string") { return malformed("the body is not a tree GC state"); } + // Another format, or this one at another schema version, may be a newer + // release's state: pause rather than replace it, so no build ever wipes + // a state it cannot read. const version = value["schema_version"]; - if (typeof version !== "number") { - return malformed("schema_version is not a number"); - } - if (version !== TREE_GC_STATE_SCHEMA_VERSION) { + if (value["format"] !== TREE_GC_STATE_FORMAT || version !== TREE_GC_STATE_SCHEMA_VERSION) { + const where = `tree GC state ${JSON.stringify(key)}`; + const detail = + value["format"] === TREE_GC_STATE_FORMAT + ? unsupportedSchemaVersionMessage( + where, + typeof version === "number" ? version : "a non-number", + TREE_GC_STATE_SCHEMA_VERSION, + ) + : `${where}: format ${JSON.stringify(String(value["format"]).slice(0, 64))} is not one this build reads.`; throw new BaerlyError( "InvalidResponse", - `${unsupportedSchemaVersionMessage( - `tree GC state ${JSON.stringify(key)}`, - version, - TREE_GC_STATE_SCHEMA_VERSION, - )} GC for this collection was written by a newer release and is paused.`, + `${detail} GC for this collection was written by a newer release and is paused.`, { resolution: "Run the app or operator CLI at that release or later." }, ); } diff --git a/packages/server/src/tree/gc.test.ts b/packages/server/src/tree/gc.test.ts index 02eb10b4..e570cdba 100644 --- a/packages/server/src/tree/gc.test.ts +++ b/packages/server/src/tree/gc.test.ts @@ -68,6 +68,8 @@ import { runTreeGcTick, treeGcCandidateCharge, treeGcCandidates } from "./gc.ts" import { createTreeGcRootView, type TreeGcMembership, treeGcMembership } from "./gc-member.ts"; import { emptyTreeGcState, encodeTreeGcState } from "./gc-state.ts"; import { readTreeHead, readTreeRoot } from "./head.ts"; +import { createTreeConfig } from "./layout.ts"; +import { sealFoldRecord } from "./record.ts"; import { openTreeView } from "./read.ts"; const MIXED: readonly GcChange[] = [ @@ -77,14 +79,33 @@ const MIXED: readonly GcChange[] = [ ]; const DELAY = TREE_GC_SUPERSEDED_DELAY_MINUTES; + +/** + * A ledger with room for exactly one candidate check at depth 3, after + * the four calls a probe tick makes before it sizes its checks (the + * state GET, the sweep LIST, the head and root GETs), each charged at + * every attempt. + */ +const ONE_CHECK_LEDGER = TREE_GC_TICK_RESERVED_CALLS + 4 * 3 + 12; const AGE = TREE_GC_SWEEP_AGE_MINUTES; const LONG = 60_000; -/** Run `check`, turning a throw into a failure message. */ +/** + * Run `check`, turning a throw into a failure message: a read that found + * a node the root names missing is reported as that, anything else as a + * throw, which the mutation block accepts only where it says so. + */ const guarded = async (check: () => Promise): Promise => { try { return await check(); } catch (error) { + if ( + error instanceof BaerlyError && + error.code === "InvalidResponse" && + /missing|absent/.test(error.message) + ) { + return `a read met a missing node: ${error.message}`; + } return `threw ${String(error)}`; } }; @@ -304,23 +325,35 @@ const reuseCounterFailure = (mutant?: TreeMutant) => return duplicates === 0 ? undefined : `${duplicates} duplicate identities`; }); -/** An attempt in flight at the head's floor is neither resolved nor stuck, and its nodes survive. */ +/** + * An attempt in flight at the head's floor for longer than the sweep + * age is neither resolved nor stuck, and once it lands everything it + * recorded is reclaimed. Treating the open floor as closed cannot + * delete here (no evidence ever names an attempt still in flight), but + * it marks the floor stuck, ages it out and retires the attempt's + * record leak-only, so what the attempt superseded leaks. + */ const openFloorFailure = (mutant?: TreeMutant) => guarded(async () => { const bucket = await GcBucket.seeded(); const flight = await bucket.startFold([["k05", 55]]); const problems: string[] = []; - for (let i = 0; i < 3; i++) { + for (let i = 0; i < AGE + 5; i++) { bucket.advance(1); await bucket.tick(gcConfig(mutant)); const state = await bucket.state(); const stuck = state?.stuck ?? null; - if (stuck !== null) { + if (stuck !== null && i === 0) { problems.push(`floor ${stuck.floor} marked stuck`); } } await flight.release(); - problems.push(...(await bucket.violations())); + bucket.advance(1); + await reclaim(bucket, gcConfig(mutant)); + const left = await reclaimedProblems(bucket); + if (left !== undefined) { + problems.push(left); + } return joined(problems); }); @@ -357,7 +390,10 @@ const regenerationFailure = (mutant?: TreeMutant) => * The sweep reclaims nodes no record names (a lost attempt whose record * is gone), leaves keys that do not parse, counting them, and never * deletes a node the root reaches or one sooner than the delay after it - * became unreachable. + * became unreachable. A sweep that took a stray key for a node would + * not count it, and would hand it to the membership check, which never + * answers "delete" for a key that does not parse; so that defect shows + * here as the missing count, with the strays still in place. */ const sweepFailure = (mutant?: TreeMutant) => guarded(async () => { @@ -417,9 +453,12 @@ const sweepInFlightFailure = (mutant?: TreeMutant) => const bucket = await GcBucket.seeded(); const watch = new MarginWatch(bucket); await watch.observe(); + // The attempt's record lags in LIST, so only the floor gate protects its nodes. + bucket.listLag.add("0".repeat(32)); const flight = await bucket.startFold([["k08", 88]], { attempt: "0".repeat(32) }); await bucket.tickFor(AGE + 10, gcConfig(mutant), watch); await flight.release(); + bucket.listLag.clear(); const problems = [...(await bucket.violations())]; await watch.observe(); await bucket.fold([["k12", 12]]); @@ -439,9 +478,11 @@ const supersededAfterNoteFailure = (mutant?: TreeMutant) => const bucket = await GcBucket.seeded(); const watch = new MarginWatch(bucket); await watch.observe(); + bucket.listLag.add("0".repeat(32)); const flight = await bucket.startFold([["k08", 88]], { attempt: "0".repeat(32) }); await bucket.tickFor(30, gcConfig(mutant), watch); await flight.release(); + bucket.listLag.clear(); await watch.observe(); await bucket.tickFor(28, gcConfig(mutant), watch); await bucket.fold([["k08", 89]]); @@ -459,6 +500,7 @@ const floorBeforeListFailure = (mutant?: TreeMutant) => guarded(async () => { const bucket = await GcBucket.seeded(); let flight: Awaited> | undefined; + bucket.listLag.add("0".repeat(32)); bucket.onList.set(GC_NODES, async () => { await bucket.fold([["k19", 1]]); flight = await bucket.startFold([["k02", 2]], { attempt: "0".repeat(32) }); @@ -470,6 +512,7 @@ const floorBeforeListFailure = (mutant?: TreeMutant) => return "setup: the LIST hook never ran"; } await flight.release(); + bucket.listLag.clear(); return joined([...watch.problems, ...(await bucket.violations())]); }); @@ -553,6 +596,196 @@ const freshOf = async (bucket: GcBucket, attempt: string): Promise => return keys.filter((key) => key.startsWith(`${GC_NODES}${attempt}/`)); }; +/** + * A duplicate identity found only after its loser entry was assigned: + * X loses a floor; a tick with room for one check resolves the floor and + * names X's record as the loser to drain, but drains nothing; then an + * attempt reusing X starts, adopting X's existing leaf. The next tick + * must not drain X's fresh nodes, and the reusing attempt's CAS lands on + * a complete tree. + */ +const lateDuplicateFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const reused = "a".repeat(32); + const loser = await bucket.prepare([["k03", 5]]); + await bucket.fold([["k19", 119]], { attempt: "b".repeat(32) }); + await bucket.publish(loser, { attempt: reused }); + // Room for one check: the probe's sweep page takes it. + const first = await bucket.tickWithLedger(ONE_CHECK_LEDGER, gcConfig(mutant)); + const state = await bucket.state(); + const entry = state?.work.find((w) => w.floor === 20); + if (first.result.candidates !== 1 || entry?.loser?.record.slice(0, 32) !== reused) { + return `setup: candidates ${first.result.candidates}, entry ${JSON.stringify(entry)}`; + } + const retry = await bucket.startFold([["k03", 5]], { attempt: reused }); + bucket.advance(1); + await bucket.tick(gcConfig(mutant)); + const outcome = await retry.release(); + if (outcome.kind !== "published" || outcome.adopted === 0) { + return `setup: the retry was ${outcome.kind}, adopting ${outcome.adopted}`; + } + return joined(await bucket.violations()); + }); + +/** + * A lost attempt's record is gone, so the sweep marks and stamps its + * nodes; before they are due an attempt reusing its identity starts and + * adopts one of them. The sweep must not delete it while that attempt + * can still land. + */ +const sweepReuseFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const reused = "a".repeat(32); + const loser = await bucket.prepare([["k07", 77]]); + await bucket.fold([["k12", 12]]); + const lost = await bucket.publish(loser, { attempt: reused }); + await bucket.memory.delete(lost.record); + let stamped = false; + for (let minute = 0; minute < 40 && !stamped; minute++) { + if (minute === 5) { + await bucket.fold([["k19", 19]]); + } + bucket.advance(1); + await bucket.tick(gcConfig(mutant)); + const state = await bucket.state(); + stamped = (state?.sweep.marks ?? []).some( + (mark) => mark.key.startsWith(reused) && mark.due_at !== null, + ); + } + if (!stamped) { + return "setup: no mark of the lost attempt was stamped"; + } + const retry = await bucket.startFold([["k07", 77]], { attempt: reused }); + await bucket.tickFor(AGE + 5, gcConfig(mutant)); + const outcome = await retry.release(); + if (outcome.kind !== "published" || outcome.adopted === 0) { + return `setup: the retry was ${outcome.kind}, adopting ${outcome.adopted}`; + } + return joined(await bucket.violations()); + }); + +/** + * A probe tick on a nearly spent ledger, at depth 3 with room for one + * check, stays within the static bound for that one check: the sweep + * page shrinks to fit instead of checking every listed key. + */ +const nearFullLedgerFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + await bucket.fold(MIXED); + let checks = 0; + const counted = gcConfig(mutant); + const isMember = counted.steps.gcIsMember ?? treeGcMembership; + const config = createTreeConfig({ + layout: counted.layout, + steps: { + ...counted.steps, + gcIsMember: (x, view) => { + checks += 1; + return isMember(x, view); + }, + }, + }); + const { result, charged } = await bucket.tickWithLedger(ONE_CHECK_LEDGER, config); + if (result.candidates !== 1 || !result.probed) { + return `setup: ${result.candidates} candidates, probed ${result.probed}`; + } + const bound = TREE_GC_TICK_RESERVED_CALLS + result.candidates * treeGcCandidateCharge(3); + const problems: string[] = []; + if (checks > result.candidates) { + problems.push(`${checks} candidate checks with room for ${result.candidates}`); + } + if (charged > bound) { + problems.push(`charged ${charged} of a ${bound}-call bound`); + } + return joined(problems); + }); + +/** + * A record of another head history at the floor a new history's floor + * resolves against: it is never the evidence that names the new floor's + * winner, so the new winner's fresh nodes are not deleted as a loser's. + */ +const generationWitnessFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded("0a"); + await bucket.fold(MIXED); + // Re-seed a new history over the old records, none reclaimed. + await bucket.memory.put(GC_HEAD, encodeJsonBytes(freshGcHead("0b"))); + bucket.rows.clear(); + const watch = new MarginWatch(bucket); + await bucket.fold(GC_SEED); + await watch.observe(); + await bucket.fold(MIXED); + await watch.observe(); + for (let i = 0; i < 4; i++) { + bucket.advance(1); + const { result } = await bucket.tick(gcConfig(mutant)); + await watch.afterTick(result.deleted); + } + return joined(watch.problems); + }); + +/** + * A node noted while its attempt was in flight is a member once the + * attempt lands, so it is dropped, not stamped: a fold that supersedes + * it late in what would have been its age leaves it the full delay. + */ +const lateSupersedeFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const watch = new MarginWatch(bucket); + await watch.observe(); + bucket.listLag.add("0".repeat(32)); + const flight = await bucket.startFold([["k08", 88]], { attempt: "0".repeat(32) }); + await bucket.tickFor(10, gcConfig(mutant), watch); + await flight.release(); + bucket.listLag.clear(); + await watch.observe(); + // A fold moves the floor, so the next probe judges every noted mark. + await bucket.fold([["k19", 19]]); + await watch.observe(); + await bucket.tickFor(AGE - 8, gcConfig(mutant), watch); + await bucket.fold([["k08", 89]]); + await watch.observe(); + await bucket.tickFor(30, gcConfig(mutant), watch); + return joined(watch.problems); + }); + +/** + * A winner whose identity shows up in other records while its list is + * still pending is never a deletion source, even in a tick whose record + * DELETEs run out before its own record is retired. + */ +const quarantineFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const winner = "c".repeat(32); + const before = await bucket.reachable(); + await bucket.fold(MIXED, { attempt: winner }); + const superseded = await supersededSince(bucket, before); + await bucket.tick(gcConfig(mutant)); + // Five more records under the winner's identity, all sorting before its own. + for (let floor = 1; floor <= 5; floor++) { + const sealed = await sealFoldRecord(GC_PREFIX, { + attempt: winner, + base: { floor, root: null, attempt: null, generation: null }, + result: { floor: floor + 1, root: null }, + fresh: [], + superseded: [], + }); + await bucket.memory.put(sealed.key, sealed.bytes); + } + bucket.advance(DELAY + 1); + const { result } = await bucket.tick(gcConfig(mutant)); + const taken = result.deleted.filter((key) => superseded.includes(key)); + return taken.length === 0 + ? undefined + : `deleted ${taken.length} of the winner's superseded nodes`; + }); + // --------------------------------------------------------------------- // Record path // --------------------------------------------------------------------- @@ -692,6 +925,21 @@ describe("membership", () => { await expect(membershipFailure()).resolves.toBeUndefined(); }); + test("a key that does not parse as a node key is never answered with non-member", async () => { + const bucket = await GcBucket.seeded(); + const config = gcConfig(); + const head = (await readTreeHead(bucket.storage, GC_PREFIX))!; + const root = await readTreeRoot(bucket.storage, head, config); + const view = createTreeGcRootView(bucket.storage, GC_PREFIX, root, config); + for (const key of [ + `${GC_NODES}${gcAttemptOf(9)}/${"0".repeat(64)}.json`, + `${GC_NODES}${"A".repeat(32)}/${"0".repeat(64)}`, + `${GC_RECORDS}0000000000000000/${gcAttemptOf(9)}/${"0".repeat(64)}`, + ]) { + await expect(treeGcMembership(key, view)).resolves.toBe("not-a-node"); + } + }); + test("at depth 0 and 1 membership reads no body", async () => { const bucket = await GcBucket.open(); await bucket.fold([ @@ -728,6 +976,26 @@ describe("attempt identity and closure", () => { await expect(reuseFailure()).resolves.toBeUndefined(); }); + test("a duplicate found after its loser entry was assigned stops that loser's drain", async () => { + await expect(lateDuplicateFailure()).resolves.toBeUndefined(); + }); + + test( + "the sweep never deletes a node of an identity a publication still in flight holds", + async () => { + await expect(sweepReuseFailure()).resolves.toBeUndefined(); + }, + LONG, + ); + + test("a winner whose identity reappears is quarantined even when its record outlives the tick", async () => { + await expect(quarantineFailure()).resolves.toBeUndefined(); + }); + + test("a record of another head history is never evidence for the new history's winner", async () => { + await expect(generationWitnessFailure()).resolves.toBeUndefined(); + }); + test("an identity in two records is counted, warned and its records retired leak-only", async () => { const bucket = await GcBucket.seeded(); const reused = "a".repeat(32); @@ -805,6 +1073,14 @@ describe("leak sweep", () => { LONG, ); + test( + "a noted node that becomes a member is dropped, so a late supersession still gets the full delay", + async () => { + await expect(lateSupersedeFailure()).resolves.toBeUndefined(); + }, + LONG, + ); + test( "a fold that lands around a probe's LIST and head GET cannot expose an attempt in flight", async () => { @@ -845,7 +1121,10 @@ describe("state and clock", () => { const bucket = await GcBucket.seeded(); await bucket.fold(MIXED); const nodes = await bucket.keys(GC_NODES); - await bucket.memory.put(GC_STATE, encodeJsonBytes({ format: "baerly-tree-gc-state-proto" })); + await bucket.memory.put( + GC_STATE, + encodeJsonBytes({ format: "baerly-tree-gc-state-proto", schema_version: 1, ticks: -1 }), + ); await expect(bucket.tick()).resolves.toMatchObject({ result: { outcome: "reset", deleted: [] }, }); @@ -853,12 +1132,13 @@ describe("state and clock", () => { await expect(bucket.keys(GC_NODES)).resolves.toEqual(nodes); }); - test("a state of a newer schema stops the tick with InvalidResponse and no write", async () => { + test.each([ + ["a newer schema", { format: "baerly-tree-gc-state-proto", schema_version: 2 }], + ["a non-number schema", { format: "baerly-tree-gc-state-proto", schema_version: "2" }], + ["another format", { format: "baerly-tree-gc-state-next", schema_version: 1 }], + ])("a state of %s stops the tick with InvalidResponse and no write", async (_name, body) => { const bucket = await GcBucket.seeded(); - await bucket.memory.put( - GC_STATE, - encodeJsonBytes({ format: "baerly-tree-gc-state-proto", schema_version: 2 }), - ); + await bucket.memory.put(GC_STATE, encodeJsonBytes(body)); const before = await bucket.memory.get(GC_STATE); const error = await bucket.tick().catch((error_: unknown) => error_); expect(error).toBeInstanceOf(BaerlyError); @@ -896,6 +1176,10 @@ describe("budget", () => { expect(treeGcCandidates(0, TREE_GC_TICK_RESERVED_CALLS + 2)).toBe(0); }); + test("a probe tick on a nearly spent ledger shortens its sweep page to fit its one check", async () => { + await expect(nearFullLedgerFailure()).resolves.toBeUndefined(); + }); + test("a ledger with no room for one candidate check skips the tick, counted", async () => { const bucket = await GcBucket.seeded(); const ledger = new RequestLedger({ internal: 30, external: 30 }); @@ -986,7 +1270,7 @@ describe("mutation", () => { [SWEEP_MEMBER_AGAINST_MARK_ROOT, [sweepInFlightFailure]], [GC_SKIPS_MEMBERSHIP_CHECK, [membershipFailure, withReusedNode(reclaimFailure)]], [PUBLISH_REUSES_ATTEMPT, [reuseCounterFailure]], - [GC_IGNORES_DUPLICATE_IDENTITY, [reuseFailure]], + [GC_IGNORES_DUPLICATE_IDENTITY, [reuseFailure, lateDuplicateFailure, sweepReuseFailure]], [GC_PROCESSES_OPEN_FLOOR, [openFloorFailure]], [GC_IGNORES_GENERATION, [regenerationFailure]], [GC_WINNER_AS_LOSER, [raceFailure]], @@ -1008,11 +1292,21 @@ describe("mutation", () => { await expect(withReusedNode(reclaimFailure)()).resolves.toBeUndefined(); }); + /** Mutants whose only consequence is a throw, and the throw each must raise; none today. */ + const throws = new Map(); + test.each(GC_MUTANTS.map((mutant) => [mutant.name, mutant] as const))( "%s turns its checks red", async (_name, mutant) => { for (const check of checks.get(mutant)!) { - await expect(check(mutant)).resolves.toBeDefined(); + const found = await check(mutant); + expect(found).toBeDefined(); + const expected = throws.get(mutant); + if (expected === undefined) { + expect(found).not.toMatch(/^threw /); + } else { + expect(found).toMatch(expected); + } } }, 2 * LONG, diff --git a/packages/server/src/tree/gc.ts b/packages/server/src/tree/gc.ts index 9631a089..c81a3a21 100644 --- a/packages/server/src/tree/gc.ts +++ b/packages/server/src/tree/gc.ts @@ -32,8 +32,9 @@ * **State.** `

/_v99/gc-pending.json` (`./gc-state.ts`) holds * progress, bound to the head's `generation` and floor. A state of * another history, or a malformed one, is replaced leak-only by the - * empty state; one of an unknown schema version stops the tick with - * `InvalidResponse`. + * empty state; one that names another format or schema version, which + * may be a newer release's, stops the tick with `InvalidResponse` and is + * left as it is. * * **Clock.** The only clock is the `serverDate` of GC's own state write. * A tick probes it (a state CAS) at most once per @@ -125,6 +126,17 @@ export const classifyFloor = ( return { winner, losers: eligible.filter((attempt) => attempt !== winner), ambiguous: false }; }; +/** + * Whether GC may delete by attempt `attempt`: not when it appears in + * more than one listed record (an identity reused), nor while it has a + * record on an open floor (it may still publish and adopt its keys). + */ +export const trustsIdentity = ( + attempt: string, + duplicates: ReadonlySet, + open: ReadonlySet, +): boolean => !duplicates.has(attempt) && !open.has(attempt); + /** Whether `dueAt` is at or before server time `now`; nothing is due without both. */ export const isDueAt = (dueAt: string | null, now: Date | undefined): boolean => dueAt !== null && now !== undefined && Date.parse(dueAt) <= now.getTime(); @@ -162,6 +174,7 @@ interface GcSteps { readonly passesFloorGate: NonNullable; readonly startsAge: NonNullable; readonly listsBeforeHead: NonNullable; + readonly trustsIdentity: NonNullable; } const gcSteps = (config: TreeConfig): GcSteps => { @@ -180,6 +193,7 @@ const gcSteps = (config: TreeConfig): GcSteps => { passesFloorGate: s.sweepPassesFloorGate ?? ((markFloor, headFloor) => headFloor > markFloor), startsAge: s.sweepStartsAge ?? ((phase) => phase === "stamp"), listsBeforeHead: s.sweepListsBeforeHead ?? (() => true), + trustsIdentity: s.gcTrustsIdentity ?? trustsIdentity, }; }; @@ -276,8 +290,8 @@ const isUnknownFate = (error: unknown): boolean => * module comment. * * @throws BaerlyError code="InvalidResponse" — the head or root is not a - * valid tree, or the GC state was written by a release with a newer - * state schema. + * valid tree, or the GC state names a format or schema version this + * build does not read. * @throws BaerlyError — a storage call fails, with its code. A lost * state write is an outcome, not an error. */ @@ -475,9 +489,19 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise a - b); const evidence = new Set(head.attempt === null ? [] : [head.attempt]); - const work: TreeGcWork[] = base.work.map((entry) => - duplicates.has(entry.winner.slice(0, 32)) ? { ...entry, quarantined: true } : entry, + // An identity found in two records, or one still publishing on an open + // floor, is never a deletion source: a later attempt may hold its keys. + const open = new Set( + records.filter((record) => !steps.isClosed(record.floor, h)).map((r) => r.attempt), ); + const deletable = (attempt: string): boolean => steps.trustsIdentity(attempt, duplicates, open); + const untrusted = new Set([...duplicates].filter((attempt) => !deletable(attempt))); + const work: TreeGcWork[] = base.work.map((entry) => { + const quarantined = entry.quarantined || !deletable(entry.winner.slice(0, 32)); + const loser = + entry.loser !== null && deletable(entry.loser.record.slice(0, 32)) ? entry.loser : null; + return { ...entry, quarantined, loser }; + }); let resolvedThrough = base.resolved_through; let stuck = base.stuck; const lastClock = base.clock === null ? undefined : new Date(base.clock); @@ -493,7 +517,7 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise record.attempt), new Set([...evidence, entry.winner.slice(0, 32)]), - duplicates, + untrusted, ); const loser = members.find( (record) => record.tail !== entry.winner && losers.includes(record.attempt), @@ -529,7 +553,7 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise record.attempt), evidence, - duplicates, + untrusted, ); if (verdict.winner !== null) { const winner = members.find((record) => record.attempt === verdict.winner)!; @@ -569,12 +593,9 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise entry.floor === record.floor && entry.loser?.record === record.tail, - ); - if (duplicates.has(record.attempt) && !named) { + if (untrusted.has(record.attempt)) { await retireRecord(record.key); } } @@ -621,8 +642,10 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise mark.key)); + let notes = 0; + /** How many listed keys this tick examined; the cursor moves past only those. */ + let examined = 0; for (const key of listed) { + if (halted || notes >= noteBudget) { + break; + } + examined += 1; const parts = steps.parsesKey(prefix, key); if (parts === null) { counter("unknown_key_total"); continue; } const tail = key.slice(nodePrefix.length); - if (halted || marked.has(tail) || marks.length >= TREE_GC_MAX_SWEEP_MARKS) { + if ( + marked.has(tail) || + marks.length >= TREE_GC_MAX_SWEEP_MARKS || + !deletable(parts.attempt) + ) { continue; } + notes += 1; const found = await steps.sweepIsMember(key, view, "note"); if (found === "corrupt") { // Counted and warned; a sweep candidate GC cannot authenticate stays. @@ -820,6 +865,7 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise boolean; /** Whether the sweep starts a mark's age in `phase`. */ readonly sweepStartsAge?: (phase: "note" | "stamp") => boolean; + /** + * Whether GC may delete by attempt `attempt`, given the attempts that + * appear in more than one listed fold record and those with a record + * on an open floor. + */ + readonly gcTrustsIdentity?: ( + attempt: string, + duplicates: ReadonlySet, + open: ReadonlySet, + ) => boolean; /** Whether a probe tick lists its sweep page before it reads the head. */ readonly sweepListsBeforeHead?: () => boolean; /** diff --git a/tests/fixtures/tree-gc-harness.ts b/tests/fixtures/tree-gc-harness.ts index efb8c72a..30cf8619 100644 --- a/tests/fixtures/tree-gc-harness.ts +++ b/tests/fixtures/tree-gc-harness.ts @@ -23,6 +23,7 @@ * injection (`aborting-storage.ts`) → server clock → memory. */ import { + RequestLedger, type DocumentData, MemoryStorage, retryStorageCall, @@ -59,6 +60,7 @@ import { import { planFold, type TreeFoldPlan } from "../../packages/server/src/tree/plan.ts"; import { publishTree, type TreePublishOutcome } from "../../packages/server/src/tree/publish.ts"; import { abortingStorage } from "./aborting-storage.ts"; +import { ledgeredStorage } from "./ledgered-storage.ts"; import { TREE_TEST_CHUNK_SALT, testChunkKey } from "./tree-chunk-salt.ts"; import { FOLD_PREFIX, SMALL_LAYOUT } from "./tree-fold-harness.ts"; import type { TreeMutant } from "./tree-mutants.ts"; @@ -140,6 +142,11 @@ export class GcBucket { serverTime = true; /** Runs once before the next LIST of the prefix it is keyed by. */ readonly onList = new Map Promise>(); + /** + * Fold-record attempts a LIST does not show yet, as a lagging LIST + * hides a create it has not caught up with. GETs still see them. + */ + readonly listLag = new Set(); /** Replaces a GET's body: return `undefined` to read the bucket. */ getOverride: ((key: string) => Uint8Array | null | undefined) | undefined; /** The rows the head's tree must hold. */ @@ -175,13 +182,16 @@ export class GcBucket { delete: (key, opts) => inner.delete(key, opts), list: (prefix, opts) => { const hook = this.onList.get(prefix); - if (hook === undefined) { - return inner.list(prefix, opts); - } this.onList.delete(prefix); + const lag = this.listLag; return (async function* () { - await hook(); - yield* inner.list(prefix, opts); + await hook?.(); + for await (const entry of inner.list(prefix, opts)) { + const tail = entry.key.slice(GC_RECORDS.length); + if (!(entry.key.startsWith(GC_RECORDS) && lag.has(tail.slice(17, 49)))) { + yield entry; + } + } })(); }, }; @@ -373,6 +383,23 @@ export class GcBucket { return { result, counters, warnings }; } + /** + * One GC tick charged to a request ledger of `limit` calls, as a host + * with a per-invocation cap runs it. Returns the tick and the calls + * the ledger was charged. + */ + async tickWithLedger( + limit: number, + config: TreeConfig = gcConfig(), + ): Promise<{ readonly result: TreeGcTickResult; readonly charged: number }> { + const ledger = new RequestLedger({ internal: limit, external: limit }); + const storage = ledgeredStorage(this.storage, "internal"); + const result = await runWithContext(createObservabilityContext({ ledger }), () => + runTreeGcTick({ storage, prefix: GC_PREFIX, config, now: () => new Date(this.local) }), + ); + return { result, charged: limit - ledger.storageRemaining() }; + } + /** Tick once a minute for `minutes` minutes, both clocks moving together. */ async tickFor(minutes: number, config = gcConfig(), watch?: MarginWatch): Promise { const deleted: string[] = []; diff --git a/tests/fixtures/tree-mutants.ts b/tests/fixtures/tree-mutants.ts index 986668ef..a831e2ae 100644 --- a/tests/fixtures/tree-mutants.ts +++ b/tests/fixtures/tree-mutants.ts @@ -562,23 +562,11 @@ export const PUBLISH_REUSES_ATTEMPT: TreeMutant = { options: { steps: { mintAttempt: () => "a".repeat(32) } }, }; -/** GC that drains an attempt found in two records as a loser. */ +/** GC that deletes by any identity, reused or still publishing. */ export const GC_IGNORES_DUPLICATE_IDENTITY: TreeMutant = { name: "gc-ignores-duplicate-identity", - defect: "an attempt id present in two records is deleted as a loser", - options: { - steps: { - gcClassify: (members, evidence, duplicates) => { - const verdict = classifyFloor(members, evidence, duplicates); - return verdict.winner === null - ? verdict - : { - ...verdict, - losers: [...verdict.losers, ...members.filter((a) => duplicates.has(a))], - }; - }, - }, - }, + defect: "an attempt id present in two records, or still publishing, is deleted by", + options: { steps: { gcTrustsIdentity: () => true } }, }; /** GC that treats the records at the head's own floor as closed. */ From 5eefb350e6d558be8197eddd51e0d7f1f1be874c Mon Sep 17 00:00:00 2001 From: Eric Baer Date: Tue, 24 Nov 2026 11:58:13 -0800 Subject: [PATCH 06/15] bench(tree): count tree GC's LISTs in its Class A rate The record LIST runs every tick and the sweep LIST every probe, and both are Class A. With in-band ticks the record LIST grows with the write rate, so the rate now takes ticks per minute as well as folds. --- bench/tree-op-model/model.test.ts | 7 +++++-- bench/tree-op-model/model.ts | 16 ++++++++++------ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/bench/tree-op-model/model.test.ts b/bench/tree-op-model/model.test.ts index 0e05b629..b2d3665a 100644 --- a/bench/tree-op-model/model.test.ts +++ b/bench/tree-op-model/model.test.ts @@ -447,7 +447,10 @@ describe("tree GC tick", () => { expect(treeGcTickBound(0, 0, true)).toBe(TREE_GC_TICK_RESERVED_CALLS); }); - test("tree GC adds about four Class A writes a minute at one fold a minute, whatever the write rate", () => { - expect(treeGcClassAPerMinute(1)).toBe(4); + test("tree GC's Class A rate: writes per fold, a probe a minute, a record LIST per tick", () => { + // One fold and one tick a minute. + expect(treeGcClassAPerMinute(1, 1)).toBe(6); + // Thirty writes a minute, each ticking: the record LIST is the term that grows. + expect(treeGcClassAPerMinute(1, 30) - treeGcClassAPerMinute(1, 1)).toBe(29); }); }); diff --git a/bench/tree-op-model/model.ts b/bench/tree-op-model/model.ts index 4bad4049..bd2fe4e4 100644 --- a/bench/tree-op-model/model.ts +++ b/bench/tree-op-model/model.ts @@ -612,12 +612,16 @@ export const treeGcTickBound = ( }; /** - * Class A writes per minute that tree GC adds, at `foldsPerMinute` folds - * a minute: each fold attempt's record create, at most one state write - * to resolve its floor, and at most two state writes per clock probe, - * one probe a minute. Independent of the app's write rate. - */ -export const treeGcClassAPerMinute = (foldsPerMinute: number): number => foldsPerMinute * 2 + 2; + * Class A operations per minute that tree GC adds, at `foldsPerMinute` + * folds and `ticksPerMinute` GC ticks a minute: each fold attempt's + * record create and at most one state write to resolve its floor; per + * clock probe (at most one a minute) two state writes and the sweep's + * LIST page; and per tick one LIST page of the fold records. Only that + * last term grows with the tick rate, so with in-band ticks it grows + * with the write rate. + */ +export const treeGcClassAPerMinute = (foldsPerMinute: number, ticksPerMinute: number): number => + foldsPerMinute * 2 + 3 + ticksPerMinute; // ── Reads ──────────────────────────────────────────────────────────────── From b6846ee2e91f6acf40a83d6a3a9ed8e554383966 Mon Sep 17 00:00:00 2001 From: Eric Baer Date: Tue, 24 Nov 2026 12:11:10 -0800 Subject: [PATCH 07/15] perf(tree): collect tree GC only on probe ticks Every in-band tick used to LIST the fold records, so GC's Class A cost grew with the write rate (about one LIST per write). Now only a probe tick, at most one per TREE_GC_CLOCK_PROBE_MINUTES of local time, runs the collecting body: sweep and record LISTs, head and root reads, resolution, deletes and state writes. Any other tick GETs the state, retires the log and ends with the new `paced` outcome. Skipping only the record LIST was not enough: that LIST builds the duplicate and open-floor identity sets every delete is checked against, so a tick that deleted from state without it would delete unchecked. With the gate, every delete follows a record LIST and a won probe CAS in the same tick, and due tests always use that probe's server time. Reclaim waits at most one more probe interval, well inside the 15-minute superseded delay. The op model's Class A rate drops its per-tick term: one record per fold plus four calls per probe. --- bench/tree-op-model/model.test.ts | 10 +- bench/tree-op-model/model.ts | 18 +- packages/server/src/tree/gc.test.ts | 30 ++++ packages/server/src/tree/gc.ts | 250 ++++++++++++++-------------- 4 files changed, 171 insertions(+), 137 deletions(-) diff --git a/bench/tree-op-model/model.test.ts b/bench/tree-op-model/model.test.ts index b2d3665a..c5b5134b 100644 --- a/bench/tree-op-model/model.test.ts +++ b/bench/tree-op-model/model.test.ts @@ -447,10 +447,10 @@ describe("tree GC tick", () => { expect(treeGcTickBound(0, 0, true)).toBe(TREE_GC_TICK_RESERVED_CALLS); }); - test("tree GC's Class A rate: writes per fold, a probe a minute, a record LIST per tick", () => { - // One fold and one tick a minute. - expect(treeGcClassAPerMinute(1, 1)).toBe(6); - // Thirty writes a minute, each ticking: the record LIST is the term that grows. - expect(treeGcClassAPerMinute(1, 30) - treeGcClassAPerMinute(1, 1)).toBe(29); + test("tree GC's Class A rate: a record per fold and one probe tick a minute", () => { + // One fold a minute: its record, then the probe's two state writes and two LISTs. + expect(treeGcClassAPerMinute(1)).toBe(5); + // No folds: the probe alone, however many writes tick. + expect(treeGcClassAPerMinute(0)).toBe(4); }); }); diff --git a/bench/tree-op-model/model.ts b/bench/tree-op-model/model.ts index bd2fe4e4..39ea5efa 100644 --- a/bench/tree-op-model/model.ts +++ b/bench/tree-op-model/model.ts @@ -612,16 +612,14 @@ export const treeGcTickBound = ( }; /** - * Class A operations per minute that tree GC adds, at `foldsPerMinute` - * folds and `ticksPerMinute` GC ticks a minute: each fold attempt's - * record create and at most one state write to resolve its floor; per - * clock probe (at most one a minute) two state writes and the sweep's - * LIST page; and per tick one LIST page of the fold records. Only that - * last term grows with the tick rate, so with in-band ticks it grows - * with the write rate. - */ -export const treeGcClassAPerMinute = (foldsPerMinute: number, ticksPerMinute: number): number => - foldsPerMinute * 2 + 3 + ticksPerMinute; + * Class A operations per minute that tree GC adds at `foldsPerMinute` + * folds a minute: each fold attempt's record create, and per probe tick + * (at most one a minute, the only ticks that collect) two state writes, + * the sweep's LIST page and the fold records' LIST page. Ticks between + * probes make only Class B calls, so the rate does not grow with the + * write rate. + */ +export const treeGcClassAPerMinute = (foldsPerMinute: number): number => foldsPerMinute + 4; // ── Reads ──────────────────────────────────────────────────────────────── diff --git a/packages/server/src/tree/gc.test.ts b/packages/server/src/tree/gc.test.ts index e570cdba..476cac3c 100644 --- a/packages/server/src/tree/gc.test.ts +++ b/packages/server/src/tree/gc.test.ts @@ -1117,6 +1117,36 @@ describe("state and clock", () => { await expect(bucket.tick()).resolves.toMatchObject({ result: { probed: true } }); }); + test("between probes a tick lists and deletes nothing, even with work due; the next probe does it", async () => { + const bucket = await GcBucket.seeded(); + await bucket.tick(); + const loser = await bucket.prepare([["k04", 44]]); + await bucket.fold([["k15", 55]]); + const lost = await bucket.publish(loser); + expect(lost.kind).toBe("cas-lost"); + const fresh = await freshOf(bucket, lost.attempt); + expect(fresh.length).toBeGreaterThan(0); + const listed: string[] = []; + bucket.onList.set(GC_RECORDS, async () => { + listed.push(GC_RECORDS); + }); + bucket.onList.set(GC_NODES, async () => { + listed.push(GC_NODES); + }); + const kept = [...(await bucket.keys(GC_NODES)), ...(await bucket.keys(GC_RECORDS))]; + bucket.advance(0.5); + const paced = await bucket.tick(); + expect(paced.result).toMatchObject({ outcome: "paced", probed: false, deleted: [] }); + expect(listed).toEqual([]); + await expect(bucket.keys(GC_NODES)).resolves.toEqual(expect.arrayContaining(fresh)); + expect([...(await bucket.keys(GC_NODES)), ...(await bucket.keys(GC_RECORDS))]).toEqual(kept); + bucket.advance(0.6); + const { result } = await bucket.tick(); + expect(result).toMatchObject({ outcome: "collected", probed: true }); + expect(result.deleted).toEqual(expect.arrayContaining([...fresh, lost.record])); + await expect(bucket.violations()).resolves.toEqual([]); + }); + test("a malformed state is replaced by the empty state, and that is the tick's only write", async () => { const bucket = await GcBucket.seeded(); await bucket.fold(MIXED); diff --git a/packages/server/src/tree/gc.ts b/packages/server/src/tree/gc.ts index c81a3a21..348665ce 100644 --- a/packages/server/src/tree/gc.ts +++ b/packages/server/src/tree/gc.ts @@ -43,12 +43,16 @@ * time, or the last one between probes. A probe that reports no server * time stamps nothing and makes nothing due. * - * **Tick.** State GET; in a probe tick, the sweep LIST; head GET; root - * GET; record LIST; resolve closed floors; the probe write; checks and - * DELETEs (active losers' fresh nodes, due winners' superseded nodes, - * due sweep marks); the sweep's notes and stamps; the state write, only - * when something changed; then `retireLogRange`. Candidate checks per - * tick are sized from the request ledger. + * **Tick.** Only a probe tick collects, so GC's LISTs and DELETEs run + * at most once per probe interval, whatever the write rate. Any other + * tick is a state GET and then `retireLogRange`. A probe tick: state + * GET; the sweep LIST; head GET; root GET; record LIST; resolve closed + * floors; the probe write; checks and DELETEs (active losers' fresh + * nodes, due winners' superseded nodes, due sweep marks); the sweep's + * notes and stamps; the state write, only when something changed; then + * `retireLogRange`. Every DELETE follows that tick's record LIST, which + * the identity checks are drawn from. Candidate checks per tick are + * sized from the request ledger. */ import { BaerlyError, @@ -81,7 +85,7 @@ import { type TreeGcState, type TreeGcWork, } from "./gc-state.ts"; -import { readTreeHead, readTreeRoot, type TreeHead } from "./head.ts"; +import { readTreeHead, readTreeRoot, treeHeadKey, type TreeHead } from "./head.ts"; import { collectionOfPrefix, parseTreeNodeKey, @@ -219,10 +223,11 @@ export interface TreeGcTickResult { * - `no-head`: the collection has no head yet; * - `reset`: the state was malformed or of another head history, and * was replaced by the empty state; + * - `paced`: no probe was due, so the tick only retired the log; * - `budget`: the request ledger had no room for one candidate check; * - `conflict`: the probe write lost, so the tick deleted nothing. */ - readonly outcome: "collected" | "no-head" | "reset" | "budget" | "conflict"; + readonly outcome: "collected" | "paced" | "no-head" | "reset" | "budget" | "conflict"; /** Every key the tick deleted, nodes and records, in order. */ readonly deleted: readonly string[]; /** The probe's server time, when the tick probed and storage reported one. */ @@ -335,8 +340,28 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise => { + try { + await retireLogRange(storage, treeHeadKey(prefix), { + ...(signal !== undefined && { signal }), + ...(input.retireWindow !== undefined && { window: input.retireWindow }), + }); + } catch (error) { + if (!isWriteConflict(error)) { + throw error; + } + } + }; + + // 2. Pacing: only a probe tick collects. A malformed state goes on to + // be reset, which needs the head. const probe = decoded?.kind !== "malformed" && probeIsDue(read?.probed_local_at ?? null, local); + if (!probe && decoded?.kind !== "malformed") { + await retire(); + return end("paced"); + } + + // The sweep page, listed before the head unless a mutant moves it. const listed: string[] = []; const listSweep = async (cursor: string | null): Promise => { for await (const entry of storage.list(nodePrefix, { @@ -600,37 +625,33 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise mark.key)); - let notes = 0; - /** How many listed keys this tick examined; the cursor moves past only those. */ - let examined = 0; - for (const key of listed) { - if (halted || notes >= noteBudget) { - break; - } - examined += 1; - const parts = steps.parsesKey(prefix, key); - if (parts === null) { - counter("unknown_key_total"); - continue; - } - const tail = key.slice(nodePrefix.length); - if ( - marked.has(tail) || - marks.length >= TREE_GC_MAX_SWEEP_MARKS || - !deletable(parts.attempt) - ) { - continue; - } - notes += 1; - const found = await steps.sweepIsMember(key, view, "note"); - if (found === "corrupt") { - // Counted and warned; a sweep candidate GC cannot authenticate stays. - await settle(key, found, "sweep", parts.attempt); - } else if (found === "path-unreadable") { - counter("path_unreadable_total"); - halted = true; - } else if (found === "non-member") { - const stamp = steps.startsAge("note") && serverTime !== undefined; - marks.push({ - key: tail, - floor: h, - due_at: stamp ? addMinutes(serverTime!, TREE_GC_SWEEP_AGE_MINUTES) : null, - }); - marked.add(tail); - } + const marked = new Set(marks.map((mark) => mark.key)); + let notes = 0; + /** How many listed keys this tick examined; the cursor moves past only those. */ + let examined = 0; + for (const key of listed) { + if (halted || notes >= noteBudget) { + break; } - const stamped: TreeGcMark[] = []; - for (const mark of marks) { - if ( - halted || - mark.due_at !== null || - serverTime === undefined || - !steps.startsAge("stamp") || - !steps.passesFloorGate(mark.floor, h) || - !deletable(mark.key.slice(0, 32)) || - budget <= 0 - ) { - stamped.push(mark); - continue; - } - budget -= 1; - const found = await steps.sweepIsMember(`${nodePrefix}${mark.key}`, view, "stamp"); - if (found === "non-member") { - stamped.push({ ...mark, due_at: addMinutes(serverTime, TREE_GC_SWEEP_AGE_MINUTES) }); - } else if (found === "path-unreadable") { - counter("path_unreadable_total"); - halted = true; - stamped.push(mark); - } else if (found === "deferred") { - stamped.push(mark); - } else if (found === "corrupt") { - await settle(`${nodePrefix}${mark.key}`, found, "sweep", mark.key.slice(0, 32)); - } - // A member, a gone node or a corrupt one leaves the sweep's list. + examined += 1; + const parts = steps.parsesKey(prefix, key); + if (parts === null) { + counter("unknown_key_total"); + continue; } - marks = stamped; - if (examined < listed.length) { - cursor = examined === 0 ? cursor : listed[examined - 1]!; - } else { - cursor = listed.length < TREE_GC_SWEEP_LIST_KEYS ? null : listed.at(-1)!; + const tail = key.slice(nodePrefix.length); + if (marked.has(tail) || marks.length >= TREE_GC_MAX_SWEEP_MARKS || !deletable(parts.attempt)) { + continue; + } + notes += 1; + const found = await steps.sweepIsMember(key, view, "note"); + if (found === "corrupt") { + // Counted and warned; a sweep candidate GC cannot authenticate stays. + await settle(key, found, "sweep", parts.attempt); + } else if (found === "path-unreadable") { + counter("path_unreadable_total"); + halted = true; + } else if (found === "non-member") { + const stamp = steps.startsAge("note") && serverTime !== undefined; + marks.push({ + key: tail, + floor: h, + due_at: stamp ? addMinutes(serverTime!, TREE_GC_SWEEP_AGE_MINUTES) : null, + }); + marked.add(tail); } } + const stamped: TreeGcMark[] = []; + for (const mark of marks) { + if ( + halted || + mark.due_at !== null || + serverTime === undefined || + !steps.startsAge("stamp") || + !steps.passesFloorGate(mark.floor, h) || + !deletable(mark.key.slice(0, 32)) || + budget <= 0 + ) { + stamped.push(mark); + continue; + } + budget -= 1; + const found = await steps.sweepIsMember(`${nodePrefix}${mark.key}`, view, "stamp"); + if (found === "non-member") { + stamped.push({ ...mark, due_at: addMinutes(serverTime, TREE_GC_SWEEP_AGE_MINUTES) }); + } else if (found === "path-unreadable") { + counter("path_unreadable_total"); + halted = true; + stamped.push(mark); + } else if (found === "deferred") { + stamped.push(mark); + } else if (found === "corrupt") { + await settle(`${nodePrefix}${mark.key}`, found, "sweep", mark.key.slice(0, 32)); + } + // A member, a gone node or a corrupt one leaves the sweep's list. + } + marks = stamped; + if (examined < listed.length) { + cursor = examined === 0 ? cursor : listed[examined - 1]!; + } else { + cursor = listed.length < TREE_GC_SWEEP_LIST_KEYS ? null : listed.at(-1)!; + } // 10. The state write, when the tick changed anything. - const prior = written ?? base; + const prior = probed; const final: TreeGcState = { ...prior, floor_seen: h, - clock: probe && serverTime !== undefined ? serverTime.toISOString() : prior.clock, + clock: serverTime !== undefined ? serverTime.toISOString() : prior.clock, resolved_through: resolvedThrough, stuck, work: remaining, @@ -916,15 +931,6 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise Date: Tue, 24 Nov 2026 12:30:06 -0800 Subject: [PATCH 08/15] fix(tree): issue tree GC record retirements only after the probe wins Resolving closed floors retired stale, stuck, untrusted and unusable fold records before the probe write, so a tick whose probe CAS lost returned `conflict` having already deleted. The resolution step now queues those retirements under the same per-tick record-delete cap and the tick issues them only once its probe CAS has won; a lost probe deletes nothing. Adds a `gcRetiresBeforeProbe` step seam and the `gc-deletes-before-probe` mutant, caught by a new lost-probe test. --- packages/server/src/tree/gc.test.ts | 42 +++++++++++++++++++++++++++++ packages/server/src/tree/gc.ts | 38 +++++++++++++++++++++----- packages/server/src/tree/layout.ts | 2 ++ tests/fixtures/tree-mutants.ts | 8 ++++++ 4 files changed, 83 insertions(+), 7 deletions(-) diff --git a/packages/server/src/tree/gc.test.ts b/packages/server/src/tree/gc.test.ts index 476cac3c..a7cd44ae 100644 --- a/packages/server/src/tree/gc.test.ts +++ b/packages/server/src/tree/gc.test.ts @@ -31,6 +31,7 @@ import { } from "../../../../tests/fixtures/tree-gc-harness.ts"; import { GC_CORRUPT_NO_RETRY, + GC_DELETES_BEFORE_PROBE, GC_DELETES_CORRUPT_CANDIDATE, GC_DELETES_UNPARSEABLE_KEY, GC_IGNORES_DUE_AT, @@ -786,6 +787,42 @@ const quarantineFailure = (mutant?: TreeMutant) => : `deleted ${taken.length} of the winner's superseded nodes`; }); +/** + * The state changes between a tick's state GET and its probe write, in a + * tick that has records to retire (an identity in two records): the + * probe loses, and the tick deletes nothing. + */ +const lostProbeFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const reused = "a".repeat(32); + const loser = await bucket.prepare([["k03", 5]]); + await bucket.fold([["k19", 119]]); + await bucket.publish(loser, { attempt: reused }); + await bucket.fold([["k03", 5]], { attempt: reused }); + const before = [...(await bucket.keys(GC_NODES)), ...(await bucket.keys(GC_RECORDS))]; + // Another tick's state write lands while this one lists its records. + const head = await bucket.head(); + const floor = head.json.log_seq_start; + bucket.onList.set(GC_RECORDS, async () => { + await bucket.memory.put(GC_STATE, encodeTreeGcState(emptyTreeGcState(null, floor))); + }); + const { result } = await bucket.tick(gcConfig(mutant)); + const after = new Set([...(await bucket.keys(GC_NODES)), ...(await bucket.keys(GC_RECORDS))]); + const problems: string[] = []; + if (result.outcome !== "conflict") { + problems.push(`setup: the tick ended ${result.outcome}`); + } + if (result.deleted.length > 0) { + problems.push(`deleted ${result.deleted.join(", ")} after losing the probe`); + } + const gone = before.filter((key) => !after.has(key)); + if (gone.length > 0) { + problems.push(`gone from the bucket: ${gone.join(", ")}`); + } + return joined(problems); + }); + // --------------------------------------------------------------------- // Record path // --------------------------------------------------------------------- @@ -1188,6 +1225,10 @@ describe("state and clock", () => { await expect(bucket.state()).resolves.toEqual(emptyTreeGcState(null, 20)); }); + test("a tick whose probe write loses deletes nothing and ends in conflict", async () => { + await expect(lostProbeFailure()).resolves.toBeUndefined(); + }); + test("a collection with no head ends the tick with no write", async () => { const bucket = new GcBucket(); await expect(bucket.tick()).resolves.toMatchObject({ result: { outcome: "no-head" } }); @@ -1312,6 +1353,7 @@ describe("mutation", () => { [SWEEP_FLOOR_BEFORE_LIST, [floorBeforeListFailure]], [SWEEP_AGE_FROM_NOTE, [supersededAfterNoteFailure]], [GC_CORRUPT_NO_RETRY, [misreadFailure]], + [GC_DELETES_BEFORE_PROBE, [lostProbeFailure]], ]); test("every GC mutant has checks", () => { diff --git a/packages/server/src/tree/gc.ts b/packages/server/src/tree/gc.ts index 348665ce..dca6225c 100644 --- a/packages/server/src/tree/gc.ts +++ b/packages/server/src/tree/gc.ts @@ -27,7 +27,9 @@ * Every DELETE is proven in its own tick by the membership check of * `./gc-member.ts` against the root of the head that tick read. Records, * the state and the clock only nominate and pace; none authorizes a - * deletion, so a stale or lost state can leak and never delete. + * deletion, so a stale or lost state can leak and never delete. No + * DELETE, of a node or a record, is issued before the tick's probe CAS + * has won: a tick that loses it deletes nothing. * * **State.** `

/_v99/gc-pending.json` (`./gc-state.ts`) holds * progress, bound to the head's `generation` and floor. A state of @@ -47,10 +49,11 @@ * at most once per probe interval, whatever the write rate. Any other * tick is a state GET and then `retireLogRange`. A probe tick: state * GET; the sweep LIST; head GET; root GET; record LIST; resolve closed - * floors; the probe write; checks and DELETEs (active losers' fresh - * nodes, due winners' superseded nodes, due sweep marks); the sweep's - * notes and stamps; the state write, only when something changed; then - * `retireLogRange`. Every DELETE follows that tick's record LIST, which + * floors, queueing the record retirements that chooses; the probe + * write; the queued retirements; checks and DELETEs (active losers' + * fresh nodes, due winners' superseded nodes, due sweep marks); the + * sweep's notes and stamps; the state write, only when something + * changed; then `retireLogRange`. Every DELETE follows that tick's record LIST, which * the identity checks are drawn from. Candidate checks per tick are * sized from the request ledger. */ @@ -179,6 +182,7 @@ interface GcSteps { readonly startsAge: NonNullable; readonly listsBeforeHead: NonNullable; readonly trustsIdentity: NonNullable; + readonly retiresBeforeProbe: NonNullable; } const gcSteps = (config: TreeConfig): GcSteps => { @@ -198,6 +202,7 @@ const gcSteps = (config: TreeConfig): GcSteps => { startsAge: s.sweepStartsAge ?? ((phase) => phase === "stamp"), listsBeforeHead: s.sweepListsBeforeHead ?? (() => true), trustsIdentity: s.gcTrustsIdentity ?? trustsIdentity, + retiresBeforeProbe: s.gcRetiresBeforeProbe ?? (() => false), }; }; @@ -452,6 +457,7 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise(); @@ -490,7 +496,16 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise => { if (retired.has(key)) { return true; @@ -499,9 +514,13 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise @@ -643,6 +662,11 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise boolean; /** Whether a probe tick lists its sweep page before it reads the head. */ readonly sweepListsBeforeHead?: () => boolean; + /** Whether GC issues the record DELETEs it chose before its probe write, not after it wins. */ + readonly gcRetiresBeforeProbe?: () => boolean; /** * The reader's tail step: walk and probe the unfolded log tail of the * head it is given, and fold it into a per-`_id` overlay. diff --git a/tests/fixtures/tree-mutants.ts b/tests/fixtures/tree-mutants.ts index a831e2ae..6693e5da 100644 --- a/tests/fixtures/tree-mutants.ts +++ b/tests/fixtures/tree-mutants.ts @@ -674,6 +674,13 @@ export const GC_CORRUPT_NO_RETRY: TreeMutant = { options: { steps: { gcRetriesCorrupt: () => false } }, }; +/** GC that retires records before its probe write wins. */ +export const GC_DELETES_BEFORE_PROBE: TreeMutant = { + name: "gc-deletes-before-probe", + defect: "a tick issues record DELETEs before its probe CAS, so one that loses it has deleted", + options: { steps: { gcRetiresBeforeProbe: () => true } }, +}; + /** The GC mutants the GC suite must catch. */ export const GC_MUTANTS: readonly TreeMutant[] = [ GC_IGNORES_LIVE_ROOT, @@ -698,4 +705,5 @@ export const GC_MUTANTS: readonly TreeMutant[] = [ SWEEP_FLOOR_BEFORE_LIST, SWEEP_AGE_FROM_NOTE, GC_CORRUPT_NO_RETRY, + GC_DELETES_BEFORE_PROBE, ]; From effa37c1d3f8a9aa355ac9d5c9560c9fc8eb12bd Mon Sep 17 00:00:00 2001 From: Eric Baer Date: Tue, 24 Nov 2026 12:31:18 -0800 Subject: [PATCH 09/15] fix(tree): retire a quarantined tree GC slot's winner record A work entry whose winner identity showed up in another record stays quarantined, and the winner drain skipped it without ever retiring its record. When the per-tick record-delete cap retired the other records under that identity first, the winner's record was left as the only one, the slot never dropped, and enough such slots fill TREE_GC_MAX_WORK_ENTRIES and stop GC. A quarantined slot now retires its winner record leak-only, deleting no node it names, once its floor's loser is done, and drops. --- packages/server/src/tree/gc.test.ts | 56 ++++++++++++++++++++++++++++- packages/server/src/tree/gc.ts | 15 ++++++-- 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/packages/server/src/tree/gc.test.ts b/packages/server/src/tree/gc.test.ts index a7cd44ae..534a2ac3 100644 --- a/packages/server/src/tree/gc.test.ts +++ b/packages/server/src/tree/gc.test.ts @@ -823,6 +823,53 @@ const lostProbeFailure = (mutant?: TreeMutant) => return joined(problems); }); +/** + * A winner's identity reappears in four records that sort before its + * own, so the tick's record DELETEs retire those four and run out before + * the winner's record. Later ticks see the identity once again, yet the + * slot stays quarantined: it drops and its record is retired, and none + * of the nodes it names is deleted. + */ +const quarantineClearsFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const winner = "c".repeat(32); + await bucket.fold(MIXED, { attempt: winner }); + await bucket.tick(gcConfig(mutant)); + const listed = await bucket.keys(GC_RECORDS); + const own = listed.find((key) => key.includes(`/${winner}/`))!; + for (let floor = 1; floor <= 4; floor++) { + const sealed = await sealFoldRecord(GC_PREFIX, { + attempt: winner, + base: { floor, root: null, attempt: null, generation: null }, + result: { floor: floor + 1, root: null }, + fresh: [], + superseded: [], + }); + await bucket.memory.put(sealed.key, sealed.bytes); + } + const deleted: string[] = []; + for (const minutes of [DELAY + 1, 1, 1, 1]) { + bucket.advance(minutes); + const { result } = await bucket.tick(gcConfig(mutant)); + deleted.push(...result.deleted); + } + const problems: string[] = []; + const nodes = deleted.filter((key) => key.startsWith(GC_NODES)); + if (nodes.length > 0) { + problems.push(`deleted nodes ${nodes.join(", ")}`); + } + const left = await bucket.keys(GC_RECORDS); + if (left.includes(own)) { + problems.push("the quarantined winner's record remains"); + } + const state = await bucket.state(); + if (state?.work.some((entry) => entry.winner.startsWith(winner))) { + problems.push("the quarantined slot remains"); + } + return joined(problems); + }); + // --------------------------------------------------------------------- // Record path // --------------------------------------------------------------------- @@ -1029,6 +1076,10 @@ describe("attempt identity and closure", () => { await expect(quarantineFailure()).resolves.toBeUndefined(); }); + test("a quarantined slot drops and retires its winner's record leak-only", async () => { + await expect(quarantineClearsFailure()).resolves.toBeUndefined(); + }); + test("a record of another head history is never evidence for the new history's winner", async () => { await expect(generationWitnessFailure()).resolves.toBeUndefined(); }); @@ -1341,7 +1392,10 @@ describe("mutation", () => { [SWEEP_MEMBER_AGAINST_MARK_ROOT, [sweepInFlightFailure]], [GC_SKIPS_MEMBERSHIP_CHECK, [membershipFailure, withReusedNode(reclaimFailure)]], [PUBLISH_REUSES_ATTEMPT, [reuseCounterFailure]], - [GC_IGNORES_DUPLICATE_IDENTITY, [reuseFailure, lateDuplicateFailure, sweepReuseFailure]], + [ + GC_IGNORES_DUPLICATE_IDENTITY, + [reuseFailure, lateDuplicateFailure, sweepReuseFailure, quarantineClearsFailure], + ], [GC_PROCESSES_OPEN_FLOOR, [openFloorFailure]], [GC_IGNORES_GENERATION, [regenerationFailure]], [GC_WINNER_AS_LOSER, [raceFailure]], diff --git a/packages/server/src/tree/gc.ts b/packages/server/src/tree/gc.ts index dca6225c..e1bb67e5 100644 --- a/packages/server/src/tree/gc.ts +++ b/packages/server/src/tree/gc.ts @@ -18,7 +18,10 @@ * `TREE_GC_SUPERSEDED_DELAY_MINUTES` after a probe of the storage * server's clock first stamps them, so reads through the replaced * root can finish. The delay is a margin, not a proof: a read that - * outlives it meets the reader's missing-node backstop. + * outlives it meets the reader's missing-node backstop. A winner + * whose identity shows up in another record is quarantined: none of + * its superseded nodes is deleted, and once its floor's loser is done + * its record is retired leak-only. * - A slow leak sweep lists the node prefix a page per probe and * deletes nodes that are unreachable, whose attempt can no longer * publish (a later fold moved the floor past the one read after the @@ -794,7 +797,15 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise Date: Tue, 24 Nov 2026 12:32:22 -0800 Subject: [PATCH 10/15] fix(tree): retry a deferred node on the tree GC record path The record drains treated a `deferred` membership result (a body that failed its decode once and read cleanly on the re-read) as done, so the slot's cursor moved past the node and, once the list ended, its record was retired: the node leaked until the sweep found it. A deferred node now stops that slot's advance for the tick, so the next probe checks it again; other slots go on draining. --- packages/server/src/tree/gc.test.ts | 17 ++++++++++++++--- packages/server/src/tree/gc.ts | 12 +++++++++--- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/packages/server/src/tree/gc.test.ts b/packages/server/src/tree/gc.test.ts index 534a2ac3..01ed5936 100644 --- a/packages/server/src/tree/gc.test.ts +++ b/packages/server/src/tree/gc.test.ts @@ -552,14 +552,19 @@ const corruptFailure = (mutant?: TreeMutant) => return joined(problems); }); -/** A one-time misread of a superseded node is read again: no corruption is counted or warned. */ +/** + * A one-time misread of a superseded node is read again: no corruption + * is counted or warned, and the record path reclaims the node on a later + * probe, well before the sweep age. + */ const misreadFailure = (mutant?: TreeMutant) => guarded(async () => { const bucket = await GcBucket.seeded(); const target = await supersededBelowRoot(bucket); + let armed = false; let misread = false; bucket.getOverride = (key) => { - if (key === target && !misread) { + if (key === target && armed && !misread) { misread = true; return new TextEncoder().encode("torn read"); } @@ -567,6 +572,8 @@ const misreadFailure = (mutant?: TreeMutant) => }; const problems: string[] = []; for (const minutes of [0, DELAY + 1, 1, 1]) { + // The misread lands on the record drain, in the tick the node is due. + armed = minutes > 0; bucket.advance(minutes); const { counters, warnings } = await bucket.tick(gcConfig(mutant)); if ((counters.get("db.tree_gc.corrupt_node_total") ?? 0) > 0) { @@ -579,6 +586,10 @@ const misreadFailure = (mutant?: TreeMutant) => if (!misread) { problems.push("setup: the target was never read"); } + const left = await bucket.keys(GC_NODES); + if (left.includes(target)) { + problems.push(`the misread node ${target} was not reclaimed`); + } return joined(problems); }); @@ -928,7 +939,7 @@ describe("record path", () => { await expect(corruptFailure()).resolves.toBeUndefined(); }); - test("a one-time misread is read again, not counted as corruption", async () => { + test("a one-time misread is read again, not counted as corruption, and reclaimed later", async () => { await expect(misreadFailure()).resolves.toBeUndefined(); }); diff --git a/packages/server/src/tree/gc.ts b/packages/server/src/tree/gc.ts index e1bb67e5..a33e2f6c 100644 --- a/packages/server/src/tree/gc.ts +++ b/packages/server/src/tree/gc.ts @@ -703,7 +703,11 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise 0) { const x = `${nodePrefix}${record.attempt}/${record.fresh[next]}`; budget -= 1; - if (!(await settle(x, await steps.isMember(x, view), "loser", record.attempt))) { + const found = await steps.isMember(x, view); + if (found === "deferred" || !(await settle(x, found, "loser", record.attempt))) { break; } next += 1; @@ -823,7 +828,8 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise Date: Tue, 24 Nov 2026 12:33:57 -0800 Subject: [PATCH 11/15] fix(tree): count every listed key toward a full tree GC record page The record page counted only keys that parse as fold-record keys when deciding whether it was full, but keys under the record prefix that do not parse still use up the LIST's maxKeys. A full page with stray keys read as complete, so a winner slot whose record lay past the page was dropped as gone and its record leaked, and a winner could be retired while a loser at its floor sat unlisted. The page is now full when the listed-entry count reaches maxKeys, whatever those keys are. --- packages/server/src/tree/gc.test.ts | 52 ++++++++++++++++++++++++++++- packages/server/src/tree/gc.ts | 6 ++-- 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/packages/server/src/tree/gc.test.ts b/packages/server/src/tree/gc.test.ts index 01ed5936..8cec08bf 100644 --- a/packages/server/src/tree/gc.test.ts +++ b/packages/server/src/tree/gc.test.ts @@ -13,7 +13,13 @@ * `tests/fixtures/tree-mutants.ts` to turn its checks red. */ import { describe, expect, test } from "vitest"; -import { BaerlyError, encodeJsonBytes, RequestLedger, type Storage } from "@baerly/protocol"; +import { + BaerlyError, + encodeJsonBytes, + GC_MARK_LIST_PAGE_KEYS, + RequestLedger, + type Storage, +} from "@baerly/protocol"; import { ledgeredStorage } from "../../../../tests/fixtures/ledgered-storage.ts"; import { freshGcHead, @@ -881,6 +887,46 @@ const quarantineClearsFailure = (mutant?: TreeMutant) => return joined(problems); }); +/** + * A full record page made only of keys that do not parse, all sorting + * before the real records: the page does not show the floors past it, + * so no winner slot whose record lies there is dropped, and once the + * stray keys are gone everything is reclaimed. + */ +const strayPageFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + await bucket.fold(MIXED); + await bucket.tick(gcConfig(mutant)); + const first = await bucket.state(); + const floors = first?.work.map((entry) => entry.floor) ?? []; + if (floors.length === 0) { + return "setup: no work entry"; + } + const strays = Array.from({ length: GC_MARK_LIST_PAGE_KEYS }, (_, i) => `${GC_RECORDS}0/${i}`); + for (const key of strays) { + await bucket.memory.put(key, new TextEncoder().encode("{}")); + } + bucket.advance(DELAY + 1); + await bucket.tick(gcConfig(mutant)); + const problems: string[] = []; + const after = await bucket.state(); + const kept = after?.work.map((entry) => entry.floor) ?? []; + const lost = floors.filter((floor) => !kept.includes(floor)); + if (lost.length > 0) { + problems.push(`slots past the page dropped: floors ${lost.join(", ")}`); + } + for (const key of strays) { + await bucket.memory.delete(key); + } + await reclaim(bucket, gcConfig(mutant)); + const left = await reclaimedProblems(bucket); + if (left !== undefined) { + problems.push(left); + } + return joined(problems); + }); + // --------------------------------------------------------------------- // Record path // --------------------------------------------------------------------- @@ -991,6 +1037,10 @@ describe("record path", () => { await expect(reclaimedProblems(bucket)).resolves.toBeUndefined(); }); + test("a full record page of keys that do not parse drops no slot past the page", async () => { + await expect(strayPageFailure()).resolves.toBeUndefined(); + }); + test("a floor with no evidence of its winner is stuck, then retired leak-only after the sweep age", async () => { const bucket = await GcBucket.seeded(); await bucket.fold(MIXED); diff --git a/packages/server/src/tree/gc.ts b/packages/server/src/tree/gc.ts index a33e2f6c..aa20e9fb 100644 --- a/packages/server/src/tree/gc.ts +++ b/packages/server/src/tree/gc.ts @@ -423,11 +423,13 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise= GC_MARK_LIST_PAGE_KEYS; + const recordPageFull = recordKeysListed >= GC_MARK_LIST_PAGE_KEYS; const lastListedFloor = records.at(-1)?.floor ?? -1; /** Whether the record page shows every record at `floor`. */ const pageCovers = (floor: number): boolean => !recordPageFull || lastListedFloor > floor; From b0bc13c66c3f878894b8009a763b88ccad354b1b Mon Sep 17 00:00:00 2001 From: Eric Baer Date: Tue, 24 Nov 2026 12:36:35 -0800 Subject: [PATCH 12/15] fix(tree): pace a tree GC tick the request ledger cannot fit A `budget` outcome returned after the sweep LIST and the head and root GETs, before the probe write and without retiring the log, so every following tick on a short ledger paid those calls again and log retirement never ran. A probe tick whose ledger has no room for one check even at depth 0 now skips straight to log retirement after the state GET, as a paced tick does, listing nothing. One whose ledger only the root's depth rules out writes the probe alone, so the ticks of the next probe interval are paced, and then retires the log. Both still count `db.maintenance.request_budget_skipped_total`. --- packages/server/src/tree/gc.test.ts | 35 ++++++++++++++++++ packages/server/src/tree/gc.ts | 56 ++++++++++++++++++++++------- tests/fixtures/tree-gc-harness.ts | 9 ++++- 3 files changed, 86 insertions(+), 14 deletions(-) diff --git a/packages/server/src/tree/gc.test.ts b/packages/server/src/tree/gc.test.ts index 8cec08bf..ef8af41f 100644 --- a/packages/server/src/tree/gc.test.ts +++ b/packages/server/src/tree/gc.test.ts @@ -1373,6 +1373,41 @@ describe("budget", () => { expect(result.outcome).toBe("budget"); }); + test("a probe tick with no room for one check at any depth lists nothing and still retires the log", async () => { + const bucket = await GcBucket.seeded(); + const listed: string[] = []; + for (const prefix of [GC_NODES, GC_RECORDS]) { + bucket.onList.set(prefix, async () => { + listed.push(prefix); + }); + } + const before = await bucket.head(); + const floorBefore = before.json.log_delete_floor ?? 0; + const { result } = await bucket.tickWithLedger(TREE_GC_TICK_RESERVED_CALLS + 2, gcConfig(), 0); + expect(result).toMatchObject({ outcome: "budget", probed: false, deleted: [] }); + expect(listed).toEqual([]); + const head = await bucket.head(); + expect(head.json.log_delete_floor).toBeGreaterThan(floorBefore); + }); + + test("a probe tick with no room at the root's depth writes the probe, so the next ticks are paced", async () => { + const bucket = await GcBucket.seeded(); + // Room for one check at depth 0 after the state GET, none at depth 3 after the root GET. + const limit = TREE_GC_TICK_RESERVED_CALLS + 4 * 3 + 5; + const first = await bucket.tickWithLedger(limit); + expect(first.result).toMatchObject({ outcome: "budget", deleted: [] }); + const listed: string[] = []; + for (const prefix of [GC_NODES, GC_RECORDS]) { + bucket.onList.set(prefix, async () => { + listed.push(prefix); + }); + } + bucket.advance(0.5); + const second = await bucket.tickWithLedger(limit); + expect(second.result.outcome).toBe("paced"); + expect(listed).toEqual([]); + }); + test("a deleting tick's charged calls stay within the static bound for its candidate count", async () => { const bucket = await GcBucket.seeded(); await bucket.fold(MIXED); diff --git a/packages/server/src/tree/gc.ts b/packages/server/src/tree/gc.ts index aa20e9fb..663d36f4 100644 --- a/packages/server/src/tree/gc.ts +++ b/packages/server/src/tree/gc.ts @@ -56,9 +56,12 @@ * write; the queued retirements; checks and DELETEs (active losers' * fresh nodes, due winners' superseded nodes, due sweep marks); the * sweep's notes and stamps; the state write, only when something - * changed; then `retireLogRange`. Every DELETE follows that tick's record LIST, which - * the identity checks are drawn from. Candidate checks per tick are - * sized from the request ledger. + * changed; then `retireLogRange`. Every DELETE follows that tick's + * record LIST, which the identity checks are drawn from. Candidate + * checks per tick are sized from the request ledger: a probe tick + * without room for one check at depth 0 lists nothing and behaves as a + * paced tick; one without room at the root's depth writes the probe + * alone, then retires the log. */ import { BaerlyError, @@ -232,7 +235,10 @@ export interface TreeGcTickResult { * - `reset`: the state was malformed or of another head history, and * was replaced by the empty state; * - `paced`: no probe was due, so the tick only retired the log; - * - `budget`: the request ledger had no room for one candidate check; + * - `budget`: the request ledger had no room for one candidate check, + * so the tick deleted nothing and only retired the log. Judged at + * depth 0 before any LIST; a tick only the root's depth rules out + * writes the probe, so the next probe interval is paced; * - `conflict`: the probe write lost, so the tick deleted nothing. */ readonly outcome: "collected" | "paced" | "no-head" | "reset" | "budget" | "conflict"; @@ -295,6 +301,10 @@ const sameState = (a: TreeGcState, b: TreeGcState): boolean => encodeTreeGcState({ ...b, floor_seen: 0 }), ); +/** Calls the current request ledger has left; unbounded without one. */ +const ledgerLeft = (): number => + currentRequestLedger()?.storageRemaining() ?? Number.POSITIVE_INFINITY; + const isUnknownFate = (error: unknown): boolean => isWriteConflict(error) || (error instanceof BaerlyError && error.code === "NetworkError"); @@ -342,8 +352,17 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise { + ctxMetrics().counter("db.maintenance.request_budget_skipped_total", 1, { + collection, + phase: "gc", + }); + }; + // 1. The state. const got = await storage.get(stateKey, opts); + // A ledger reports its room only once it has charged a storage call. + const leftAfterState = ledgerLeft(); const decoded = got === null ? null : decodeTreeGcState(stateKey, got.body); const e0 = got?.etag ?? null; const read = decoded?.kind === "state" ? decoded.state : null; @@ -368,6 +387,13 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise { const ledger = new RequestLedger({ internal: limit, external: limit }); const storage = ledgeredStorage(this.storage, "internal"); const result = await runWithContext(createObservabilityContext({ ledger }), () => - runTreeGcTick({ storage, prefix: GC_PREFIX, config, now: () => new Date(this.local) }), + runTreeGcTick({ + storage, + prefix: GC_PREFIX, + config, + now: () => new Date(this.local), + ...(retireWindow !== undefined && { retireWindow }), + }), ); return { result, charged: limit - ledger.storageRemaining() }; } From 1a1ec4a2cbdab2f850728ffc2e41690e18706c8e Mon Sep 17 00:00:00 2001 From: Eric Baer Date: Tue, 24 Nov 2026 12:37:49 -0800 Subject: [PATCH 13/15] fix(tree): re-probe the tree GC clock early only on a clock reset A tick probed whenever its local time read earlier than the previous probe's. Writers on different instances share one GC state, so two whose clocks differ by a minute or more each saw the other's probe in their future or past and probed on every tick. A tick now probes when there is no previous probe, when its local time is at least TREE_GC_CLOCK_PROBE_MINUTES past the previous one, or when it reads more than the new TREE_GC_CLOCK_RESET_MINUTES (60) before it. A smaller backward reading is skew between instances and waits for the probe interval. Local time is still only compared with local time and never decides a deletion. --- packages/server/src/tree/constants.ts | 12 ++++++++++++ packages/server/src/tree/gc.test.ts | 24 +++++++++++++++++++++++- packages/server/src/tree/gc.ts | 17 +++++++++++------ 3 files changed, 46 insertions(+), 7 deletions(-) diff --git a/packages/server/src/tree/constants.ts b/packages/server/src/tree/constants.ts index b124cca5..8db6f08f 100644 --- a/packages/server/src/tree/constants.ts +++ b/packages/server/src/tree/constants.ts @@ -226,6 +226,18 @@ export const TREE_GC_SWEEP_AGE_MINUTES = 60; */ export const TREE_GC_CLOCK_PROBE_MINUTES = 1; +/** + * How far, in local-clock minutes, a tick's local time must read before + * the previous probe's local time for the tick to probe early. Writers + * on different instances share one state, and their local clocks + * differ: a smaller backward reading is skew between instances, so the + * tick waits for the probe interval as usual instead of probing on every + * tick. Only a jump this large, a real clock reset, re-probes early. + * Local time is only ever compared with local time; it never decides a + * deletion. + */ +export const TREE_GC_CLOCK_RESET_MINUTES = 60; + /** * Candidate checks one GC tick makes, the sweep page's listed keys * included: the floor a tick uses wherever its ledger does not admit diff --git a/packages/server/src/tree/gc.test.ts b/packages/server/src/tree/gc.test.ts index ef8af41f..0fa7c93b 100644 --- a/packages/server/src/tree/gc.test.ts +++ b/packages/server/src/tree/gc.test.ts @@ -65,6 +65,7 @@ import { } from "../../../../tests/fixtures/tree-mutants.ts"; import { createObservabilityContext, runWithContext } from "../observability/context.ts"; import { + TREE_GC_CLOCK_RESET_MINUTES, TREE_GC_SUPERSEDED_DELAY_MINUTES, TREE_GC_SWEEP_AGE_MINUTES, TREE_GC_TICK_CANDIDATES, @@ -95,6 +96,7 @@ const DELAY = TREE_GC_SUPERSEDED_DELAY_MINUTES; */ const ONE_CHECK_LEDGER = TREE_GC_TICK_RESERVED_CALLS + 4 * 3 + 12; const AGE = TREE_GC_SWEEP_AGE_MINUTES; +const RESET = TREE_GC_CLOCK_RESET_MINUTES; const LONG = 60_000; /** @@ -1261,11 +1263,31 @@ describe("state and clock", () => { await expect(bucket.tick()).resolves.toMatchObject({ result: { probed: false } }); bucket.advance(0.6, 0); await expect(bucket.tick()).resolves.toMatchObject({ result: { probed: true } }); - // A local clock that went backwards probes at once. + // A local clock a little behind the last probe's is skew, and waits. bucket.advance(-10, 0); + await expect(bucket.tick()).resolves.toMatchObject({ result: { probed: false } }); + // A jump back past the reset bound is a clock reset, and probes at once. + bucket.advance(-RESET, 0); await expect(bucket.tick()).resolves.toMatchObject({ result: { probed: true } }); }); + test("writers on two instances whose clocks are 2 minutes apart do not probe on every tick", async () => { + const bucket = await GcBucket.seeded(); + let probes = 0; + const ticks = 24; + for (let i = 0; i < ticks; i++) { + // Fifteen seconds apart, alternating between an instance on time and one 2 minutes behind. + bucket.advance(0.25); + const behind = i % 2 === 1 ? 2 * 60_000 : 0; + bucket.local -= behind; + const { result } = await bucket.tick(); + bucket.local += behind; + probes += result.probed ? 1 : 0; + } + // Six minutes of ticks: about one probe a minute, not one a tick. + expect(probes).toBeLessThanOrEqual(7); + }); + test("between probes a tick lists and deletes nothing, even with work due; the next probe does it", async () => { const bucket = await GcBucket.seeded(); await bucket.tick(); diff --git a/packages/server/src/tree/gc.ts b/packages/server/src/tree/gc.ts index 663d36f4..3c32d549 100644 --- a/packages/server/src/tree/gc.ts +++ b/packages/server/src/tree/gc.ts @@ -44,9 +44,11 @@ * **Clock.** The only clock is the `serverDate` of GC's own state write. * A tick probes it (a state CAS) at most once per * `TREE_GC_CLOCK_PROBE_MINUTES` of local time, judged only against the - * local time of the previous probe. Due tests use that probe's server - * time, or the last one between probes. A probe that reports no server - * time stamps nothing and makes nothing due. + * local time of the previous probe; a local time reading earlier than + * that one probes only past `TREE_GC_CLOCK_RESET_MINUTES`, so writers + * whose clocks are skewed do not probe on every tick. Due tests use + * that probe's server time, or the last one between probes. A probe + * that reports no server time stamps nothing and makes nothing due. * * **Tick.** Only a probe tick collects, so GC's LISTs and DELETEs run * at most once per probe interval, whatever the write rate. Any other @@ -74,6 +76,7 @@ import { retireLogRange } from "../log-retention.ts"; import { ctxMetrics, getCurrentContext } from "../observability/context.ts"; import { TREE_GC_CLOCK_PROBE_MINUTES, + TREE_GC_CLOCK_RESET_MINUTES, TREE_GC_MAX_SWEEP_MARKS, TREE_GC_MAX_WORK_ENTRIES, TREE_GC_SUPERSEDED_DELAY_MINUTES, @@ -162,15 +165,17 @@ export const stateBindsHead = (state: TreeGcState, head: TreeHead): boolean => /** * Whether a tick probes the server clock, by local time alone: the * first probe, at least `TREE_GC_CLOCK_PROBE_MINUTES` after the last, - * or when the local clock reads earlier than the last probe's. + * or more than `TREE_GC_CLOCK_RESET_MINUTES` before it (a clock reset). + * A smaller backward reading is skew between instances, and waits. */ export const probeIsDue = (probedLocalAt: string | null, local: Date): boolean => { if (probedLocalAt === null) { return true; } - const last = Date.parse(probedLocalAt); + const elapsed = local.getTime() - Date.parse(probedLocalAt); return ( - local.getTime() < last || local.getTime() - last >= TREE_GC_CLOCK_PROBE_MINUTES * MINUTE_MS + elapsed >= TREE_GC_CLOCK_PROBE_MINUTES * MINUTE_MS || + elapsed < -TREE_GC_CLOCK_RESET_MINUTES * MINUTE_MS ); }; From 1181a896d5033d1f1f2e8b161d5309b8c3d5201b Mon Sep 17 00:00:00 2001 From: Eric Baer Date: Tue, 24 Nov 2026 12:38:59 -0800 Subject: [PATCH 14/15] fix(tree): check each superseded node's identity in the tree GC drain The winner drain checked that the winner's identity was trusted but not the identity each superseded node carries, unlike the sweep. A winner can supersede every node of an earlier attempt; if an attempt reusing that identity is then in flight and adopts those nodes, the drain deleted them as non-members of the current root and the reusing attempt landed on a tree with missing nodes. A superseded ref whose own attempt is a duplicate or still publishing is now skipped, leak-only, and left to the sweep. --- packages/server/src/tree/gc.test.ts | 36 ++++++++++++++++++++++++++++- packages/server/src/tree/gc.ts | 9 +++++++- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/packages/server/src/tree/gc.test.ts b/packages/server/src/tree/gc.test.ts index 0fa7c93b..2941aeed 100644 --- a/packages/server/src/tree/gc.test.ts +++ b/packages/server/src/tree/gc.test.ts @@ -929,6 +929,30 @@ const strayPageFailure = (mutant?: TreeMutant) => return joined(problems); }); +/** + * Attempt A changes one row and W changes it again, superseding every + * node A wrote. Once they are due, an attempt reusing A's identity + * starts and adopts some of them by writing A's value back. W is a + * trusted winner, but the identity its superseded nodes carry is not: + * GC must not delete them while that attempt can still land. + */ +const supersededReuseFailure = (mutant?: TreeMutant) => + guarded(async () => { + const bucket = await GcBucket.seeded(); + const reused = "a".repeat(32); + await bucket.fold([["k03", 103]], { attempt: reused }); + await bucket.fold([["k03", 303]], { attempt: "c".repeat(32) }); + await bucket.tick(gcConfig(mutant)); + bucket.advance(DELAY + 1); + const retry = await bucket.startFold([["k03", 103]], { attempt: reused }); + await bucket.tick(gcConfig(mutant)); + const outcome = await retry.release(); + if (outcome.kind !== "published" || outcome.adopted === 0) { + return `setup: the retry was ${outcome.kind}, adopting ${outcome.adopted}`; + } + return joined(await bucket.violations()); + }); + // --------------------------------------------------------------------- // Record path // --------------------------------------------------------------------- @@ -1143,6 +1167,10 @@ describe("attempt identity and closure", () => { await expect(quarantineClearsFailure()).resolves.toBeUndefined(); }); + test("a winner's superseded node whose own identity is untrusted is not deleted", async () => { + await expect(supersededReuseFailure()).resolves.toBeUndefined(); + }); + test("a record of another head history is never evidence for the new history's winner", async () => { await expect(generationWitnessFailure()).resolves.toBeUndefined(); }); @@ -1512,7 +1540,13 @@ describe("mutation", () => { [PUBLISH_REUSES_ATTEMPT, [reuseCounterFailure]], [ GC_IGNORES_DUPLICATE_IDENTITY, - [reuseFailure, lateDuplicateFailure, sweepReuseFailure, quarantineClearsFailure], + [ + reuseFailure, + lateDuplicateFailure, + sweepReuseFailure, + quarantineClearsFailure, + supersededReuseFailure, + ], ], [GC_PROCESSES_OPEN_FLOOR, [openFloorFailure]], [GC_IGNORES_GENERATION, [regenerationFailure]], diff --git a/packages/server/src/tree/gc.ts b/packages/server/src/tree/gc.ts index 3c32d549..729d2f7b 100644 --- a/packages/server/src/tree/gc.ts +++ b/packages/server/src/tree/gc.ts @@ -18,7 +18,8 @@ * `TREE_GC_SUPERSEDED_DELAY_MINUTES` after a probe of the storage * server's clock first stamps them, so reads through the replaced * root can finish. The delay is a margin, not a proof: a read that - * outlives it meets the reader's missing-node backstop. A winner + * outlives it meets the reader's missing-node backstop. A superseded + * node whose own attempt GC cannot trust is left to the sweep. A winner * whose identity shows up in another record is quarantined: none of * its superseded nodes is deleted, and once its floor's loser is done * its record is retired leak-only. @@ -863,6 +864,12 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise 0) { const ref = record.superseded[next]!; + if (!deletable(ref.slice(0, 32))) { + // A node of an untrusted identity may be adopted again: it is + // left to the sweep, never deleted from this list. + next += 1; + continue; + } const x = `${nodePrefix}${ref}`; budget -= 1; const found = await steps.isMember(x, view); From a093bf8d738d4c6c0574e37d592b5f3e5a46c0f2 Mon Sep 17 00:00:00 2001 From: Eric Baer Date: Wed, 25 Nov 2026 12:40:51 -0800 Subject: [PATCH 15/15] fix(tree): retain open duplicate publication records Keep duplicate-identity records while their floor can still publish so later GC ticks retain the guard for adopted nodes. Add a regression that verifies a paused adopter survives a due sweep with a duplicate record. Validation: regression fails before the fix; 113 focused tests pass. Repository verification and all 14 bundle budgets pass. --- packages/server/src/tree/gc.test.ts | 17 ++++++++++++++++- packages/server/src/tree/gc.ts | 5 +++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/packages/server/src/tree/gc.test.ts b/packages/server/src/tree/gc.test.ts index 2941aeed..8898ecc0 100644 --- a/packages/server/src/tree/gc.test.ts +++ b/packages/server/src/tree/gc.test.ts @@ -654,7 +654,7 @@ const lateDuplicateFailure = (mutant?: TreeMutant) => * adopts one of them. The sweep must not delete it while that attempt * can still land. */ -const sweepReuseFailure = (mutant?: TreeMutant) => +const sweepReuseFailure = (mutant?: TreeMutant, duplicateRecord = false) => guarded(async () => { const bucket = await GcBucket.seeded(); const reused = "a".repeat(32); @@ -677,6 +677,17 @@ const sweepReuseFailure = (mutant?: TreeMutant) => if (!stamped) { return "setup: no mark of the lost attempt was stamped"; } + if (duplicateRecord) { + const duplicate = await bucket.prepare([ + ["k07", 77], + ["k09", 99], + ]); + await bucket.refreshTailHint(); + const lostAgain = await bucket.publish(duplicate, { attempt: reused }); + if (lostAgain.kind !== "cas-lost") { + return `setup: the duplicate was ${lostAgain.kind}`; + } + } const retry = await bucket.startFold([["k07", 77]], { attempt: reused }); await bucket.tickFor(AGE + 5, gcConfig(mutant)); const outcome = await retry.release(); @@ -1159,6 +1170,10 @@ describe("attempt identity and closure", () => { LONG, ); + test("retiring duplicate records preserves an open publisher's sweep protection", async () => { + await expect(sweepReuseFailure(undefined, true)).resolves.toBeUndefined(); + }); + test("a winner whose identity reappears is quarantined even when its record outlives the tick", async () => { await expect(quarantineFailure()).resolves.toBeUndefined(); }); diff --git a/packages/server/src/tree/gc.ts b/packages/server/src/tree/gc.ts index 729d2f7b..c9a5ed17 100644 --- a/packages/server/src/tree/gc.ts +++ b/packages/server/src/tree/gc.ts @@ -678,9 +678,10 @@ export const runTreeGcTick = async (input: TreeGcInput): Promise