@gusto/baerly-storage 0.1.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +108 -44
- package/dist/API.md +192 -121
- package/dist/CHANGELOG.md +144 -0
- package/dist/THIRD-PARTY-LICENSES.txt +312 -0
- package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-BIzyAKzy.d.ts} +14 -2
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +288 -288
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +10 -10
- package/dist/baerly.js.map +1 -1
- package/dist/bytes-BXdamO3L.js.map +1 -1
- package/dist/{client-DYZfoZb9.d.ts → client-BJXF3XJA.d.ts} +10 -10
- package/dist/client-react.d.ts +76 -85
- package/dist/client-react.js +95 -53
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-CINJPKCW.js → cloudflare-Cn2ibODt.js} +178 -2
- package/dist/cloudflare-Cn2ibODt.js.map +1 -0
- package/dist/cloudflare.d.ts +4 -4
- package/dist/cloudflare.js +10 -11
- package/dist/cloudflare.js.map +1 -1
- package/dist/{subcommand-DZcHcsYp.js → config-CGyBopy3.js} +643 -439
- package/dist/config-CGyBopy3.js.map +1 -0
- package/dist/context-DRZ3tZ5l.js.map +1 -1
- package/dist/{cost-CQt1YRkA.js → cost-BZ_MDBmn.js} +6 -4
- package/dist/cost-BZ_MDBmn.js.map +1 -0
- package/dist/{current-json-C-EyJqs0.js → current-json-DsN7FNY1.js} +47 -13
- package/dist/current-json-DsN7FNY1.js.map +1 -0
- package/dist/{db-BM3y2JQw.d.ts → db-CCT6tDfY.d.ts} +26 -108
- package/dist/{deploy-CrAbfgCq.js → deploy-BKKyGlSJ.js} +11 -4
- package/dist/deploy-BKKyGlSJ.js.map +1 -0
- package/dist/dev-vite.d.ts +5 -5
- package/dist/dev-vite.js +5 -5
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-Db-hzPmE.js → doctor-BVU4GNXN.js} +13 -132
- package/dist/doctor-BVU4GNXN.js.map +1 -0
- package/dist/{dump-BYA55NLP.js → dump-DPEAKub6.js} +5 -3
- package/dist/dump-DPEAKub6.js.map +1 -0
- package/dist/errors-DOdL95kK.js.map +1 -1
- package/dist/{export-Bhbz90-z.js → export-BcuCLFFe.js} +6 -4
- package/dist/{export-Bhbz90-z.js.map → export-BcuCLFFe.js.map} +1 -1
- package/dist/{fsck-CPPZWt9p.js → fsck-RXgLOaJG.js} +23 -11
- package/dist/fsck-RXgLOaJG.js.map +1 -0
- package/dist/{http-Cw8p6y5b.js → http-Bd4byR4n.js} +45 -61
- package/dist/http-Bd4byR4n.js.map +1 -0
- package/dist/http.d.ts +15 -15
- package/dist/http.js +1 -1
- package/dist/{index-cUY-36AN.d.ts → index-BDceQQi-.d.ts} +20 -4
- package/dist/{index-C3JAH1Yo.d.ts → index-Cmsxx-ZN.d.ts} +9 -9
- package/dist/{index-DSvwEUeF.d.ts → index-DW7GT6M2.d.ts} +50 -42
- package/dist/{index-DwDTWPSU.d.ts → index-DnBGSeuU.d.ts} +10 -7
- package/dist/index.d.ts +6 -6
- package/dist/index.js +4 -4
- package/dist/{indexes-DAu2AkTW.d.ts → indexes-Cx7uMXm0.d.ts} +2 -2
- package/dist/{inspect-Bdbzvi-_.js → inspect-DhI49PSi.js} +16 -8
- package/dist/inspect-DhI49PSi.js.map +1 -0
- package/dist/{snapshot-SS8USDUF.js → log-tail-DXeDkWEp.js} +154 -83
- package/dist/log-tail-DXeDkWEp.js.map +1 -0
- package/dist/{maintenance-BRrThz8V.d.ts → maintenance-BkhUr72A.d.ts} +91 -26
- package/dist/{maintenance-ClzBC1Vv.js → maintenance-CWBQpZ2y.js} +368 -161
- package/dist/maintenance-CWBQpZ2y.js.map +1 -0
- package/dist/{maintenance-BvOv6BMM.js → maintenance-C_KSkVjd.js} +204 -82
- package/dist/maintenance-C_KSkVjd.js.map +1 -0
- package/dist/maintenance.d.ts +3 -2
- package/dist/maintenance.js +3 -2
- package/dist/node.d.ts +13 -8
- package/dist/node.js +1 -1
- package/dist/normalize-XWY25_sG.js.map +1 -1
- package/dist/{observability-CpOiEN0k.js → observability-BYd-RzEx.js} +63 -55
- package/dist/observability-BYd-RzEx.js.map +1 -0
- package/dist/observability.d.ts +3 -3
- package/dist/observability.js +1 -1
- package/dist/{plan-DOTl21vq.js → plan-DIu_B6fy.js} +7 -4
- package/dist/plan-DIu_B6fy.js.map +1 -0
- package/dist/{query-BmiQy328.js → query-sQNO5vU_.js} +1071 -1099
- package/dist/query-sQNO5vU_.js.map +1 -0
- package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-DP4CqSSs.js} +5 -4
- package/dist/rebuild-index-DP4CqSSs.js.map +1 -0
- package/dist/{restore-C6IcmLeA.js → restore-DpQYef6r.js} +362 -328
- package/dist/restore-DpQYef6r.js.map +1 -0
- package/dist/shared-secret-BJdSwpgw.js.map +1 -1
- package/dist/{src-QQ7jDeL2.js → src-CWpkSbvJ.js} +40 -20
- package/dist/src-CWpkSbvJ.js.map +1 -0
- package/dist/{src-DU1sCMlr.js → src-D24wDpzR.js} +269 -258
- package/dist/src-D24wDpzR.js.map +1 -0
- package/dist/{src-zhEAmmF7.js → src-Db4-qVtM.js} +36 -96
- package/dist/src-Db4-qVtM.js.map +1 -0
- package/dist/subcommand-CP9NY2J4.js +159 -0
- package/dist/subcommand-CP9NY2J4.js.map +1 -0
- package/dist/{usage-CLjirdD-.js → usage-CTfDq9HR.js} +3 -3
- package/dist/{usage-CLjirdD-.js.map → usage-CTfDq9HR.js.map} +1 -1
- package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
- package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
- package/package.json +42 -31
- package/dist/cloudflare-CINJPKCW.js.map +0 -1
- package/dist/config-DVfDGyw1.js +0 -278
- package/dist/config-DVfDGyw1.js.map +0 -1
- package/dist/cost-CQt1YRkA.js.map +0 -1
- package/dist/current-json-C-EyJqs0.js.map +0 -1
- package/dist/deploy-CrAbfgCq.js.map +0 -1
- package/dist/doctor-Db-hzPmE.js.map +0 -1
- package/dist/dump-BYA55NLP.js.map +0 -1
- package/dist/fsck-CPPZWt9p.js.map +0 -1
- package/dist/http-Cw8p6y5b.js.map +0 -1
- package/dist/inspect-Bdbzvi-_.js.map +0 -1
- package/dist/maintenance-BvOv6BMM.js.map +0 -1
- package/dist/maintenance-ClzBC1Vv.js.map +0 -1
- package/dist/observability-CpOiEN0k.js.map +0 -1
- package/dist/plan-DOTl21vq.js.map +0 -1
- package/dist/query-BmiQy328.js.map +0 -1
- package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
- package/dist/restore-C6IcmLeA.js.map +0 -1
- package/dist/snapshot-SS8USDUF.js.map +0 -1
- package/dist/src-DU1sCMlr.js.map +0 -1
- package/dist/src-QQ7jDeL2.js.map +0 -1
- package/dist/src-zhEAmmF7.js.map +0 -1
- package/dist/subcommand-DZcHcsYp.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"restore-C6IcmLeA.js","names":["#storage","#currentJsonKey","#maxRetries","#initialBackoffMs","#random","#indexes","#verifyLogIntegrityOnCommit","#singleAttemptCommit","#backoff","#verifyFenceUnchanged","#emitWriteMetrics","#provisionCurrentJson","#walkLog","#observe429","#readPreImage"],"sources":["../packages/server/src/log-conflict-adoption.ts","../packages/server/src/writer.ts","../packages/cli/src/admin/restore.ts"],"sourcesContent":["/**\n * Self-session log-conflict adoption — the one decision that\n * distinguishes a retry of our own prior commit attempt from a\n * peer racing us at the same `seq`.\n *\n * Background. `Writer.#singleAttemptCommit` PUTs each log entry with\n * `If-None-Match: \"*\"`. A 412 on `/log/<seq>.json` can mean either\n *\n * (a) a peer wrote a DIFFERENT entry at the same seq — we lost\n * the race; the caller's CAS will also fail; or\n * (b) our OWN previous attempt landed the log PUT but lost the\n * subsequent `current.json` CAS-advance, and we're now\n * re-driving the same logical commit.\n *\n * This function makes the (a)/(b) call. It is callable, separately\n * testable, and patent-disclosable in isolation from the rest of the\n * commit path.\n *\n * ## Soundness invariant\n *\n * Adoption is sound iff all three hold:\n *\n * 1. **Same session.** `existing.session === self.session`. The\n * session id is a per-commit, in-RAM-only secret minted at\n * `Writer.commit` from `crypto.randomUUID().slice(0,\n * SESSION_ID_LENGTH)`; an adversary with bucket-write access\n * can forge any other field but cannot forge a value they\n * did not observe being PUT.\n * 2. **Matching seq.** `existing.seq === self.expectedSeq`. The\n * seq match is also implied by the key shape (the writer\n * reads `/log/<expectedSeq>.json`), but is re-asserted here\n * so the invariant is visible at the decision site.\n * 3. **Single-input commit.** `self.batchSize === 1`. Batches\n * surface a log-PUT 412 as `Conflict` immediately — the\n * caller (`Db.transaction`) decides whether to re-run the\n * body. Adoption inside a batch would require per-input\n * adoption decisions that don't compose with the\n * all-or-nothing CAS-advance on `current.json`.\n *\n * When any of (1)/(2)/(3) fails, the writer MUST throw\n * `BaerlyError{code:\"Conflict\"}` and let the caller's retry-or-\n * surface logic run.\n *\n * ## Threat model\n *\n * The adversary may (a) write arbitrary bytes to any key in the\n * bucket, (b) replay any PUT they previously observed on the wire,\n * (c) reorder or drop network packets between the writer and the\n * bucket. The adversary may NOT (d) read the writer's local RAM\n * and therefore cannot learn the per-commit `session` id before\n * observing the writer's own `/log/<seq>.json` PUT. Under these\n * constraints, conditions (1)+(2)+(3) close every attack path in\n * the adversarial-replay property test\n * (`tests/integration/log-conflict-adversarial.test.ts`).\n *\n * **Pinned by:** `tests/integration/log-conflict-forgery.test.ts`\n * exercises the session-id-unguessability claim under a\n * `ForgeryStorage` adversary that plants arbitrary entries at the\n * writer's expected log key. Property verified by default at\n * `numRuns: 1000`; `FC_NUM_RUNS=10000` for the hardening sweep.\n *\n * ## Prior art\n *\n * SlateDB's manifest-pivot writer protocol (rfcs/0001-manifest.md,\n * scenarios 1–4) is the closest published prior art on the broader\n * commit-protocol skeleton. SlateDB's scenario 3 — \"conflicting SST\n * has same `writer_epoch` as me\" — is explicitly labelled an\n * **illegal state that should panic**. The three-clause adoption\n * decision encoded here (same session ∧ matching seq ∧ single-input)\n * recognises that case as the writer's own prior in-flight attempt\n * and adopts it as success rather than aborting, closing the recovery\n * gap SlateDB leaves to operator intervention.\n *\n * Apache Iceberg and Delta Lake commits surface analogous failures as\n * `CommitFailedException` / commit-conflict retries; neither inspects\n * the conflicting object to determine ownership.\n *\n * See `docs/spec/prior-art.md` for the consolidated IDS-shaped\n * differentiation.\n *\n * @see docs/spec/sync-protocol.md §\"Self-session log-conflict adoption\"\n */\n\nimport type { LogEntry } from \"@baerly/protocol\";\n\n/**\n * Inputs to {@link tryAdoptOwnSessionLogEntry}. All fields are\n * required; the writer constructs this struct at the call site.\n */\nexport interface AdoptionContext {\n /**\n * The entry the writer just attempted to PUT. Carries the\n * writer's session, expected seq, and the rest of the LogEntry\n * shape minted in `Writer.#singleAttemptCommit` step 3.\n */\n readonly self: LogEntry;\n /**\n * The entry currently stored at `/log/<self.seq>.json`, as read\n * back after a 412. The caller is responsible for the GET (the\n * function is pure, no I/O).\n */\n readonly existing: LogEntry;\n /**\n * `inputs.length` for the parent commit attempt. `1` for\n * `Writer.commit`; `inputs.length` for `Writer.commitBatch`.\n * Adoption is only safe when this is exactly `1`.\n */\n readonly batchSize: number;\n}\n\n/**\n * Discriminated outcome of {@link tryAdoptOwnSessionLogEntry}.\n * `adopt: true` carries the existing entry (which by the\n * invariant is byte-identical to `self` modulo `commit_ts`); the\n * caller substitutes it for `self` so the returned `CommitResult`\n * matches what's actually stored. `adopt: false` carries a\n * machine-readable `reason` so callers and tests can discriminate\n * which clause of the invariant failed.\n */\nexport type AdoptionDecision =\n | { readonly adopt: true; readonly entry: LogEntry }\n | { readonly adopt: false; readonly reason: \"foreign-session\" | \"wrong-seq\" | \"batch\" };\n\n/**\n * Decide whether the entry already at `/log/<seq>.json` is the\n * writer's own prior in-flight attempt and may be adopted. Pure\n * function; no I/O. The caller performs the GET (when the log PUT\n * surfaces 412) and passes the read-back body in `ctx.existing`.\n *\n * @see {@link AdoptionDecision} for the return shape.\n * @see The soundness invariant in this module's header docstring.\n */\nexport const tryAdoptOwnSessionLogEntry = (ctx: AdoptionContext): AdoptionDecision => {\n // Clause (3) — single-input commit. Evaluated first so a batched\n // call short-circuits before any field comparison.\n if (ctx.batchSize !== 1) {\n return { adopt: false, reason: \"batch\" };\n }\n // Clause (1) — same session.\n if (ctx.existing.session !== ctx.self.session) {\n return { adopt: false, reason: \"foreign-session\" };\n }\n // Clause (2) — matching seq. The seq is also implied by the\n // key the caller read from, but re-asserted here for\n // patent-disclosure clarity.\n if (ctx.existing.seq !== ctx.self.seq) {\n return { adopt: false, reason: \"wrong-seq\" };\n }\n return { adopt: true, entry: ctx.existing };\n};\n","/**\n * `Writer` — stateless multi-instance write engine.\n *\n * Each {@link Writer.commit} call reads `current.json` FRESH from\n * the bucket, mints the next {@link LogEntry}, PUTs the content body\n * and the log entry, and CAS-advances `current.json` with `If-Match`.\n * Up to {@link S3_REQUEST_MAX_RETRIES} attempts on contention before\n * surfacing `BaerlyError{code:\"Conflict\"}`. The optional integrity\n * walk over the live log tail is gated by\n * {@link WriterOptions.verifyLogIntegrityOnCommit} (default off\n * — see the option's docstring).\n *\n * The instance carries no per-write cache: every commit re-reads\n * `current.json`, so N stateless server instances writing the same\n * tenant prefix contend at exactly one place — the conditional PUT\n * on `current.json` — and one loses cleanly with a 412.\n *\n * **Manifest-first ordering is REVERSED relative to the legacy\n * `src/syncer.ts` write loop.** Old loop: PUT manifest → PUT content\n * → CAS. New loop: PUT content → PUT log entry → CAS-advance\n * `current.json`. A crashed mid-loop writer leaves an unreferenced\n * content body (no log entry points at it), not an orphan log entry\n * with missing content. The compactor sweeps the orphan content\n * later.\n *\n * **`LogEntry` shape.** Emitted entries follow the contract in\n * `packages/protocol/src/log.ts` (see {@link LogEntry}) and\n * `docs/spec/log-entry-shape.md`. The on-bucket key is\n * `log/<seq>.json` (the integer `seq` is the load-bearing\n * identifier; the `lsn` string is schema-only).\n *\n * @see docs/spec/sync-protocol.md for the protocol invariants this\n * loop preserves.\n * @see docs/spec/log-entry-shape.md for the per-field contract.\n */\n\nimport {\n CURRENT_JSON_SCHEMA_VERSION,\n type CurrentJson,\n type CurrentJsonRead,\n type DocumentData,\n type LogEntry,\n type MetricsRecorder,\n createCurrentJson,\n decodeJsonBytes,\n encodeJsonBytes,\n logSeqStartOf,\n BaerlyError,\n noopMetricsRecorder,\n type Storage,\n type StoragePutOptions,\n type StoragePutResult,\n S3_REQUEST_MAX_RETRIES,\n SESSION_ID_LENGTH,\n WRITE_TICK_GC_INTERVAL,\n countKey,\n readCurrentJson,\n timestamp,\n uuid,\n versionFromContent,\n} from \"@baerly/protocol\";\nimport { allIndexKeysFor, type IndexDefinition, validateIndexDefinition } from \"./indexes.ts\";\nimport { readLogEntry, walkLogRange } from \"./log-walk.ts\";\nimport { tryAdoptOwnSessionLogEntry } from \"./log-conflict-adoption.ts\";\nimport {\n dispatchInlineAwaited,\n runBoundedMaintenance,\n shouldFireMaintenance,\n} from \"./maintenance.ts\";\nimport { getCurrentContext } from \"./observability/context.ts\";\n\nconst ctxMetrics = (): MetricsRecorder => getCurrentContext()?.recorder ?? noopMetricsRecorder;\n\n/**\n * Tunables for {@link Writer}. All optional; defaults match the\n * legacy retry budget so the new loop is a drop-in replacement.\n */\nexport interface WriterOptions {\n /**\n * Max CAS attempts on 412 before throwing `Conflict`. Default\n * {@link S3_REQUEST_MAX_RETRIES} (8). Override only in tests.\n */\n readonly maxRetries?: number;\n\n /** Initial backoff in ms; doubles per attempt, capped at 1500ms. Default 25. */\n readonly initialBackoffMs?: number;\n\n /**\n * Pure function returning a number in [0, 1). Used for jitter; tests\n * inject a deterministic generator. Defaults to `Math.random`.\n */\n readonly random?: () => number;\n\n /**\n * Optional. Indexes declared for the collection this writer\n * commits to. Each commit emits one zero-byte PUT per declared\n * index (when the indexed field is set on the doc) inside the\n * same fence as the log entry and content body. On U/D, the\n * writer reads the pre-image content body from the log (one\n * back-walk per indexed collection, NOT per index) to compute\n * the stale-key set; stale keys are DELETE'd inside the same\n * fence.\n *\n * Validated at construction via {@link validateIndexDefinition} —\n * an invalid def throws `BaerlyError{code:\"SchemaError\"}`\n * synchronously, before the first commit. Empty / undefined is\n * a no-op (writer behaves identically to the no-index path — no\n * extra GET, no extra PUTs).\n *\n * Note: `Writer` is per-collection (the `currentJsonKey`\n * is per-collection), so this array applies to one collection\n * only — adapters that serve multiple collections instantiate\n * one writer per collection.\n *\n * Emits one new metric when at least one index is declared:\n * - `db.write.index_ops_per_logical_write` (histogram,\n * labelled by `collection`) — `K (PUT) + L (DELETE)` per\n * successful commit.\n */\n readonly indexes?: ReadonlyArray<IndexDefinition>;\n\n /**\n * When `true`, every commit walks the live log range\n * `[log_seq_start, next_seq)` before minting a new entry, surfacing\n * a missing or malformed entry as `BaerlyError{code:\"Internal\"}`\n * (or `\"InvalidResponse\"` for parse failures). The walk is purely\n * observational — the per-doc fold lives in the read path\n * (`./query.ts`) and any hole inside the visible range would also\n * fire on the next read.\n *\n * Production callers default this OFF: under contention the walk\n * issues `O(tail)` Class-B GETs per CAS attempt and the retry\n * budget multiplies that by {@link S3_REQUEST_MAX_RETRIES}. Tests\n * that intentionally puncture bucket state to exercise the\n * invariant trigger opt in by passing `true`.\n *\n * Default `false`.\n */\n readonly verifyLogIntegrityOnCommit?: boolean;\n}\n\n/**\n * Single-doc mutation request. One `commit()` ↔ one {@link LogEntry}.\n */\nexport interface CommitInput {\n /** The mutation op. Maps directly to {@link LogEntry.op}. */\n readonly op: \"I\" | \"U\" | \"D\";\n\n /** The collection (table) name. Becomes {@link LogEntry.collection}. */\n readonly collection: string;\n\n /** The document primary key. Becomes {@link LogEntry.doc_id}. */\n readonly docId: string;\n\n /**\n * For `I` / `U`: the post-image. Becomes {@link LogEntry.after}. Must\n * be `undefined` for `op: \"D\"`.\n */\n readonly body?: DocumentData;\n\n /** Optional ISO-8601 origin marker; becomes {@link LogEntry.origin}. */\n readonly origin?: string;\n}\n\n/** Return shape of {@link Writer.commit}. */\nexport interface CommitResult {\n /** The committed `LogEntry`. Caller can ack on `entry.lsn`. */\n readonly entry: LogEntry;\n\n /** New ETag of `current.json` after the CAS-advance landed. */\n readonly currentEtag: string;\n\n /** How many CAS attempts it took (1 = first try won). */\n readonly attempts: number;\n}\n\n/** Return shape of {@link Writer.commitBatch}. */\nexport interface CommitBatchResult {\n /**\n * One emitted `LogEntry` per input, in input order.\n * `entries[i]` corresponds to `inputs[i]`. `entries.length ===\n * inputs.length`. On an empty input array `entries` is empty and\n * no I/O happened.\n */\n readonly entries: readonly LogEntry[];\n\n /**\n * New ETag of `current.json` after the CAS-advance landed.\n * `undefined` on an empty input array (the CAS step is skipped).\n */\n readonly currentEtag: string | undefined;\n}\n\nconst DEFAULT_INITIAL_BACKOFF_MS = 25;\nconst MAX_BACKOFF_MS = 1500;\nconst APPLICATION_JSON = \"application/json\";\n\n/**\n * Empty body for index entries. Each index entry is a fact (\"doc\n * `<docId>` has `<field> = <value>`\"), not data — readers list the\n * prefix, extract the doc id, then GET the content body separately.\n * Pre-allocated module-level constant so every index PUT shares one\n * zero-length buffer.\n */\nconst EMPTY_BODY = new Uint8Array(0);\n\n/**\n * Successful outcome of one full {@link Writer.#singleAttemptCommit}\n * attempt. Retryable failures (log-peer race, CAS 412) throw\n * `BaerlyError{code:\"Conflict\"}` directly; the caller catches via\n * {@link isPreconditionFailed} and decides whether to retry. Non-retryable\n * failures (fence bump, protocol-invariant violations, network errors)\n * also throw, but the caller verifies the fence OUTSIDE the catch arm so\n * the fence-bump `Conflict` propagates instead of being mistaken for a\n * retryable CAS loss.\n */\ninterface SingleAttemptSuccess {\n readonly entries: readonly LogEntry[];\n readonly currentEtag: string;\n readonly classAOps: number;\n readonly expectedEpoch: number;\n}\n\n/**\n * Stateless write engine for the multi-instance core.\n *\n * Construction is cheap and performs zero I/O — adapters build a\n * fresh `Writer` per request and discard it. All real work\n * happens in {@link commit}.\n *\n * @example\n * ```ts\n * import { Writer } from \"@gusto/baerly-storage\";\n * import { MemoryStorage } from \"@gusto/baerly-storage\";\n *\n * const writer = new Writer({\n * storage: new MemoryStorage(),\n * currentJsonKey: \"app/tickets/tenant/acme/manifests/tickets/current.json\",\n * });\n *\n * const result = await writer.commit({\n * op: \"I\",\n * collection: \"tickets\",\n * docId: \"doc-1\",\n * body: { _id: \"doc-1\", title: \"hello\" },\n * });\n * console.log(result.entry.seq, result.attempts);\n * ```\n */\nexport class Writer {\n readonly #storage: Storage;\n readonly #currentJsonKey: string;\n readonly #maxRetries: number;\n readonly #initialBackoffMs: number;\n readonly #random: () => number;\n readonly #indexes: ReadonlyArray<IndexDefinition>;\n readonly #verifyLogIntegrityOnCommit: boolean;\n\n constructor(opts: {\n storage: Storage;\n /**\n * Full bucket-relative key of the CAS pointer, e.g.\n * `app/tickets/tenant/acme/manifests/tickets/current.json`. The\n * collection-prefix half lives at\n * `currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"))` — the\n * log and content keys are derived from it.\n */\n currentJsonKey: string;\n options?: WriterOptions;\n }) {\n this.#storage = opts.storage;\n this.#currentJsonKey = opts.currentJsonKey;\n this.#maxRetries = opts.options?.maxRetries ?? S3_REQUEST_MAX_RETRIES;\n this.#initialBackoffMs = opts.options?.initialBackoffMs ?? DEFAULT_INITIAL_BACKOFF_MS;\n this.#random = opts.options?.random ?? Math.random;\n const indexes = opts.options?.indexes ?? [];\n for (const def of indexes) {\n validateIndexDefinition(def);\n }\n this.#indexes = indexes;\n this.#verifyLogIntegrityOnCommit = opts.options?.verifyLogIntegrityOnCommit ?? false;\n }\n\n /**\n * Atomically commit one mutation. Reads `current.json` fresh, mints\n * the next log entry at `seq = current.next_seq`, PUTs the content\n * body and the log entry, then CAS-advances `current.json` with\n * `If-Match`. Retries on conflict up to `maxRetries`.\n *\n * The hot-path cost under no contention is 1 GET + 3 PUTs (4 ops);\n * an in-flight peer write costs one extra GET + the backoff sleep\n * per retry.\n *\n * Idempotency: PUT content uses `If-None-Match: \"*\"`, so a retry of\n * the same logical write produces the same content key and the\n * second PUT no-ops. PUT log entry also uses `If-None-Match: \"*\"`,\n * so two writers racing the same `next_seq` cause exactly one PUT\n * to land — the loser falls into the CAS retry path.\n *\n * @throws BaerlyError code=\"Conflict\" when the retry budget is\n * exhausted (genuine high-contention case), or when the underlying\n * `current.json` CAS PUT lost.\n * @throws BaerlyError code=\"Conflict\" — the writer fence\n * (`current.json.writer_fence.epoch`) was bumped by a concurrent\n * `claimWriter` call between this commit's read of\n * `current.json` and its CAS-advance. The stale writer aborts\n * to honour the new authority — the kernel does NOT retry under\n * the old epoch. See {@link claimWriter} for the rotation\n * recipe.\n * @throws BaerlyError code=\"Internal\" when a log entry expected in\n * `[0, next_seq)` is missing — a protocol-invariant violation\n * (compactor bug or stale `current.json`).\n * @throws BaerlyError code=\"InvalidResponse\" when a log-entry body\n * isn't valid JSON.\n *\n * **Implicit provisioning.** When `current.json` does not exist at\n * `currentJsonKey` (fresh bucket, fresh collection), the writer\n * auto-creates it with a zero-state manifest before the commit\n * lands. The cost is one extra Class A PUT on the very first\n * commit per collection; steady-state cost is unchanged. A peer\n * racing the same first-write loses cleanly on the create CAS\n * and re-reads to pick up the winner's manifest.\n */\n async commit(input: CommitInput): Promise<CommitResult> {\n const session = uuid().slice(0, SESSION_ID_LENGTH);\n const logPrefix = this.#currentJsonKey.slice(0, this.#currentJsonKey.lastIndexOf(\"/\"));\n\n for (let attempt = 1; attempt <= this.#maxRetries; attempt++) {\n let success: SingleAttemptSuccess;\n try {\n success = await this.#singleAttemptCommit(\n [input],\n session,\n logPrefix,\n \"Writer\",\n /* adoptOwnSessionOnLogConflict */ true,\n );\n } catch (error) {\n // Only retryable conflicts (storage 412 on log PUT or\n // current.json CAS) come back as `Conflict`. The fence-bump\n // throw happens AFTER the helper returns, so it never\n // reaches this catch arm. Anything else propagates.\n if (!isPreconditionFailed(error)) {\n throw error;\n }\n await this.#backoff(attempt);\n continue;\n }\n // Fence verify lives in the caller so its `Conflict` propagates\n // past the retry-catch arm above. Bypasses the retry loop —\n // the stale writer must defer to the new authority.\n await this.#verifyFenceUnchanged(success.expectedEpoch, \"Writer\");\n // `success.classAOps` is the per-attempt base; add `(attempt\n // - 1)` to bill prior failed attempts as one PUT each (the\n // simple-and-test-locked cost model — not a precise replay\n // of every PUT in every dropped attempt).\n this.#emitWriteMetrics(input.collection, success.classAOps + (attempt - 1));\n return {\n entry: success.entries[0]!,\n currentEtag: success.currentEtag,\n attempts: attempt,\n };\n }\n\n // Retry budget exhausted.\n throw new BaerlyError(\n \"Conflict\",\n `Writer: CAS conflict on ${this.#currentJsonKey} after ${this.#maxRetries} attempts`,\n );\n }\n\n /**\n * Single-attempt batched commit. Reads `current.json` ONCE, mints\n * `inputs.length` log entries with contiguous `seq` numbers\n * starting at the current `next_seq`, PUTs each content body and\n * each log entry, then CAS-advances `current.json` from\n * `next_seq = N` to `next_seq = N + inputs.length` with\n * `If-Match`.\n *\n * NO retry on CAS loss. On `current.json` 412, throws\n * `BaerlyError{code:\"Conflict\"}` immediately — the caller (here:\n * `Db.transaction`) decides whether to retry by re-running the\n * body, or to surface to the app. Likewise on a log-entry 412\n * (a peer wrote our seq).\n *\n * Empty `inputs`: returns `{ entries: [], currentEtag: undefined }`\n * after zero storage operations.\n *\n * @throws BaerlyError code=\"Conflict\" — CAS lost on `current.json`,\n * or a log entry already exists at our seq (peer wrote ahead).\n * @throws BaerlyError code=\"Conflict\" — the writer fence\n * (`current.json.writer_fence.epoch`) was bumped by a concurrent\n * `claimWriter` call between this batch's read of\n * `current.json` and its CAS-advance. The stale writer aborts\n * to honour the new authority — the kernel does NOT retry under\n * the old epoch. See {@link claimWriter} for the rotation\n * recipe.\n * @throws BaerlyError code=\"Internal\" — protocol-invariant violation\n * (missing log entry inside `[0, next_seq)`).\n * @throws BaerlyError code=\"InvalidResponse\" — malformed log body.\n *\n * **Implicit provisioning.** Like {@link commit}, this path auto-\n * creates `current.json` with a zero-state manifest on a missing\n * read. Because `commitBatch` does NOT retry on CAS loss, a peer\n * racing the same first-write surfaces `Conflict` to the caller\n * (`Db.transaction` re-runs the body); the manifest is durable\n * regardless of which writer won the create.\n */\n async commitBatch(inputs: readonly CommitInput[]): Promise<CommitBatchResult> {\n if (inputs.length === 0) {\n return { entries: [], currentEtag: undefined };\n }\n\n const session = uuid().slice(0, SESSION_ID_LENGTH);\n const logPrefix = this.#currentJsonKey.slice(0, this.#currentJsonKey.lastIndexOf(\"/\"));\n\n // No retry — `#singleAttemptCommit`'s `Conflict` (log-peer race\n // or `current.json` CAS loss) propagates verbatim to the caller\n // (`Db.transaction` decides whether to re-run the body). The\n // fence-bump check sits AFTER the helper returns so its\n // `Conflict` propagates with the fence-bump message rather than\n // a generic CAS-loss one.\n const success = await this.#singleAttemptCommit(\n inputs,\n session,\n logPrefix,\n \"Writer.commitBatch\",\n /* adoptOwnSessionOnLogConflict */ false,\n );\n await this.#verifyFenceUnchanged(success.expectedEpoch, \"Writer.commitBatch\");\n // Pick the first input's collection as the batch label; in the\n // current `Db.transaction` model every input shares one\n // collection, so this is exact. If future tickets relax that\n // we'll need a per-collection split here.\n this.#emitWriteMetrics(inputs[0]!.collection, success.classAOps);\n return { entries: success.entries, currentEtag: success.currentEtag };\n }\n\n /**\n * One full commit attempt — the shared body of {@link commit} and\n * {@link commitBatch}. Reads `current.json`, walks the log, mints N\n * entries, PUTs content + indexes in parallel, PUTs log entries,\n * CAS-advances `current.json`. Returns the success payload + the\n * pre-commit fence epoch so the caller can run\n * {@link #verifyFenceUnchanged} outside the retry-catch arm.\n *\n * Retryable failures (a peer wrote our seq; a peer won the CAS on\n * `current.json`) throw `BaerlyError{code:\"Conflict\"}`. The caller\n * catches via {@link isPreconditionFailed} and either retries\n * (`commit`) or surfaces (`commitBatch`). Fence-bump and protocol-\n * invariant violations are NOT thrown from this helper — the fence\n * check lives in the caller so its `Conflict` propagates past the\n * retry-catch arm. Other thrown `BaerlyError`s (Internal,\n * InvalidResponse, NetworkError) bypass `isPreconditionFailed` and\n * propagate naturally.\n *\n * Crash safety invariant: content / index PUTs are awaited before\n * log PUTs, which are awaited before the CAS. A crashed mid-attempt\n * writer leaves orphan content / index entries (no log entry\n * references them) — the compactor sweeps the orphans. The\n * inverse — orphan log entry with missing content — is never\n * produced.\n */\n async #singleAttemptCommit(\n inputs: readonly CommitInput[],\n session: string,\n logPrefix: string,\n errorPrefix: string,\n adoptOwnSessionOnLogConflict: boolean,\n ): Promise<SingleAttemptSuccess> {\n // ── Step 1. Read current.json (fresh; carries the ETag). ────────\n // On a fresh bucket / fresh collection the manifest doesn't exist\n // yet. Auto-create it with a zero-state initial so `db.collection(x)\n // .insert(...)` works zero-shot. A peer racing the same create\n // loses cleanly on `If-None-Match: \"*\"`; we re-read to pick up\n // the winner's manifest. Cost: one extra Class A PUT on the very\n // first commit per collection, zero overhead thereafter.\n const read =\n (await readCurrentJson(this.#storage, this.#currentJsonKey)) ??\n (await this.#provisionCurrentJson());\n const current = read.json;\n const baseEtag = read.etag;\n const expectedEpoch = current.writer_fence.epoch;\n\n // ── Step 2. Optional integrity walk (`verifyLogIntegrityOnCommit`,\n // default off). Surfaces missing / malformed entries inside\n // `[log_seq_start, next_seq)` as `Internal` / `InvalidResponse`;\n // entries below `log_seq_start` are folded into the snapshot\n // by `compact()` and possibly swept by `runGc()`, so the walk is\n // bounded to the live tail. The read path catches the same\n // conditions on the next consult — production callers leave the\n // walk off to avoid `O(tail)` Class-B GETs per CAS attempt.\n if (this.#verifyLogIntegrityOnCommit) {\n await this.#walkLog(logPrefix, logSeqStartOf(current), current.next_seq);\n }\n\n // ── Step 3. Mint N LogEntries with contiguous seqs. ─────────────\n // All entries share `session` (one session per logical commit) and\n // a single commit instant: `lsn`'s timestamp and `commit_ts` are\n // derived from ONE clock read so they can't drift apart under skew\n // (a reader validates `commit_ts` against `LAG_WINDOW_MILLIS`, and\n // two independent reads could straddle that band). Intra-batch\n // ordering is by `seq` (the `countKey` lsn suffix), not the shared\n // timestamp, so one instant for the whole batch is correct.\n const commitNowMs = Date.now();\n const commitTs = new Date(commitNowMs).toISOString();\n const lsnTimestamp = timestamp(commitNowMs);\n const entries: LogEntry[] = [];\n for (let i = 0; i < inputs.length; i++) {\n const input = inputs[i]!;\n const seq = current.next_seq + i;\n const lsn = `${lsnTimestamp}_${session}_${countKey(seq)}`;\n const entry: LogEntry = {\n lsn,\n commit_ts: commitTs,\n op: input.op,\n collection: input.collection,\n doc_id: input.docId,\n session,\n seq,\n ...(input.op !== \"D\" && input.body !== undefined ? { after: input.body } : {}),\n ...(input.origin !== undefined ? { origin: input.origin } : {}),\n };\n entries.push(entry);\n }\n\n // ── Step 4. PUT content bodies + index entries in parallel. ─────\n // Content PUT: `ifNoneMatch: \"*\"` makes a same-hash re-write a\n // no-op (412 swallowed). Crash-recovery and same-body replay\n // both rely on this idempotency property.\n //\n // Index PUT: each declared index emits one zero-byte PUT per new\n // key. On `U` / `D` the pre-image is sourced from an earlier\n // same-`docId` input in this batch (if any) before falling back\n // to a log back-walk — preserves correctness when a transaction\n // does `[I, U]` or `[U, D]` on the same doc.\n //\n // Empty `#indexes` short-circuits the index block (including the\n // pre-image GET), preserving zero behaviour change for\n // collections without declared indexes.\n //\n // Filter-aware projection (T4): `allIndexKeysFor` short-circuits\n // on `def.predicate` miss. The writer's diff `oldKeys` vs\n // `newKeys` transparently covers all four U-quadrants without any\n // structural change here:\n //\n // match → match : both non-empty; diff PUTs/DELETEs as today.\n // match → miss : oldKeys non-empty, newKeys empty → DELETE all.\n // miss → match : oldKeys empty, newKeys non-empty → PUT all.\n // miss → miss : both empty → no-op for this def.\n //\n // All four quadrants are pinned by named tests in\n // `writer.test.ts` (\"Writer — filtered index\"). Do\n // not collapse them into one combined case — a regression in one\n // quadrant should fail exactly one named test so the bug is\n // localisable.\n let contentPutCount = 0;\n let indexClassA = 0;\n const parallelPuts: Array<Promise<unknown>> = [];\n // Per-docId in-batch image map: tracks the latest post-image\n // each input lays down so a later input on the same docId reads\n // the in-batch pre-image, not the on-disk one.\n const inBatchImage = new Map<string, DocumentData | undefined>();\n for (const input of inputs) {\n if (input.op !== \"D\" && input.body !== undefined) {\n contentPutCount++;\n const bytes = encodeJsonBytes(input.body);\n const version = await versionFromContent(bytes);\n const contentKey = `${logPrefix}/content/${version}.json`;\n parallelPuts.push(\n this.#storage\n .put(contentKey, bytes, { ifNoneMatch: \"*\", contentType: APPLICATION_JSON })\n .catch((error: unknown) => {\n this.#observe429(error, input.collection);\n if (isPreconditionFailed(error)) {\n return;\n }\n throw error;\n }),\n );\n }\n if (this.#indexes.length > 0) {\n let newKeys: readonly string[] = [];\n let staleKeys: readonly string[] = [];\n if (input.op === \"I\") {\n newKeys = allIndexKeysFor(logPrefix, this.#indexes, input.body, input.docId);\n } else if (input.op === \"U\") {\n const preImage = inBatchImage.has(input.docId)\n ? inBatchImage.get(input.docId)\n : await this.#readPreImage(logPrefix, input.collection, input.docId, current.next_seq);\n const oldKeys = allIndexKeysFor(logPrefix, this.#indexes, preImage, input.docId);\n newKeys = allIndexKeysFor(logPrefix, this.#indexes, input.body, input.docId);\n const newSet = new Set(newKeys);\n staleKeys = oldKeys.filter((k) => !newSet.has(k));\n } else {\n const preImage = inBatchImage.has(input.docId)\n ? inBatchImage.get(input.docId)\n : await this.#readPreImage(logPrefix, input.collection, input.docId, current.next_seq);\n staleKeys = allIndexKeysFor(logPrefix, this.#indexes, preImage, input.docId);\n }\n for (const k of newKeys) {\n parallelPuts.push(\n this.#storage\n .put(k, EMPTY_BODY, { ifNoneMatch: \"*\", contentType: APPLICATION_JSON })\n .catch((error: unknown) => {\n this.#observe429(error, input.collection);\n if (isPreconditionFailed(error)) {\n return;\n }\n throw error;\n }),\n );\n }\n for (const k of staleKeys) {\n // Storage.delete is contractually idempotent — no defensive catch.\n parallelPuts.push(this.#storage.delete(k));\n }\n indexClassA += newKeys.length + staleKeys.length;\n if (newKeys.length + staleKeys.length > 0) {\n ctxMetrics().histogram(\n \"db.write.index_ops_per_logical_write\",\n newKeys.length + staleKeys.length,\n { collection: input.collection },\n );\n }\n inBatchImage.set(input.docId, input.op === \"D\" ? undefined : input.body);\n }\n }\n await Promise.all(parallelPuts);\n\n // ── Step 5. PUT log entries. ────────────────────────────────────\n // `ifNoneMatch: \"*\"` per entry. On 412 we bump the counter and\n // record the rejection; the disposition (adopt vs surface) is\n // computed below from the aggregated results.\n //\n // Two cases on 412:\n // (a) a peer wrote a DIFFERENT entry at the same seq — we lost\n // the race; the caller's CAS will also fail.\n // (b) (single-input commit only) our OWN previous attempt\n // landed step 5 but lost step 6, and we're now re-driving\n // the same logical commit. Adopt it and proceed to CAS so\n // the advance gets a chance to commit.\n //\n // We discriminate by `session`: the random per-call id uniquely\n // identifies \"our own previous attempt.\" Adoption is only safe\n // when there's exactly one entry to compare (`commit`'s N=1 case);\n // batch commits surface log-PUT 412s as `Conflict` immediately.\n type LogPutOutcome = { readonly ok: true } | { readonly ok: false };\n const logPutOne = async (entry: LogEntry): Promise<LogPutOutcome> => {\n const logEntryKey = `${logPrefix}/log/${entry.seq}.json`;\n const logBytes = encodeJsonBytes(entry);\n try {\n await this.#storage.put(logEntryKey, logBytes, {\n ifNoneMatch: \"*\",\n contentType: APPLICATION_JSON,\n });\n return { ok: true };\n } catch (error) {\n this.#observe429(error, entry.collection);\n if (!isPreconditionFailed(error)) {\n throw error;\n }\n ctxMetrics().counter(\"db.r2.put.412_total\", 1, {\n collection: entry.collection,\n step: \"log-put\",\n });\n return { ok: false };\n }\n };\n const logPutResults = await Promise.all(entries.map(logPutOne));\n let committedEntries: readonly LogEntry[] = entries;\n const firstConflictIdx = logPutResults.findIndex((r) => !r.ok);\n if (firstConflictIdx !== -1) {\n const conflictedEntry = entries[firstConflictIdx]!;\n const logEntryKey = `${logPrefix}/log/${conflictedEntry.seq}.json`;\n if (adoptOwnSessionOnLogConflict) {\n const existing = await readLogEntry(this.#storage, logEntryKey);\n const decision = tryAdoptOwnSessionLogEntry({\n self: conflictedEntry,\n existing,\n batchSize: inputs.length,\n });\n if (decision.adopt) {\n committedEntries = [decision.entry];\n } else {\n throw new BaerlyError(\n \"Conflict\",\n `${errorPrefix}: log entry already exists at ${logEntryKey}; ${decision.reason}`,\n );\n }\n } else {\n throw new BaerlyError(\n \"Conflict\",\n `${errorPrefix}: log entry already exists at ${logEntryKey}; peer wrote our seq`,\n );\n }\n }\n\n // ── Step 6. CAS-advance current.json with If-Match. ─────────────\n // Bind to `baseEtag` from step 1 — re-reading would risk advancing\n // `next_seq` past a seq we never wrote a log entry for.\n //\n // Accumulate `tail_bytes` EXACTLY. The compactor later subtracts the\n // bytes of the log objects it folds, summed from the fetched object\n // bodies — i.e. exactly what the writer PUT per entry\n // (`encodeJsonBytes(entry)` in `logPutOne`). Counting the writer-add\n // and the compactor-subtract over the identical bytes keeps\n // `tail_bytes` exact under the full-fence CAS. Sum over\n // `committedEntries` (the source of truth for what's actually in the\n // tail — `entries` normally, or the single adopted entry on the\n // own-session-adoption path), NOT `inputs`.\n const batchLogBytes = committedEntries.reduce(\n (sum, e) => sum + encodeJsonBytes(e).byteLength,\n 0,\n );\n const next: CurrentJson = {\n ...current,\n next_seq: current.next_seq + inputs.length,\n tail_bytes: current.tail_bytes + batchLogBytes,\n };\n // Cadence-invariant assert (cheap, load-bearing). The GC write-tick\n // cadence keys off `next_seq` advancing by exactly the number of log\n // entries written. Today one input ⇒ one log entry, so `next_seq`\n // advances by `inputs.length` and `committedEntries.length ===\n // inputs.length` (the adoption path adopts the single in-flight\n // entry of a 1-input commit, preserving the identity). Pin it so a\n // future change that makes one input emit ≠1 entries fails LOUD here\n // instead of silently skewing the GC cadence.\n if (next.next_seq - current.next_seq !== inputs.length) {\n throw new BaerlyError(\n \"Internal\",\n `${errorPrefix}: GC-cadence invariant violated — next_seq advanced by ${\n next.next_seq - current.next_seq\n } but ${inputs.length} input(s) were committed on ${this.#currentJsonKey}`,\n );\n }\n const nextBody = encodeJsonBytes(next);\n const putOpts: StoragePutOptions = {\n ifMatch: baseEtag,\n contentType: APPLICATION_JSON,\n };\n let result: StoragePutResult;\n try {\n result = await this.#storage.put(this.#currentJsonKey, nextBody, putOpts);\n } catch (error) {\n this.#observe429(error, inputs[0]!.collection);\n if (isPreconditionFailed(error)) {\n ctxMetrics().counter(\"db.r2.put.412_total\", 1, {\n collection: inputs[0]!.collection,\n step: \"current-json-cas\",\n });\n throw new BaerlyError(\n \"Conflict\",\n `${errorPrefix}: CAS conflict on ${this.#currentJsonKey}`,\n );\n }\n throw error;\n }\n\n // ── Step 6b. Write-tick maintenance dispatch. ───────────────────\n // Single funnel site reached by BOTH `commit()` and `commitBatch()`\n // exactly once per logical commit (a CAS retry re-enters this helper\n // and dispatches once per successful attempt — but a successful CAS\n // ends the retry loop, so a logical commit dispatches once). Sits\n // BEFORE the caller's `#verifyFenceUnchanged` — a write that then\n // fails its fence check may have paid for one bounded maintenance\n // pass; that's the intended single funnel, bounded and safe.\n //\n // Config rides the per-request observability context\n // (`getCurrentContext()?.maintenance`), set by the adapter — NOT the\n // Writer constructor / `Db.create`. Absent ⇒ inline dispatch +\n // CF-free-safe caps, so a bare `Db.create(...).collection(...)\n // .insert(...)` maintains inline by default once enough writes\n // accrue.\n const prevSeq = current.next_seq; // pre-CAS seq, already in scope\n const maint = getCurrentContext()?.maintenance;\n if (maint?.disabled !== true) {\n const gcInterval = maint?.options?.gcInterval ?? WRITE_TICK_GC_INTERVAL;\n if (shouldFireMaintenance(next, prevSeq, gcInterval)) {\n const dispatch = maint?.dispatch ?? dispatchInlineAwaited;\n // `await dispatch(...)`: `dispatchInlineAwaited` returns the\n // task's promise (awaited inline — deterministic for tests +\n // correct for serverful Node). A `ctx.waitUntil`-style dispatch\n // returns void (fire-and-forget off the ack); `await void` is a\n // no-op. The `.then(() => {}, () => {})` is belt-and-suspenders:\n // `runBoundedMaintenance` already swallows internally, but this\n // guarantees a dispatched task can NEVER reject the commit even\n // if a future change makes it throw.\n await dispatch(() =>\n runBoundedMaintenance(\n {\n storage: this.#storage,\n currentJsonKey: this.#currentJsonKey,\n prevSeq,\n // `disabled` is intentionally NOT forwarded: the outer\n // `maint?.disabled !== true` gate already guarantees we only\n // reach here when maintenance is enabled, so passing it would\n // only ever forward `false` (a no-op) and imply a coupling\n // that doesn't exist.\n ...(maint?.maxFoldBytes !== undefined && { maxFoldBytes: maint.maxFoldBytes }),\n },\n maint?.options,\n ).then(\n () => {},\n () => {},\n ),\n );\n }\n }\n\n // Step 7 — the fence-verify GET — lives in the caller, not here.\n // Both fence-bump and a 412-driven CAS retry use\n // `BaerlyError{code:\"Conflict\"}`; keeping the fence check outside\n // this helper's body lets the caller's retry-catch arm\n // (`isPreconditionFailed`) match ONLY retryable conflicts thrown\n // from inside, while the fence-bump throw propagates.\n\n // Base class-A op count for this attempt: content PUTs (skipping\n // `op:\"D\"`) + log PUTs (= N) + index PUTs + index DELETEs + 1\n // current.json CAS. The fence-verify GET is Class B and excluded.\n // The caller of `commit()` adds `(attempt - 1)` for retry cost.\n const classAOps = contentPutCount + entries.length + indexClassA + 1;\n return {\n entries: committedEntries,\n currentEtag: result.etag,\n classAOps,\n expectedEpoch,\n };\n }\n\n /**\n * Read the pre-image content body for a doc by walking the live\n * log backwards from `currentNextSeq` looking for the\n * most-recent I/U entry on this `(collection, docId)`. Returns\n * `undefined` when:\n *\n * - the doc's most-recent op was `D` (tombstone — no live body);\n * - no entry for this doc lives inside the visible log range\n * `[log_seq_start, currentNextSeq)` (a fresh-insert race or\n * the doc has been folded into the snapshot but is no longer\n * referenced).\n *\n * Used ONLY by the index-emission path on `U` / `D` to compute\n * the stale-key set. Bounded by `log_seq_start`: entries below\n * have been folded into the snapshot and may already be swept\n * off the bucket — a snapshot fold is the rebuild command's job\n * (see `./rebuild-index.ts`), not the writer's.\n *\n * **Cost note:** linear walk, O(snapshot lag). For day-one Phase\n * 8 collections (helpdesk-shape: 100s of docs, <10k log entries)\n * this is fine — the compactor folds the live tail every ~100\n * entries (`packages/server/src/compactor.ts`). A follow-up ticket\n * caches per-doc index head in `current.json` for O(1) lookup.\n * The bound is documented; out of scope here.\n */\n /**\n * Auto-create the per-collection `current.json` at\n * `this.#currentJsonKey` with a zero-state initial manifest. Called\n * by `#singleAttemptCommit` when the read returned `null` (fresh\n * bucket / fresh collection).\n *\n * Concurrency: `createCurrentJson` uses `If-None-Match: \"*\"`. If a\n * peer raced us and won, the storage layer surfaces `Conflict`; we\n * recover by re-reading the now-present manifest. We do NOT retry\n * the create — a single recover-via-read covers every race that\n * could have produced our null read.\n *\n * The seed shape (`snapshot: null`, `next_seq: 0`, `log_seq_start:\n * 0`, `writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" }`)\n * matches `ensureTable` and `baerly deploy`'s pre-warm path, so an\n * operator who pre-provisions and a writer who auto-creates land\n * on byte-identical bytes.\n *\n * @throws BaerlyError code=\"InvalidResponse\" — the post-recover\n * re-read also returned null. Defensive guard; in practice\n * unreachable because the Conflict implies the key now exists.\n */\n async #provisionCurrentJson(): Promise<CurrentJsonRead> {\n const initial: CurrentJson = {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n next_seq: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" },\n tail_bytes: 0,\n snapshot_bytes: 0,\n snapshot_rows: 0,\n };\n try {\n return await createCurrentJson(this.#storage, this.#currentJsonKey, initial);\n } catch (error) {\n if (!(error instanceof BaerlyError) || error.code !== \"Conflict\") {\n throw error;\n }\n }\n const recovered = await readCurrentJson(this.#storage, this.#currentJsonKey);\n if (recovered === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `Writer: current.json missing at ${this.#currentJsonKey} after auto-create raced and recover read returned null`,\n );\n }\n return recovered;\n }\n\n async #readPreImage(\n logPrefix: string,\n collection: string,\n docId: string,\n currentNextSeq: number,\n ): Promise<DocumentData | undefined> {\n // Walk newest-to-oldest so we hit the most-recent op first.\n // `s = -1` is the natural empty-bucket sentinel.\n for (let s = currentNextSeq - 1; s >= 0; s--) {\n const logKey = `${logPrefix}/log/${s}.json`;\n const got = await this.#storage.get(logKey);\n if (got === null) {\n // A hole below the visible range — either we walked past\n // `log_seq_start` (the entry was folded + swept) or a peer\n // is mid-CAS on a write we don't see yet. Bail; the\n // rebuild command (`rebuildIndex`) handles holes by\n // re-projecting from the snapshot.\n continue;\n }\n let entry: LogEntry;\n try {\n entry = decodeJsonBytes<LogEntry>(got.body);\n } catch {\n // Malformed entry shouldn't propagate up the index-emission\n // path — let the outer commit's `#walkLog` (step 2) flag it\n // as the protocol violation. Skip.\n continue;\n }\n if (entry.collection !== collection || entry.doc_id !== docId) {\n continue;\n }\n if (entry.op === \"D\") {\n return undefined;\n } // last op was delete\n if ((entry.op === \"I\" || entry.op === \"U\") && entry.after !== undefined) {\n return entry.after;\n }\n }\n return undefined;\n }\n\n /**\n * Walk `log/<logSeqStart>.json` … `log/<nextSeq - 1>.json` with\n * bounded parallelism via `walkLogRange`. Materialised entries are\n * discarded — the walk's only job is to surface a hole or a\n * malformed body inside the visible range as\n * `BaerlyError{code:\"Internal\"}` / `\"InvalidResponse\"`.\n *\n * Gated on `verifyLogIntegrityOnCommit`; default off in production\n * because the per-doc fold already lives in the read path. See the\n * option's docstring for the rationale and the opt-in convention.\n *\n * `logSeqStart` is the boundary set by the compactor on\n * `current.json.log_seq_start`. Entries below it have been folded\n * into the snapshot and may have been swept off the bucket, so the\n * walk MUST NOT GET-require them.\n */\n async #walkLog(logPrefix: string, logSeqStart: number, nextSeq: number): Promise<void> {\n await walkLogRange(this.#storage, logPrefix, logSeqStart, nextSeq);\n }\n\n /**\n * Bump the `db.r2.put.429_total` counter when `err` looks like an\n * R2 prefix-partition rate-limit. Best-effort: detected via\n * `BaerlyError{code:\"NetworkError\"}` with a `429` token in the\n * message. Called from every PUT call site's catch arm; mutually\n * exclusive in practice with `isPreconditionFailed` (412 ≠ 429).\n */\n #observe429(err: unknown, collection: string): void {\n if (is429(err)) {\n ctxMetrics().counter(\"db.r2.put.429_total\", 1, { collection });\n }\n }\n\n /**\n * Emit the per-logical-write `class_a_ops_per_logical_write`\n * histogram shared by `commit` and `commitBatch`. `classAOps`\n * differs between the two paths (retry-budget vs batch shape),\n * so each caller computes it.\n */\n #emitWriteMetrics(collection: string, classAOps: number): void {\n ctxMetrics().histogram(\"db.write.class_a_ops_per_logical_write\", classAOps, { collection });\n }\n\n /**\n * Re-read `current.json` after a successful CAS and assert the\n * writer-fence epoch is still ours. The CAS only mutated `next_seq`\n * (the fence is preserved from `current`), so a post-write epoch\n * mismatch can only mean another writer claimed the fence between\n * our step-1 read and step-6 PUT — the exact split-brain\n * `WriterFence` prevents. Throws `Conflict`; no retry, since the\n * stale writer must defer to the new authority.\n *\n * The fence-verify GET is Class B and intentionally NOT counted in\n * `class_a_ops_per_logical_write`.\n */\n async #verifyFenceUnchanged(expectedEpoch: number, where: string): Promise<void> {\n const postRead = await readCurrentJson(this.#storage, this.#currentJsonKey);\n if (postRead === null) {\n return;\n }\n if (postRead.json.writer_fence.epoch === expectedEpoch) {\n return;\n }\n throw new BaerlyError(\n \"Conflict\",\n `${where}: writer fence bumped from epoch ${expectedEpoch} to ${postRead.json.writer_fence.epoch} during commit on ${this.#currentJsonKey}; stale writer aborting`,\n );\n }\n\n /**\n * Exponential backoff with full jitter. `25 * 2^(attempt-1)` capped\n * at 1500ms; uniform jitter in `[0, base)` keeps colliding peers\n * from re-racing in lockstep. Worst-case total wait across the\n * default 8 attempts is roughly 2.5 s — well under a typical\n * Worker request budget.\n */\n async #backoff(attempt: number): Promise<void> {\n const base = Math.min(this.#initialBackoffMs * 2 ** (attempt - 1), MAX_BACKOFF_MS);\n const sleepMs = base * this.#random();\n if (sleepMs <= 0) {\n return;\n }\n await new Promise<void>((r) => setTimeout(r, sleepMs));\n }\n}\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\n/**\n * `true` when the underlying storage surfaced a `PreconditionFailed`\n * 412 (or its non-S3 equivalents). Every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`.\n */\nconst isPreconditionFailed = (err: unknown): boolean =>\n err instanceof BaerlyError && err.code === \"Conflict\";\n\n/**\n * `true` when the underlying storage surfaced an R2 prefix-partition\n * rate-limit. {@link S3HttpStorage} stamps the upstream HTTP status\n * onto `BaerlyError.cause` as `{ status }`; we discriminate on that\n * structured field rather than regex-matching the message.\n */\nconst is429 = (err: unknown): boolean => {\n if (!(err instanceof BaerlyError) || err.code !== \"NetworkError\") {\n return false;\n }\n const cause = err.cause as { status?: number } | undefined;\n return cause?.status === 429;\n};\n","/**\n * `baerly admin restore` — bulk-import NDJSON into a fresh collection.\n *\n * Reads NDJSON from stdin, reconstructs each row, and calls\n * `Writer.commit({op:\"I\"})` per row into the target bucket.\n * Programmatic callers (today: tests + the export round-trip\n * integration test) can divert the input by passing\n * `{ streams: { stdin } }` to {@link runRestore}. Idempotent on a fresh\n * bucket: re-running on a half-completed restore **refuses** unless\n * `--force` is set (which bumps the writer fence and seeds a fresh\n * `current.json` first).\n *\n * Args:\n * --bucket Required. Target bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Target collection name.\n * --force Truncate the target if it exists (fence-bump + reseed).\n * --json JSON envelope.\n *\n * stdin: NDJSON, one `{_id, ...}` row per line. Empty lines tolerated.\n * EOF terminates.\n *\n * Cost shape: 1 PUT current.json (initial) + N × (1 PUT log + 1 PUT\n * content + 1 PUT current.json CAS) = 3N + 1 Class A ops for N rows.\n *\n * Partial-restore semantics: a mid-stream Network / Internal / parse\n * error leaves the target in a partial state (some rows committed,\n * `current.json` advanced to wherever the last successful commit\n * landed). Re-run with `--force` to truncate, or hand-clean. The\n * malformed-line case (missing `_id`, bad JSON) fails fast on that\n * line; rows committed BEFORE it survive.\n *\n * Exit codes:\n * 0 — every row committed.\n * 1 — InvalidConfig (bad bucket URI, missing args).\n * 2 — Network / storage error mid-stream, or a malformed NDJSON\n * line (raised as a plain `Error`, not `BaerlyError`).\n * 3 — Conflict from a pre-existing target without --force, or from a\n * concurrent writer when --force was used.\n */\n\nimport { createInterface } from \"node:readline\";\nimport { type ArgsDef } from \"citty\";\nimport {\n BaerlyError,\n CURRENT_JSON_SCHEMA_VERSION,\n createCurrentJson,\n type CurrentJson,\n type DocumentData,\n encodeJsonBytes,\n readCurrentJson,\n} from \"@baerly/protocol\";\nimport { Writer } from \"@baerly/server/_internal/testing\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport { defineBaerlySubcommand } from \"../subcommand.ts\";\n\nconst RESTORE_OWNER = \"baerly-restore\";\n\nconst RESTORE_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Target bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Target collection name.\",\n valueHint: \"name\",\n },\n force: {\n type: \"boolean\",\n description: \"Truncate the target if it exists (bump fence + reseed current.json).\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.restore\",\n meta: {\n description: \"Bulk-import canonical NDJSON into a fresh collection.\",\n },\n args: RESTORE_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n\n const head = await readCurrentJson(bucket.storage, currentJsonKey);\n if (head !== null && args.force !== true) {\n throw new BaerlyError(\n \"Conflict\",\n `baerly admin restore: ${currentJsonKey} exists; pass --force to truncate`,\n );\n }\n if (head !== null) {\n // --force: bump the fence on the existing record so any\n // in-flight writer aborts, then overwrite `current.json` with a\n // fresh seed under If-Match. A concurrent writer landing\n // between our read and our CAS PUT surfaces Conflict (exit 3).\n //\n // CRITICAL: stale log entries from the old generation still\n // live on disk under `log/<seq>.json` paths. The writer's\n // `If-None-Match: \"*\"` log PUT will 412 if we restart `next_seq`\n // at 0 and collide with `log/0.json`. We instead advance\n // `next_seq` and `log_seq_start` past the old data so new\n // commits land at fresh sequence numbers and the old log files\n // become unreferenced orphans (the compactor / GC sweep them on\n // the next maintenance pass).\n const truncatedNext = head.json.next_seq;\n const reseeded: CurrentJson = {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n next_seq: truncatedNext,\n log_seq_start: truncatedNext,\n writer_fence: {\n epoch: head.json.writer_fence.epoch + 1,\n owner: RESTORE_OWNER,\n claimed_at: \"\",\n },\n tail_bytes: 0,\n snapshot_bytes: 0,\n snapshot_rows: 0,\n };\n try {\n await bucket.storage.put(currentJsonKey, encodeJsonBytes(reseeded), {\n ifMatch: head.etag,\n contentType: \"application/json\",\n });\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"NetworkError\",\n `baerly admin restore: failed to reseed current.json: ${(error as Error).message}`,\n );\n }\n } else {\n // Fresh target: seed `current.json` with `next_seq=0`.\n const seed: CurrentJson = {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n next_seq: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: RESTORE_OWNER, claimed_at: \"\" },\n tail_bytes: 0,\n snapshot_bytes: 0,\n snapshot_rows: 0,\n };\n await createCurrentJson(bucket.storage, currentJsonKey, seed);\n }\n\n const writer = new Writer({ storage: bucket.storage, currentJsonKey });\n\n const input = ctx.streams?.stdin ?? process.stdin;\n const rl = createInterface({ input, crlfDelay: Infinity });\n let count = 0;\n let lineNo = 0;\n for await (const line of rl) {\n lineNo++;\n if (line.length === 0) {\n continue;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch (error) {\n // Malformed NDJSON mid-stream → exit 2 (the ticket's\n // partial-restore contract: the line that failed wasn't\n // committed, but anything BEFORE it survives). Bare `Error`\n // (not `BaerlyError`) routes through the helper's \"unknown\"\n // arm → exit 2.\n throw new Error(\n `baerly admin restore: line ${lineNo} is not valid JSON: ${(error as Error).message}`,\n { cause: error },\n );\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(`baerly admin restore: line ${lineNo} is not a JSON object`);\n }\n const row = parsed as Record<string, unknown>;\n const id = row[\"_id\"];\n if (typeof id !== \"string\" || id.length === 0) {\n throw new Error(`baerly admin restore: line ${lineNo} missing non-empty string _id`);\n }\n // Pass the full object as the body — `_id` is part of the\n // body in the doc shape, and the writer keys on `docId`\n // separately.\n const body = row as unknown as DocumentData;\n await writer.commit({\n op: \"I\",\n collection: args.collection,\n docId: id,\n body,\n });\n count++;\n }\n emitSuccess({\n command: \"admin.restore\",\n status: \"ok\",\n collection: args.collection,\n restored: count,\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin restore`. */\nexport const restoreCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runRestore = bundle.run;\n"],"mappings":";;;;;;;;;;;;;;;;AAoIA,MAAa,8BAA8B,QAA2C;CAGpF,IAAI,IAAI,cAAc,GACpB,OAAO;EAAE,OAAO;EAAO,QAAQ;CAAQ;CAGzC,IAAI,IAAI,SAAS,YAAY,IAAI,KAAK,SAC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MAAM,IAAI,MACR,8BAA8B,OAAO,sBAAuB,MAAgB,WAC5E,EAAE,OAAO,MAAM,CACjB;GACF;GACA,IAAI,WAAW,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GACvE,MAAM,IAAI,MAAM,8BAA8B,OAAO,sBAAsB;GAE7E,MAAM,MAAM;GACZ,MAAM,KAAK,IAAI;GACf,IAAI,OAAO,OAAO,YAAY,GAAG,WAAW,GAC1C,MAAM,IAAI,MAAM,8BAA8B,OAAO,8BAA8B;GAKrF,MAAM,OAAO;GACb,MAAM,OAAO,OAAO;IAClB,IAAI;IACJ,YAAY,KAAK;IACjB,OAAO;IACP;GACF,CAAC;GACD;EACF;EACA,YAAY;GACV,SAAS;GACT,QAAQ;GACR,YAAY,KAAK;GACjB,UAAU;EACZ,CAAC;EACD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,aAAa,OAAO;AAOP,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"snapshot-SS8USDUF.js","names":[],"sources":["../packages/protocol/src/coordination/current-json.ts","../packages/protocol/src/snapshot-hash.ts","../packages/server/src/log-walk.ts","../packages/server/src/snapshot.ts"],"sourcesContent":["/**\n * `current.json` — the per-collection CAS-protected control object — and\n * its embedded {@link WriterFence} epoch token.\n *\n * A dedicated `coordination/` namespace (parallel to `storage/`) holds\n * primitives whose contract is \"atomic agreement over a small JSON\n * object\" rather than \"byte I/O.\" Future siblings (compactor\n * manifest, sweeper checkpoint) join here, not at the top\n * level. The module lives inside `@baerly/protocol` because it is pure\n * (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,\n * no implicit globals) and must remain Worker-bundleable — every byte\n * of network traffic threads through the {@link Storage} seam.\n *\n * Contract surface:\n * - {@link readCurrentJson} — fetch + parse + validate\n * - {@link createCurrentJson} — create-only (CAS via `If-None-Match:\"*\"`)\n * - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)\n * - {@link claimWriter} — bump epoch + stamp server-clock claim time\n *\n * Why the two-round-trip claim protocol: `claimed_at` MUST come from\n * `StoragePutResult.serverDate` (the single shared clock across\n * instances), not the local clock. `serverDate` is only known *after*\n * the CAS PUT lands, so {@link claimWriter} writes the record with\n * `claimed_at: \"\"` first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. The epoch bump is\n * already durable from the first put either way; a peer landing\n * between the two writes loses cleanly with `Conflict`.\n *\n * Why CAS errors are wrapped: every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`. Downstream\n * callers — the Writer, the compactor, the sweeper —\n * discriminate by `code` to decide whether to retry.\n * We re-wrap here only to add the `current.json at <key>` location\n * context to the message; the `code` is unchanged.\n */\n\nimport { encodeJsonBytes } from \"../bytes.ts\";\nimport { CURRENT_JSON_CONTENT_TYPE, CURRENT_JSON_SCHEMA_VERSION } from \"../constants.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport type { Storage, StoragePutOptions, StoragePutResult } from \"../storage/types.ts\";\n\n/**\n * Per-collection control object. CAS-protected. One per\n * `(tenant, collection)` key — for example\n * `<tenant>/<collection>/current.json`. The compactor swaps\n * snapshot generations by CAS-writing this object; the\n * Writer reads it on every commit to find the snapshot\n * pointer; the sweeper reads `writer_fence` to decide which log\n * entries are eligible for GC.\n *\n * The schema is forward-compatible: adding a new optional field is\n * non-breaking. Renaming or removing a field requires bumping\n * {@link CURRENT_JSON_SCHEMA_VERSION}; readers MUST reject\n * unknown major versions with `BaerlyError{code:\"InvalidResponse\"}`.\n */\nexport interface CurrentJson {\n /**\n * Schema version. Today: `2`. Bump on any breaking change to\n * field semantics; readers must reject unknown major versions\n * with `BaerlyError{code:\"InvalidResponse\"}`.\n */\n schema_version: 2;\n\n /**\n * Pointer to the current snapshot generation. `null` before the\n * first compaction has produced a snapshot — readers fall back\n * to log-only replay. Shape is opaque-to-this-module; the\n * compactor owns its interpretation.\n */\n snapshot: string | null;\n\n /**\n * Sequence number of the next log entry. Monotonic per\n * collection. The Writer reads this on commit to mint the\n * next log filename; CAS-write back with `next_seq + 1` ensures\n * no two writers pick the same sequence.\n */\n next_seq: number;\n\n /**\n * Lowest live log sequence number. Entries with `seq < log_seq_start`\n * have been folded into the snapshot at {@link snapshot} (or, if\n * `snapshot === null`, have been dropped because the collection was\n * truncated). Readers walk `[log_seq_start, next_seq)`. Always\n * present on disk — fresh `current.json` writes via\n * {@link createCurrentJson} set this to `0`; the compactor advances\n * it on every fold.\n *\n * Invariants the compactor maintains:\n * - `0 <= log_seq_start <= next_seq`\n * - `log_seq_start` advances monotonically (never decreases)\n * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot\n * covers `[0, log_seq_start)`)\n */\n log_seq_start: number;\n\n /**\n * Embedded write-fence epoch. See {@link WriterFence}.\n */\n writer_fence: WriterFence;\n\n // New in v2:\n\n /** EXACT byte size of the live log tail [log_seq_start, next_seq). Maintained exactly\n * by the full-fence CAS on BOTH paths: each write adds its log bytes; a successful\n * fold (which proves no concurrent write) resets to 0 from a known-empty tail. */\n tail_bytes: number;\n\n /** Byte size of the snapshot pointed to by `snapshot`. */\n snapshot_bytes: number;\n\n /** Row count of the snapshot (= compactor `base.size`, free). With next_seq - log_seq_start\n * (tail entries) this gives the fold's entry count for the ENTRY ceiling `E`. Seeded 0. */\n snapshot_rows: number;\n\n /** Baseline for rate-limiting the graduation defer-warn off SHARED durable state, not\n * per-isolate memory. The warn fires when next_seq - last_warned_seq >=\n * MAINTENANCE_WARN_INTERVAL_WRITES, and that firing CASes last_warned_seq = next_seq.\n * Absent → 0. */\n last_warned_seq?: number;\n}\n\n/**\n * Fence-token sub-shape embedded in {@link CurrentJson}. The\n * monotonically-bumped `epoch` is the only safety-critical field —\n * `owner` is informational and may be missing in older records;\n * `claimed_at` is the server response date at claim time, NOT the\n * local clock; `lease_until` is reserved for manual rotation and\n * is not consumed by any ticket in this batch.\n *\n * Borrowed from FoundationDB's `recoveryCount` on cstate, IsleDB's\n * `writer_fence` on `manifest/CURRENT`, and TigerBeetle's VSR view\n * number. The mechanism is the same in all three: every commit\n * checks the epoch on the control object; an entry stamped with\n * a stale epoch is discarded at replay.\n */\nexport interface WriterFence {\n /**\n * Monotonic unsigned integer. Bumped only by an explicit\n * {@link claimWriter} call — do NOT bump on every cold start, do\n * NOT bump on every commit. Triggers per design: (a) detected\n * CAS conflict the writer wants to claim through, (b) admin\n * rotation. The sweeper discards log entries whose stamped epoch\n * is `< current.writer_fence.epoch`.\n */\n epoch: number;\n\n /**\n * Owner identifier — debug only, NOT consulted for safety.\n * Suggested shape: `<worker_id>@<deploy_id>`. May be the empty\n * string when claim provenance is unknown (e.g. initial\n * creation). Safety derives from `epoch`, not from `owner`.\n */\n owner: string;\n\n /**\n * ISO-8601 timestamp from the `StoragePutResult.serverDate` on\n * the successful CAS PUT. **Never use `new Date()` or\n * `Date.now()` to populate this field** — under multi-instance\n * deployment the local clock may disagree with peers; the\n * server's clock is the only one all instances share. Format\n * via `serverDate.toISOString()`. The empty string `\"\"` means\n * \"claim time unknown\" — readers MUST treat it as such rather\n * than parsing it.\n */\n claimed_at: string;\n\n /**\n * Optional explicit lease horizon, also ISO-8601. Reserved for\n * future manual rotation workflows; current code only writes\n * the field through if a caller supplies it and does not read\n * it.\n */\n lease_until?: string;\n}\n\n/**\n * Return shape from {@link readCurrentJson} et al.: the parsed JSON\n * plus the ETag needed for a follow-up CAS write.\n */\nexport interface CurrentJsonRead {\n readonly json: CurrentJson;\n readonly etag: string;\n}\n\n/**\n * Read + parse `current.json` at `key`. Returns `null` on not-found.\n *\n * @throws BaerlyError{code:\"InvalidResponse\"} — body is not valid\n * JSON, or `schema_version` is unknown, or the shape fails\n * the runtime guard.\n */\nexport async function readCurrentJson(\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead | null> {\n const got = await storage.get(key, opts);\n if (got === null) {\n return null;\n }\n const text = new TextDecoder().decode(got.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: body is not valid JSON`,\n error,\n );\n }\n return { json: assertCurrentJson(parsed, key), etag: got.etag };\n}\n\n/**\n * Create `current.json` if-and-only-if it does not exist (S3\n * `If-None-Match: \"*\"`). Use this once per collection at provisioning\n * time; subsequent updates go through {@link casUpdateCurrentJson}.\n *\n * @throws BaerlyError{code:\"Conflict\"} — the key already exists.\n * Caller decides whether to read + reconcile or surface.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `initial` fails the\n * runtime shape guard.\n */\nexport async function createCurrentJson(\n storage: Storage,\n key: string,\n initial: CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n // Catch shape bugs in callers before they hit storage. Cheap.\n assertCurrentJson(initial, key);\n const body = encodeJson(initial);\n const putOpts: StoragePutOptions = {\n ifNoneMatch: \"*\",\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: initial, etag: result.etag };\n}\n\n/**\n * Read-modify-write `current.json` under CAS. The `mutator` receives\n * a deep clone of the current parsed JSON (mutate freely) and returns\n * the new state. The new state is written with `If-Match:\n * <currentEtag>`; on conflict, throws.\n *\n * `mutator` MUST be synchronous and deterministic — it may be called\n * multiple times if the caller wraps this in a retry loop, so it\n * must not have side effects.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer landed a write\n * between this function's read and write. Caller decides\n * whether to retry (read + remutate + rewrite).\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist\n * (use {@link createCurrentJson} instead) or body doesn't\n * parse / fails the shape guard.\n */\nexport async function casUpdateCurrentJson(\n storage: Storage,\n key: string,\n mutator: (current: CurrentJson) => CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n // Defensive deep clone so a mutator that mutates its argument can't\n // corrupt the original record on the caller's retry path.\n // `structuredClone` is a global on Node ≥17 and Workers; the package\n // targets Node ≥24 so it is safe.\n const next = mutator(structuredClone(existing.json));\n assertCurrentJson(next, key);\n const body = encodeJson(next);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: next, etag: result.etag };\n}\n\n/**\n * Claim ownership of the write fence by bumping `epoch` and stamping\n * `claimed_at` from `StoragePutResult.serverDate`. The common call\n * site is \"I detected a CAS conflict during a commit and want to\n * claim the fence before retrying\"; admin rotation is the other call\n * site.\n *\n * `owner` is informational — see {@link WriterFence.owner}. Safety\n * derives from the monotonic `epoch`, not from `owner`.\n *\n * Implementation note (two round-trips): because\n * `StoragePutResult.serverDate` is only known *after* the CAS PUT\n * lands, this function writes the record with `claimed_at: \"\"`\n * first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. A peer landing between\n * the two writes loses cleanly with `Conflict` — the epoch bump is\n * already durable from the first put either way. If `serverDate` is\n * `undefined` on the first PUT (impl doesn't surface it), the second\n * write is skipped and `claimed_at` remains the empty string;\n * readers MUST treat the empty string as \"unknown claim time\"\n * rather than parsing it.\n *\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the full failure envelope (absent / lying / non-monotonic Date,\n * peer-between-PUTs, bounded clock skew).\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the \"Differentiation from mps3\" subsection that frames the §103\n * non-obviousness story.\n * @see {@link ../../../../docs/spec/prior-art.md} —\n * IDS-shaped prior-art differentiation against mps3, SlateDB,\n * Iceberg, Delta, and the broader S3-leader-election literature.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer claimed the\n * fence between this call's read and write. Caller decides\n * whether to retry.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist.\n */\nexport async function claimWriter(\n storage: Storage,\n key: string,\n owner: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n const provisional: CurrentJson = {\n ...existing.json,\n writer_fence: {\n epoch: existing.json.writer_fence.epoch + 1,\n owner,\n // Will be overwritten with serverDate.toISOString() once the put\n // returns, when the impl surfaces it. Stays `\"\"` (\"unknown\") if\n // the impl doesn't.\n claimed_at: \"\",\n // Stryker disable next-line ConditionalExpression: `→true` spreads `{lease_until: undefined}` which JSON.stringify omits, so the stored bytes are identical to the normal `→false` path (no key emitted). Genuine equivalent mutant.\n ...(existing.json.writer_fence.lease_until !== undefined && {\n lease_until: existing.json.writer_fence.lease_until,\n }),\n },\n };\n const body = encodeJson(provisional);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n // No server clock surfaced — leave `claimed_at` empty. The epoch\n // bump is durable; safety is unaffected.\n if (result.serverDate === undefined) {\n return { json: provisional, etag: result.etag };\n }\n // Stamp the server clock through a second CAS-on-our-own-etag. A\n // peer landing between the two writes loses cleanly with Conflict\n // (the fence is safe — next claim will bump past both).\n const stamped: CurrentJson = {\n ...provisional,\n writer_fence: {\n ...provisional.writer_fence,\n claimed_at: result.serverDate.toISOString(),\n },\n };\n const stampedBody = encodeJson(stamped);\n const stampPutOpts: StoragePutOptions = {\n ifMatch: result.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let stampResult: StoragePutResult;\n try {\n stampResult = await storage.put(key, stampedBody, stampPutOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: stamped, etag: stampResult.etag };\n}\n\n/**\n * Read `current.json.log_seq_start` — the low-water mark of the live\n * log range `[log_seq_start, next_seq)`. The field is always present\n * on disk (every `createCurrentJson` write seeds it; the compactor\n * advances it on every fold); this helper exists to document intent\n * at call sites that walk the log range or assert the snapshot\n * invariants.\n */\nexport const logSeqStartOf = (c: CurrentJson): number => c.log_seq_start;\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nconst encodeJson = (json: CurrentJson): Uint8Array => encodeJsonBytes(json);\n\n/**\n * Runtime guard for `parsed` to be a {@link CurrentJson}. Throws\n * `BaerlyError{code:\"InvalidResponse\"}` rather than coercing. Tolerant\n * reader: unknown keys ignored, new required fields bump\n * `schema_version` (move (b), ADR-007).\n */\nconst assertCurrentJson = (parsed: unknown, key: string): CurrentJson => {\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: parsed body is not an object`,\n );\n }\n const r = parsed as Record<string, unknown>;\n if (r[\"schema_version\"] === 1) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} is schema v1 (pre-maintenance); this build requires v2. Pre-launch, no production buckets — delete and re-seed the local-fs/Minio/Verdaccio scratch bucket, or recreate the R2/S3 bucket.`,\n );\n }\n if (r[\"schema_version\"] !== CURRENT_JSON_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: unsupported schema_version ${String(r[\"schema_version\"])}; expected ${CURRENT_JSON_SCHEMA_VERSION}`,\n );\n }\n if (!(typeof r[\"snapshot\"] === \"string\" || r[\"snapshot\"] === null)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot must be string|null`,\n );\n }\n // Stryker disable next-line ConditionalExpression,StringLiteral: three equivalent mutants on this line — (1) `typeof r[\"next_seq\"] !== \"number\"` → false is subsumed by !Number.isInteger (which rejects all non-numbers); (2) `r[\"next_seq\"] < 0` → false is subsumed by the downstream `log_seq_start > next_seq` cross-check (log_seq_start ≥ 0, so log_seq_start > negative_next_seq always fires); (3) StringLiteral \"next_seq\" → \"\" turns r[\"\"] → undefined → !Number.isInteger(undefined) still true → still throws.\n if (typeof r[\"next_seq\"] !== \"number\" || !Number.isInteger(r[\"next_seq\"]) || r[\"next_seq\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: next_seq must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"log_seq_start\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers anyway, making the typeof check fully subsumed.\n typeof r[\"log_seq_start\"] !== \"number\" ||\n !Number.isInteger(r[\"log_seq_start\"]) ||\n r[\"log_seq_start\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start must be a non-negative integer`,\n );\n }\n if (r[\"log_seq_start\"] > r[\"next_seq\"]) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start ${String(r[\"log_seq_start\"])} > next_seq ${String(r[\"next_seq\"])}`,\n );\n }\n const fence = r[\"writer_fence\"];\n if (fence === null || typeof fence !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `current.json at ${key}: writer_fence missing`);\n }\n const f = fence as Record<string, unknown>;\n // Stryker disable next-line ConditionalExpression: `typeof f[\"epoch\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof guard fully subsumed.\n if (typeof f[\"epoch\"] !== \"number\" || !Number.isInteger(f[\"epoch\"]) || f[\"epoch\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.epoch must be a non-negative integer`,\n );\n }\n if (typeof f[\"owner\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.owner must be a string`,\n );\n }\n if (typeof f[\"claimed_at\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.claimed_at must be a string`,\n );\n }\n if (f[\"lease_until\"] !== undefined && typeof f[\"lease_until\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.lease_until must be string if present`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"tail_bytes\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"tail_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"tail_bytes\"]) ||\n r[\"tail_bytes\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: tail_bytes must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_bytes\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_bytes\"]) ||\n r[\"snapshot_bytes\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_bytes must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_rows\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_rows\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_rows\"]) ||\n r[\"snapshot_rows\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_rows must be a non-negative integer`,\n );\n }\n if (\n r[\"last_warned_seq\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: `typeof r[\"last_warned_seq\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n (typeof r[\"last_warned_seq\"] !== \"number\" ||\n !Number.isInteger(r[\"last_warned_seq\"]) ||\n r[\"last_warned_seq\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: last_warned_seq must be a non-negative integer if present`,\n );\n }\n return parsed as CurrentJson;\n};\n\n/**\n * Wrap a storage-level error with `current.json at <key>` location\n * context. `Conflict` (the storage layer's CAS-lost signal) is\n * re-thrown with an annotated message; other `BaerlyError`s pass\n * through; non-`BaerlyError` falls through as `InvalidResponse` (in\n * practice unreachable — every in-tree `Storage` impl wraps).\n */\nconst translateCasError = (e: unknown, key: string): BaerlyError => {\n if (e instanceof BaerlyError && e.code === \"Conflict\") {\n return new BaerlyError(\"Conflict\", `current.json CAS lost at ${key}: ${e.message}`, e);\n }\n if (e instanceof BaerlyError) {\n return e;\n }\n return new BaerlyError(\"InvalidResponse\", `current.json write at ${key} failed: ${String(e)}`, e);\n};\n","/**\n * SHA-256 of `bytes` as a 64-char lowercase hex string. Used to seal\n * snapshot filenames so a crashed mid-PUT can't produce a body that\n * readers consume as truth: the filename embeds the hash; readers\n * recompute on load and reject any mismatch as \"file missing.\"\n *\n * Distinct from {@link versionFromContent} (truncated to 32 chars for\n * content keys) — snapshot bodies are larger and longer-lived;\n * 256-bit collision resistance matters here.\n */\nexport const snapshotHash = async (bytes: Uint8Array): Promise<string> => {\n // Copy via fresh ArrayBuffer: tsgo narrows `Uint8Array` to\n // `Uint8Array<ArrayBufferLike>`, which `crypto.subtle.digest` rejects\n // (wants `ArrayBufferView<ArrayBuffer>`). See microsoft/TypeScript#61375\n // and `versionFromContent` in ./hashing.ts for the same workaround.\n const view = new Uint8Array(bytes.byteLength);\n view.set(bytes);\n const digest = await crypto.subtle.digest(\"SHA-256\", view);\n const out = new Uint8Array(digest);\n let hex = \"\";\n for (let i = 0; i < out.length; i++) {\n hex += out[i]!.toString(16).padStart(2, \"0\");\n }\n return hex;\n};\n","/**\n * Shared log-walk primitives consumed by the read path (`query.ts`),\n * the compactor (`compactor.ts`), and the optional integrity walk in\n * `Writer.#singleAttemptCommit` (`writer.ts`).\n *\n * Two operations: read one log entry, or walk a contiguous range of\n * log entries with bounded parallelism. Each kernel call site\n * previously inlined the same range-build + unbounded `Promise.all`\n * pattern; on a free-tier collection where the compactor lags the\n * tail to 50-100 entries, that fans out 50-100 concurrent GETs per\n * call — and a contended writer multiplies that by the CAS retry\n * budget. `walkLogRange` caps concurrency at\n * {@link MAX_PARALLEL_LOG_READS} so a single call costs at most that\n * many simultaneous GETs against the storage backend.\n *\n * Order invariant: results are returned in seq order regardless of\n * resolution order. The read-side fold is order-sensitive (`U` then\n * `D` on the same doc must apply in that order); callers may iterate\n * the returned array as-is.\n *\n * Signal invariant: when the caller's `AbortSignal` fires, no further\n * chunks dispatch. In-flight reads see the signal via the underlying\n * `Storage.get` call.\n */\n\nimport {\n type DocumentData,\n type LogEntry,\n type Storage,\n BaerlyError,\n decodeJsonBytes,\n MAX_PARALLEL_LOG_READS,\n} from \"@baerly/protocol\";\n\n/**\n * Fetch a single log entry. Centralises the \"missing entry inside the\n * visible log range is a protocol-invariant violation\" rule used by\n * every caller.\n *\n * @throws BaerlyError code=\"Internal\" when the key resolves to no\n * body — a hole inside `[log_seq_start, next_seq)` is a corruption\n * the kernel can't continue past.\n * @throws BaerlyError code=\"InvalidResponse\" when the body isn't\n * valid JSON.\n */\nexport const readLogEntry = async (\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<LogEntry> => {\n const got = await readLogEntryWithBytes(storage, key, opts);\n return got.entry;\n};\n\n/**\n * Like {@link readLogEntry}, but also surfaces `bytes` — the\n * byteLength of the STORED log-object body exactly as it was GET back\n * from storage (`got.body.byteLength`).\n *\n * The compactor uses this to subtract from `current.json.tail_bytes`\n * the EXACT bytes the writer PUT for the folded slice. The writer\n * accumulated `encodeJsonBytes(entry).byteLength` per committed entry\n * (`writer.ts` Step 6); the stored body IS those bytes, so summing\n * `got.body.byteLength` over the folded range == the writer's\n * accumulated total for that range — no re-encode, no round-trip\n * assumption (a re-encode of the parsed `LogEntry` could drift if\n * key-order/whitespace ever diverged from what was PUT).\n *\n * Same error semantics as {@link readLogEntry}.\n */\nexport const readLogEntryWithBytes = async (\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<{ entry: LogEntry; bytes: number }> => {\n const got = await storage.get(\n key,\n opts?.signal !== undefined ? { signal: opts.signal } : undefined,\n );\n if (got === null) {\n throw new BaerlyError(\n \"Internal\",\n `log-walk: missing log entry at ${key}; protocol invariant violation`,\n );\n }\n try {\n return { entry: decodeJsonBytes<LogEntry>(got.body), bytes: got.body.byteLength };\n } catch (error) {\n throw new BaerlyError(\"InvalidResponse\", `log-walk: malformed log entry at ${key}`, error);\n }\n};\n\n/**\n * Walk `[fromSeq, toSeqExclusive)` of `${logPrefix}/log/<seq>.json`\n * in chunks of {@link MAX_PARALLEL_LOG_READS} concurrent GETs.\n * Returns the materialised entries in seq order.\n *\n * Empty range (`fromSeq >= toSeqExclusive`) returns `[]` and issues\n * zero GETs.\n *\n * Same error semantics as {@link readLogEntry}: a missing entry\n * throws `Internal`, a malformed body throws `InvalidResponse`.\n */\nexport const walkLogRange = async (\n storage: Storage,\n logPrefix: string,\n fromSeq: number,\n toSeqExclusive: number,\n opts?: { signal?: AbortSignal },\n): Promise<LogEntry[]> => {\n const withBytes = await walkLogRangeWithBytes(storage, logPrefix, fromSeq, toSeqExclusive, opts);\n return withBytes.map((r) => r.entry);\n};\n\n/**\n * Like {@link walkLogRange}, but each element also carries `bytes` —\n * the STORED log-object body byteLength (see {@link readLogEntryWithBytes}).\n * Same seq-order, empty-range, error, and bounded-parallelism\n * ({@link MAX_PARALLEL_LOG_READS}) guarantees as {@link walkLogRange};\n * this is the bytes-aware core `walkLogRange` is implemented on top of.\n *\n * The compactor consumes this so it gets BOTH the parsed entries (for\n * the fold) AND the exact byte sum (to decrement `tail_bytes`) from a\n * single walk.\n */\nexport const walkLogRangeWithBytes = async (\n storage: Storage,\n logPrefix: string,\n fromSeq: number,\n toSeqExclusive: number,\n opts?: { signal?: AbortSignal },\n): Promise<Array<{ entry: LogEntry; bytes: number }>> => {\n if (fromSeq >= toSeqExclusive) {\n return [];\n }\n const total = toSeqExclusive - fromSeq;\n const out: Array<{ entry: LogEntry; bytes: number }> = Array.from({ length: total });\n for (let chunkStart = 0; chunkStart < total; chunkStart += MAX_PARALLEL_LOG_READS) {\n opts?.signal?.throwIfAborted();\n const chunkEnd = Math.min(chunkStart + MAX_PARALLEL_LOG_READS, total);\n const promises: Array<Promise<{ entry: LogEntry; bytes: number }>> = [];\n for (let i = chunkStart; i < chunkEnd; i++) {\n const seq = fromSeq + i;\n promises.push(readLogEntryWithBytes(storage, `${logPrefix}/log/${seq}.json`, opts));\n }\n const results = await Promise.all(promises);\n for (let i = 0; i < results.length; i++) {\n out[chunkStart + i] = results[i]!;\n }\n }\n return out;\n};\n\n/**\n * Fold a sequence of `LogEntry` records onto a doc-id-keyed map,\n * applying the protocol's per-doc-replace semantics:\n *\n * - `I` / `U`: when `entry.after !== undefined`, set\n * `map.set(entry.doc_id, entry.after)`. Entries with `after ===\n * undefined` (the partial-merge writer's future patch-only shape)\n * are ignored — today's writer always emits `after`, so this is a\n * forward-compat guard, not a live branch.\n * - `D`: tombstone — `map.delete(entry.doc_id)`.\n *\n * Entries whose `collection` does not match `opts.collection`, or\n * whose `doc_id` is `undefined`, are skipped. When\n * `opts.docIdFilter` is provided, only entries whose `doc_id` is\n * present in the filter set are folded — used by the index-walk\n * read path to scope the fold to the docs the planner already\n * resolved.\n *\n * This is the canonical fold used by the read path\n * (`query.ts`) and the index reconciler (`rebuild-index.ts`).\n * Centralising it keeps the\n * \"straight `set` on I/U; tombstone on D\" protocol invariant in one place.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\nexport const foldLogEntriesOnto = <T extends DocumentData>(\n map: Map<string, T>,\n entries: Iterable<LogEntry>,\n opts: {\n readonly collection: string;\n readonly docIdFilter?: ReadonlySet<string>;\n },\n): void => {\n const { collection, docIdFilter } = opts;\n for (const entry of entries) {\n if (entry.collection !== collection) {\n continue;\n }\n if (entry.doc_id === undefined) {\n continue;\n }\n if (docIdFilter !== undefined && !docIdFilter.has(entry.doc_id)) {\n continue;\n }\n switch (entry.op) {\n case \"I\":\n case \"U\": {\n if (entry.after === undefined) {\n continue;\n }\n map.set(entry.doc_id, entry.after as T);\n break;\n }\n case \"D\": {\n map.delete(entry.doc_id);\n break;\n }\n }\n }\n};\n","/**\n * Snapshot file shape + parse. Lifted out of `./compactor.ts` so that\n * the kernel barrel (`packages/server/src/index.ts`) — which re-exports\n * these four symbols — does not transitively pull `withObservability`\n * via `compact()`. `./compactor.ts` imports its own snapshot primitives\n * back from this module; the public API surface is unchanged.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\n\nimport {\n BaerlyError,\n decodeJsonBytes,\n type DocumentData,\n encodeJsonBytes,\n snapshotHash,\n type Storage,\n} from \"@baerly/protocol\";\n\n/**\n * Single-level snapshot at L9; the level prefix is forward-compatible\n * with future L0..L9 rolling merges without a wire change.\n */\nexport const SNAPSHOT_LEVEL = 9 as const;\n\n/**\n * `minSeq` and `maxSeq` are padded to {@link SEQ_DIGITS} digits so\n * `list(prefix)` returns snapshots in seq order without needing to\n * parse the filename. 12 digits caps at ~10^12 entries per collection;\n * a real bucket hits S3's per-prefix QPS ceiling long before that.\n */\nexport const SEQ_DIGITS = 12 as const;\n\nconst MAX_SEQ = 10 ** SEQ_DIGITS - 1;\n\n/**\n * Build the on-bucket key for a snapshot file. `sha256` must be the\n * lowercase hex digest of the canonical body\n * ({@link encodeSnapshotBody}); the filename embeds it so a crashed\n * mid-PUT body that doesn't match its own filename hash is rejected\n * by readers as \"missing.\"\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `minSeq`/`maxSeq` are\n * out of range or `sha256` is not 64 hex chars.\n */\nexport const snapshotKey = (\n collectionPrefix: string,\n minSeq: number,\n maxSeq: number,\n sha256: string,\n): string => {\n if (minSeq < 0 || maxSeq < 0 || minSeq > maxSeq || maxSeq > MAX_SEQ) {\n throw new BaerlyError(\"InvalidConfig\", `snapshotKey: invalid range [${minSeq}, ${maxSeq})`);\n }\n if (!/^[0-9a-f]{64}$/.test(sha256)) {\n throw new BaerlyError(\"InvalidConfig\", \"snapshotKey: sha256 must be 64 hex chars\");\n }\n const pad = (n: number): string => n.toString().padStart(SEQ_DIGITS, \"0\");\n return `${collectionPrefix}/snapshot/L${SNAPSHOT_LEVEL}/${pad(minSeq)}-${pad(maxSeq)}-${sha256}.json`;\n};\n\n/**\n * On-bucket body of a snapshot file. The reader recomputes the SHA-256\n * over the canonical serialisation ({@link encodeSnapshotBody}) and\n * rejects any mismatch with the filename hash.\n *\n * `docs` is sorted by `_id` for deterministic byte output — two\n * compactions over the same fold produce byte-identical snapshots,\n * which means same filename, which means an idempotent re-run never\n * leaves an orphan.\n */\nexport interface SnapshotBody {\n readonly schema_version: 1;\n readonly min_seq: number;\n readonly max_seq: number;\n readonly collection: string;\n readonly docs: ReadonlyArray<{\n readonly _id: string;\n readonly body: DocumentData;\n }>;\n}\n\n/**\n * Canonical byte encoding of a {@link SnapshotBody}. Only the\n * compactor produces snapshots, and only this function does the\n * serialisation — so the byte output is deterministic for a given\n * `SnapshotBody` (identical input ⇒ identical bytes ⇒ identical\n * filename hash).\n */\nexport const encodeSnapshotBody = (s: SnapshotBody): Uint8Array => encodeJsonBytes(s);\n\n/**\n * Load a snapshot file as a `Map<_id, DocumentData>`. Verifies the\n * body hash against the filename, checks the schema version, and\n * cross-checks `body.collection` against the caller's expectation.\n *\n * @example\n * ```ts\n * import { loadSnapshotAsMap } from \"@gusto/baerly-storage\";\n *\n * const map =\n * srcCurrent.snapshot === null\n * ? new Map<string, DocumentData>()\n * : await loadSnapshotAsMap(src.storage, srcCurrent.snapshot, \"tickets\");\n * ```\n *\n * @throws BaerlyError code=\"Internal\" — pointer resolves to no body,\n * or the body's SHA-256 doesn't match the hash embedded in the\n * filename. (Protocol invariant violation; a corrupted snapshot\n * the reader cannot continue past.)\n * @throws BaerlyError code=\"InvalidResponse\" — body isn't valid JSON,\n * isn't an object, has an unsupported `schema_version`, or carries a\n * `collection` that doesn't match `expectedCollection`.\n */\nexport const loadSnapshotAsMap = async (\n storage: Storage,\n key: string,\n expectedCollection: string,\n signal?: AbortSignal,\n): Promise<Map<string, DocumentData>> => {\n const got = await storage.get(key, signal !== undefined ? { signal } : undefined);\n if (got === null) {\n throw new BaerlyError(\n \"Internal\",\n `compact: snapshot pointer ${key} resolves to no body; protocol violation`,\n );\n }\n // Verify hash: the filename shape is\n // `<...>/snapshot/L<n>/<min>-<max>-<sha256>.json`. The sha256 is\n // the segment after the LAST `-` (the two seq fields don't contain\n // dashes), with `.json` stripped.\n const filename = key.slice(key.lastIndexOf(\"/\") + 1).replace(/\\.json$/, \"\");\n const lastDash = filename.lastIndexOf(\"-\");\n const expectedHash = filename.slice(lastDash + 1);\n const actualHash = await snapshotHash(got.body);\n if (actualHash !== expectedHash) {\n throw new BaerlyError(\n \"Internal\",\n `compact: snapshot ${key} body hash mismatch (got ${actualHash}); protocol violation`,\n );\n }\n let parsed: unknown;\n try {\n parsed = decodeJsonBytes(got.body);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} body is not valid JSON`,\n error,\n );\n }\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `compact: snapshot ${key} body is not an object`);\n }\n const body = parsed as SnapshotBody;\n if (body.schema_version !== 1) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} has unsupported schema_version ${String(body.schema_version)}`,\n );\n }\n if (body.collection !== expectedCollection) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} carries collection ${body.collection}, expected ${expectedCollection}`,\n );\n }\n const out = new Map<string, Doc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