@gusto/baerly-storage 0.1.0 → 0.1.2
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/README.md +9 -5
- package/dist/API.md +161 -10
- package/dist/{app-config-Cb5dO2s9.d.ts → app-config-C0Bbw_Z6.d.ts} +18 -9
- package/dist/app-config.d.ts +1 -1
- package/dist/app-config.js.map +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/baerly.js +10 -10
- package/dist/baerly.js.map +1 -1
- package/dist/bytes-BXdamO3L.js +11 -0
- package/dist/bytes-BXdamO3L.js.map +1 -0
- package/dist/{client-BLf3Ae5s.d.ts → client-DYZfoZb9.d.ts} +3 -3
- package/dist/client-react.d.ts +3 -3
- package/dist/client.d.ts +3 -3
- package/dist/cloudflare.d.ts +31 -4
- package/dist/cloudflare.js +72 -6
- package/dist/cloudflare.js.map +1 -1
- package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
- package/dist/config-DVfDGyw1.js.map +1 -0
- package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
- package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
- package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
- package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
- package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
- package/dist/current-json-C-EyJqs0.js.map +1 -0
- package/dist/{db-D62JguBc.d.ts → db-BM3y2JQw.d.ts} +3 -3
- package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
- package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
- package/dist/dev-vite.d.ts +3 -3
- package/dist/dev-vite.js +3 -3
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
- package/dist/doctor-Db-hzPmE.js.map +1 -0
- package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
- package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
- package/dist/errors-DOdL95kK.js.map +1 -1
- package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
- package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
- package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
- package/dist/fsck-CPPZWt9p.js.map +1 -0
- package/dist/{http-CjUO1Bec.js → http-Cw8p6y5b.js} +8 -8
- package/dist/{http-CjUO1Bec.js.map → http-Cw8p6y5b.js.map} +1 -1
- package/dist/http.d.ts +6 -6
- package/dist/http.js +1 -1
- package/dist/{index-BYv0hb8M.d.ts → index-C3JAH1Yo.d.ts} +14 -2
- package/dist/{index-BGC-ENnj.d.ts → index-DSvwEUeF.d.ts} +63 -54
- package/dist/{index-BquQkhJi.d.ts → index-DwDTWPSU.d.ts} +2 -2
- package/dist/{index-COsQ-Mlz.d.ts → index-cUY-36AN.d.ts} +3 -3
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/{indexes-DwOXkn1Y.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
- package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
- package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
- package/dist/maintenance-BRrThz8V.d.ts +449 -0
- package/dist/maintenance-BvOv6BMM.js +1295 -0
- package/dist/maintenance-BvOv6BMM.js.map +1 -0
- package/dist/maintenance-ClzBC1Vv.js +1895 -0
- package/dist/maintenance-ClzBC1Vv.js.map +1 -0
- package/dist/maintenance.d.ts +2 -323
- package/dist/maintenance.js +2 -2
- package/dist/node.d.ts +20 -79
- package/dist/node.js +2 -2
- package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
- package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
- package/dist/observability.d.ts +2 -2
- package/dist/observability.js +2 -2
- package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
- package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
- package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
- package/dist/query-BmiQy328.js.map +1 -0
- package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
- package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
- package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
- package/dist/restore-C6IcmLeA.js.map +1 -0
- package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
- package/dist/snapshot-SS8USDUF.js.map +1 -0
- package/dist/{src-DyET_VPP.js → src-DU1sCMlr.js} +315 -278
- package/dist/src-DU1sCMlr.js.map +1 -0
- package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
- package/dist/src-QQ7jDeL2.js.map +1 -0
- package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
- package/dist/src-zhEAmmF7.js.map +1 -0
- package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
- package/dist/subcommand-DZcHcsYp.js.map +1 -0
- package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
- package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
- package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
- package/dist/validate-DCq_0DIn.js.map +1 -0
- package/package.json +13 -6
- package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
- package/dist/config-Bsg8wgwo.js.map +0 -1
- package/dist/current-json-BkatBzF7.js.map +0 -1
- package/dist/doctor-B8h9GCN9.js.map +0 -1
- package/dist/fsck-DEz9lyCy.js.map +0 -1
- package/dist/indexes-BXn7a06a.js +0 -297
- package/dist/indexes-BXn7a06a.js.map +0 -1
- package/dist/log-walk-DIru96UT.js.map +0 -1
- package/dist/maintenance-Bn6ul9aV.js +0 -758
- package/dist/maintenance-Bn6ul9aV.js.map +0 -1
- package/dist/query-DcSbFLJt.js.map +0 -1
- package/dist/rebuild-index-C5gTXryd.js +0 -119
- package/dist/rebuild-index-C5gTXryd.js.map +0 -1
- package/dist/restore-CbKVMMpm.js.map +0 -1
- package/dist/snapshot-D7C4_FSl.js +0 -71
- package/dist/snapshot-D7C4_FSl.js.map +0 -1
- package/dist/snapshot-z_N9hpTe.js +0 -917
- package/dist/snapshot-z_N9hpTe.js.map +0 -1
- package/dist/src-Chafbw8r.js.map +0 -1
- package/dist/src-DyET_VPP.js.map +0 -1
- package/dist/src-n0Te1r98.js.map +0 -1
- package/dist/subcommand-BWs6K7zb.js +0 -110
- package/dist/subcommand-BWs6K7zb.js.map +0 -1
- package/dist/validate-DhH1lO8I.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"maintenance-Bn6ul9aV.js","names":["ctxMetrics","APPLICATION_JSON","internal"],"sources":["../packages/protocol/src/coordination/gc-pending.ts","../packages/server/src/compactor.ts","../packages/server/src/gc.ts","../packages/server/src/rebuild-index.ts","../packages/server/src/maintenance.ts"],"sourcesContent":["/**\n * `gc/pending.json` — the per-collection GC candidate ledger. CAS-\n * protected; one per `(tenant, collection)` key — for example\n * `<tenant>/<collection>/gc/pending.json`. `runGc()` in\n * `packages/server/src/gc.ts` is the single writer that adds and\n * removes entries. Stays small in steady state because every\n * candidate is deleted once `due_at` passes.\n *\n * \"Mark\" appends candidates with a future `due_at`; \"sweep\" deletes\n * candidates whose `due_at` is in the past. The two phases run in\n * the same compactor pass — see `runGc()` in\n * `packages/server/src/gc.ts`.\n *\n * Lives next to {@link CurrentJson} in `coordination/` — same shape\n * of \"CAS-protected small control object.\" Pure module; no Node\n * imports; Worker-bundleable.\n *\n * @see packages/server/src/gc.ts\n */\n\nimport { decodeJsonBytes, encodeJsonBytes } from \"../bytes.ts\";\nimport { GC_PENDING_CONTENT_TYPE, GC_PENDING_SCHEMA_VERSION } from \"../constants.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport type { Storage, StoragePutOptions, StoragePutResult } from \"../storage/types.ts\";\n\n/**\n * On-bucket body of `gc/pending.json`. Bounded by\n * `GC_MAX_PENDING_CANDIDATES`. The shape is forward-compatible:\n * adding a new optional field is non-breaking. Renaming or removing\n * a field requires bumping {@link GC_PENDING_SCHEMA_VERSION} to `2`;\n * readers MUST reject unknown major versions with\n * `BaerlyError{code:\"InvalidResponse\"}`.\n */\nexport interface GcPending {\n /** Schema version. Today `1`. Readers MUST reject unknown majors. */\n schema_version: 1;\n /**\n * Candidate deletions. The compactor MUST keep this list bounded —\n * `runGc()` caps the per-run marks and sweeps.\n */\n candidates: ReadonlyArray<GcCandidate>;\n /**\n * Server-clock ISO-8601 timestamp of the last successful sweep\n * completion. Drives the `db.gc.entries_swept_per_second` metric.\n * Empty string `\"\"` before the first sweep.\n */\n last_swept_at: string;\n}\n\n/**\n * One pending deletion entry. The `runGc()` mark phase appends these\n * with a future `due_at`; the sweep phase deletes entries whose\n * `due_at` is in the past and prunes them from the list.\n */\nexport interface GcCandidate {\n /** Full bucket-relative key of the deletion candidate. */\n key: string;\n /** ISO-8601 server-clock time after which the key may be deleted. */\n due_at: string;\n /** Why the key is a candidate. */\n reason: \"stale-log\" | \"orphan-snapshot\" | \"orphan-content\";\n}\n\n/**\n * Return shape from {@link readGcPending}: the parsed JSON plus the\n * ETag needed for a follow-up CAS write.\n */\nexport interface GcPendingRead {\n readonly json: GcPending;\n readonly etag: string;\n}\n\n/**\n * Read + parse `gc/pending.json` at `key`. Returns `null` on\n * 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 const readGcPending = async (\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<GcPendingRead | null> => {\n const got = await storage.get(key, opts);\n if (got === null) {\n return null;\n }\n let parsed: unknown;\n try {\n parsed = decodeJsonBytes(got.body);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json at ${key}: body is not valid JSON`,\n error,\n );\n }\n return { json: assertGcPending(parsed, key), etag: got.etag };\n};\n\n/**\n * Create `gc/pending.json` if-and-only-if it does not exist (S3\n * `If-None-Match: \"*\"`). Use this once per collection at first GC\n * run; subsequent updates go through {@link casUpdateGcPending}.\n *\n * @throws BaerlyError{code:\"Conflict\"} — the key already exists.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `initial` fails the\n * runtime shape guard.\n */\nexport const createGcPending = async (\n storage: Storage,\n key: string,\n initial: GcPending,\n opts?: { signal?: AbortSignal },\n): Promise<GcPendingRead> => {\n assertGcPending(initial, key);\n const body = encodeJsonBytes(initial);\n const putOpts: StoragePutOptions = {\n ifNoneMatch: \"*\",\n contentType: GC_PENDING_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 `gc/pending.json` under CAS. The `mutator`\n * receives a deep clone of the current parsed JSON and returns the\n * new state. The new state is written with `If-Match: <currentEtag>`;\n * on conflict, throws `BaerlyError{code:\"Conflict\"}`.\n *\n * `mutator` MUST be deterministic — it may be called multiple times\n * if the caller wraps this in a retry loop, so it must not have side\n * effects.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer landed a write\n * between this function's read and write.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist\n * (use {@link createGcPending} instead) or body doesn't\n * parse / fails the shape guard.\n */\nexport const casUpdateGcPending = async (\n storage: Storage,\n key: string,\n mutator: (current: GcPending) => GcPending,\n opts?: { signal?: AbortSignal },\n): Promise<GcPendingRead> => {\n const existing = await readGcPending(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json at ${key} does not exist; use createGcPending first`,\n );\n }\n const next = mutator(structuredClone(existing.json));\n assertGcPending(next, key);\n const body = encodeJsonBytes(next);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: GC_PENDING_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// Internals\n// ---------------------------------------------------------------------\n\nconst VALID_REASONS = new Set<GcCandidate[\"reason\"]>([\n \"stale-log\",\n \"orphan-snapshot\",\n \"orphan-content\",\n]);\n\n/**\n * Runtime guard for `parsed` to be a {@link GcPending}. Throws\n * `BaerlyError{code:\"InvalidResponse\"}` rather than coercing.\n */\nconst assertGcPending = (parsed: unknown, key: string): GcPending => {\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json at ${key}: parsed body is not an object`,\n );\n }\n const r = parsed as Record<string, unknown>;\n if (r[\"schema_version\"] !== GC_PENDING_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json at ${key}: unsupported schema_version ${String(r[\"schema_version\"])}; expected ${GC_PENDING_SCHEMA_VERSION}`,\n );\n }\n if (!Array.isArray(r[\"candidates\"])) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json at ${key}: candidates must be an array`,\n );\n }\n for (let i = 0; i < r[\"candidates\"].length; i++) {\n const c = r[\"candidates\"][i];\n if (c === null || typeof c !== \"object\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json at ${key}: candidates[${String(i)}] is not an object`,\n );\n }\n const cr = c as Record<string, unknown>;\n if (typeof cr[\"key\"] !== \"string\" || cr[\"key\"].length === 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json at ${key}: candidates[${String(i)}].key must be a non-empty string`,\n );\n }\n if (typeof cr[\"due_at\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json at ${key}: candidates[${String(i)}].due_at must be a string`,\n );\n }\n if (\n typeof cr[\"reason\"] !== \"string\" ||\n !VALID_REASONS.has(cr[\"reason\"] as GcCandidate[\"reason\"])\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json at ${key}: candidates[${String(i)}].reason must be one of stale-log|orphan-snapshot|orphan-content`,\n );\n }\n }\n if (typeof r[\"last_swept_at\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json at ${key}: last_swept_at must be a string`,\n );\n }\n return parsed as GcPending;\n};\n\n/**\n * Wrap a storage-level error with `gc/pending.json at <key>`\n * location context. `Conflict` (the storage layer's CAS-lost signal)\n * is re-thrown with an annotated message; other `BaerlyError`s pass\n * through; non-`BaerlyError` falls through as `InvalidResponse`.\n */\nconst translateCasError = (e: unknown, key: string): BaerlyError => {\n if (e instanceof BaerlyError && e.code === \"Conflict\") {\n return new BaerlyError(\"Conflict\", `gc/pending.json CAS lost at ${key}: ${e.message}`, e);\n }\n if (e instanceof BaerlyError) {\n return e;\n }\n return new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json write at ${key} failed: ${String(e)}`,\n e,\n );\n};\n","/* eslint-disable no-underscore-dangle -- `_id` is the locked primary-key\n field on document shapes (see `@baerly/protocol/src/collection-api.ts`'s `Collection<T>` /\n `Query<T>` declarations); the snapshot body carries it through. */\n\n/**\n * Compactor: fold a prefix of the live log into a content-\n * hashed snapshot file and CAS-advance `current.json` to swap the\n * pointer.\n *\n * The hard correctness requirement is **atomic snapshot generation**:\n * a compactor that crashes mid-write must not leave a corrupted body\n * that readers consume as truth. The design: every snapshot's filename\n * embeds the SHA-256 of its body. A crashed mid-PUT leaves a body that\n * doesn't match its own filename hash, and readers reject it as\n * \"missing.\" The atomic moment is the CAS-swap of\n * `current.json.snapshot`, which is a single conditional PUT.\n *\n * Order of operations (matches `Writer.commit`'s manifest-first-\n * REVERSED ordering): PUT snapshot body → CAS-advance `current.json`.\n * A crash before the swap leaves an orphan snapshot file; the swap\n * succeeds iff our captured ETag still matches.\n *\n * Why level-prefixed chunked snapshots over the alternatives: a\n * single monolithic snapshot (every compaction rewrites one well-\n * known key) makes partial writes catastrophic and serializes every\n * writer on one key. WAL-checkpointing in the rqlite / Raft tradition\n * requires a consensus layer Baerly doesn't have. The Litestream-\n * style multi-level scheme — small fixed number of levels, chunked\n * files keyed by sequence range — keeps random GETs cheap on\n * S3-compatible storage and avoids LIST. Current ship is single-\n * level at L9 (one snapshot replaces the prior; no multi-level merge\n * yet); the key format is forward-compatible with future L0..L9\n * rolling merges without a wire change.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\n\nimport {\n type CurrentJson,\n type DocumentData,\n type MetricsRecorder,\n encodeJsonBytes,\n logSeqStartOf,\n BaerlyError,\n noopMetricsRecorder,\n readCurrentJson,\n snapshotHash,\n type Storage,\n type StoragePutOptions,\n} from \"@baerly/protocol\";\nimport { walkLogRange } from \"./log-walk.ts\";\nimport { getCurrentContext } from \"./observability/context.ts\";\nimport {\n encodeSnapshotBody,\n loadSnapshotAsMap,\n type SnapshotBody,\n snapshotKey,\n} from \"./snapshot.ts\";\n\nconst ctxMetrics = (): MetricsRecorder => getCurrentContext()?.recorder ?? noopMetricsRecorder;\n\n/**\n * Public configuration knobs for {@link compact}. All optional; the\n * engine works unbounded by default. Opt into a per-run cap via the\n * `CLOUDFLARE_FREE_TIER` profile (from `./maintenance.ts`) or by\n * reaching for {@link InternalCompactOptions} via the\n * `@baerly/server/_internal/testing` subpath.\n */\nexport interface CompactOptions {\n /**\n * Minimum log-tail length to compact. Skips work when there are\n * fewer than this many live entries past the last snapshot.\n * Default 100.\n */\n readonly minEntriesToCompact?: number;\n\n /** Optional AbortSignal forwarded to every storage call. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Internal-only widening of {@link CompactOptions}. Surfaced via the\n * `@baerly/server/_internal/testing` subpath (NOT in the published\n * `publishConfig.exports`); production callers should use\n * {@link CompactOptions}.\n *\n * @internal\n */\nexport interface InternalCompactOptions extends CompactOptions {\n /**\n * @internal Budget cap for the CF free-tier subrequest budget;\n * `CLOUDFLARE_FREE_TIER` sets it. Tests also set it to exercise\n * the cap path. The compactor's I/O profile is\n * `maxEntriesPerRun + 3` subrequests (N GETs + 1 PUT snapshot +\n * 1 GET current + 1 PUT current). The default is effectively\n * unbounded (`Number.MAX_SAFE_INTEGER`).\n */\n readonly maxEntriesPerRun?: number;\n}\n\nexport interface CompactResult {\n /** `true` iff a new snapshot landed and `current.json` was advanced. */\n readonly written: boolean;\n /** Reason `written === false`. */\n readonly skippedReason?: \"below-min-threshold\" | \"current-json-missing\" | \"cas-lost\";\n /** Prior snapshot key (`null` if no prior snapshot existed). */\n readonly previousSnapshotKey: string | null;\n /** New snapshot key (`undefined` if `written === false` and no PUT happened). */\n readonly newSnapshotKey?: string;\n /** `log_seq_start` before the run. */\n readonly logSeqStartBefore: number;\n /** `log_seq_start` after the run. */\n readonly logSeqStartAfter: number;\n /** Number of log entries folded into the new snapshot. */\n readonly entriesFolded: number;\n}\n\nconst DEFAULT_MAX_PER_RUN = Number.MAX_SAFE_INTEGER;\nconst DEFAULT_MIN_TO_COMPACT = 100;\nconst APPLICATION_JSON = \"application/json\";\n\n/**\n * Fold a prefix of the live log into a new snapshot and CAS-advance\n * `current.json`. Idempotent: a second run with no new writes is a\n * no-op (below-min-threshold).\n *\n * Single-attempt: on CAS conflict we return\n * `{written: false, skippedReason: \"cas-lost\", newSnapshotKey}` — the\n * caller (the cron handler invoking `runScheduledMaintenance` from\n * `./maintenance.ts`) decides whether to schedule another run. The\n * orphan snapshot file just written will be swept by `runGc()`.\n *\n * @throws BaerlyError code=\"InvalidResponse\" — `current.json` is\n * present but malformed, or a snapshot body fails its schema /\n * collection cross-check.\n * @throws BaerlyError code=\"Internal\" — protocol-invariant violation:\n * a log entry missing inside `[log_seq_start, foldEnd)`, or the\n * prior-snapshot pointer resolves to no body / a body whose hash\n * doesn't match its filename.\n *\n * @example\n * ```ts\n * import { compact } from \"@gusto/baerly-storage\";\n *\n * const res = await compact(\n * { storage, currentJsonKey: \"app/x/tenant/t/manifests/tickets/current.json\" },\n * { minEntriesToCompact: 100, maxEntriesPerRun: 40 },\n * );\n * if (res.written) console.log(\"snapshot landed at\", res.newSnapshotKey);\n * ```\n */\nexport const compact = async (\n args: {\n storage: Storage;\n /** Full bucket-relative key of the CAS pointer. */\n currentJsonKey: string;\n },\n options: CompactOptions = {},\n): Promise<CompactResult> => {\n const { storage, currentJsonKey } = args;\n // The internal cap fields ride on the same runtime object even\n // though the public `CompactOptions` doesn't surface them. The cast\n // is safe — the JS runtime carries every property regardless of TS\n // narrowing — and keeps the public type honest.\n const internal = options as InternalCompactOptions;\n const maxPerRun = internal.maxEntriesPerRun ?? DEFAULT_MAX_PER_RUN;\n const minToCompact = options.minEntriesToCompact ?? DEFAULT_MIN_TO_COMPACT;\n const collectionPrefix = currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"));\n const collectionName = collectionPrefix.slice(collectionPrefix.lastIndexOf(\"/\") + 1);\n\n // ── Step 1. Read current.json fresh. ────────────────────────────\n const read = await readCurrentJson(\n storage,\n currentJsonKey,\n options.signal !== undefined ? { signal: options.signal } : undefined,\n );\n if (read === null) {\n return {\n written: false,\n skippedReason: \"current-json-missing\",\n previousSnapshotKey: null,\n logSeqStartBefore: 0,\n logSeqStartAfter: 0,\n entriesFolded: 0,\n };\n }\n const current = read.json;\n const baseEtag = read.etag;\n const logSeqStartBefore = logSeqStartOf(current);\n const nextSeq = current.next_seq;\n const available = nextSeq - logSeqStartBefore;\n if (available < minToCompact) {\n return {\n written: false,\n skippedReason: \"below-min-threshold\",\n previousSnapshotKey: current.snapshot,\n logSeqStartBefore,\n logSeqStartAfter: logSeqStartBefore,\n entriesFolded: 0,\n };\n }\n\n const foldEnd = Math.min(nextSeq, logSeqStartBefore + maxPerRun);\n\n // ── Step 2. Load the previous snapshot (if any) as the fold base.\n const base =\n current.snapshot === null\n ? new Map<string, DocumentData>()\n : await loadSnapshotAsMap(storage, current.snapshot, collectionName, options.signal);\n\n // ── Step 3. Parallel-fetch [logSeqStartBefore, foldEnd) entries. ──\n const entries = await walkLogRange(storage, collectionPrefix, logSeqStartBefore, foldEnd, {\n signal: options.signal,\n });\n\n // ── Step 4. Apply the fold onto `base`. ─────────────────────────\n // I / U overwrite with the post-image (today's per-doc-replace\n // model: writer emits `entry.new` as the full post-image, see\n // packages/protocol/src/log.ts:67-72). D tombstones. T / M are\n // forward-compat shapes (writer doesn't emit them today).\n for (const entry of entries) {\n if (entry.collection !== collectionName) {\n continue;\n }\n if (entry.doc_id === undefined) {\n continue;\n }\n switch (entry.op) {\n case \"I\":\n case \"U\": {\n if (entry.new !== undefined) {\n base.set(entry.doc_id, entry.new);\n }\n break;\n }\n case \"D\": {\n base.delete(entry.doc_id);\n break;\n }\n case \"T\":\n case \"M\": {\n // No-op for this ticket.\n break;\n }\n }\n }\n\n // ── Step 5. Build the canonical snapshot body. ──────────────────\n // Sort by `_id` so the byte output is deterministic — same fold ⇒\n // same body ⇒ same hash ⇒ same filename. Idempotent re-runs.\n const sortedDocs = Array.from(base.entries())\n .toSorted(([a], [b]) => {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n })\n .map(([id, body]) => ({ _id: id, body }));\n const snapshotBody: SnapshotBody = {\n schema_version: 1,\n min_seq: 0,\n max_seq: foldEnd,\n collection: collectionName,\n docs: sortedDocs,\n };\n const bodyBytes = encodeSnapshotBody(snapshotBody);\n const sha256 = await snapshotHash(bodyBytes);\n const newKey = snapshotKey(collectionPrefix, 0, foldEnd, sha256);\n\n // ── Step 6. PUT the snapshot. ───────────────────────────────────\n // No CAS guard — content-hash filenames make collisions impossible\n // for distinct bodies. If a concurrent compactor produced the same\n // body, this PUT is an idempotent overwrite of the same bytes.\n const putOpts: StoragePutOptions = {\n contentType: APPLICATION_JSON,\n ...(options.signal !== undefined && { signal: options.signal }),\n };\n await storage.put(newKey, bodyBytes, putOpts);\n\n // ── Step 7. CAS-advance current.json. ───────────────────────────\n const next: CurrentJson = {\n ...current,\n snapshot: newKey,\n log_seq_start: foldEnd,\n };\n const nextBody = encodeJsonBytes(next);\n const casOpts: StoragePutOptions = {\n ifMatch: baseEtag,\n contentType: APPLICATION_JSON,\n ...(options.signal !== undefined && { signal: options.signal }),\n };\n try {\n await storage.put(currentJsonKey, nextBody, casOpts);\n } catch (error) {\n if (isCasConflict(error)) {\n // Another writer landed between our read and write. The\n // snapshot file we just wrote is now an orphan (correct\n // content, unreferenced) — `runGc()` will sweep it. Surface\n // cas-lost; the cron handler can rerun us next tick.\n return {\n written: false,\n skippedReason: \"cas-lost\",\n previousSnapshotKey: current.snapshot,\n newSnapshotKey: newKey,\n logSeqStartBefore,\n logSeqStartAfter: logSeqStartBefore,\n entriesFolded: foldEnd - logSeqStartBefore,\n };\n }\n throw error;\n }\n\n // ── Step 8. Emit metrics on a successful run. ───────────────────\n // `lag_window_depth` is the post-compaction live tail length —\n // entries still pending fold after this run. `entries_folded` is\n // the per-run histogram sample. Metrics are in-memory only; they\n // add zero storage ops.\n const entriesFolded = foldEnd - logSeqStartBefore;\n const metrics = ctxMetrics();\n metrics.histogram(\"db.compact.entries_folded\", entriesFolded, { collection: collectionName });\n metrics.gauge(\"db.manifest.lag_window_depth\", current.next_seq - foldEnd, {\n collection: collectionName,\n });\n\n return {\n written: true,\n previousSnapshotKey: current.snapshot,\n newSnapshotKey: newKey,\n logSeqStartBefore,\n logSeqStartAfter: foldEnd,\n entriesFolded,\n };\n};\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\n/**\n * `true` when an `If-Match` CAS guard lost. Every in-tree\n * {@link Storage} impl surfaces a lost CAS as\n * `BaerlyError{code:\"Conflict\"}`.\n */\nconst isCasConflict = (err: unknown): boolean =>\n err instanceof BaerlyError && err.code === \"Conflict\";\n","/**\n * GC mark + sweep.\n *\n * `runGc` is a single-pass garbage collector that:\n * 1. Reads `current.json` (and bootstraps `gc/pending.json` on first\n * run).\n * 2. Marks new orphan candidates by LISTing the three artifact\n * prefixes — log, snapshot, content — and classifying each key.\n * 3. Sweeps any already-pending candidate whose `due_at` has passed.\n * 4. CAS-writes the updated `gc/pending.json`.\n *\n * Two-phase by design: every candidate sits in `gc/pending.json` for a\n * grace period (default 7 days, see {@link GC_GRACE_PERIOD_MILLIS})\n * before it is deleted. The grace bounds the worst plausible\n * writer-retry window — a paused-process writer that resumes hours\n * later still finds its idempotency anchor on the bucket.\n *\n * Idempotent: same input bucket state ⇒ same `pending.json` output.\n * Unbounded by default — the run marks and sweeps the entire eligible\n * set in one pass. Callers on the Cloudflare 50-subrequest free-tier\n * budget opt INTO caps via the `CLOUDFLARE_FREE_TIER` profile's\n * `gc.maxMarksPerRun` / `maxSweepsPerRun` knobs (`InternalRunGcOptions`,\n * not on the public `RunGcOptions`).\n *\n * Three categories of orphan:\n * - `stale-log`: `<collectionPrefix>/log/<seq>.json` with\n * `seq < log_seq_start`. After `compact()` folds these into a\n * snapshot, they're unreferenced.\n * - `orphan-snapshot`: a `<collectionPrefix>/snapshot/L<n>/...` key not\n * equal to `current.snapshot`. Each compactor run replaces the\n * pointer; the prior file becomes unreferenced.\n * - `orphan-content`: `<collectionPrefix>/content/<sha>.json` whose\n * 32-hex truncated-SHA-256 hash is not in the live content-hash\n * set (computed by hashing every live `entry.new` post-image —\n * the same hash the writer's step 4 produces). Surfaces writer\n * crashes between the content PUT and the log-entry PUT.\n *\n * CAS-lost on `gc/pending.json` is non-fatal: the DELETEs already\n * issued are durable, so we return a successful result and the next\n * pass will pick up any work this pass lost.\n */\n\nimport {\n type CurrentJson,\n type GcCandidate,\n type GcPending,\n type MetricsRecorder,\n type Storage,\n type StorageListEntry,\n GC_GRACE_PERIOD_MILLIS,\n GC_MAX_PENDING_CANDIDATES,\n GC_PENDING_SCHEMA_VERSION,\n BaerlyError,\n casUpdateGcPending,\n createGcPending,\n decodeJsonBytes,\n encodeJsonBytes,\n logSeqStartOf,\n noopMetricsRecorder,\n readCurrentJson,\n readGcPending,\n versionFromContent,\n} from \"@baerly/protocol\";\nimport { loadSnapshotAsMap } from \"./snapshot.ts\";\nimport { getCurrentContext } from \"./observability/context.ts\";\n\nconst ctxMetrics = (): MetricsRecorder => getCurrentContext()?.recorder ?? noopMetricsRecorder;\n\n/**\n * Public tunables for {@link runGc}. All optional; the engine works\n * unbounded by default. Opt into per-run caps via the\n * `CLOUDFLARE_FREE_TIER` profile (from `./maintenance.ts`) or by\n * reaching for {@link InternalRunGcOptions} via the\n * `@baerly/server/_internal/testing` subpath.\n */\nexport interface RunGcOptions {\n readonly signal?: AbortSignal;\n}\n\n/**\n * Internal-only widening of {@link RunGcOptions}. Surfaced via the\n * `@baerly/server/_internal/testing` subpath (NOT in the published\n * `publishConfig.exports`); production callers should use\n * {@link RunGcOptions}.\n *\n * @internal\n */\nexport interface InternalRunGcOptions extends RunGcOptions {\n /**\n * @internal Override grace-period for tests. Defaults to\n * {@link GC_GRACE_PERIOD_MILLIS} (7 days). Tests use `0` to bypass\n * the grace and exercise the sweep path in one pass.\n */\n readonly graceMillis?: number;\n\n /**\n * @internal Budget cap on candidates marked per category per run.\n * `CLOUDFLARE_FREE_TIER` sets it; bounds LIST + classification\n * cost per pass. The default is effectively unbounded\n * (`Number.MAX_SAFE_INTEGER`).\n */\n readonly maxMarksPerRun?: number;\n\n /**\n * @internal Budget cap on keys deleted per run.\n * `CLOUDFLARE_FREE_TIER` sets it — CF free-tier safe when paired\n * with `compact()` in the same scheduled handler. The default is\n * effectively unbounded (`Number.MAX_SAFE_INTEGER`).\n */\n readonly maxSweepsPerRun?: number;\n\n /**\n * @internal Clock injection for tests. Defaults to\n * `() => new Date()`. The function is invoked at mark time (to\n * compute `due_at` when `lastModified` is absent) and at sweep\n * time (to compare against candidate `due_at`).\n */\n readonly now?: () => Date;\n}\n\n/**\n * Return shape of {@link runGc}.\n */\nexport interface RunGcResult {\n /** Per-category counts of newly-marked candidates in this pass. */\n readonly marked: {\n readonly stale_log: number;\n readonly orphan_snapshot: number;\n readonly orphan_content: number;\n };\n /** Number of keys deleted in this pass. */\n readonly swept: number;\n /**\n * Depth of `gc/pending.json` after this pass. Drives the\n * `db.orphan.candidate_count` metric. Best-effort on `cas-lost` —\n * see module JSDoc.\n */\n readonly pendingDepth: number;\n}\n\nconst DEFAULT_MAX_MARKS = Number.MAX_SAFE_INTEGER;\nconst DEFAULT_MAX_SWEEPS = Number.MAX_SAFE_INTEGER;\n\n/**\n * Single GC pass — mark new orphans, sweep due-elapsed candidates,\n * persist via CAS-update on `gc/pending.json`.\n *\n * Returns immediately if `current.json` is missing — there's nothing\n * to do until a writer has bootstrapped the collection.\n *\n * @example\n * ```ts\n * import { runGc } from \"@gusto/baerly-storage\";\n *\n * const r = await runGc({ storage, currentJsonKey });\n * console.log(`marked ${r.marked.stale_log} stale logs, swept ${r.swept}`);\n * ```\n */\nexport const runGc = async (\n args: { storage: Storage; currentJsonKey: string },\n options: RunGcOptions = {},\n): Promise<RunGcResult> => {\n const { storage, currentJsonKey } = args;\n // The internal seam fields (caps + clock + grace) ride on the same\n // runtime object even though the public `RunGcOptions` doesn't\n // surface them. Safe cast — the JS runtime carries every property.\n const internal = options as InternalRunGcOptions;\n const grace = internal.graceMillis ?? GC_GRACE_PERIOD_MILLIS;\n const maxMarks = internal.maxMarksPerRun ?? DEFAULT_MAX_MARKS;\n const maxSweeps = internal.maxSweepsPerRun ?? DEFAULT_MAX_SWEEPS;\n const now = internal.now ?? ((): Date => new Date());\n const collectionPrefix = currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"));\n const collectionName = collectionPrefix.slice(collectionPrefix.lastIndexOf(\"/\") + 1);\n const gcPendingKey = `${collectionPrefix}/gc/pending.json`;\n const signal = options.signal;\n const signalOpts = signal !== undefined ? { signal } : undefined;\n\n // ── Step 1. Read current.json (skip silently if absent). ────────\n const cur = await readCurrentJson(storage, currentJsonKey, signalOpts);\n if (cur === null) {\n return {\n marked: { stale_log: 0, orphan_snapshot: 0, orphan_content: 0 },\n swept: 0,\n pendingDepth: 0,\n };\n }\n const current = cur.json;\n const logSeqStart = logSeqStartOf(current);\n\n // ── Step 2. Read or create gc/pending.json. ─────────────────────\n // Race-tolerant create: a concurrent pass may have bootstrapped\n // between our read and our create. Re-read on Conflict.\n let pending = await readGcPending(storage, gcPendingKey, signalOpts);\n if (pending === null) {\n const initial: GcPending = {\n schema_version: GC_PENDING_SCHEMA_VERSION,\n candidates: [],\n last_swept_at: \"\",\n };\n try {\n pending = await createGcPending(storage, gcPendingKey, initial, signalOpts);\n } catch (error) {\n if (error instanceof BaerlyError && error.code === \"Conflict\") {\n pending = await readGcPending(storage, gcPendingKey, signalOpts);\n if (pending === null) {\n throw error;\n }\n } else {\n throw error;\n }\n }\n }\n\n // Set of keys already pending — don't re-mark.\n const known = new Set(pending.json.candidates.map((c) => c.key));\n\n // ── Step 3. Mark stale log entries [0, log_seq_start). ──────────\n const newCandidates: GcCandidate[] = [];\n let markedStaleLog = 0;\n if (logSeqStart > 0) {\n for await (const entry of listBounded(storage, `${collectionPrefix}/log/`, maxMarks, signal)) {\n if (markedStaleLog >= maxMarks) {\n break;\n }\n const seq = parseSeqFromLogKey(entry.key);\n if (seq === null || seq >= logSeqStart) {\n continue;\n }\n if (known.has(entry.key)) {\n continue;\n }\n newCandidates.push({\n key: entry.key,\n due_at: computeDueAt(entry, now, grace),\n reason: \"stale-log\",\n });\n markedStaleLog++;\n }\n }\n\n // ── Step 4. Mark orphan snapshots. ──────────────────────────────\n let markedOrphanSnapshot = 0;\n for await (const entry of listBounded(\n storage,\n `${collectionPrefix}/snapshot/`,\n maxMarks,\n signal,\n )) {\n if (markedOrphanSnapshot >= maxMarks) {\n break;\n }\n if (entry.key === current.snapshot) {\n continue;\n }\n if (known.has(entry.key)) {\n continue;\n }\n newCandidates.push({\n key: entry.key,\n due_at: computeDueAt(entry, now, grace),\n reason: \"orphan-snapshot\",\n });\n markedOrphanSnapshot++;\n }\n\n // ── Step 5. Mark orphan content. ────────────────────────────────\n // Build the live content-hash set by hashing every live post-image:\n // - log entries [log_seq_start, next_seq)\n // - snapshot rows (via `loadSnapshotAsMap` so the hash check\n // defends against a tampered snapshot)\n // Hash with the same `versionFromContent` (32-hex truncated SHA-256)\n // the writer used to mint the content key.\n const liveHashes = await collectLiveContentHashes(\n storage,\n collectionPrefix,\n collectionName,\n current,\n logSeqStart,\n signal,\n );\n let markedOrphanContent = 0;\n for await (const entry of listBounded(\n storage,\n `${collectionPrefix}/content/`,\n maxMarks,\n signal,\n )) {\n if (markedOrphanContent >= maxMarks) {\n break;\n }\n const hash = parseHashFromContentKey(entry.key);\n if (hash === null || liveHashes.has(hash)) {\n continue;\n }\n if (known.has(entry.key)) {\n continue;\n }\n newCandidates.push({\n key: entry.key,\n due_at: computeDueAt(entry, now, grace),\n reason: \"orphan-content\",\n });\n markedOrphanContent++;\n }\n\n // ── Step 6. Sweep candidates whose due_at is in the past. ───────\n // Eligible set = previously-pending entries PLUS this pass's freshly\n // marked entries. Including the new marks lets `runGc({graceMillis:0})`\n // mark-and-sweep in a single pass — useful for tests and for\n // grace-bypassing maintenance jobs. Order: pre-existing first\n // (they've been waiting longer), then new marks.\n const nowMs = now().getTime();\n const sweepCandidates: GcCandidate[] = [...pending.json.candidates, ...newCandidates];\n const toSweep: GcCandidate[] = [];\n const remaining: GcCandidate[] = [];\n for (const cand of sweepCandidates) {\n if (toSweep.length < maxSweeps && Date.parse(cand.due_at) <= nowMs) {\n toSweep.push(cand);\n } else {\n remaining.push(cand);\n }\n }\n // Idempotent DELETE on every in-tree Storage impl — a 404 is a\n // no-op. Parallel via Promise.all; one failure aborts the rest,\n // but the per-key DELETEs that landed are durable.\n await Promise.all(toSweep.map((c) => storage.delete(c.key, signalOpts)));\n\n // ── Step 7. CAS-write pending.json. ─────────────────────────────\n // Un-swept candidates (pre-existing un-due + new un-due) form the\n // post-pass ledger. Bounded by GC_MAX_PENDING_CANDIDATES.\n const merged: GcCandidate[] = remaining.slice(0, GC_MAX_PENDING_CANDIDATES);\n const lastSweptAt = toSweep.length > 0 ? now().toISOString() : pending.json.last_swept_at;\n const markedSummary = {\n stale_log: markedStaleLog,\n orphan_snapshot: markedOrphanSnapshot,\n orphan_content: markedOrphanContent,\n };\n let pendingDepth: number;\n try {\n const updated = await casUpdateGcPending(\n storage,\n gcPendingKey,\n () => ({\n schema_version: GC_PENDING_SCHEMA_VERSION,\n candidates: merged,\n last_swept_at: lastSweptAt,\n }),\n signalOpts,\n );\n pendingDepth = updated.json.candidates.length;\n } catch (error) {\n // CAS-lost on pending.json: another GC pass landed concurrently.\n // The DELETEs we issued are durable; the next pass picks up any\n // marks we couldn't persist. Surface success — re-throwing here\n // would mask the work we DID complete.\n if (error instanceof BaerlyError && error.code === \"Conflict\") {\n // Best-effort: we know `remaining.length` is at least the\n // post-sweep depth; concurrent passes may have moved it.\n pendingDepth = remaining.length;\n } else {\n throw error;\n }\n }\n\n // ── Step 8. Emit metrics. ───────────────────────────────────────\n // In-memory only — zero storage ops. Emit regardless of CAS-lost\n // (the operator wants visibility into best-effort runs too).\n const labels = { collection: collectionName };\n const metrics = ctxMetrics();\n metrics.gauge(\"db.orphan.candidate_count\", pendingDepth, labels);\n metrics.gauge(\"db.gc.entries_swept_per_second\", toSweep.length, labels);\n if (toSweep.length > 0) {\n const byReason = new Map<GcCandidate[\"reason\"], number>();\n for (const c of toSweep) {\n byReason.set(c.reason, (byReason.get(c.reason) ?? 0) + 1);\n }\n for (const [reason, count] of byReason) {\n metrics.counter(\"db.gc.swept_total\", count, { collection: collectionName, reason });\n }\n }\n\n return {\n marked: markedSummary,\n swept: toSweep.length,\n pendingDepth,\n };\n};\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\n/**\n * `Storage.list` with a hard ceiling — bounds the I/O cost of a\n * single pass when a runaway prefix has accumulated many keys.\n */\nconst listBounded = async function* (\n storage: Storage,\n prefix: string,\n cap: number,\n signal: AbortSignal | undefined,\n): AsyncGenerator<StorageListEntry> {\n let yielded = 0;\n const opts = signal !== undefined ? { signal } : undefined;\n for await (const entry of storage.list(prefix, opts)) {\n if (yielded >= cap) {\n return;\n }\n yield entry;\n yielded++;\n }\n};\n\n/**\n * Parse `<...>/log/<seq>.json` and return `seq`. Returns `null` on\n * any shape that doesn't look like a log entry key — defensively\n * tolerates an unrelated key under the log prefix.\n */\nconst parseSeqFromLogKey = (key: string): number | null => {\n const match = /\\/log\\/(\\d+)\\.json$/.exec(key);\n if (match === null) {\n return null;\n }\n const n = Number.parseInt(match[1]!, 10);\n return Number.isFinite(n) && n >= 0 ? n : null;\n};\n\n/**\n * Parse `<...>/content/<sha-32>.json` and return the 32-hex hash.\n * Returns `null` on any shape that doesn't match the writer's\n * `versionFromContent`-produced key format.\n */\nconst parseHashFromContentKey = (key: string): string | null => {\n const match = /\\/content\\/([0-9a-f]{32})\\.json$/.exec(key);\n return match === null ? null : match[1]!;\n};\n\n/**\n * Anchor `due_at` to `lastModified` when the storage adapter\n * surfaces it; fall back to the injected `now` so a Storage impl\n * without a server clock still GCs after `grace` from the mark\n * moment.\n */\nconst computeDueAt = (entry: StorageListEntry, now: () => Date, graceMs: number): string => {\n const base = entry.lastModified ?? now();\n return new Date(base.getTime() + graceMs).toISOString();\n};\n\n/**\n * Build the live content-hash set. The set covers every live\n * post-image: every `entry.new` in `[logSeqStart, next_seq)` plus\n * every row body in the current snapshot.\n *\n * A snapshot read that throws (corrupt body, hash mismatch) is\n * tolerated — the worst-case effect is missing some live hashes,\n * which could mark a live content blob as orphan. The grace period\n * absorbs the false-positive: a retry that re-PUTs the same hash\n * recreates the key before the sweep deletes it.\n */\nconst collectLiveContentHashes = async (\n storage: Storage,\n collectionPrefix: string,\n collectionName: string,\n current: CurrentJson,\n logSeqStart: number,\n signal: AbortSignal | undefined,\n): Promise<Set<string>> => {\n const hashes = new Set<string>();\n const getOpts = signal !== undefined ? { signal } : undefined;\n\n // Live log tail.\n const logReads: Array<Promise<void>> = [];\n for (let s = logSeqStart; s < current.next_seq; s++) {\n logReads.push(\n (async (): Promise<void> => {\n const got = await storage.get(`${collectionPrefix}/log/${s}.json`, getOpts);\n if (got === null) {\n return;\n }\n let entry: { new?: unknown };\n try {\n entry = decodeJsonBytes<{ new?: unknown }>(got.body);\n } catch {\n // A malformed log entry is the writer's concern, not GC's.\n // Skip and let other invariants catch it.\n return;\n }\n if (entry.new === undefined) {\n return;\n }\n const bodyBytes = encodeJsonBytes(entry.new);\n hashes.add(await versionFromContent(bodyBytes));\n })(),\n );\n }\n await Promise.all(logReads);\n\n // Snapshot rows.\n if (current.snapshot !== null) {\n try {\n const map = await loadSnapshotAsMap(storage, current.snapshot, collectionName, signal);\n const rowReads: Array<Promise<void>> = [];\n for (const body of map.values()) {\n rowReads.push(\n (async (): Promise<void> => {\n const bytes = encodeJsonBytes(body);\n hashes.add(await versionFromContent(bytes));\n })(),\n );\n }\n await Promise.all(rowReads);\n } catch {\n // Snapshot read failure is non-fatal — see the docstring.\n }\n }\n\n return hashes;\n};\n","/**\n * Idempotent reconciliation for one secondary index.\n *\n * {@link rebuildIndex} folds the live `(snapshot, log_tail)` of a\n * collection into the doc set the writer's index emission would\n * have produced, then PUTs every missing index key and DELETEs every\n * orphaned one. Same-key zero-byte PUTs are no-ops (the entries are\n * content-addressed by composition); same-key DELETEs are\n * contractually idempotent.\n *\n * Invariants:\n *\n * - **Re-running on a healthy index is a no-op.** `added = 0`,\n * `removed = 0`.\n * - **Re-running after a crashed mid-commit** reconciles toward\n * the live `current.json` view — orphans deleted, missing keys\n * PUT.\n * - **Re-running while writes are in flight** is safe up to a\n * race window: a write that lands during the rebuild may\n * produce a transient \"orphan\" the rebuild sweeps, which the\n * next live write then re-PUTs. The race converges on the next\n * commit.\n *\n * The function reads the same fold the writer / reader use\n * (snapshot via {@link loadSnapshotAsMap}; log tail by direct\n * `get(<logPrefix>/log/<seq>.json)`) so it MUST agree with the\n * writer on the live doc set by construction.\n *\n * @see ./indexes.ts — `IndexDefinition`, `allIndexKeysFor`,\n * `indexKeyPrefix`.\n * @see ./writer.ts — the fence-time emission path this\n * command reconciles.\n */\n\nimport {\n BaerlyError,\n type DocumentData,\n logSeqStartOf,\n readCurrentJson,\n type Storage,\n} from \"@baerly/protocol\";\nimport { loadSnapshotAsMap } from \"./snapshot.ts\";\nimport { allIndexKeysFor, type IndexDefinition, indexKeyPrefix } from \"./indexes.ts\";\nimport { foldLogEntriesOnto, walkLogRange } from \"./log-walk.ts\";\n\nconst EMPTY_BODY = new Uint8Array(0);\nconst APPLICATION_JSON = \"application/json\";\n\n/**\n * Reconciliation summary.\n *\n * In a normal (mutating) run, the counts describe what was actually\n * PUT / DELETEd. In `dryRun` mode ({@link RebuildIndexOptions.dryRun}),\n * `added` / `removed` report the counts that a real rebuild *would*\n * have produced — storage is unchanged. `kept` counts pre-existing\n * intersection keys (`expected ∩ actual`) at function entry. In a real\n * run, `kept` may also include keys promoted from `added` via the\n * Conflict-race fallback (a PUT with `ifNoneMatch:\"*\"` returned 412\n * because a peer wrote the same key first, so the key was already\n * in place by the time we observed it); dryRun mode never issues\n * those PUTs and therefore does not observe that race.\n */\nexport interface RebuildIndexResult {\n /**\n * Keys PUT because they were missing on storage. In `dryRun` mode,\n * the predicted PUT count — no writes were issued.\n */\n readonly added: number;\n /**\n * Keys DELETEd because the doc no longer exists / no longer projects\n * them. In `dryRun` mode, the predicted DELETE count — no deletes\n * were issued.\n */\n readonly removed: number;\n /** Keys already in place. The healthy-index re-run reports this as the full expected count. */\n readonly kept: number;\n}\n\n/**\n * Optional knobs accepted by {@link rebuildIndex}. Every field is\n * optional; the function behaves identically to the older\n * positional-arg shape when `opts` is omitted.\n *\n * @public — surfaced from `baerly-storage` so admin tooling and the\n * observability layer can opt in.\n */\nexport interface RebuildIndexOptions {\n /**\n * Cancellation signal. Forwarded to every storage `list` call so\n * long-running rebuilds over large collections can be cut short\n * by admin tooling. Storage `get` / `put` / `delete` calls inside\n * the reconciliation loop do not currently honour the signal\n * (the per-call durations are short enough that cooperative\n * cancellation between calls suffices); future tightening can\n * forward it through without breaking callers.\n */\n readonly signal?: AbortSignal;\n /**\n * When `true`, walk the expected-vs-actual diff and return the\n * counts that a real rebuild would have produced WITHOUT issuing\n * any PUT or DELETE. Used by `baerly admin fsck --indexes`\n * to report drift cheaply. Defaults to `false`.\n *\n * `kept` is reported as the pre-existing intersection\n * (`expected ∩ actual`); a real run can additionally fold\n * Conflict-race-demoted PUTs into `kept`, which dryRun does not\n * observe. See {@link RebuildIndexResult}.\n */\n readonly dryRun?: boolean;\n}\n\n/**\n * Idempotently reconcile one secondary index for one collection.\n *\n * @param storage Storage handle (any in-tree `Storage`).\n * @param currentJsonKey The collection's `current.json` key.\n * @param def The index to reconcile. Single-field today;\n * composite definitions are accepted by the\n * key encoder but the read path only consults\n * single-field keys.\n * @param opts Optional knobs — see {@link RebuildIndexOptions}.\n * Strictly additive: existing positional-arg\n * callers compile and behave unchanged when\n * omitted.\n *\n * @throws BaerlyError code=\"InvalidResponse\" — `current.json` missing.\n * @throws BaerlyError code=\"Internal\" — protocol-invariant\n * violation (snapshot hash mismatch, missing log entry inside\n * `[log_seq_start, next_seq)`).\n */\nexport const rebuildIndex = async (\n storage: Storage,\n currentJsonKey: string,\n def: IndexDefinition,\n opts: RebuildIndexOptions = {},\n): Promise<RebuildIndexResult> => {\n const read = await readCurrentJson(storage, currentJsonKey);\n if (read === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `rebuildIndex: current.json missing at ${JSON.stringify(currentJsonKey)}`,\n );\n }\n const lastSlash = currentJsonKey.lastIndexOf(\"/\");\n if (lastSlash < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `rebuildIndex: currentJsonKey ${JSON.stringify(currentJsonKey)} must contain \"/\"`,\n );\n }\n const collectionPrefix = currentJsonKey.slice(0, lastSlash);\n const collection = collectionPrefix.slice(collectionPrefix.lastIndexOf(\"/\") + 1);\n const logSeqStart = logSeqStartOf(read.json);\n const nextSeq = read.json.next_seq;\n\n // 1. Build the live doc set by folding snapshot + log tail.\n // Same shape the reader uses in `runRead` and the CLI uses in\n // `doCopy`.\n const live =\n read.json.snapshot === null\n ? new Map<string, DocumentData>()\n : await loadSnapshotAsMap(storage, read.json.snapshot, collection);\n const entries = await walkLogRange(storage, collectionPrefix, logSeqStart, nextSeq);\n foldLogEntriesOnto(live, entries, { collection });\n\n // 2. Compute the expected index-key set.\n const expected = new Set<string>();\n for (const [docId, body] of live) {\n for (const k of allIndexKeysFor(collectionPrefix, [def], body, docId)) {\n expected.add(k);\n }\n }\n\n // 3. List actual keys under the index prefix. Forward the abort\n // signal so admin tooling can cut short a rebuild over a huge\n // collection; the storage `list` contract is the only step\n // here that's unbounded in cost.\n const actual = new Set<string>();\n const listOpts: { signal?: AbortSignal } = {};\n if (opts.signal !== undefined) {\n listOpts.signal = opts.signal;\n }\n for await (const entry of storage.list(indexKeyPrefix(collectionPrefix, def.name), listOpts)) {\n actual.add(entry.key);\n }\n\n // 4. Reconcile: PUT what's missing, DELETE what's orphaned.\n // `ifNoneMatch:\"*\"` makes a same-key re-issue no-op; on the\n // rare race where the entry already exists, swallow the 412 and\n // count it as `kept` rather than `added`.\n //\n // Under `opts.dryRun`, we walk the same diff but skip every\n // mutating storage call — `added` / `removed` then report the\n // counts a real rebuild WOULD have produced, leaving storage\n // untouched. This is what `baerly admin fsck --indexes`\n // consumes to surface drift without paying the rebuild cost.\n const dryRun = opts.dryRun === true;\n let added = 0;\n let removed = 0;\n let kept = 0;\n for (const k of expected) {\n if (actual.has(k)) {\n kept += 1;\n continue;\n }\n if (dryRun) {\n added += 1;\n continue;\n }\n try {\n await storage.put(k, EMPTY_BODY, {\n ifNoneMatch: \"*\",\n contentType: APPLICATION_JSON,\n });\n added += 1;\n } catch (error) {\n // 412 = a peer wrote the entry between our `list` and our\n // PUT. The entry exists; we couldn't have written different\n // bytes (zero-byte body); count it as kept and move on.\n if (error instanceof BaerlyError && error.code === \"Conflict\") {\n kept += 1;\n } else {\n throw error;\n }\n }\n }\n for (const k of actual) {\n if (expected.has(k)) {\n continue;\n }\n if (dryRun) {\n removed += 1;\n continue;\n }\n // Storage.delete is contractually idempotent — no defensive catch.\n await storage.delete(k);\n removed += 1;\n }\n return { added, removed, kept };\n};\n","/**\n * `runScheduledMaintenance` — single-pass compose of `compact()` and\n * `runGc()` over one collection. Designed to fit a single Cloudflare\n * Cron Trigger invocation's 50-subrequest free-tier budget when\n * called with the {@link CLOUDFLARE_FREE_TIER} profile (which the\n * caller pairs with even/odd-minute alternation between compact and\n * GC ticks); unbounded on Node.\n *\n * Single-attempt: returns the combined result. The caller (cron\n * handler) is responsible for scheduling the next invocation; this\n * function does not loop or retry. `compact()` and `runGc()` are\n * already CAS-protected single-attempts — a restart safely retries\n * next tick.\n *\n * Callers that want only one phase to fire this tick should invoke\n * the underlying primitive directly (`compact()` or `runGc()` from\n * this same module's re-exports). The even/odd-minute CF cron\n * pattern uses exactly that.\n */\n\nimport { type Storage } from \"@baerly/protocol\";\nimport {\n compact,\n type CompactOptions,\n type CompactResult,\n type InternalCompactOptions,\n} from \"./compactor.ts\";\nimport { runGc, type InternalRunGcOptions, type RunGcOptions, type RunGcResult } from \"./gc.ts\";\n\nexport { type CompactOptions, type CompactResult, compact } from \"./compactor.ts\";\nexport { type RunGcOptions, type RunGcResult, runGc } from \"./gc.ts\";\nexport {\n type RebuildIndexOptions,\n type RebuildIndexResult,\n rebuildIndex,\n} from \"./rebuild-index.ts\";\n\nexport interface MaintenanceArgs {\n readonly storage: Storage;\n /** Full bucket-relative key of the CAS pointer for the target collection. */\n readonly currentJsonKey: string;\n}\n\nexport interface MaintenanceOptions {\n /** Forwarded to `compact()`. */\n readonly compact?: CompactOptions;\n /** Forwarded to `runGc()`. */\n readonly gc?: RunGcOptions;\n /** Forwarded to both primitives. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Internal-only widening of {@link MaintenanceOptions}. Surfaced via\n * the `@baerly/server/_internal/testing` subpath (NOT in the\n * published `publishConfig.exports`); production callers should use\n * {@link MaintenanceOptions}.\n *\n * @internal\n */\nexport interface InternalMaintenanceOptions extends MaintenanceOptions {\n /** @internal Internal compact options (budget caps). */\n readonly compact?: InternalCompactOptions;\n /** @internal Internal GC options (budget caps + clock seam + grace). */\n readonly gc?: InternalRunGcOptions;\n}\n\nexport interface MaintenanceResult {\n readonly compact: CompactResult;\n readonly gc: RunGcResult;\n}\n\n/**\n * Single maintenance pass for one collection. Runs `compact()` then\n * `runGc()` (in that order; the compactor's advance of\n * `log_seq_start` produces the stale-log candidates the GC then\n * marks). Callers wanting a single phase per tick invoke\n * `compact()` or `runGc()` directly instead.\n *\n * Errors propagate — the caller's cron handler is responsible for\n * logging them. The Cloudflare runtime ships uncaught Worker errors\n * to the dashboard; Node operators wrap their `node-cron` callbacks\n * themselves.\n *\n * @example\n * ```ts\n * import { runScheduledMaintenance, CLOUDFLARE_FREE_TIER } from \"@gusto/baerly-storage/maintenance\";\n *\n * // Node (unbounded — defaults fold the entire live tail):\n * const res = await runScheduledMaintenance(\n * { storage, currentJsonKey: \"app/x/tenant/t/manifests/tickets/current.json\" },\n * );\n * console.log(\"compacted:\", res.compact.entriesFolded, \"swept:\", res.gc.swept);\n *\n * // Cloudflare free tier (50-subrequest cap, single phase per tick):\n * await runScheduledMaintenance({ storage, currentJsonKey }, CLOUDFLARE_FREE_TIER);\n * ```\n */\nexport const runScheduledMaintenance = async (\n args: MaintenanceArgs,\n options: MaintenanceOptions = {},\n): Promise<MaintenanceResult> => {\n const compactRes = await compact(args, {\n ...options.compact,\n ...(options.signal !== undefined && { signal: options.signal }),\n });\n const gcRes = await runGc(args, {\n ...options.gc,\n ...(options.signal !== undefined && { signal: options.signal }),\n });\n return { compact: compactRes, gc: gcRes };\n};\n\n/**\n * Tuning profile for the 50-subrequest Cloudflare free-tier budget.\n *\n * Budget arithmetic (worst case):\n * compact: 1 GET current + 1 GET snapshot (if any) + N GETs log\n * + 1 PUT snapshot + 1 PUT current = 3 + N (N = maxEntriesPerRun).\n * runGc: 1 GET current + 1 GET pending + 3 LISTs (one page each)\n * + M GETs log (live tail for content hashes) + S DELETEs + 1 PUT\n * pending = 6 + M + S.\n *\n * With N=20, M=20, S=10 the totals are: compact ≈ 23, gc ≈ 36 — over\n * the 50 cap combined. The Cloudflare scheduled handler therefore\n * alternates phases per tick (even minute → compact, odd minute →\n * GC) by calling `compact()` / `runGc()` directly instead of\n * `runScheduledMaintenance`; the `maintenance.budget.test.ts`\n * worst-case test proves each phase in isolation sits under 50 ops\n * with these bounds.\n */\nconst cfFreeTier: InternalMaintenanceOptions = {\n compact: { maxEntriesPerRun: 20, minEntriesToCompact: 50 },\n gc: { maxMarksPerRun: 20, maxSweepsPerRun: 10 },\n};\nexport const CLOUDFLARE_FREE_TIER: MaintenanceOptions = cfFreeTier;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFA,MAAa,gBAAgB,OAC3B,SACA,KACA,SACkC;CAClC,MAAM,MAAM,MAAM,QAAQ,IAAI,KAAK,IAAI;CACvC,IAAI,QAAQ,MACV,OAAO;CAET,IAAI;CACJ,IAAI;EACF,SAAS,gBAAgB,IAAI,IAAI;CACnC,SAAS,OAAO;EACd,MAAM,IAAI,YACR,mBACA,sBAAsB,IAAI,2BAC1B,KACF;CACF;CACA,OAAO;EAAE,MAAM,gBAAgB,QAAQ,GAAG;EAAG,MAAM,IAAI;CAAK;AAC9D;;;;;;;;;;AAWA,MAAa,kBAAkB,OAC7B,SACA,KACA,SACA,SAC2B;CAC3B,gBAAgB,SAAS,GAAG;CAC5B,MAAM,OAAO,gBAAgB,OAAO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O;EAAE,SAAS,MARO,QAAQ,MAAM;GACrC,GAAG,QAAQ;GACX,GAAI,QAAQ,WAAW,KAAA,KAAa,EAAE,QAAQ,QAAQ,OAAO;EAC/D,CAAC;EAK6B,IAAI,MAJd,MAAM,MAAM;GAC9B,GAAG,QAAQ;GACX,GAAI,QAAQ,WAAW,KAAA,KAAa,EAAE,QAAQ,QAAQ,OAAO;EAC/D,CAAC;CACuC;AAC1C;AAwBA,MAAa,uBAA2C;CAHtD,SAAS;EAAE,kBAAkB;EAAI,qBAAqB;CAAG;CACzD,IAAI;EAAE,gBAAgB;EAAI,iBAAiB;CAAG;AAEQ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"query-DcSbFLJt.js","names":["#storage","#currentJsonKey","#maxRetries","#initialBackoffMs","#random","#indexes","#verifyLogIntegrityOnCommit","#singleAttemptCommit","#backoff","#verifyFenceUnchanged","#emitWriteMetrics","#provisionCurrentJson","#walkLog","#observe429","#readPreImage"],"sources":["../packages/protocol/src/json.ts","../packages/protocol/src/query/merge.ts","../packages/protocol/src/types.ts","../packages/protocol/src/time.ts","../packages/protocol/src/log.ts","../packages/server/src/log-conflict-adoption.ts","../packages/server/src/writer.ts","../packages/server/src/query-planner-implies.ts","../packages/server/src/query-planner.ts","../packages/server/src/schema.ts","../packages/server/src/query.ts"],"sourcesContent":["import { FORBIDDEN_MERGE_KEYS } from \"./constants.ts\";\n\n/**\n * The shape constraint for documents stored in a {@link Collection}.\n *\n * Plain JSON object: string-keyed; values are strings, numbers,\n * booleans, nested {@link DocumentData}, or arrays of\n * {@link DocumentValue}.\n *\n * The document **body** itself must be an object (not an array) —\n * Baerly's writer is built on JSON Merge Patch (RFC 7396), which\n * is only defined over object documents. Array *values* at any\n * nested level are fine; per RFC 7396, an array in a patch\n * replaces the target array wholesale (Baerly has no array-merge\n * semantics).\n */\nexport type DocumentData = { [x: string]: DocumentValue };\n\n/**\n * A single field value inside a {@link DocumentData}. The recursive\n * type that backs {@link DocumentData}, also used by predicate and\n * order-spec types in `@baerly/protocol/query`.\n *\n * Arrays are valid values; they are replaced (not merged) on patch.\n */\nexport type DocumentValue = string | number | boolean | DocumentData | Array<DocumentValue>;\n\nexport type JSONObject = { [x: string]: JSONValue };\nexport type JSONValue = string | number | boolean | null | JSONObject | Array<JSONValue>;\n\nconst isPlainObject = (value: DocumentValue | undefined): value is DocumentData =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * JSON Merge Patch (RFC 7396).\n *\n * Update `target` with a merge patch. Plain-object values recurse\n * key-by-key; primitives, arrays, and type-mismatched values replace\n * the target wholesale. A `null` value in `patch` deletes the key.\n *\n * RFC 7396 explicitly treats arrays as opaque values: an array in a\n * patch replaces the target array — there is no element-wise merge.\n */\nexport function merge<T extends DocumentValue>(\n target: T | undefined,\n patch: Partial<T> | null | undefined,\n): T | undefined {\n if (patch === undefined) {\n return target;\n }\n if (patch === null) {\n return undefined;\n }\n\n // Patch is primitive or an array → replace target wholesale.\n if (!isPlainObject(patch as DocumentValue)) {\n return patch as T;\n }\n // Patch is a plain object but target isn't → replace.\n if (!isPlainObject(target)) {\n return patch as T;\n }\n\n const combined = { ...(target as DocumentData) } as T;\n for (const key of Object.keys(patch) as Array<Extract<keyof T, string>>) {\n // Object.keys returns own enumerable string keys — but `__proto__`\n // is an own property when patches arrive via JSON.parse (HTTP PATCH\n // bodies hit this path through query.ts:runUpdate). Guard remains\n // load-bearing. See predicate.test.ts for the same vector.\n if (FORBIDDEN_MERGE_KEYS.has(key)) {\n continue;\n }\n if (patch[key] === null) {\n delete combined[key];\n } else {\n combined[key] = merge(target[key] as DocumentValue, patch[key] as DocumentValue) as T[Extract<\n keyof T,\n string\n >];\n }\n }\n return combined as T;\n}\n","/**\n * AND-merge two validated wire predicates. Powers chained\n * `Query<T>.where(...).where(...)`: each new clause set AND's with\n * the existing wire by clause-list concatenation; the per-field\n * satisfiability check runs across the combined list.\n *\n * Companion modules: `./validate.ts`, `./matches.ts`, `./wire.ts`.\n */\n\nimport { assertWireSatisfiable } from \"./satisfiable.ts\";\nimport type { PredicateWire } from \"./wire.ts\";\n\n/**\n * AND-merge two validated wire predicates. The result accepts a\n * document iff both `a` and `b` would accept it.\n *\n * Wire-level: clause lists concatenate. The per-field satisfiability\n * check runs across the combined list, surfacing\n * `BaerlyError{code:\"UnsatisfiablePredicate\"}` on empty residual\n * intervals / empty `in()` intersections / `eq` outside the merged\n * interval, and `BaerlyError{code:\"InvalidConfig\"}` on conflicting\n * `eq` clauses for the same field (mirrors the pre-redesign\n * conflict-on-shared-keys semantics).\n *\n * @example\n * ```ts\n * mergePredicateWires(\n * { clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] },\n * { clauses: [{ op: \"eq\", field: \"priority\", value: \"p1\" }] },\n * );\n * // → { clauses: [\n * // { op: \"eq\", field: \"status\", value: \"open\" },\n * // { op: \"eq\", field: \"priority\", value: \"p1\" },\n * // ] }\n *\n * mergePredicateWires(\n * { clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] },\n * { clauses: [{ op: \"eq\", field: \"status\", value: \"closed\" }] },\n * );\n * // throws BaerlyError{InvalidConfig}: conflicting equality clauses on \"status\"\n *\n * mergePredicateWires(\n * { clauses: [{ op: \"gt\", field: \"x\", value: 10 }] },\n * { clauses: [{ op: \"lt\", field: \"x\", value: 5 }] },\n * );\n * // throws BaerlyError{UnsatisfiablePredicate}: empty interval\n * ```\n */\nexport const mergePredicateWires = (a: PredicateWire, b: PredicateWire): PredicateWire => {\n const merged: PredicateWire = { clauses: [...a.clauses, ...b.clauses] };\n assertWireSatisfiable(merged);\n return merged;\n};\n","declare const brand: unique symbol;\ntype Brand<B> = { [brand]: B };\n\n/**\n * Nominal-typing helper. `Branded<string, \"UUID\">` is a `string` at\n * runtime but the type system rejects mixing it with a plain `string` or\n * a string branded as something else. Used to prevent confusion bugs at\n * protocol boundaries (UUIDs vs. content versions are both strings, but\n * using the wrong one corrupts the manifest log).\n *\n * Construct branded values via the helpers in this file (e.g. {@link uuid})\n * or with a tagged cast at a single, deliberate boundary — never `as string`\n * to widen one back. See `docs/contributing/conventions/src.md`.\n */\nexport type Branded<T, B> = T & Brand<B>;\n\n/**\n * A v4 UUID minted by this client. Used as session IDs and content\n * identifiers in non-versioned mode.\n */\nexport type UUID = Branded<string, \"UUID\">;\n\n/**\n * SHA-256 content digest, lowercase hex truncated to\n * `VERSION_HEX_LENGTH` (32 chars). Minted by\n * `versionFromContent` in `useVersioning=false` mode and used as\n * the `<key>@<version>` suffix in content keys.\n *\n * The synthetic `local-${op}` placeholder used for in-flight\n * optimistic updates also wears this brand — it never round-trips\n * to S3, only flows through the local manifest poll loop.\n */\nexport type ContentVersionId = Branded<string, \"ContentVersionId\">;\n\n/**\n * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle\n * `<UUID>crypto.randomUUID()` throughout the codebase.\n */\nexport const uuid = (): UUID => crypto.randomUUID() as UUID;\n\n/**\n * Mint a UUIDv7 — 48-bit Unix-millis prefix + 74 bits of randomness,\n * formatted as a standard 8-4-4-4-12 UUID string per RFC 9562 §5.7.\n * Lex-sortable by mint time, so it pairs well with object-storage\n * list semantics. Returns a branded {@link UUID}.\n *\n * Uses `crypto.getRandomValues` which is universally available\n * (Node 19+, Workerd, Bun, browsers).\n *\n * @example\n * ```ts\n * const id = uuidv7();\n * // e.g. \"01956cad-4cc8-7abc-9def-0123456789ab\"\n * ```\n */\nexport const uuidv7 = (): UUID => {\n const millis = Date.now();\n const rand = new Uint8Array(10);\n crypto.getRandomValues(rand);\n // Version nibble: top 4 bits of rand[0] = 0b0111 (v7). The byte\n // sits at the start of the \"version-and-rand-a\" group below.\n rand[0] = (rand[0]! & 0x0f) | 0x70;\n // Variant bits: top 2 bits of rand[2] = 0b10 (RFC 4122 variant).\n // This byte starts the \"variant-and-rand-b\" group below.\n rand[2] = (rand[2]! & 0x3f) | 0x80;\n const millisHex = millis.toString(16).padStart(12, \"0\");\n const b = Array.from(rand, (n) => n.toString(16).padStart(2, \"0\")).join(\"\");\n return `${millisHex.slice(0, 8)}-${millisHex.slice(8, 12)}-${b.slice(0, 4)}-${b.slice(4, 8)}-${b.slice(8, 20)}` as UUID;\n};\n\n/**\n * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).\n * `COUNT_BIT_WIDTH = 10` (matches `packages/protocol/src/log.ts:145`)\n * gives a 2-char descending base-32 string with a domain of 0..1023.\n *\n * Used together with {@link timestamp} (the descending base-32\n * encoding of millis-since-epoch). See {@link uint2strDesc} for the\n * lex-reversal property both rely on.\n */\nexport const countKey = (number: number): string => uint2strDesc(number, 10);\n\nexport const uint2str = (num: number, bits: number) => {\n const maxBase32Length = Math.ceil(bits / 5); // Change from 4 to 5 because log2(32) is roughly 5.\n const base32Representation = num.toString(32);\n return base32Representation.padStart(maxBase32Length, \"0\");\n};\n\nexport const str2uint = (str: string) => {\n return parseInt(str, 32); // Parse the string as base 32.\n};\n\n/**\n * Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.\n * Pads to `Math.ceil(bits/5)` chars so all values in the domain compare\n * lex against each other.\n *\n * **Order-reversal property:** for any pair of integers `a < b` (with\n * `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`\n * lexicographically. Composed into an LSN of shape\n * `<base32-time>_<session>_<seq>` (where both `<base32-time>` and\n * `<seq>` use this encoder), a forward `Storage.list(prefix)`\n * returns log entries in reverse-causal order — newer entries first.\n *\n * This is the structural property the read path leans on:\n * `ListObjectsV2` is forward-only on S3, but the descending encoding\n * makes \"fetch the K newest entries\" a single bounded LIST with\n * `maxKeys=K` instead of a full-population LIST + in-memory reverse.\n *\n * Behaviourally verified across randomized populations in\n * `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified\n * bytes-listed reduction is in\n * `docs/spec/attachments/lsn-reverse-walk-baseline.json`\n * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:\n * `docs/spec/sync-protocol.md` §\"Subtleties of the manifest key\".\n */\nexport const uint2strDesc = (num: number, bits: number): string => {\n const maxValue = Math.pow(2, bits) - 1;\n return uint2str(maxValue - num, bits);\n};\n\nexport const str2uintDesc = (str: string, bits: number): number => {\n const maxValue = Math.pow(2, bits) - 1;\n const num = parseInt(str, 32); // Convert base32 string to number\n return maxValue - num;\n};\n","import { TIMESTAMP_BIT_WIDTH } from \"./constants.ts\";\nimport { uint2strDesc } from \"./types.ts\";\n\nexport const timestamp = (epoch: number = 0) => uint2strDesc(epoch, TIMESTAMP_BIT_WIDTH);\n\n/**\n * Delay for `ms` milliseconds, with optional cancellation. If\n * `signal` aborts before the delay elapses, the returned promise\n * rejects with `signal.reason`. Used by `S3HttpStorage`'s retry\n * loop so shutdown can interrupt an in-flight backoff instead of\n * waiting for it to complete.\n */\nexport const delay = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(signal.reason);\n },\n { once: true },\n );\n });\n","import { BaerlyError } from \"./errors.ts\";\nimport type { DocumentData, JSONValue } from \"./json.ts\";\nimport { str2uintDesc } from \"./types.ts\";\n\n/**\n * Postgres-logical-replication-shaped log entry. One per mutation.\n *\n * **Shape is fixed at this point and never changes after.** This is the\n * migration contract behind `baerly export --target=postgres` — the\n * keys are public, consumers ack on `lsn`, and any rename / removal is\n * a major-version migration.\n *\n * Field requirement matrix:\n * - Always: `lsn`, `commit_ts`, `op`, `collection`, `schema_version`,\n * `session`, `seq`.\n * - For I/U/D: `doc_id`.\n * - For I/U: `new`, `patch` (equal in today's per-doc-replace model).\n * - Optional: `old` (when `replica_identity === \"FULL\"`), `key_old`\n * (U/D when `replica_identity !== \"PATCH_ONLY\"`), `origin`.\n *\n * @see docs/spec/log-entry-shape.md\n */\nexport interface LogEntry {\n /**\n * Opaque, monotonic, lex-asc cursor. Shape is\n * `<base32-time>_<session>_<seq>` — minted inside\n * `Writer.commit` (see\n * `packages/server/src/writer.ts`) from `timestamp()` +\n * the per-commit `session` + `countKey(seq)`. Consumers ack and\n * resume from this string.\n *\n * When you have a `LogEntry` in hand, prefer the structured\n * `session` / `seq` fields below over parsing this string. The\n * one place that *does* need to crack it open is the\n * `/v1/since` boundary, where a client resumes from an opaque\n * `next_cursor` and no `LogEntry` is in scope — that path uses\n * `lsnParts` (the kernel-blessed parser) rather than ad-hoc\n * `split(\"_\")`.\n */\n lsn: string;\n\n /** ISO-8601 ms timestamp. Redundant with `lsn` but cheap. */\n commit_ts: string;\n\n /**\n * Insert / Update / Delete / Truncate / Message. `M` is the\n * `pg_logical_emit_message` analogue — useful for app-defined\n * markers like deploy boundaries, snapshots, or out-of-band\n * schema announcements consumed via `schema_version`. `T`\n * truncates a whole collection. Today the emitter only produces\n * `I`/`U`/`D`; `T` and `M` are shape-only for forward\n * compatibility.\n */\n op: \"I\" | \"U\" | \"D\" | \"T\" | \"M\";\n\n /**\n * Collection name — the pgoutput RELATION analogue. Today derived\n * from the path segment immediately under the manifest prefix\n * (the part of `ref.key` before the first `/`); falls back to\n * `ref.bucket` for flat keys with no separator. The table API\n * makes collections first-class.\n */\n collection: string;\n\n /** Required for I/U/D; omitted for T (TRUNCATE) and M (MESSAGE). */\n doc_id?: string;\n\n /**\n * Monotonic per collection. Schema for the doc body is announced\n * out-of-band via `M` (MESSAGE) entries; this field lets the\n * consumer match a log entry to the schema in effect at write\n * time. Forward-only — renaming or removing the field is a\n * major-version migration; bumping the value is non-breaking.\n * Inlining the schema in every entry was rejected as bloat for a\n * field that changes rarely. Always `0` today; reserved for a\n * future schema-versioning scheme.\n */\n schema_version: number;\n\n /** Required for I, U. The post-image. */\n new?: DocumentData;\n\n /**\n * JSON-merge-patch (RFC 7386) form. Required for U; for I equals\n * `new`. In today's per-doc-replace model `new` and `patch` are\n * always equal; that changes when partial-doc merge writes land.\n */\n patch?: DocumentData;\n\n /**\n * The pre-image. Present iff the collection's `replica_identity`\n * is `FULL`. ~2× log size on update-heavy collections; off by\n * default.\n */\n old?: DocumentData;\n\n /**\n * Pre-image of the primary key. U/D always carry this when\n * `replica_identity` is not `PATCH_ONLY`. (For Baerly today,\n * `_id` is the only PK.)\n */\n key_old?: { readonly [pk: string]: JSONValue };\n\n /** ORIGIN analogue — the writer session id. */\n origin?: string;\n\n /**\n * Causal metadata (Baerly-only; no pgoutput analogue). The\n * session id that built the `lsn`. Surfaces here so consumers\n * can dedupe / order without parsing the cursor.\n */\n session: string;\n\n /** Per-session sequence number embedded in the `lsn`. */\n seq: number;\n}\n\n/**\n * Per-collection setting controlling how much pre-image data each\n * `U` / `D` entry carries.\n *\n * - `PATCH_ONLY` (default today, applied unconditionally): `U`\n * carries `{ patch, new }`; no `old`, no `key_old`.\n * Bandwidth-cheap. SQL consumers rebuilding before-images need\n * to maintain a shadow table.\n * - `FULL`: `U` additionally carries `old` and `key_old`. ~2× log\n * size on update-heavy collections; buys true 1:1 logical\n * replication and \"previous value\" answerable from the log\n * alone.\n *\n * Per-collection opt-in is not yet wired; every collection is\n * currently `PATCH_ONLY`.\n */\nexport type ReplicaIdentity = \"PATCH_ONLY\" | \"FULL\";\n\n/**\n * S3 path segment for log entries (under the manifest prefix). The\n * full key shape is `<manifestPrefix>/log/<seq>.json` — composed\n * inline by callers (`writer`, `gc`, `rebuild-index`,\n * `http/since`) since the `<seq>` integer is the load-bearing\n * identifier and a one-arg helper would just hide the join.\n */\nexport const LOG_KEY_PREFIX = \"log\";\n\nconst COUNT_BIT_WIDTH = 10;\n\n/**\n * Extract the `session` and `seq` embedded in an `lsn` of shape\n * `<base32-time>_<session>_<seq>`. The seq portion is decoded as a\n * descending base-32 integer (matches `countKey` in `./types`).\n *\n * Use this at the `/v1/since` cursor-decoding boundary, where a\n * client resumes from an opaque `SinceResponse.next_cursor` and no\n * `LogEntry` is in scope. When iterating `LogEntry` records, read\n * `entry.session` / `entry.seq` directly instead.\n *\n * Throws on malformed input; callers should pass only lsns minted\n * by `Writer.commit` (see\n * `packages/server/src/writer.ts`).\n */\nexport const lsnParts = (lsn: string): { session: string; seq: number } => {\n const parts = lsn.split(\"_\");\n if (parts.length !== 3) {\n throw new BaerlyError(\"InvalidResponse\", `invalid lsn shape: ${lsn}`);\n }\n return {\n session: parts[1]!,\n seq: str2uintDesc(parts[2]!, COUNT_BIT_WIDTH),\n };\n};\n","/**\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 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 { 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 /**\n * The mutation op. Maps directly to {@link LogEntry.op}. `T` and `M`\n * (TRUNCATE / MESSAGE) are out of scope here.\n */\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.new} *and*\n * {@link LogEntry.patch} (today's per-doc-replace model). Must be\n * `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).\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 = `${timestamp(Date.now())}_${session}_${countKey(seq)}`;\n const entry: LogEntry = {\n lsn,\n commit_ts: new Date().toISOString(),\n op: input.op,\n collection: input.collection,\n doc_id: input.docId,\n schema_version: 0,\n session,\n seq,\n ...(input.op !== \"D\" && input.body !== undefined\n ? { new: input.body, patch: input.body }\n : {}),\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 const next: CurrentJson = { ...current, next_seq: current.next_seq + inputs.length };\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 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 };\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.new !== undefined) {\n return entry.new;\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 * Filtered-index implication checker — decides whether every\n * document accepted by a query predicate is also accepted by a\n * filtered index's predicate. The query planner uses the result to\n * rank candidate indexes; see {@link \"./query-planner.ts\".planQuery}.\n *\n * Pure-function module: no I/O, no `Db` / `Storage` imports. Lives\n * in `@baerly/server` (not in `@baerly/protocol`) because the\n * planner is the only caller.\n *\n * Operates on the wire form: both inputs are {@link PredicateWire}s\n * with clauses already grouped by `(op, field, value)`. The\n * normaliser at `@baerly/protocol`'s `./query/normalize.ts` has\n * already flattened nested literal sub-predicates into dotted-path\n * `eq` clauses, so there is no recursion on nested objects here.\n */\n\nimport {\n deepEqualDocumentValue,\n type DocumentValue,\n type PredicateClause,\n type PredicateWire,\n} from \"@baerly/protocol\";\n\n/**\n * One side of a range bound extracted from a clause group. The\n * `inclusive` flag distinguishes `gte` / `lte` (inclusive) from\n * `gt` / `lt` (exclusive). Private to {@link predicateImplies}.\n */\ninterface RangeInfo {\n readonly value: DocumentValue;\n readonly inclusive: boolean;\n}\n\n/**\n * Normalised view of one field's clause group. A field may carry an\n * `eq` clause, range bounds (`lo` / `hi`), and/or an `in` clause.\n * Multiple clauses on one field AND together; the validator has\n * already proved the group is internally consistent. An \"unknown\n * shape\" sentinel surfaces when the planner can't safely reason\n * about the group (e.g. two `in` clauses on one field — the\n * intersection requires set arithmetic we don't do at plan time).\n * Private to {@link predicateImplies}.\n */\ninterface OperatorBundle {\n readonly eq?: DocumentValue;\n readonly lo?: RangeInfo;\n readonly hi?: RangeInfo;\n readonly in?: ReadonlyArray<DocumentValue>;\n}\n\ntype DecodeResult = OperatorBundle | \"unknown-shape\";\n\n/**\n * Group a wire's clauses by `field` so the per-field implication\n * check can reason over one bundle at a time. Inlined small helper\n * (not exported) so the planner module doesn't need to expose its\n * grouping helper as a cross-module contract.\n */\nconst groupByField = (wire: PredicateWire): Map<string, ReadonlyArray<PredicateClause>> => {\n const groups = new Map<string, PredicateClause[]>();\n for (const clause of wire.clauses) {\n const bucket = groups.get(clause.field);\n if (bucket === undefined) {\n groups.set(clause.field, [clause]);\n } else {\n bucket.push(clause);\n }\n }\n return groups;\n};\n\n/**\n * Collapse a per-field clause list into an {@link OperatorBundle}.\n * Returns `\"unknown-shape\"` when the group has more than one `in`\n * clause (set-intersection at plan time is out of scope) or\n * unrecognised ops slipping through (defensive — the validator\n * already locked the op vocabulary). Multiple `eq` clauses on one\n * field: the validator proves they all agree, so we pick the first.\n * Multiple range clauses on one field: take the strictest bound\n * (tightest `lo` = numerically largest; tightest `hi` = numerically\n * smallest).\n */\nconst decodeGroup = (clauses: ReadonlyArray<PredicateClause>): DecodeResult => {\n const bundle: {\n eq?: DocumentValue;\n lo?: RangeInfo;\n hi?: RangeInfo;\n in?: ReadonlyArray<DocumentValue>;\n } = {};\n for (const clause of clauses) {\n const v = clause.value;\n if (clause.op === \"eq\") {\n // Validator: every eq on a field carries the same value.\n bundle.eq = v as DocumentValue;\n } else if (clause.op === \"gte\") {\n const next: RangeInfo = { value: v as DocumentValue, inclusive: true };\n bundle.lo = tightestLo(bundle.lo, next);\n } else if (clause.op === \"gt\") {\n const next: RangeInfo = { value: v as DocumentValue, inclusive: false };\n bundle.lo = tightestLo(bundle.lo, next);\n } else if (clause.op === \"lte\") {\n const next: RangeInfo = { value: v as DocumentValue, inclusive: true };\n bundle.hi = tightestHi(bundle.hi, next);\n } else if (clause.op === \"lt\") {\n const next: RangeInfo = { value: v as DocumentValue, inclusive: false };\n bundle.hi = tightestHi(bundle.hi, next);\n } else if (clause.op === \"in\") {\n if (bundle.in !== undefined) {\n // Multiple `in` clauses on one field: the validator already\n // proved the intersection is non-empty, but reasoning about\n // the intersection's containment at plan time is out of\n // scope — bail out to \"unknown-shape\" so the caller refuses\n // implication conservatively.\n return \"unknown-shape\";\n }\n if (!Array.isArray(v)) {\n return \"unknown-shape\";\n }\n bundle.in = v as ReadonlyArray<DocumentValue>;\n } else {\n return \"unknown-shape\";\n }\n }\n return bundle;\n};\n\nconst tightestLo = (existing: RangeInfo | undefined, next: RangeInfo): RangeInfo => {\n if (existing === undefined) {\n return next;\n }\n if (typeof existing.value !== typeof next.value) {\n // Mixed types — bail to existing; the validator already proves\n // the group is satisfiable, so this case is a defensive no-op.\n return existing;\n }\n if (next.value > existing.value) {\n return next;\n }\n if (next.value < existing.value) {\n return existing;\n }\n // Equal value — strictest inclusivity wins (exclusive > inclusive\n // for lo bounds).\n if (!next.inclusive && existing.inclusive) {\n return next;\n }\n return existing;\n};\n\nconst tightestHi = (existing: RangeInfo | undefined, next: RangeInfo): RangeInfo => {\n if (existing === undefined) {\n return next;\n }\n if (typeof existing.value !== typeof next.value) {\n return existing;\n }\n if (next.value < existing.value) {\n return next;\n }\n if (next.value > existing.value) {\n return existing;\n }\n if (!next.inclusive && existing.inclusive) {\n return next;\n }\n return existing;\n};\n\n/**\n * Does the query's lower bound `loQ` (`undefined` if none) prove that\n * every matching doc satisfies the filter's lower bound `loF`?\n *\n * `loF.inclusive` true → need doc ≥ loF.value; `loF.inclusive` false →\n * need doc > loF.value. A stricter `loQ` (numerically larger or with\n * tighter inclusivity) always implies a looser `loF`.\n */\nconst lowerBoundImplies = (loF: RangeInfo, loQ: RangeInfo | undefined): boolean => {\n if (loQ === undefined) {\n return false;\n }\n // Mixed types: comparison is `false` either way; refuse implication.\n if (typeof loF.value !== typeof loQ.value) {\n return false;\n }\n if (loQ.value > loF.value) {\n return true;\n }\n if (loQ.value < loF.value) {\n return false;\n }\n // Equal values: implies iff loQ.inclusive ⇒ loF.inclusive, OR loQ is\n // strictly stricter than loF (loQ exclusive, loF inclusive). Concretely:\n // loF inclusive + loQ inclusive → doc ≥ Q == F ≥ F → ok\n // loF inclusive + loQ exclusive → doc > Q == F > F-ε → doc > F ≥ F → ok\n // loF exclusive + loQ inclusive → doc ≥ Q == F → doc could be == F → NOT > F → fail\n // loF exclusive + loQ exclusive → doc > Q == F → ok\n if (loF.inclusive) {\n return true;\n } // inclusive filter is the loosest case\n return !loQ.inclusive; // strict filter needs strict query at equal bound\n};\n\n/** Mirror of lowerBoundImplies for upper bounds. */\nconst upperBoundImplies = (hiF: RangeInfo, hiQ: RangeInfo | undefined): boolean => {\n if (hiQ === undefined) {\n return false;\n }\n if (typeof hiF.value !== typeof hiQ.value) {\n return false;\n }\n if (hiQ.value < hiF.value) {\n return true;\n }\n if (hiQ.value > hiF.value) {\n return false;\n }\n if (hiF.inclusive) {\n return true;\n }\n return !hiQ.inclusive;\n};\n\n// Derive the tightest lower-bound the query enforces, preferring (in\n// order): an `eq` clamp, the smallest `in` value, an explicit `lo`.\n// Returns `undefined` when the query gives the planner nothing to lean\n// on — the implication check then fails fast.\nconst loFromQuery = (q: OperatorBundle): RangeInfo | undefined => {\n if (q.eq !== undefined) {\n return { value: q.eq, inclusive: true };\n }\n if (q.in !== undefined && q.in.length > 0) {\n return {\n value: q.in.reduce((acc, v) => (v < acc ? v : acc), q.in[0]!),\n inclusive: true,\n };\n }\n return q.lo;\n};\n\n// Mirror of {@link loFromQuery} for upper bounds.\nconst hiFromQuery = (q: OperatorBundle): RangeInfo | undefined => {\n if (q.eq !== undefined) {\n return { value: q.eq, inclusive: true };\n }\n if (q.in !== undefined && q.in.length > 0) {\n return {\n value: q.in.reduce((acc, v) => (v > acc ? v : acc), q.in[0]!),\n inclusive: true,\n };\n }\n return q.hi;\n};\n\n/**\n * Filtered-index implication checker — decides whether every document\n * accepted by `queryWire` is also accepted by `indexFilterWire`. When\n * `true`, a walk over an index declared with `predicate: indexFilterWire`\n * is **complete** for `queryWire`: no matching doc is missing\n * from the smaller key set, so the planner can prefer it.\n *\n * Implication on `eq`, `gt` / `gte`, `lt` / `lte`, and `in` is\n * sound and complete in pure operator form; combined shapes (e.g.\n * range-on-filter and `in`-on-query) follow the algebra in the body\n * JSDoc.\n *\n * Algorithm — group both wires by `field`, then for every field\n * present in `indexFilterWire`:\n *\n * 1. Decode the filter's clause group into an {@link OperatorBundle}.\n * \"unknown-shape\" → refuse implication conservatively.\n * 2. The query MUST have at least one clause on that field —\n * otherwise the query says nothing about that field and cannot\n * possibly imply the filter's constraint.\n * 3. Decode the query's clause group on the same field.\n * 4. For each non-empty slot of the filter bundle, the query bundle\n * must establish the constraint:\n * - `eq` → query establishes equality (via its own `eq`).\n * - `in` → query is contained in the set (via `eq` ∈ set or\n * `in` ⊆ set).\n * - `lo` / `hi` → query establishes the bound via `eq`, `in`\n * (then min/max of the set), or its own `lo`/`hi` with the\n * inclusivity rules in {@link lowerBoundImplies} /\n * {@link upperBoundImplies}.\n * Mixed types (e.g. number filter vs string query) refuse\n * implication conservatively.\n *\n * Returns `true` iff every clause was satisfied. An empty\n * `indexFilterWire` is vacuously implied by any `queryWire`.\n *\n * Soundness contract — when this function returns `true`,\n * `matchesWire(queryWire, doc) ⇒ matchesWire(indexFilterWire, doc)` for\n * any document `doc`. Tests pin this property; see\n * `./query-planner-implies.test.ts`.\n */\nexport const predicateImplies = (\n indexFilterWire: PredicateWire,\n queryWire: PredicateWire,\n): boolean => {\n const filterGroups = groupByField(indexFilterWire);\n const queryGroups = groupByField(queryWire);\n\n for (const [field, filterClauses] of filterGroups) {\n const filterBundle = decodeGroup(filterClauses);\n if (filterBundle === \"unknown-shape\") {\n return false;\n }\n\n const queryClauses = queryGroups.get(field);\n if (queryClauses === undefined) {\n return false;\n }\n const queryBundle = decodeGroup(queryClauses);\n if (queryBundle === \"unknown-shape\") {\n return false;\n }\n\n if (filterBundle.eq !== undefined) {\n // Filter pins an exact value. Query must establish equality.\n if (queryBundle.eq === undefined) {\n return false;\n }\n if (!deepEqualDocumentValue(queryBundle.eq, filterBundle.eq)) {\n return false;\n }\n continue;\n }\n if (filterBundle.in !== undefined) {\n const set = filterBundle.in;\n const contains = (v: DocumentValue): boolean => set.some((m) => deepEqualDocumentValue(m, v));\n if (queryBundle.eq !== undefined) {\n if (!contains(queryBundle.eq)) {\n return false;\n }\n } else if (queryBundle.in !== undefined) {\n for (const v of queryBundle.in) {\n if (!contains(v)) {\n return false;\n }\n }\n } else {\n return false; // range query against `in` filter — not a subset\n }\n // `in` filter clause forbids any extra range constraint on the\n // filter side (enforced upstream by `validateWire`); nothing\n // else to check.\n continue;\n }\n // Range filter (lo / hi). Both bounds (if set) must be implied.\n if (filterBundle.lo !== undefined) {\n if (!lowerBoundImplies(filterBundle.lo, loFromQuery(queryBundle))) {\n return false;\n }\n }\n if (filterBundle.hi !== undefined) {\n if (!upperBoundImplies(filterBundle.hi, hiFromQuery(queryBundle))) {\n return false;\n }\n }\n }\n return true;\n};\n","/**\n * Pure-function query planner. Picks a walk plan (or a full-scan\n * decision) from a predicate + the collection's declared indexes.\n *\n * Zero I/O, zero storage-encoding awareness, zero `Db`/`Storage`\n * imports. The planner sits between `runRead`'s predicate intake and\n * the executor that walks index entries; the executor handles every\n * storage-encoding boundary (`encodeIndexValue`, `Storage.list`,\n * etc.).\n *\n * T2 shipped equality-only walks — single-field, composite full,\n * and composite partial-prefix. T3 fills the `rangeOn` / `inOn`\n * slots reserved on {@link IndexWalkPlan} so range / `$in` clauses\n * on the LAST indexed field beyond the equality prefix get pushed\n * into the walk too. T4 adds the filtered-index cost bias.\n *\n * Numeric range / `$in` are routed normally; the encoder at\n * `./indexes.ts:encodeIndexValue` is value-order-preserving for\n * numbers.\n */\n\nimport { type DocumentValue, type PredicateWire } from \"@baerly/protocol\";\nimport type { IndexDefinition } from \"./indexes.ts\";\nimport { predicateImplies } from \"./query-planner-implies.ts\";\n\n/**\n * Tagged union returned by {@link planQuery}. The read path\n * routes on `kind` — `index-walk` invokes the executor, `full-scan`\n * falls through to the snapshot + log fold.\n */\nexport type QueryPlan = IndexWalkPlan | FullScanPlan;\n\n/**\n * Plan to satisfy the predicate by walking one declared index. The\n * executor encodes `equalityKeys` via `encodeIndexValue` at the I/O\n * boundary and lists `<collectionPrefix>/index/<indexName>/<v0>/.../<vN>/`.\n *\n * `rangeOn` and `inOn` are reserved for T3 — both `undefined` under\n * T2's equality-only routing. The executor re-applies the FULL\n * original wire via `matchesWire(...)` after fetching rows; that\n * single check is both the stale-index defence and the residue\n * consumer, so the planner does NOT emit a separate `postFilter`.\n */\nexport interface IndexWalkPlan {\n readonly kind: \"index-walk\";\n /** Name of the chosen IndexDefinition. */\n readonly indexName: string;\n /**\n * Left-anchored raw equality values, one per indexed field consumed.\n * Length ≥ 1. The executor encodes these via `encodeIndexValue` at\n * the I/O boundary; the planner stays storage-encoding-free.\n */\n readonly equalityKeys: ReadonlyArray<DocumentValue>;\n /**\n * T3 fills this slot. Range bound on the LAST indexed field beyond\n * the equality prefix. Mutually exclusive with `inOn`.\n */\n readonly rangeOn?: {\n readonly field: string;\n readonly lo?: DocumentValue;\n readonly hi?: DocumentValue;\n readonly loInclusive: boolean;\n readonly hiInclusive: boolean;\n };\n /**\n * T3 fills this slot. $in multi-walk on the LAST indexed field\n * beyond the equality prefix. Mutually exclusive with `rangeOn`.\n */\n readonly inOn?: {\n readonly field: string;\n readonly values: ReadonlyArray<DocumentValue>;\n };\n}\n\n/**\n * Plan to fall through to the snapshot + log fold. The `reason`\n * field is diagnostic only — it is NOT part of the public API and\n * is consumed by the planner's tests / future observability.\n */\nexport interface FullScanPlan {\n readonly kind: \"full-scan\";\n /** Diagnostic — not part of the public API. */\n readonly reason:\n | \"no-predicate\"\n | \"no-indexes-declared\"\n | \"no-matching-index\"\n | \"predicate-uses-operators-only\";\n}\n\n/**\n * `$in` fan-out threshold. `$in: [...]` with `values.length`\n * at or below this number emits an `inOn` walk plan; over this\n * number the planner falls back to `FullScanPlan` because N\n * parallel-fan-out LIST round-trips cost more than one snapshot+log\n * fold on every backend we benchmark (see `bench/load-harness/`).\n *\n * Hard-coded at the value that survives Cloudflare's 50-subrequest\n * budget. If the default proves wrong on cheap-LIST backends\n * (Minio / S3 / GCS), file a bug — the answer is \"good, let's tune\n * the default,\" not \"make it configurable.\"\n */\nexport const IN_FANOUT_THRESHOLD = 50;\n\n/**\n * Per-field range bound bundle decoded from a {@link PredicateWire}.\n * Mirrors the shape the executor consumes on the plan's `rangeOn`\n * slot.\n */\ninterface RangeOpInfo {\n readonly lo?: DocumentValue;\n readonly hi?: DocumentValue;\n readonly loInclusive: boolean;\n readonly hiInclusive: boolean;\n}\n\n/**\n * Choose a query plan over the wire predicate + declared indexes.\n * Pure function. The executor enforces the I/O semantics; the\n * planner's only contract is \"given these inputs, this is the\n * routing decision.\"\n *\n * Algorithm:\n * 1. `wire === undefined` or empty → `no-predicate`.\n * 2. `indexes.length === 0` → `no-indexes-declared`.\n * 3. Partition wire clauses per field into:\n * - `equality[f] = v` from `eq` clauses.\n * - `rangeOps[f] = {lo, hi, loInclusive, hiInclusive}` from\n * one or more of `gt`/`gte`/`lt`/`lte` clauses on `f`.\n * - `inOps[f] = [...]` from a single `in` clause on `f`.\n * - Defensive: any field whose clause group mixes op-channels\n * (mostly impossible post-validation) is marked unroutable\n * and skipped — the executor's full-wire `matchesWire(...)`\n * post-fetch catches the residue automatically.\n * 4. If no equality / range / `in` candidates exist →\n * `predicate-uses-operators-only`.\n * 5. For each `def`, walk `def.on` left-to-right consuming\n * equality clauses for each indexed field. On the FIRST field\n * where the equality clause is absent, check whether a range\n * or `in` clause is available for that field — if so, that's\n * the \"tail slot\" of the walk.\n * 6. Score candidates by `(equalityPrefixLen, hasTailExtension)`.\n * Longest prefix wins; tail-extension breaks ties. If no\n * candidate consumed at least one field (equality OR\n * range/`in`): `no-matching-index`.\n * 7. `in` FAN-OUT GUARD: if the chosen plan's `in` slot has\n * `values.length > IN_FANOUT_THRESHOLD`, fall back to\n * `FullScanPlan{reason:\"no-matching-index\"}` — N sequential\n * LISTs cost more than a snapshot+log fold.\n *\n * The planner deliberately treats `def.on` as the LITERAL tuple of\n * field names — top-level only. Dotted paths are out of scope here\n * (the projector at `indexes.ts:projectIndexValues` is top-level-\n * only too).\n *\n * **Range/`in` is allowed only on the LAST indexed field beyond the\n * equality prefix** — on a composite `[a, b]`, a range on `a` with\n * equality on `b` is NOT contiguous under the key encoding (the `b`\n * slot sits to the right of the varying `a` slot). Clauses landing\n * outside the tail slot are simply left for the executor's full-\n * predicate re-check.\n */\nexport const planQuery = (\n wire: PredicateWire | undefined,\n indexes: ReadonlyArray<IndexDefinition>,\n): QueryPlan => {\n if (wire === undefined || wire.clauses.length === 0) {\n return { kind: \"full-scan\", reason: \"no-predicate\" };\n }\n if (indexes.length === 0) {\n return { kind: \"full-scan\", reason: \"no-indexes-declared\" };\n }\n\n // Partition wire clauses per-field into:\n // - equality (one `eq` clause on a field)\n // - rangeOps (one or more of `gt`/`gte`/`lt`/`lte` on a field)\n // - inOps (one `in` clause on a field)\n // - \"unroutable\" fields are skipped — the executor re-applies the\n // FULL original wire via `matchesWire(...)` post-fetch, which\n // catches the residue automatically.\n //\n // Validator-guaranteed invariants we lean on:\n // - Single op per field is the common case; multi-eq + multi-range\n // are pre-collapsed to a satisfiable group.\n // - An `eq` clause never coexists with `in` on the same field.\n // - An `in` clause never coexists with other ops on the same field.\n //\n // Defensive posture for \"mixed eq+in\" or \"two `in` clauses\" (which\n // the validator does NOT explicitly forbid for routing's sake but\n // are not worth set-intersecting at plan time): mark the field as\n // unroutable and let the executor's full-wire post-filter cover\n // correctness.\n const equality = new Map<string, DocumentValue>();\n const rangeOps = new Map<string, RangeOpInfo>();\n const inOps = new Map<string, ReadonlyArray<DocumentValue>>();\n const unroutable = new Set<string>();\n\n // First pass: per field, accumulate the lo/hi bounds and detect\n // collisions between op channels.\n interface RangeAcc {\n lo?: DocumentValue;\n hi?: DocumentValue;\n loInclusive: boolean;\n hiInclusive: boolean;\n }\n const rangeAcc = new Map<string, RangeAcc>();\n for (const clause of wire.clauses) {\n const field = clause.field;\n if (unroutable.has(field)) {\n continue;\n }\n if (clause.op === \"eq\") {\n if (inOps.has(field) || rangeAcc.has(field)) {\n // Defensive: shouldn't happen post-validation, but keep the\n // executor's post-filter as the safety net.\n unroutable.add(field);\n equality.delete(field);\n inOps.delete(field);\n rangeAcc.delete(field);\n continue;\n }\n // Multiple `eq` on a field: the validator proves agreement; pick\n // the first observed (overwrite is fine — values agree).\n equality.set(field, clause.value as DocumentValue);\n } else if (clause.op === \"in\") {\n if (equality.has(field) || rangeAcc.has(field) || inOps.has(field)) {\n unroutable.add(field);\n equality.delete(field);\n inOps.delete(field);\n rangeAcc.delete(field);\n continue;\n }\n if (!Array.isArray(clause.value)) {\n unroutable.add(field);\n continue;\n }\n inOps.set(field, clause.value as ReadonlyArray<DocumentValue>);\n } else {\n // Range op (gt / gte / lt / lte).\n if (equality.has(field) || inOps.has(field)) {\n unroutable.add(field);\n equality.delete(field);\n inOps.delete(field);\n rangeAcc.delete(field);\n continue;\n }\n const acc: RangeAcc = rangeAcc.get(field) ?? { loInclusive: false, hiInclusive: false };\n const v = clause.value as DocumentValue;\n if (clause.op === \"gte\") {\n // Tighten lo upward.\n if (acc.lo === undefined || v > acc.lo) {\n acc.lo = v;\n acc.loInclusive = true;\n } else if (v === acc.lo && !acc.loInclusive) {\n // existing exclusive is stricter — keep it\n }\n } else if (clause.op === \"gt\") {\n if (acc.lo === undefined || v > acc.lo) {\n acc.lo = v;\n acc.loInclusive = false;\n } else if (v === acc.lo) {\n // Same value; exclusive wins.\n acc.loInclusive = false;\n }\n } else if (clause.op === \"lte\") {\n if (acc.hi === undefined || v < acc.hi) {\n acc.hi = v;\n acc.hiInclusive = true;\n }\n } else if (clause.op === \"lt\") {\n if (acc.hi === undefined || v < acc.hi) {\n acc.hi = v;\n acc.hiInclusive = false;\n } else if (v === acc.hi) {\n acc.hiInclusive = false;\n }\n }\n rangeAcc.set(field, acc);\n }\n }\n // Project the range accumulators into the final `RangeOpInfo` map.\n for (const [field, acc] of rangeAcc) {\n rangeOps.set(field, {\n ...(acc.lo !== undefined ? { lo: acc.lo } : {}),\n ...(acc.hi !== undefined ? { hi: acc.hi } : {}),\n loInclusive: acc.loInclusive,\n hiInclusive: acc.hiInclusive,\n });\n }\n\n if (equality.size === 0 && rangeOps.size === 0 && inOps.size === 0) {\n return { kind: \"full-scan\", reason: \"predicate-uses-operators-only\" };\n }\n\n // Enumerate every viable candidate over the declared indexes,\n // then sort with the T4 tie-break:\n //\n // (1) Implied filter — a filtered index whose\n // `predicateImplies(def.predicate, queryWire)` is `true`\n // outranks an unfiltered alternative (sparser key range →\n // smaller LIST). An unfiltered index outranks a filtered one\n // whose `predicateImplies` is `false` — walking the smaller\n // set would miss matching docs.\n // (2) Longest total consumed length wins among ties on (1).\n // (3) Definition order among ties on (1) and (2).\n interface Candidate {\n readonly def: IndexDefinition;\n readonly defIndex: number;\n readonly prefixLen: number;\n readonly equalityKeys: DocumentValue[];\n readonly tail?:\n | { kind: \"range\"; field: string; info: RangeOpInfo }\n | { kind: \"in\"; field: string; values: ReadonlyArray<DocumentValue> };\n }\n const candidates: Candidate[] = [];\n for (let defIndex = 0; defIndex < indexes.length; defIndex++) {\n const def = indexes[defIndex]!;\n const tuple: readonly string[] = typeof def.on === \"string\" ? [def.on] : def.on;\n const equalityKeys: DocumentValue[] = [];\n let tail: Candidate[\"tail\"] | undefined;\n for (let i = 0; i < tuple.length; i++) {\n const field = tuple[i]!;\n const v = equality.get(field);\n if (v !== undefined) {\n equalityKeys.push(v);\n continue;\n }\n // First field WITHOUT equality — this is the \"tail slot\"\n // candidate for range/$in. Range and $in are mutually\n // exclusive on a single walk; the partitioning above is\n // mutually exclusive per-field, so at most one applies.\n const range = rangeOps.get(field);\n if (range !== undefined) {\n tail = { kind: \"range\", field, info: range };\n } else {\n const inVals = inOps.get(field);\n if (inVals !== undefined) {\n tail = { kind: \"in\", field, values: inVals };\n }\n }\n break;\n }\n const candidateLen = equalityKeys.length + (tail !== undefined ? 1 : 0);\n if (candidateLen === 0) {\n continue;\n }\n candidates.push({\n def,\n defIndex,\n prefixLen: candidateLen,\n equalityKeys,\n ...(tail !== undefined ? { tail } : {}),\n });\n }\n if (candidates.length === 0) {\n return { kind: \"full-scan\", reason: \"no-matching-index\" };\n }\n\n // T4 cost-bias rank: 0 = filtered + implied (best), 1 = unfiltered\n // (mid), 2 = filtered + NOT implied (worst). A filtered candidate\n // whose filter is NOT implied is STILL eligible — but only as a\n // last resort. The post-fetch `matchesWire(wire, ...)` re-check\n // would still drop the rows that fall outside the filter, so the\n // index walk is unsound for the query (it would silently miss\n // matching rows that fell outside the filter), and only the\n // sort order keeps it last.\n const rank = (c: Candidate): number => {\n if (c.def.predicate === undefined) {\n return 1;\n }\n return predicateImplies(c.def.predicate, wire) ? 0 : 2;\n };\n candidates.sort((a, b) => {\n const aRank = rank(a);\n const bRank = rank(b);\n if (aRank !== bRank) {\n return aRank - bRank;\n }\n if (b.prefixLen !== a.prefixLen) {\n return b.prefixLen - a.prefixLen;\n }\n return a.defIndex - b.defIndex;\n });\n const best: Candidate = candidates[0]!;\n\n // `$in` fan-out guard. Over {@link IN_FANOUT_THRESHOLD}, N\n // sequential LISTs cost more than one snapshot+log fold on every\n // backend we benchmark — refuse routing. Full-scan is correct.\n if (best.tail !== undefined && best.tail.kind === \"in\") {\n if (best.tail.values.length > IN_FANOUT_THRESHOLD) {\n return { kind: \"full-scan\", reason: \"no-matching-index\" };\n }\n }\n\n // Residue (unconsumed wire clauses) is intentionally NOT\n // surfaced on the plan — the executor re-applies the FULL\n // original wire via `matchesWire(...)` post-fetch, which is\n // both the stale-index defence and the residue consumer. See\n // `query.ts` (\"simpler invariant\").\n const plan: IndexWalkPlan = {\n kind: \"index-walk\",\n indexName: best.def.name,\n equalityKeys: best.equalityKeys,\n ...(best.tail !== undefined && best.tail.kind === \"range\"\n ? {\n rangeOn: {\n field: best.tail.field,\n ...(best.tail.info.lo !== undefined ? { lo: best.tail.info.lo } : {}),\n ...(best.tail.info.hi !== undefined ? { hi: best.tail.info.hi } : {}),\n loInclusive: best.tail.info.loInclusive,\n hiInclusive: best.tail.info.hiInclusive,\n },\n }\n : {}),\n ...(best.tail !== undefined && best.tail.kind === \"in\"\n ? { inOn: { field: best.tail.field, values: best.tail.values } }\n : {}),\n };\n return plan;\n};\n","/**\n * Schema-validator runtime helper for `Db.insert` / `Query.update` /\n * `Collection.replace` boundary checks.\n *\n * The `SchemaValidator` / `SchemaIssue` TYPES live in\n * `@baerly/protocol` (cross-platform). This module owns the runtime\n * helper `validateOrThrow` that runs a validator and raises a\n * `BaerlyError{code:\"SchemaError\"}` on failure.\n *\n * @example\n * ```ts\n * import { z } from \"zod\";\n * import { defineConfig } from \"@gusto/baerly-storage/config\";\n *\n * const Ticket = z.object({\n * _id: z.string(),\n * status: z.enum([\"open\", \"closed\"]),\n * title: z.string().min(1),\n * });\n *\n * export default defineConfig({\n * collections: {\n * tickets: { schema: Ticket },\n * },\n * });\n * ```\n */\n\nimport { BaerlyError, type SchemaValidator } from \"@baerly/protocol\";\n\nexport type { SchemaIssue, SchemaValidator } from \"@baerly/protocol\";\n\n/**\n * Run a validator and throw `BaerlyError{code:\"SchemaError\"}` on failure.\n * On success returns the validator's output (which for transforming\n * validators may differ from the input).\n *\n * Field paths are normalised to `(string | number)[]` so the wire shape\n * is JSON-clean. Symbol keys (rare; StandardSchemaV1 permits them) are\n * coerced to `String(sym)` — we never emit `symbol` on the wire.\n *\n * The thrown error's `message` carries a one-line summary\n * (`\"<collection>.<verb>: <issuesCount> field(s) failed validation: <first>\"`)\n * for stderr-readable logs; the structured `issues` are on `.issues`.\n */\nexport const validateOrThrow = async <TIn, TOut>(\n schema: SchemaValidator<TIn, TOut>,\n candidate: unknown,\n context: { readonly collection: string; readonly verb: \"insert\" | \"update\" | \"replace\" },\n): Promise<TOut> => {\n const result = await schema[\"~standard\"].validate(candidate);\n if (result.issues === undefined) {\n return result.value;\n }\n const issues = result.issues.map((i) => ({\n path: (i.path ?? []).map((p) => {\n // StandardSchemaV1 permits `{ key: PropertyKey }` segments\n // (Zod 3.24+, Valibot 0.36+) alongside bare PropertyKeys.\n const raw = typeof p === \"object\" && p !== null && \"key\" in p ? p.key : p;\n return typeof raw === \"number\" ? raw : String(raw);\n }),\n message: i.message,\n }));\n const first = issues[0];\n const summary =\n first === undefined\n ? \"schema validation failed (no issues reported)\"\n : `${first.path.length === 0 ? \"<root>\" : first.path.join(\".\")}: ${first.message}`;\n throw new BaerlyError(\n \"SchemaError\",\n `${context.collection}.${context.verb}: ${issues.length} field${issues.length === 1 ? \"\" : \"s\"} failed validation: ${summary}`,\n undefined,\n issues,\n );\n};\n","/* eslint-disable no-underscore-dangle -- `_id` is the locked primary-key\n field on document shapes (see `@baerly/protocol/src/collection-api.ts`'s `Collection<T>` /\n `Query<T>` declarations); mutation verbs surface and route it by name. */\n\n/**\n * Read engine + mutation terminals: `Query<T>` builder, the\n * three read terminals (`first`, `all`, `count`) that fold the log\n * under a fresh `current.json` snapshot, and the four mutation\n * terminals (`insert`, `update`, `replace`, `delete`) that each\n * compile to one or more `Writer.commit()` round-trips.\n *\n * Every modifier (`.where` / `.order` / `.limit`) returns a NEW\n * `Query<T>` carrying merged frozen state — the input state is never\n * mutated. Identity inequality between the original and the returned\n * builder is intentional: callers cannot share a chain.\n *\n * `.where()` AND-merges through `mergePredicateWires` (clause-level\n * AND on the normalised wire form).\n * `.order()` and `.limit()` are last-call-wins (state replace).\n *\n * Each terminal reads `current.json` FRESH and walks `[0, next_seq)`\n * directly — no cache, no `list()` round-trip. Per the multi-\n * instance rules, every read sees a fresh CAS snapshot.\n *\n * Mutation terminals are SINGLE-ATTEMPT per call site. CAS contention\n * retries (up to 8 attempts) live inside `Writer.commit()`; the\n * verbs do NOT add their own retry loop. On retry-budget exhaustion\n * `commit()` throws `BaerlyError{code:\"Conflict\"}` and the verb\n * surfaces it unchanged — the caller's option is to wrap in\n * `db.transaction(...)`.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\n\nimport {\n type CurrentJson,\n type DocumentValue,\n type DocumentData,\n logSeqStartOf,\n MANIFEST_POINTER_EMPTY_SNAPSHOT,\n matchesWire,\n merge,\n mergePredicateWires,\n normalizePredicateArg,\n validateWire,\n BaerlyError,\n type OrderSpec,\n type PredicateWire,\n type Query,\n readCurrentJson,\n type Storage,\n uuidv7,\n} from \"@baerly/protocol\";\nimport { loadSnapshotAsMap } from \"./snapshot.ts\";\nimport type { TxContext } from \"./db.ts\";\nimport { encodeIndexValue, type IndexDefinition } from \"./indexes.ts\";\nimport { foldLogEntriesOnto, walkLogRange } from \"./log-walk.ts\";\nimport { type IndexWalkPlan, planQuery, type QueryPlan } from \"./query-planner.ts\";\nimport { type SchemaValidator, validateOrThrow } from \"./schema.ts\";\nimport { Writer } from \"./writer.ts\";\n\n/**\n * What a `Query<T>` needs to issue a read against the bucket. The\n * `Db` builds this once and hands it to `Collection` / `Query`; the chain\n * carries it forward unchanged.\n *\n * The `collectionPrefix` shape matches what `Writer` writes under —\n * e.g. `\"app/<app>/tenant/<tenant>/manifests/<name>\"`. Drift between\n * the reader and writer prefix is the most likely bug class; both\n * compose the same string from `app`/`tenant`/`name`.\n *\n * @internal\n */\nexport interface CollectionReadContext {\n readonly storage: Storage;\n /** Physical key prefix — already includes `app/<app>/tenant/<tenant>/manifests/<name>`. */\n readonly collectionPrefix: string;\n readonly collectionName: string;\n /**\n * When defined, mutation verbs (`Collection.insert`, `Query.update`,\n * `Collection.replace`, `Query.delete`) buffer a {@link BufferedMutation}\n * onto `txCtx.mutations` instead of calling `Writer.commit`\n * directly. Reads ignore `txCtx` entirely — they go through\n * `Storage` live, by design (no MVCC; see `Db.transaction`'s JSDoc\n * in `./db.ts`). Threaded in by `Db.transaction(...)`; `undefined`\n * outside a transaction.\n *\n * @internal\n */\n readonly txCtx?: TxContext;\n /**\n * Optional StandardSchemaV1-shaped validator for this collection.\n * When set, `runInsert`, `runUpdate`, and `runReplaceById` validate the\n * post-image before committing or buffering — invalid input throws\n * `BaerlyError{code:\"SchemaError\"}` carrying a `.issues` array of\n * `{ path, message }` entries. `undefined` means no validation\n * (today's behaviour — zero overhead).\n *\n * Threaded in by {@link Db.collectionReadContext} from the per-collection\n * map handed to {@link Db.create}; the boundary calls happen in\n * `query.ts`, not `writer.ts`, so schemas plug in at the\n * read/write API surface rather than at the writer layer.\n *\n * @internal\n */\n readonly schema?: SchemaValidator;\n /**\n * Per-collection {@link IndexDefinition}s threaded onto every\n * read. Consumed by `planQuery(...)` inside `runRead` to pick an\n * index-walk plan when the predicate's equality fields cover a\n * declared index's `on` tuple left-to-right. Empty array means\n * \"no indexes declared\" — every read falls through to the\n * snapshot + log fold path.\n *\n * Mirrors the shape callers build when flattening\n * `BaerlyConfig.collections[*].indexes` into a map keyed by name\n * before constructing the `Db`; we keep the `Db` itself library-\n * agnostic by accepting the pre-flattened map (not the full\n * `BaerlyConfig`).\n *\n * @internal\n */\n readonly indexes: ReadonlyArray<IndexDefinition>;\n}\n\n/**\n * What `runRead` hands back: the materialised rows plus the cursor\n * + freshness pair surfaced as `_meta` on read response envelopes\n * (see `contract.ts:HttpOkMeta`). The public `Query<T>` terminals\n * destructure and discard the cursor — only the in-router\n * `*WithMeta` helpers consume it.\n *\n * @internal\n */\nexport interface ReadResult<T extends DocumentData> {\n readonly rows: T[];\n readonly manifestPointer: string;\n readonly fresh: boolean;\n}\n\n/**\n * Serialise a {@link CurrentJson} head into the wire cursor format\n * `\"<snapshot>@<next_seq>\"`. `null` snapshots stringify as\n * {@link MANIFEST_POINTER_EMPTY_SNAPSHOT} so the cursor is never the\n * empty string.\n *\n * @internal — exported for `query.test.ts`.\n */\nexport const serializeManifestPointer = (json: CurrentJson): string =>\n `${json.snapshot ?? MANIFEST_POINTER_EMPTY_SNAPSHOT}@${json.next_seq}`;\n\n/**\n * Frozen state carried along a `Query<T>` chain. Every modifier\n * produces a fresh `QueryState<T>` via spread + `Object.freeze`; the\n * wire / order / limit fields are never mutated in place.\n *\n * The chain carries the normalised wire form ({@link PredicateWire})\n * — the public seam (`.where(p)` accepting `PredicateArg<T>`) routes\n * incoming object-form / callback-form predicates through\n * `normalizePredicateArg` before they reach this state, so every\n * downstream consumer (planner, executor, post-filter) reads the\n * same shape.\n *\n * @internal\n */\nexport interface QueryState<T extends DocumentData> {\n readonly wire: PredicateWire | undefined;\n readonly order: OrderSpec<T> | undefined;\n readonly limit: number | undefined;\n}\n\n/**\n * Returns the id iff `wire` carries exactly one clause and that\n * clause is `{op:\"eq\", field:\"_id\", value:<string>}` — the shape\n * `runRead` short-circuits to a single `Map.get`. Any other shape\n * (multi-clause, non-`eq` op, non-`_id` field, non-string value)\n * returns `undefined` and falls through to the scan path.\n *\n * Kernel-internal `_id`-shaped wires (built by `byId`,\n * `runByIdWithMeta`, `runInsert`) bypass the wire validator by\n * design (`_id` at the root is a wire-only rejection); this\n * recogniser matches the same shape so the fast-path stays\n * symmetric.\n *\n * @internal\n */\nexport const singleIdFromPredicate = (wire: PredicateWire | undefined): string | undefined => {\n if (wire === undefined) {\n return undefined;\n }\n if (wire.clauses.length !== 1) {\n return undefined;\n }\n const clause = wire.clauses[0]!;\n if (clause.op !== \"eq\" || clause.field !== \"_id\") {\n return undefined;\n }\n return typeof clause.value === \"string\" ? clause.value : undefined;\n};\n\n/**\n * Build a `Query<T>` from a context + frozen state. Every modifier\n * returns a NEW `Query<T>` carrying merged state — the input state\n * is never mutated. Identity inequality with the input chain is\n * intentional.\n *\n * Validation happens at the public seams — `Query.where(p)`\n * normalises + validates the incoming fragment before merging into\n * `state.wire`. By the time `makeQuery` is reached from elsewhere\n * (`Collection.where`, `runAllWithMeta`, kernel-internal `_id`-shaped\n * wires from `byId` / `runByIdWithMeta` / `runInsert`), the wire is\n * already trusted.\n *\n * @example\n * ```ts\n * const q = makeQuery<Ticket>(ctx, { wire: undefined, order: undefined, limit: undefined });\n * const open = await q.where({ status: \"open\" }).order({ created_at: \"desc\" }).limit(10).all();\n * ```\n *\n * @internal\n */\nexport const makeQuery = <T extends DocumentData>(\n ctx: CollectionReadContext,\n state: QueryState<T>,\n): Query<T> => {\n // Every modifier below produces a fresh spread; identity inequality\n // with `state` is intentional and load-bearing. A shallow `Object.freeze`\n // would only protect the top-level object (the chain never mutates it\n // anyway) and not nested wire / order objects — pure ceremony.\n return {\n where: (p) => {\n // Normalise + validate the incoming fragment before merge so\n // error messages pin the offender to `p`, not the merged whole.\n // The validator is the wire-arrival contract surface; running\n // it once per fragment is sufficient because `mergePredicateWires`\n // preserves the per-clause shape that `validateWire` already\n // approved.\n const incoming = normalizePredicateArg<T>(p);\n validateWire(incoming);\n return makeQuery<T>(ctx, {\n ...state,\n wire: state.wire === undefined ? incoming : mergePredicateWires(state.wire, incoming),\n });\n },\n order: (s) => makeQuery<T>(ctx, { ...state, order: s }),\n limit: (n) => makeQuery<T>(ctx, { ...state, limit: n }),\n first: async () => {\n const { rows } = await runRead<T>(ctx, { ...state, limit: 1 });\n return rows[0]; // undefined when rows.length === 0\n },\n all: async () => {\n const res = await runRead<T>(ctx, state);\n return res.rows;\n },\n count: async () => {\n const res = await runRead<T>(ctx, state);\n return res.rows.length;\n },\n update: (patch) => runUpdate<T>(ctx, state, patch),\n delete: () => runDelete<T>(ctx, state),\n };\n};\n\n/**\n * Server-internal read entry surfacing the manifest-pointer cursor\n * and freshness flag alongside the materialised rows. The HTTP\n * router calls this directly so the read-response handler can pack\n * `_meta` onto the envelope; the public `Query<T>` terminals\n * destructure the rows out and discard the cursor to keep the\n * locked interface signature. Single-row routes (`GET /v1/c/:collection/:id`)\n * call this with `limit:1` and pick `rows[0]`.\n *\n * `state.wire` is assumed already validated — the public seam\n * (`Query.where(p)` → `normalizePredicateArg` → `validateWire`) is\n * the wire-arrival contract surface. Router callers parsing\n * `?where=` run `validateWire` themselves inside `parseWhereParam`,\n * keeping a single validation pass per wire.\n *\n * @internal\n */\nexport const runAllWithMeta = <T extends DocumentData>(\n ctx: CollectionReadContext,\n state: QueryState<T>,\n): Promise<ReadResult<T>> => {\n return runRead<T>(ctx, state);\n};\n\n/**\n * By-id read entry surfacing the same `ReadResult<T>` shape as\n * {@link runAllWithMeta} so the HTTP router can preserve the\n * `_meta` wire envelope while routing through the PK-lookup\n * fast-path. Mirrors {@link runAllWithMeta}'s signature; the\n * wire is built internally as a single-clause `{op:\"eq\",\n * field:\"_id\", value:id}` shape (same form as the `byId` helper in\n * `./collection.ts` and the `runInsert` duplicate-collision check)\n * which routes through `runRead`'s `singleIdFromPredicate`\n * short-circuit automatically.\n *\n * Bypasses {@link validateWire} — the wire is kernel-constructed,\n * never wire-submitted, so it would always pass the structural\n * rules. Skipping the validator also keeps this helper usable\n * from kernel-internal sites (`Collection<T>.get` etc.) without\n * tripping the wire-only rule that bans top-level `_id`.\n *\n * @internal — router uses this to preserve `_meta` envelope;\n * mirrors {@link runAllWithMeta} and {@link Collection.get}.\n */\nexport const runByIdWithMeta = <T extends DocumentData>(\n ctx: CollectionReadContext,\n id: string,\n): Promise<ReadResult<T>> => {\n return runRead<T>(ctx, {\n wire: { clauses: [{ op: \"eq\", field: \"_id\", value: id }] },\n order: undefined,\n limit: 1,\n });\n};\n\n// ---------------------------------------------------------------------\n// Mutation terminals\n// ---------------------------------------------------------------------\n\n/**\n * Build a fresh `Writer` bound to this collection's `current.json`.\n * Construction is zero-I/O (writer.ts:160) so we mint one per\n * `commit()` rather than caching on the chain — same writer object\n * shared across N commits would inherit retry-budget state we want\n * fresh per call.\n */\nconst writerFor = (ctx: CollectionReadContext): Writer =>\n new Writer({\n storage: ctx.storage,\n currentJsonKey: `${ctx.collectionPrefix}/current.json`,\n options: {\n indexes: ctx.indexes,\n },\n });\n\n/**\n * `Collection.insert` / `Query.insert` implementation. Mints a UUIDv7 `_id`\n * when the caller omits it (or supplies an empty string); honours a\n * caller-supplied non-empty `_id`. On collision (the materialised\n * collection already carries that `_id`) throws\n * `BaerlyError{code:\"Conflict\"}` BEFORE issuing the writer round-trip\n * — matches the locked `Collection.insert` contract\n * (`packages/protocol/src/collection-api.ts:123–125`).\n *\n * The emitted `LogEntry` has `op:\"I\"` and `new === patch === {...doc, _id}`\n * (today's per-doc-replace model — `packages/protocol/src/log.ts:67–72`).\n *\n * @throws BaerlyError code=\"Conflict\" — `_id` collision (pre-commit check) or\n * CAS retry budget exhausted inside `Writer.commit()`.\n * @throws BaerlyError code=\"SchemaError\" — from the per-collection\n * `SchemaValidator` threaded via {@link Db.collectionReadContext}.\n *\n * @internal — exported for `Collection.insert` in `./collection.ts` to delegate\n * without duplicating the auto-id / collision-check /\n * commit pipeline.\n */\nexport const runInsert = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n doc: Partial<T> & DocumentData,\n): Promise<{ _id: string }> => {\n // Auto-id semantics: caller-supplied non-empty `_id` wins; otherwise\n // mint a UUIDv7. The locked contract\n // (`packages/protocol/src/collection-api.ts:120–122`) names UUIDv7 as the\n // auto-id source.\n const supplied = doc[\"_id\"];\n const _id = typeof supplied === \"string\" && supplied.length > 0 ? supplied : uuidv7();\n // The locked input type `Partial<T> & DocumentData` is an\n // intersection of optional-keyed and required-keyed: at runtime the\n // DocumentData half is authoritative (Partial widens types\n // but doesn't add `undefined` to the runtime shape). Cast through\n // the runtime-authoritative half.\n const body: DocumentData = { ...(doc as DocumentData), _id };\n\n // Schema validation against the post-image. Runs BEFORE the\n // pre-commit collision check and before the writer round-trip so\n // a malformed doc never reaches the wire. Inside a transaction it\n // also runs before `txCtx.mutations.push` — a `SchemaError` thrown\n // here aborts the body, dropping every buffered mutation, before\n // the commit fires.\n if (ctx.schema !== undefined) {\n await validateOrThrow(ctx.schema, body, {\n collection: ctx.collectionName,\n verb: \"insert\",\n });\n }\n\n // Pre-commit `_id`-collision check. Costs one log walk; matches the\n // locked `Collection.insert` throws contract\n // (`packages/protocol/src/collection-api.ts:123–125`). Without it a caller-\n // supplied duplicate `_id` would land a second `I` entry that the\n // read fold collapses silently — a contract violation. The CAS\n // retry budget in `Writer` does not surface this case\n // (no `current.json` conflict; both writes succeed at different seqs).\n //\n // Inside a transaction the read sees LIVE state (no MVCC, no read-\n // your-writes); a buffered insert in the same transaction is NOT\n // visible here. The collision check still defends against a doc\n // ALREADY committed to the bucket.\n const existing = await runRead<DocumentData>(ctx, {\n wire: { clauses: [{ op: \"eq\", field: \"_id\", value: _id }] },\n order: undefined,\n limit: 1,\n });\n if (existing.rows.length > 0) {\n throw new BaerlyError(\n \"Conflict\",\n `Query.insert: _id ${JSON.stringify(_id)} already exists in collection ${JSON.stringify(ctx.collectionName)}`,\n );\n }\n\n if (ctx.txCtx !== undefined) {\n assertTxBindMatches(ctx);\n ctx.txCtx.mutations.push({ op: \"I\", docId: _id, body });\n return { _id };\n }\n\n // Single-attempt at the verb level; CAS retries are internal to\n // `Writer.commit()`. If `commit` throws `Conflict`, the\n // budget is exhausted and we surface unchanged.\n await writerFor(ctx).commit({\n op: \"I\",\n collection: ctx.collectionName,\n docId: _id,\n body,\n });\n\n return { _id };\n};\n\n/**\n * `Query.update` implementation. Materialises the predicate/order/\n * limit-filtered match set, applies RFC 7386 `merge(prev, patch)`\n * per row, and emits one `op:\"U\"` `LogEntry` per affected `doc_id`\n * — one `Writer.commit()` round-trip apiece.\n *\n * Atomicity is per row, not across the N-row batch. The locked\n * contract (`packages/protocol/src/collection-api.ts:178–184`) is explicit on\n * this: all-or-nothing across multiple rows is what\n * `db.transaction(...)` exists to deliver.\n *\n * `replica_identity` defaults to `PATCH_ONLY` for every collection\n * today — emitted `U` entries carry `{ new, patch }` (equal) and\n * neither `old` nor `key_old`. Consumers rebuilding pre-images\n * under `PATCH_ONLY` need to maintain a shadow table — see\n * `packages/protocol/src/log.ts:102–118`.\n *\n * @throws BaerlyError code=\"Conflict\" — any one row's CAS retry budget\n * exhausted inside `Writer.commit()`. The partial-progress\n * `modified` count is NOT returned in that case.\n * @throws BaerlyError code=\"SchemaError\" — `merge(prev, patch)` produced\n * `undefined` (defensive — `Partial<T>` cannot be `null` at the\n * root in the type system).\n */\nconst runUpdate = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n state: QueryState<T>,\n patch: Partial<T>,\n): Promise<{ modified: number }> => {\n const { rows } = await runRead<T>(ctx, state);\n const tx = ctx.txCtx;\n if (tx !== undefined) {\n assertTxBindMatches(ctx);\n }\n let modified = 0;\n for (const doc of rows) {\n const merged = merge(doc as DocumentData, patch as Partial<DocumentData>);\n if (merged === undefined) {\n // `merge(target, patch)` returns undefined only when patch is\n // null at the root. `Partial<T>` cannot be `null` at the type\n // level; defensive check for runtime caller misuse via cast.\n throw new BaerlyError(\n \"SchemaError\",\n `Query.update: merge produced undefined for doc ${JSON.stringify(doc[\"_id\"])}`,\n );\n }\n // Validate the merged post-image, not the incoming patch.\n // Patches are partial by design — validating the patch itself\n // would reject valid updates against schemas that require fields\n // the patch doesn't touch. The post-image is what the schema\n // actually models. Atomicity stays per-row: a violation on row\n // N aborts the batch without rolling back rows 0..N-1.\n if (ctx.schema !== undefined) {\n await validateOrThrow(ctx.schema, merged, {\n collection: ctx.collectionName,\n verb: \"update\",\n });\n }\n if (tx !== undefined) {\n tx.mutations.push({ op: \"U\", docId: String(doc[\"_id\"]), body: merged });\n } else {\n await writerFor(ctx).commit({\n op: \"U\",\n collection: ctx.collectionName,\n docId: String(doc[\"_id\"]),\n body: merged,\n });\n }\n modified++;\n }\n return { modified };\n};\n\n/**\n * `Collection.replace` implementation. Existence check via `runRead` over\n * a `byId`-shaped wire so the `singleIdFromPredicate` PK fast path\n * (`Map.get`) fires and any transaction-buffered insert of `id` is\n * visible. Missing row → `NotFound` directly (no Conflict-string\n * indirection through the router). Present row → emit a single\n * `op:\"U\"` `LogEntry` carrying `doc` as the post-image, with `_id`\n * forced to the requested `id` so doc identity is preserved across\n * replaces even if the supplied `doc._id` differs.\n *\n * @throws BaerlyError code=\"NotFound\" — no row exists at `id`.\n * @throws BaerlyError code=\"SchemaError\" — post-image rejected by\n * the collection's bound validator.\n * @throws BaerlyError code=\"Conflict\" — writer CAS retry budget\n * exhausted.\n */\nexport const runReplaceById = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n id: string,\n doc: T,\n): Promise<void> => {\n const wire: PredicateWire = {\n clauses: [{ op: \"eq\", field: \"_id\", value: id }],\n };\n const state: QueryState<T> = {\n wire,\n order: undefined,\n limit: undefined,\n };\n const { rows } = await runRead<T>(ctx, state);\n if (rows.length === 0) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n const body: DocumentData = { ...(doc as DocumentData), _id: id };\n // Schema validation runs against the post-image — same shape as\n // `runInsert`. Buffers in a transaction only after validation\n // passes; an invalid replace inside a tx aborts the body and\n // drops every previously-buffered mutation.\n if (ctx.schema !== undefined) {\n await validateOrThrow(ctx.schema, body, {\n collection: ctx.collectionName,\n verb: \"replace\",\n });\n }\n if (ctx.txCtx !== undefined) {\n assertTxBindMatches(ctx);\n ctx.txCtx.mutations.push({ op: \"U\", docId: id, body });\n return;\n }\n await writerFor(ctx).commit({\n op: \"U\",\n collection: ctx.collectionName,\n docId: id,\n body,\n });\n};\n\n/**\n * `Query.delete` implementation. Tombstones every matched row with a\n * single `op:\"D\"` `LogEntry` per `doc_id`. `replica_identity` defaults\n * to `PATCH_ONLY`, so emitted `D` entries carry neither `new`/`patch`\n * nor `old`/`key_old`.\n * Consumers rebuilding pre-images under `PATCH_ONLY` need to\n * maintain a shadow table — see `packages/protocol/src/log.ts:102–118`.\n *\n * Atomicity is per row, not across the N-row batch — same shape as\n * `Query.update`. `db.transaction(...)` is where all-or-nothing\n * semantics live.\n *\n * @throws BaerlyError code=\"Conflict\" — any one row's CAS retry budget\n * exhausted. The partial-progress `deleted` count is NOT returned\n * in that case.\n */\nconst runDelete = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n state: QueryState<T>,\n): Promise<{ deleted: number }> => {\n const { rows } = await runRead<T>(ctx, state);\n const tx = ctx.txCtx;\n if (tx !== undefined) {\n assertTxBindMatches(ctx);\n }\n let deleted = 0;\n for (const doc of rows) {\n if (tx !== undefined) {\n tx.mutations.push({ op: \"D\", docId: String(doc[\"_id\"]) });\n } else {\n await writerFor(ctx).commit({\n op: \"D\",\n collection: ctx.collectionName,\n docId: String(doc[\"_id\"]),\n });\n }\n deleted++;\n }\n return { deleted };\n};\n\n/**\n * Runtime guard for the txCtx-Collection-name binding. The type system\n * already prevents the legitimate path (the body callback gets one\n * `Collection<T>`, no `Db`), so this only catches a bug where a stale\n * `Query<T>` outlives its `Collection<T>` and is somehow re-attached to a\n * transaction over a different collection.\n *\n * @throws BaerlyError code=\"Internal\" — txCtx ↔ Collection name mismatch.\n */\nconst assertTxBindMatches = (ctx: CollectionReadContext): void => {\n if (ctx.txCtx === undefined) {\n return;\n }\n if (ctx.txCtx.collection !== ctx.collectionName) {\n throw new BaerlyError(\n \"Internal\",\n `Transaction context bound to ${JSON.stringify(ctx.txCtx.collection)} but mutation issued on collection ${JSON.stringify(ctx.collectionName)}`,\n );\n }\n};\n\n/**\n * Load `current.json` fresh, walk `[0, next_seq)` in parallel, fold\n * per-`doc_id`, then apply predicate / order / limit in memory.\n *\n * Error mapping:\n * - `current.json` missing → empty result (collection not provisioned).\n * - `current.json` malformed → `InvalidResponse` (from `readCurrentJson`).\n * - log entry missing in `[0, next_seq)` → `Internal`.\n * - log entry malformed → `InvalidResponse`.\n */\nconst runRead = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n state: QueryState<T>,\n): Promise<ReadResult<T>> => {\n // ── Step 1. Read current.json. ────────────────────────────────────\n // Every read GETs `current.json` fresh — mirrors the multi-instance\n // rules: every read sees a fresh CAS snapshot, matching the writer's\n // per-commit GET.\n const currentJsonKey = `${ctx.collectionPrefix}/current.json`;\n const head = await readCurrentJson(ctx.storage, currentJsonKey);\n\n // Capture the wire cursor before the rest of the fold runs. A\n // not-found head (\"collection not yet provisioned\") still emits a\n // well-defined cursor so the wire shape never carries `\"\"`.\n const manifestPointer =\n head === null ? `${MANIFEST_POINTER_EMPTY_SNAPSHOT}@0` : serializeManifestPointer(head.json);\n // Every read is strong by construction — `fresh` reflects that.\n const fresh = true;\n\n // Not-found is \"collection not yet provisioned\" — return empty rather\n // than throw. Mirrors `Storage.get` returning null on miss.\n if (head === null) {\n return { rows: [], manifestPointer, fresh };\n }\n\n // ── Optional index-walk fast path. ──────────────────────────────\n // `planQuery` is a pure function over `(wire, indexes)`. It picks\n // the longest-prefix-matching index from the collection's declared\n // indexes and emits a `FullScanPlan` when nothing matches. We\n // route on `plan.kind`; the in-memory `matchesWire(...)` re-check\n // on every fetched doc defends against stale index entries AND\n // consumes the planner's residue (range clauses, unrelated\n // equality on non-indexed fields).\n const plan: QueryPlan = planQuery(state.wire, ctx.indexes);\n if (plan.kind === \"index-walk\") {\n let rows = await runIndexWalkPlan<T>(ctx, head.json, state, plan);\n if (state.order !== undefined) {\n rows = sortByOrderSpec(rows, state.order);\n }\n if (state.limit !== undefined && state.limit < rows.length) {\n rows = rows.slice(0, state.limit);\n }\n return { rows, manifestPointer, fresh };\n }\n // plan.kind === \"full-scan\" — fall through to the snapshot+log fold.\n\n // Load the snapshot, if any. `compact()` guarantees:\n // `snapshot !== null` iff `log_seq_start > 0`. The snapshot is\n // sealed by its filename hash; `loadSnapshotAsMap` recomputes on\n // load and throws `Internal` on mismatch. Entries with\n // `seq < log_seq_start` have been folded into the snapshot (or\n // dropped on truncation) and MUST NOT be GET-required here — the\n // bucket may have already swept them via `runGc()`.\n const nextSeq = head.json.next_seq;\n const logSeqStart = logSeqStartOf(head.json);\n const baseDocs: Map<string, DocumentData> =\n head.json.snapshot === null\n ? new Map()\n : await loadSnapshotAsMap(ctx.storage, head.json.snapshot, ctx.collectionName);\n\n // ── Step 2. Bounded parallel-fetch of [log_seq_start, next_seq). ──\n const entries = await walkLogRange(ctx.storage, ctx.collectionPrefix, logSeqStart, nextSeq);\n\n // ── Step 3. Fold per doc_id, seeded from the snapshot. ────────────\n // I / U: post-image overwrite (today's per-doc-replace model). The\n // writer emits `entry.new` as the FULL post-image\n // (`packages/protocol/src/log.ts:67–72`: `new === patch`),\n // so the fold is a straight `set`, not a `merge`. A future\n // partial-merge writer will introduce `entry.patch !== entry.new`\n // — at that point the fold switches to `merge(prev, entry.patch)`\n // for `patch` entries while keeping the straight `set` for\n // full-post-image entries. Crucially, RFC-7386 deletions\n // (a `null` value in `Query.update`'s patch) are encoded\n // TODAY as \"the post-image omits the key\" — `merge(prev, post)`\n // would carry the dropped key forward; a straight `set` lets\n // the deletion land.\n // D: tombstone — remove from the map.\n // T / M: ignored (T not yet wired; M is a marker).\n const docs = new Map<string, T>(baseDocs as Map<string, T>);\n foldLogEntriesOnto(docs, entries, { collection: ctx.collectionName });\n\n // ── Step 4. Apply predicate. ──────────────────────────────────────\n // PK fast-path: a single `eq` clause on `_id` short-circuits the\n // O(n) scan with a `Map.get` on the same snapshot — observable\n // contract unchanged.\n const fastId = singleIdFromPredicate(state.wire);\n let rows: T[];\n if (fastId !== undefined) {\n const hit = docs.get(fastId);\n rows = hit === undefined ? [] : [hit];\n } else {\n rows = Array.from(docs.values());\n if (state.wire !== undefined) {\n const w = state.wire;\n rows = rows.filter((d) => matchesWire(w, d));\n }\n }\n\n // ── Step 5. Apply order. ──────────────────────────────────────────\n if (state.order !== undefined) {\n rows = sortByOrderSpec(rows, state.order);\n }\n\n // ── Step 6. Apply limit. ──────────────────────────────────────────\n if (state.limit !== undefined && state.limit < rows.length) {\n rows = rows.slice(0, state.limit);\n }\n\n return { rows, manifestPointer, fresh };\n};\n\n/**\n * Range-walk exclusive-lower sentinel. `Storage.list({startAfter})`\n * is strict-greater; to position the cursor PAST every entry whose\n * value-segment equals `ENCODE(lo)`, append a character that\n * lex-sorts strictly greater than every base-32 character (the\n * encoder alphabet is `[0-9a-v]`, topping out at `v` = 0x76) AND\n * strictly greater than the path separator `/` (0x2F).\n *\n * `~` (0x7E) satisfies both. The cursor `${eqPrefix}${ENCODE(lo)}/~`\n * lex-sorts strictly greater than the LARGEST possible key under\n * the `lo` value bucket but strictly less than the smallest key\n * under any bucket with a larger value-segment. The next LIST\n * result is the first entry with value-segment strictly greater\n * than `ENCODE(lo)` — exactly the exclusive-lower semantics we\n * want.\n */\nconst RANGE_EXCLUSIVE_LOWER_SENTINEL = \"~\";\n\n/**\n * Bounded parallelism for `$in` multi-walk LISTs. Each batch of this\n * many `$in` values dispatches its `list()` calls concurrently; the\n * loop waits on the batch before starting the next.\n *\n * Picked low (8) to stay well under any cloud-provider per-call concurrency\n * ceiling while still amortising LIST round-trip latency on multi-value\n * `$in` queries. The planner's `IN_FANOUT_THRESHOLD` (50) caps the total\n * fan-out independently — see `packages/server/src/query-planner.ts`.\n */\nconst IN_FANOUT_PARALLELISM = 8;\n\n/**\n * Execute an {@link IndexWalkPlan} against the bucket. Returns the\n * post-filtered, fully-resolved row set. The full original\n * `state.wire` is re-applied via `matchesWire(...)` after fetching\n * rows — this defends against stale index entries AND consumes the\n * planner's residue (range clauses, unrelated equality on\n * non-indexed fields) in one place.\n *\n * Storage shape (equality-only walks):\n * - Single-field walk (`equalityKeys.length === 1`): list\n * `<collectionPrefix>/index/<name>/<v0-b32>/`; each yielded key has\n * tail `<docId>.json` (single segment).\n * - Composite full walk (`equalityKeys.length === def.on.length`):\n * list `<collectionPrefix>/index/<name>/<v0-b32>/<v1-b32>/.../<vN-b32>/`;\n * each yielded key has tail `<docId>.json` (single segment).\n * - Composite partial-prefix walk (`equalityKeys.length <\n * def.on.length`): list `<collectionPrefix>/index/<name>/<v0-b32>/\n * .../<vM-b32>/`; each yielded key has tail\n * `<v{M+1}-b32>/.../<vN-b32>/<docId>.json` — MULTI-segment.\n * Split on `/` and take the last segment.\n *\n * Storage shape (T3, range / `$in` walks):\n * - Range walk (`plan.rangeOn !== undefined`): list\n * `<collectionPrefix>/index/<name>/<eq-segs>/` and break on the\n * first decoded value-segment past the upper bound. Lower\n * bound is enforced via `startAfter` (exclusive lower) or an\n * in-loop skip (inclusive lower) — see\n * {@link RANGE_EXCLUSIVE_LOWER_SENTINEL}.\n * - `$in` walk (`plan.inOn !== undefined`): one LIST per value,\n * with the equality prefix prepended to each, dispatched in\n * batches of {@link IN_FANOUT_PARALLELISM} `Promise.all`-style.\n * Doc-ids accumulate into a single Set (union semantics).\n *\n * Stale-row defence:\n * - An index entry pointing at a docId whose underlying doc has\n * since been updated to a different value (rebuild hasn't run)\n * is dropped by the in-memory `matchesWire(...)` re-check.\n * - An index entry pointing at a docId whose underlying doc has\n * been deleted (tombstone in the log) is dropped during the\n * fold (the `D` op removes it from the materialised set).\n *\n * @internal\n */\nconst runIndexWalkPlan = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n head: CurrentJson,\n state: QueryState<T>,\n plan: IndexWalkPlan,\n): Promise<T[]> => {\n const encodedSegments = plan.equalityKeys.map((v) => encodeIndexValue(v));\n const eqPrefix =\n encodedSegments.length === 0\n ? `${ctx.collectionPrefix}/index/${plan.indexName}/`\n : `${ctx.collectionPrefix}/index/${plan.indexName}/${encodedSegments.join(\"/\")}/`;\n\n // 1. List index entries; extract docId from the LAST segment of\n // each key's tail. Multi-segment tails appear under composite\n // partial-prefix walks; single-segment tails appear under\n // single-field walks and composite full walks.\n const docIdSet = new Set<string>();\n\n if (plan.rangeOn !== undefined) {\n // Range-LIST under the equality prefix. The value-segment sits\n // immediately after `eqPrefix`; we lex-compare it against the\n // encoded bounds. Lex comparison is sound because\n // `encodeIndexValue` is value-order-preserving for every\n // supported type — numbers via the sortable IEEE 754 payload,\n // strings via UTF-8 byte order, all framed under the type-tag\n // prefix that keeps types disjoint.\n const r = plan.rangeOn;\n const loEncoded = r.lo === undefined ? undefined : encodeIndexValue(r.lo);\n const hiEncoded = r.hi === undefined ? undefined : encodeIndexValue(r.hi);\n // Exclusive lower → position the cursor past all entries\n // whose value-segment equals `ENCODE(r.lo)` via the sentinel.\n // Inclusive lower → no startAfter; in-loop skip filters values\n // strictly less than `ENCODE(r.lo)` (no-op for the bucket\n // matching `ENCODE(r.lo)` itself).\n const startAfter =\n r.lo !== undefined && !r.loInclusive\n ? `${eqPrefix}${loEncoded}/${RANGE_EXCLUSIVE_LOWER_SENTINEL}`\n : undefined;\n const listOpts = startAfter === undefined ? {} : { startAfter };\n for await (const entry of ctx.storage.list(eqPrefix, listOpts)) {\n const tail = entry.key.slice(eqPrefix.length);\n const firstSlash = tail.indexOf(\"/\");\n if (firstSlash < 0) {\n continue;\n } // defensive: malformed key\n const valueSeg = tail.slice(0, firstSlash);\n // Inclusive-lower in-loop skip (couldn't push to startAfter).\n if (loEncoded !== undefined && valueSeg < loEncoded) {\n continue;\n }\n // Upper-bound break — lex-ascending enumeration, so once we\n // pass the upper bound we're done.\n if (hiEncoded !== undefined) {\n if (r.hiInclusive ? valueSeg > hiEncoded : valueSeg >= hiEncoded) {\n break;\n }\n }\n // Decode the doc-id from the LAST `/`-separated segment of\n // the tail. Single-field walk → tail is `<valueSeg>/<docId>.json`\n // and the LAST segment is `<docId>.json`. Composite walk with\n // tail extension → tail is `<valueSeg>/...moreSegs/<docId>.json`\n // and the LAST segment is still `<docId>.json`.\n const lastSlash = tail.lastIndexOf(\"/\");\n const last =\n lastSlash === firstSlash ? tail.slice(firstSlash + 1) : tail.slice(lastSlash + 1);\n if (!last.endsWith(\".json\")) {\n continue;\n }\n const docId = last.slice(0, -\".json\".length);\n if (docId.length === 0) {\n continue;\n }\n docIdSet.add(docId);\n }\n } else if (plan.inOn !== undefined) {\n // `$in` multi-walk: dispatch up to IN_FANOUT_PARALLELISM `list()` calls\n // in parallel per batch. Union of doc-ids across all values; per-value\n // walks are independent so batching is sound. The planner has already\n // vetted the total fan-out (≤ IN_FANOUT_THRESHOLD); the encoder is\n // value-order-preserving across every supported type, so numeric\n // members route the same as strings.\n //\n // Cancellation note: `Promise.all` rejects on the first rejection but\n // does NOT cancel the other in-flight `list()` calls — the `Storage`\n // contract doesn't promise mid-stream cancellation. Storage errors\n // are rare; tightening this is out of scope.\n const values = plan.inOn.values;\n const walkOne = async (value: DocumentValue): Promise<string[]> => {\n const valPrefix = `${eqPrefix}${encodeIndexValue(value)}/`;\n const ids: string[] = [];\n for await (const entry of ctx.storage.list(valPrefix)) {\n const tail = entry.key.slice(valPrefix.length);\n if (!tail.endsWith(\".json\")) {\n continue;\n }\n const lastSlash = tail.lastIndexOf(\"/\");\n const docId =\n lastSlash === -1\n ? tail.slice(0, -\".json\".length)\n : tail.slice(lastSlash + 1, -\".json\".length);\n if (docId.length === 0) {\n continue;\n }\n ids.push(docId);\n }\n return ids;\n };\n for (let i = 0; i < values.length; i += IN_FANOUT_PARALLELISM) {\n const batch = values.slice(i, i + IN_FANOUT_PARALLELISM);\n const results = await Promise.all(batch.map(walkOne));\n for (const ids of results) {\n for (const id of ids) {\n docIdSet.add(id);\n }\n }\n }\n } else {\n // Equality-only walk (T2 path).\n for await (const entry of ctx.storage.list(eqPrefix)) {\n const tail = entry.key.slice(eqPrefix.length);\n if (!tail.endsWith(\".json\")) {\n continue;\n }\n const lastSlash = tail.lastIndexOf(\"/\");\n const docId =\n lastSlash === -1\n ? tail.slice(0, -\".json\".length)\n : tail.slice(lastSlash + 1, -\".json\".length);\n if (docId.length === 0) {\n continue;\n }\n docIdSet.add(docId);\n }\n }\n const docIds = Array.from(docIdSet);\n if (docIds.length === 0) {\n return [];\n }\n\n // 2. Resolve each docId by folding `(snapshot, log)` scoped to the\n // matched set. Same fold the table-scan path uses, scoped to\n // one Set<docId>.\n const matched = new Set(docIds);\n const baseDocs: Map<string, DocumentData> =\n head.snapshot === null\n ? new Map()\n : await loadSnapshotAsMap(ctx.storage, head.snapshot, ctx.collectionName);\n const docs = new Map<string, T>();\n for (const id of matched) {\n const seeded = baseDocs.get(id);\n if (seeded !== undefined) {\n docs.set(id, seeded as T);\n }\n }\n const logSeqStart = logSeqStartOf(head);\n const nextSeq = head.next_seq;\n const entries = await walkLogRange(ctx.storage, ctx.collectionPrefix, logSeqStart, nextSeq);\n foldLogEntriesOnto(docs, entries, { collection: ctx.collectionName, docIdFilter: matched });\n\n // 3. Apply the FULL original wire as the stale-row defence, then\n // the planner's residue postFilter on top. `matchesWire` is\n // open-world, so applying the full original wire (which the\n // planner partly consumed) is the simpler invariant: if the\n // doc still passes the original wire, it stays. Range / `in`\n // clauses that landed in `plan.postFilter` are part of\n // `state.wire` — they pass through here automatically.\n const rows: T[] = [];\n const wire = state.wire;\n for (const doc of docs.values()) {\n if (wire === undefined || matchesWire(wire, doc)) {\n rows.push(doc);\n }\n }\n return rows;\n};\n\n/**\n * Stable multi-key sort built from an `OrderSpec`. Keys are taken in\n * the spec's insertion order, which matches the caller's source-order\n * expectation. `Array.prototype.sort` is stable on Node 24+ and Workerd.\n *\n * Top-level fields only (locked at `OrderSpec<T>`).\n * Values are `DocumentValue` — string / number / boolean / object —\n * but only the primitive types are sensibly orderable; comparing two\n * objects falls through to \"considered equal,\" which preserves the\n * stable-sort order of the input.\n */\nconst sortByOrderSpec = <T extends DocumentData>(rows: T[], spec: OrderSpec<T>): T[] => {\n const entries = Object.entries(spec) as Array<[keyof T, \"asc\" | \"desc\"]>;\n return rows.toSorted((a, b) => {\n for (const [field, dir] of entries) {\n const av: T[keyof T] | undefined = a[field];\n const bv: T[keyof T] | undefined = b[field];\n if (av === bv) {\n continue;\n }\n // `undefined` (missing field) sorts low under asc / high under\n // desc — same shape SQL's `NULLS FIRST` gives on asc.\n if (av === undefined) {\n return dir === \"desc\" ? 1 : -1;\n }\n if (bv === undefined) {\n return dir === \"desc\" ? -1 : 1;\n }\n // string / number / boolean compare uniformly under `<`. Booleans\n // compare false < true (JS default). Object values fall through\n // as \"considered equal\" — see JSDoc above.\n if (typeof av === \"object\" || typeof bv === \"object\") {\n continue;\n }\n const cmp = av < bv ? -1 : 1;\n return dir === \"desc\" ? -cmp : cmp;\n }\n return 0;\n });\n};\n"],"mappings":";;;;;;AA8BA,MAAM,iBAAiB,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;;;;;;;;;AAYrE,SAAgB,MACd,QACA,OACe;CACf,IAAI,UAAU,KAAA,GACZ,OAAO;CAET,IAAI,UAAU,MACZ;CAIF,IAAI,CAAC,cAAc,KAAsB,GACvC,OAAO;CAGT,IAAI,CAAC,cAAc,MAAM,GACvB,OAAO;CAGT,MAAM,WAAW,EAAE,GAAI,OAAwB;CAC/C,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GAAsC;EAKvE,IAAI,qBAAqB,IAAI,GAAG,GAC9B;EAEF,IAAI,MAAM,SAAS,MACjB,OAAO,SAAS;OAEhB,SAAS,OAAO,MAAM,OAAO,MAAuB,MAAM,IAAqB;CAKnF;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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