@gusto/baerly-storage 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +157 -92
  2. package/dist/API.md +64 -32
  3. package/dist/CHANGELOG.md +295 -5
  4. package/dist/RECIPES.md +125 -0
  5. package/dist/THIRD-PARTY-LICENSES.txt +22 -96
  6. package/dist/{app-config-BIzyAKzy.d.ts → app-config-DyiFK3_k.d.ts} +43 -11
  7. package/dist/app-config.d.ts +1 -1
  8. package/dist/auth.d.ts +1 -1
  9. package/dist/auth.js +13 -13
  10. package/dist/auth.js.map +1 -1
  11. package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
  12. package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
  13. package/dist/baerly.js +35 -15
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +342 -0
  16. package/dist/{client-BJXF3XJA.d.ts → client-Fe8CwB73.d.ts} +3 -3
  17. package/dist/client-react.d.ts +3 -3
  18. package/dist/client-react.js +4 -4
  19. package/dist/client-react.js.map +1 -1
  20. package/dist/client.d.ts +4 -4
  21. package/dist/client.js +3 -3
  22. package/dist/{cloudflare-Cn2ibODt.js → cloudflare-DzKBrUlg.js} +2 -2
  23. package/dist/{cloudflare-Cn2ibODt.js.map → cloudflare-DzKBrUlg.js.map} +1 -1
  24. package/dist/cloudflare.d.ts +49 -6
  25. package/dist/cloudflare.js +55 -21
  26. package/dist/cloudflare.js.map +1 -1
  27. package/dist/config-1tv0-Yzm.js +2693 -0
  28. package/dist/config-1tv0-Yzm.js.map +1 -0
  29. package/dist/constants-CfeMWQWk.js +222 -0
  30. package/dist/constants-CfeMWQWk.js.map +1 -0
  31. package/dist/{cost-BZ_MDBmn.js → cost-DSMIVqzL.js} +42 -43
  32. package/dist/cost-DSMIVqzL.js.map +1 -0
  33. package/dist/{current-json-DsN7FNY1.js → current-json-C6nhPOm1.js} +6 -204
  34. package/dist/current-json-C6nhPOm1.js.map +1 -0
  35. package/dist/{db-CCT6tDfY.d.ts → db-DsPkOVEH.d.ts} +3 -3
  36. package/dist/{deploy-BKKyGlSJ.js → deploy-DonTr-CV.js} +4 -4
  37. package/dist/{deploy-BKKyGlSJ.js.map → deploy-DonTr-CV.js.map} +1 -1
  38. package/dist/dev-vite.d.ts +9 -5
  39. package/dist/dev-vite.js +5 -4
  40. package/dist/dev-vite.js.map +1 -1
  41. package/dist/dev.d.ts +1 -1
  42. package/dist/dev.js +1 -1
  43. package/dist/{doctor-BVU4GNXN.js → doctor-DSIyCDg_.js} +5 -8
  44. package/dist/{doctor-BVU4GNXN.js.map → doctor-DSIyCDg_.js.map} +1 -1
  45. package/dist/{dump-DPEAKub6.js → dump-Bh5k26VQ.js} +9 -32
  46. package/dist/dump-Bh5k26VQ.js.map +1 -0
  47. package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
  48. package/dist/errors-Dfa3p78c.js.map +1 -0
  49. package/dist/{export-BcuCLFFe.js → export-DtF5tDIM.js} +9 -32
  50. package/dist/{export-BcuCLFFe.js.map → export-DtF5tDIM.js.map} +1 -1
  51. package/dist/{fsck-RXgLOaJG.js → fsck-D_djMO5D.js} +10 -33
  52. package/dist/fsck-D_djMO5D.js.map +1 -0
  53. package/dist/{http-Bd4byR4n.js → http-DxM9MflO.js} +123 -35
  54. package/dist/http-DxM9MflO.js.map +1 -0
  55. package/dist/http.d.ts +42 -26
  56. package/dist/http.js +3 -2
  57. package/dist/{index-DnBGSeuU.d.ts → index-0rZcMBwy.d.ts} +2 -2
  58. package/dist/{index-Cmsxx-ZN.d.ts → index-B6oexfOB.d.ts} +7 -7
  59. package/dist/{index-BDceQQi-.d.ts → index-BNRh23K9.d.ts} +4 -4
  60. package/dist/{index-DW7GT6M2.d.ts → index-BYk9oCNf.d.ts} +193 -163
  61. package/dist/index.d.ts +6 -6
  62. package/dist/index.js +4 -4
  63. package/dist/{indexes-Cx7uMXm0.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
  64. package/dist/{inspect-DhI49PSi.js → inspect-6WZ-pC7-.js} +10 -33
  65. package/dist/inspect-6WZ-pC7-.js.map +1 -0
  66. package/dist/key-Di6yyxFu.js +35 -0
  67. package/dist/key-Di6yyxFu.js.map +1 -0
  68. package/dist/{log-tail-DXeDkWEp.js → log-tail-D98U1JBo.js} +31 -7
  69. package/dist/log-tail-D98U1JBo.js.map +1 -0
  70. package/dist/{maintenance-CWBQpZ2y.js → maintenance-B4Dki6Ig.js} +77 -22
  71. package/dist/maintenance-B4Dki6Ig.js.map +1 -0
  72. package/dist/{maintenance-BkhUr72A.d.ts → maintenance-B_e0T99L.d.ts} +28 -5
  73. package/dist/{maintenance-C_KSkVjd.js → maintenance-C7coQp4c.js} +17 -16
  74. package/dist/maintenance-C7coQp4c.js.map +1 -0
  75. package/dist/maintenance.d.ts +3 -3
  76. package/dist/maintenance.js +3 -3
  77. package/dist/node.d.ts +168 -65
  78. package/dist/node.js +3 -2
  79. package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
  80. package/dist/normalize-rjnZLwS4.js.map +1 -0
  81. package/dist/{observability-BYd-RzEx.js → observability-wzs3-BL_.js} +233 -71
  82. package/dist/observability-wzs3-BL_.js.map +1 -0
  83. package/dist/observability.d.ts +2 -2
  84. package/dist/observability.js +1 -1
  85. package/dist/{plan-DIu_B6fy.js → plan-a7PJHBCy.js} +2 -2
  86. package/dist/{plan-DIu_B6fy.js.map → plan-a7PJHBCy.js.map} +1 -1
  87. package/dist/{query-sQNO5vU_.js → query-rAtXNQQB.js} +96 -207
  88. package/dist/query-rAtXNQQB.js.map +1 -0
  89. package/dist/{rebuild-index-DP4CqSSs.js → rebuild-index-BVzQSZlm.js} +9 -32
  90. package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
  91. package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
  92. package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
  93. package/dist/{restore-DpQYef6r.js → restore-R-4rbciV.js} +73 -100
  94. package/dist/restore-R-4rbciV.js.map +1 -0
  95. package/dist/runtime-spec-qL3_lTTU.js +391 -0
  96. package/dist/runtime-spec-qL3_lTTU.js.map +1 -0
  97. package/dist/s3-http-B-z8th6O.d.ts +60 -0
  98. package/dist/s3.d.ts +47 -0
  99. package/dist/s3.js +45 -0
  100. package/dist/s3.js.map +1 -0
  101. package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
  102. package/dist/shared-secret-DgEicd3x.js.map +1 -0
  103. package/dist/src-BG20LZs7.js +2271 -0
  104. package/dist/src-BG20LZs7.js.map +1 -0
  105. package/dist/{src-Db4-qVtM.js → src-CYHFDrKz.js} +51 -8
  106. package/dist/src-CYHFDrKz.js.map +1 -0
  107. package/dist/{src-CWpkSbvJ.js → src-DYZ4H1aF.js} +6 -5
  108. package/dist/src-DYZ4H1aF.js.map +1 -0
  109. package/dist/{subcommand-CP9NY2J4.js → subcommand-DoDA-K7d.js} +44 -6
  110. package/dist/subcommand-DoDA-K7d.js.map +1 -0
  111. package/dist/time-DUqvFMHq.js +119 -0
  112. package/dist/time-DUqvFMHq.js.map +1 -0
  113. package/dist/{usage-CTfDq9HR.js → usage-DBV1eQHC.js} +7 -22
  114. package/dist/usage-DBV1eQHC.js.map +1 -0
  115. package/dist/wire-izfGZDvr.js.map +1 -1
  116. package/package.json +52 -28
  117. package/dist/config-CGyBopy3.js +0 -5326
  118. package/dist/config-CGyBopy3.js.map +0 -1
  119. package/dist/cost-BZ_MDBmn.js.map +0 -1
  120. package/dist/current-json-DsN7FNY1.js.map +0 -1
  121. package/dist/dump-DPEAKub6.js.map +0 -1
  122. package/dist/errors-DOdL95kK.js.map +0 -1
  123. package/dist/fsck-RXgLOaJG.js.map +0 -1
  124. package/dist/http-Bd4byR4n.js.map +0 -1
  125. package/dist/inspect-DhI49PSi.js.map +0 -1
  126. package/dist/log-tail-DXeDkWEp.js.map +0 -1
  127. package/dist/maintenance-CWBQpZ2y.js.map +0 -1
  128. package/dist/maintenance-C_KSkVjd.js.map +0 -1
  129. package/dist/normalize-XWY25_sG.js.map +0 -1
  130. package/dist/observability-BYd-RzEx.js.map +0 -1
  131. package/dist/query-sQNO5vU_.js.map +0 -1
  132. package/dist/rebuild-index-DP4CqSSs.js.map +0 -1
  133. package/dist/restore-DpQYef6r.js.map +0 -1
  134. package/dist/shared-secret-BJdSwpgw.js.map +0 -1
  135. package/dist/src-CWpkSbvJ.js.map +0 -1
  136. package/dist/src-D24wDpzR.js +0 -6247
  137. package/dist/src-D24wDpzR.js.map +0 -1
  138. package/dist/src-Db4-qVtM.js.map +0 -1
  139. package/dist/subcommand-CP9NY2J4.js.map +0 -1
  140. package/dist/usage-CTfDq9HR.js.map +0 -1
  141. /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"maintenance-B4Dki6Ig.js","names":["ctxMetrics","APPLICATION_JSON","ctxMetrics"],"sources":["../packages/protocol/src/coordination/gc-pending.ts","../packages/protocol/src/query/_internals.ts","../packages/protocol/src/query/matches.ts","../packages/protocol/src/query/satisfiable.ts","../packages/protocol/src/query/validate.ts","../packages/protocol/src/hashing.ts","../packages/protocol/src/log-key.ts","../packages/protocol/src/snapshot-hash.ts","../packages/server/src/log-tail.ts","../packages/server/src/names.ts","../packages/server/src/snapshot.ts","../packages/server/src/indexes.ts","../packages/server/src/log-walk.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 {\n GC_PENDING_CAS_MAX_ATTEMPTS,\n GC_PENDING_CONTENT_TYPE,\n GC_PENDING_SCHEMA_VERSION,\n} 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 * Rotation cursor for `runGc`'s orphan-content LIST — the last\n * content key examined last pass. Successive bounded passes resume\n * `startAfter` this so the whole `content/` keyspace is swept over a\n * rotation, within the per-pass `maxMarksPerRun` budget. Absent /\n * reset to `undefined` ⇒ start from the lexicographic beginning\n * (wrap).\n *\n * Optional + additive: a v1 `gc/pending.json` written before this\n * field existed stays valid — absent means \"start from the\n * beginning\", so {@link GC_PENDING_SCHEMA_VERSION} is NOT bumped.\n */\n content_scan_cursor?: 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, with a bounded retry\n * loop. Each attempt re-reads the latest body, hands the `mutator`\n * that latest value, and writes the result with\n * `If-Match: <latest etag>`. On `Conflict` (a concurrent writer landed\n * between this attempt's read and write) the loop re-reads and\n * re-applies the mutator, up to {@link GC_PENDING_CAS_MAX_ATTEMPTS}\n * total attempts, then surfaces `Conflict`.\n *\n * `mutator` MUST be a pure, deterministic MERGE of this pass's results\n * INTO the `latest` value it is handed — it is called once per attempt\n * (so it must not have side effects), and it MUST read `latest` rather\n * than ignore it and write a precomputed set. Ignoring `latest` would\n * silently overwrite a concurrent pass's candidates: the\n * If-Match succeeds (it used the fresh etag), so no conflict is\n * raised, and the concurrent marks are lost. See {@link mergeGcPending}.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer kept landing a\n * write between this function's read and write for every\n * attempt.\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: (latest: GcPending) => GcPending,\n opts?: { signal?: AbortSignal },\n): Promise<GcPendingRead> => {\n let lastConflict: BaerlyError | undefined;\n for (let attempt = 0; attempt < GC_PENDING_CAS_MAX_ATTEMPTS; attempt++) {\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 try {\n const result = await storage.put(key, body, putOpts);\n return { json: next, etag: result.etag };\n } catch (error) {\n const translated = translateCasError(error, key);\n // Only `Conflict` is retryable — re-read latest and re-merge.\n // Anything else (AccessDenied, InvalidResponse, …) is terminal.\n if (translated.code !== \"Conflict\") {\n throw translated;\n }\n lastConflict = translated;\n }\n }\n // Exhausted the retry budget — surface the last conflict.\n throw lastConflict;\n};\n\n/**\n * Pure merge of one GC pass's results INTO the `latest`\n * `gc/pending.json` value, used as the {@link casUpdateGcPending}\n * mutator. Deterministic, no I/O — the kernel unit + mutation test\n * surface. Splitting it out is what makes the CAS write correct under\n * concurrency: each retry re-merges against fresh `latest` rather than\n * overwriting it with a stale precomputed set.\n *\n * Semantics:\n * - **candidates**: start from `latest.candidates`, DROP any whose key\n * this pass already DELETED (`sweptKeys`), then APPEND every fresh\n * mark whose key is not already present AND was not itself swept\n * this pass (a `graceMillis: 0` pass can mark-and-sweep a key in one\n * go — re-adding it to the ledger after deleting it would be wrong;\n * dedup also drops a key a concurrent pass already marked). Capped at\n * `maxCandidates`.\n * - **last_swept_at**: the lexicographically LATER of `latest`'s and\n * this pass's (ISO-8601 UTC; `\"\"` sorts lowest so a real timestamp\n * always wins). Never regress a concurrent pass's newer sweep time.\n * - **content_scan_cursor**: rotation cursor — liveness, not\n * correctness; just don't regress forward progress. The two sides\n * are NOT symmetric: `pass.nextContentCursor === undefined` means\n * THIS pass examined to the END of the keyspace (WRAP — the most-\n * advanced position), whereas `latest.content_scan_cursor` absent\n * means the stored ledger has no cursor yet (start-from-beginning).\n * So:\n * - our pass WRAPPED ⇒ result wraps (key omitted) — our pass is\n * the most advanced; this is the single-writer rotation reset.\n * - else (our pass advanced to a defined cursor):\n * - latest cursor defined ⇒ take the lexicographically GREATER\n * (don't regress a concurrent pass's advance);\n * - latest cursor absent ⇒ keep OUR advance (don't lose it).\n */\nexport const mergeGcPending = (\n latest: GcPending,\n pass: {\n readonly sweptKeys: ReadonlySet<string>;\n readonly newCandidates: ReadonlyArray<GcCandidate>;\n readonly lastSweptAt: string;\n readonly nextContentCursor: string | undefined;\n readonly maxCandidates: number;\n },\n): GcPending => {\n const surviving = latest.candidates.filter((c) => !pass.sweptKeys.has(c.key));\n const present = new Set(surviving.map((c) => c.key));\n const appended: GcCandidate[] = [];\n for (const c of pass.newCandidates) {\n // Skip keys this pass already swept (mark-and-sweep in one pass)\n // and keys already in the surviving ledger (dedup vs. a concurrent\n // pass's mark).\n if (!pass.sweptKeys.has(c.key) && !present.has(c.key)) {\n present.add(c.key);\n appended.push(c);\n }\n }\n const candidates = [...surviving, ...appended].slice(0, pass.maxCandidates);\n\n const lastSweptAt =\n pass.lastSweptAt > latest.last_swept_at ? pass.lastSweptAt : latest.last_swept_at;\n\n // Cursor (asymmetric — see JSDoc): our-pass-undefined = WRAP (the\n // most-advanced); latest-absent = no cursor yet (least-advanced).\n // Our wrap wins (single-writer rotation reset). Otherwise our pass\n // advanced: take the greater vs. a defined latest (don't regress a\n // concurrent advance), else keep our advance.\n const latestCursor = latest.content_scan_cursor;\n const passCursor = pass.nextContentCursor;\n let cursor: string | undefined;\n if (passCursor === undefined) {\n cursor = undefined;\n } else if (latestCursor !== undefined) {\n cursor = passCursor > latestCursor ? passCursor : latestCursor;\n } else {\n cursor = passCursor;\n }\n\n return {\n schema_version: GC_PENDING_SCHEMA_VERSION,\n candidates,\n last_swept_at: lastSweptAt,\n ...(cursor !== undefined && { content_scan_cursor: cursor }),\n };\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 // Stryker disable next-line ConditionalExpression: typeof guard is a short-circuit optimization; !VALID_REASONS.has() alone rejects all non-string and invalid-string values, so → false on typeof is genuinely equivalent\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 // Optional + additive: absent is valid (⇒ scan starts from the\n // lexicographic beginning). If present it must be a string.\n if (r[\"content_scan_cursor\"] !== undefined && typeof r[\"content_scan_cursor\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json at ${key}: content_scan_cursor must be a string when present`,\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","/**\n * Shared helpers for the predicate algebras in `./validate.ts`,\n * `./matches.ts`, and `./merge.ts`. These exist as a single module\n * because more than one of those files uses them and duplicating\n * the implementations would drift over time.\n *\n * Only {@link deepEqualDocumentValue} is part of the public surface;\n * the comparator primitives (`compareScalar`, `sameComparableType`,\n * `formatPath`) are internal to the protocol package and imported\n * by `./validate.ts` / `./merge.ts` / `./normalize.ts` directly.\n */\n\nimport type { DocumentValue } from \"../json.ts\";\n\n/** @internal Same primitive type for comparison purposes. */\nexport const sameComparableType = (a: DocumentValue, b: DocumentValue): boolean =>\n (typeof a === \"string\" && typeof b === \"string\") ||\n (typeof a === \"number\" && typeof b === \"number\");\n\n/**\n * @internal Returns negative / zero / positive for a<b / a==b / a>b.\n */\nexport const compareScalar = (a: DocumentValue, b: DocumentValue): number => {\n if (typeof a === \"number\" && typeof b === \"number\") {\n return a - b;\n }\n if (typeof a === \"string\" && typeof b === \"string\") {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n }\n return 0;\n};\n\n/** @internal Render a predicate path for use in error messages. */\nexport const formatPath = (path: ReadonlyArray<string>): string =>\n path.length === 0 ? \"<root>\" : path.map((p) => JSON.stringify(p)).join(\".\");\n\n/**\n * Recursive structural equality for `DocumentValue` values. Lifted to\n * `export` so the filtered-index implication checker (in\n * `@baerly/server`'s query planner) and other callers can reuse the\n * same comparison rule the validator + merger already trust. Two\n * values `a` and `b` are equal iff:\n *\n * - they are reference-equal (covers primitives and object identity);\n * - or they are both non-`null` objects with the same key set, and\n * every value pair is recursively equal.\n *\n * Arrays are out-of-band for `DocumentValue`; this function rejects\n * them implicitly via the same key-set walk (an array reads as an\n * object with numeric-string keys plus a `length` exposure that\n * `Object.keys` happens to skip — defensive callers should still gate\n * with `Array.isArray` first).\n */\nexport const deepEqualDocumentValue = (a: DocumentValue, b: DocumentValue): boolean => {\n if (a === b) {\n return true;\n } // primitives + object identity\n if (typeof a !== \"object\" || typeof b !== \"object\") {\n return false;\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n for (const key of aKeys) {\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — a key in aKeys but absent from b makes b[key] undefined, which the `aSub === undefined || bSub === undefined` guard below catches identically; no input observes the difference.\n if (!(key in b)) {\n return false;\n }\n const aSub = (a as Record<string, DocumentValue>)[key];\n const bSub = (b as Record<string, DocumentValue>)[key];\n // Stryker disable next-line LogicalOperator,ConditionalExpression: equivalent — this guard is a redundant fast-path. Whichever way it is mutated (operator `||`→`&&`, or either `=== undefined` operand forced to false), a slot that is undefined still flows into deepEqualDocumentValue below, whose typeof check returns false for `(undefined, defined)`; the only case that reaches `true` is both-undefined, which the surviving sibling operand still catches. No input over 500k randomized DocumentValues observes a difference.\n if (aSub === undefined || bSub === undefined) {\n return false;\n }\n if (!deepEqualDocumentValue(aSub, bSub)) {\n return false;\n }\n }\n return true;\n};\n","/**\n * Wire predicate evaluator. Walks a validated {@link PredicateWire}\n * against a `JSONObject` document and returns `true` iff every\n * clause holds. Multiple clauses across all fields AND together.\n *\n * Pre-condition: `wire` must have been returned by\n * {@link validateWire} (see `./validate.ts`). Passing an\n * un-validated wire is a caller bug; behaviour is undefined.\n *\n * Companion modules: `./validate.ts` (construction-time check),\n * `./merge.ts` (AND-merge), `./wire.ts` (types).\n */\n\nimport type { DocumentValue, JSONObject, JSONValue } from \"../json.ts\";\n\nimport type { PredicateClause, PredicateWire } from \"./wire.ts\";\n\n/**\n * Evaluate a validated wire-form predicate against a `JSONObject`\n * document. Returns `true` iff every clause holds.\n *\n * @example\n * ```ts\n * matchesWire(\n * { clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] },\n * { status: \"open\", priority: \"p1\" },\n * ); // true\n *\n * matchesWire(\n * { clauses: [{ op: \"in\", field: \"priority\", value: [\"p1\", \"p2\"] }] },\n * { priority: \"p3\" },\n * ); // false\n *\n * matchesWire(\n * {\n * clauses: [\n * { op: \"gte\", field: \"count\", value: 1 },\n * { op: \"lt\", field: \"count\", value: 10 },\n * ],\n * },\n * { count: 5 },\n * ); // true\n * ```\n */\nexport const matchesWire = (wire: PredicateWire, doc: JSONObject): boolean => {\n for (const clause of wire.clauses) {\n const actual = lookupPath(doc, clause.field);\n if (!matchesClause(clause, actual)) {\n return false;\n }\n }\n return true;\n};\n\nconst lookupPath = (doc: JSONObject, field: string): JSONValue | undefined => {\n // Fast path: no dot → top-level lookup. Avoids allocating a split\n // array for the common case.\n // Stryker disable next-line StringLiteral,BlockStatement,ConditionalExpression: fast-path equivalence — for any valid field, the slow split-and-traverse path produces the same result; the fast path is a performance optimisation only\n if (!field.includes(\".\")) {\n return doc[field];\n }\n const segments = field.split(\".\");\n let cursor: JSONValue | undefined = doc;\n for (const segment of segments) {\n if (\n // Stryker disable next-line ConditionalExpression: redundant guard — cursor===undefined is always caught by the typeof check on the next line (typeof undefined!==\"object\" is true); removing this check is observationally equivalent\n cursor === undefined ||\n cursor === null ||\n // Stryker disable next-line ConditionalExpression: redundant guard — for non-object primitives, (primitive as JSONObject)[segment] returns undefined; the next iteration's cursor===undefined check catches it; removing this check produces the same return value\n typeof cursor !== \"object\" ||\n Array.isArray(cursor)\n ) {\n // Traversal hit a primitive, null, missing key, or array\n // before consuming the path. Predicate cannot match.\n return undefined;\n }\n cursor = (cursor as JSONObject)[segment];\n }\n return cursor;\n};\n\nconst matchesClause = (clause: PredicateClause, actual: JSONValue | undefined): boolean => {\n switch (clause.op) {\n case \"eq\": {\n return matchesEq(clause.value as DocumentValue, actual);\n }\n case \"in\": {\n return matchesIn(clause.value as ReadonlyArray<DocumentValue>, actual);\n }\n case \"gt\": {\n return compareGT(actual, clause.value as DocumentValue, false);\n }\n case \"gte\": {\n return compareGT(actual, clause.value as DocumentValue, true);\n }\n case \"lt\": {\n return compareLT(actual, clause.value as DocumentValue, false);\n }\n case \"lte\": {\n return compareLT(actual, clause.value as DocumentValue, true);\n }\n }\n};\n\nconst matchesEq = (expected: DocumentValue, actual: JSONValue | undefined): boolean => {\n if (typeof expected === \"object\") {\n // Nested object equality is a sub-predicate match — open-world:\n // doc may carry extra keys. The object-form normaliser flattens\n // nested sub-predicates to dotted-path clauses on the way in, so\n // the only callers reaching this branch are callback-form\n // `q.eq(\"nested\", { ... })`.\n if (\n // Stryker disable next-line ConditionalExpression: redundant guard — actual===undefined is caught by the typeof check below (typeof undefined!==\"object\" is true); removing this check produces the same false result\n actual === undefined ||\n actual === null ||\n typeof actual !== \"object\" ||\n Array.isArray(actual)\n ) {\n return false;\n }\n for (const subKey of Object.keys(expected)) {\n const subExpected = (expected as Record<string, DocumentValue>)[subKey];\n if (subExpected === undefined) {\n continue;\n }\n const subActual = (actual as JSONObject)[subKey];\n if (!matchesEq(subExpected, subActual)) {\n return false;\n }\n }\n return true;\n }\n return expected === actual;\n};\n\nconst matchesIn = (\n members: ReadonlyArray<DocumentValue>,\n actual: JSONValue | undefined,\n): boolean => {\n for (const m of members) {\n // Stryker disable next-line ConditionalExpression: equivalence — for non-null primitives, matchesEq(m, actual) reduces to `m === actual` (the typeof check fails); routing all members through matchesEq (→true) gives the same result as the two-branch structure\n if (typeof m === \"object\") {\n if (matchesEq(m, actual)) {\n return true;\n }\n } else if (m === actual) {\n return true;\n }\n }\n return false;\n};\n\nconst compareGT = (\n actual: JSONValue | undefined,\n bound: DocumentValue,\n inclusive: boolean,\n): boolean => {\n if (typeof bound === \"string\") {\n return typeof actual === \"string\" && (inclusive ? actual >= bound : actual > bound);\n }\n if (typeof bound === \"number\") {\n return typeof actual === \"number\" && (inclusive ? actual >= bound : actual > bound);\n }\n // Validator forbids boolean / null / object range bounds; defensive miss.\n return false;\n};\n\nconst compareLT = (\n actual: JSONValue | undefined,\n bound: DocumentValue,\n inclusive: boolean,\n): boolean => {\n if (typeof bound === \"string\") {\n return typeof actual === \"string\" && (inclusive ? actual <= bound : actual < bound);\n }\n if (typeof bound === \"number\") {\n return typeof actual === \"number\" && (inclusive ? actual <= bound : actual < bound);\n }\n return false;\n};\n","/**\n * Per-field satisfiability check for a {@link PredicateWire}. Groups\n * clauses by field, then runs the same logic the pre-redesign\n * `assertOpObjectSatisfiable` ran on a single op-object — but\n * generalised across N clauses on the same field (the wire merger\n * concatenates lists without coalescing).\n *\n * Triggers:\n * - Two `eq` clauses on the same field with different values →\n * `InvalidConfig` (the same conflict that pre-redesign\n * `mergePredicates` threw on shared primitive keys).\n * - Range bounds with `lo > hi` (or `lo == hi` with strict on\n * either side) → `UnsatisfiablePredicate`.\n * - `eq` value outside the residual range interval or absent from\n * every `in` set on the same field → `UnsatisfiablePredicate`.\n * - `in` sets that intersect to empty across multiple clauses →\n * `UnsatisfiablePredicate`.\n *\n * Used by both `./validate.ts` (wire-arrival check) and\n * `./merge.ts` (post-merge re-check, kept in lockstep).\n */\n\nimport { BaerlyError } from \"../errors.ts\";\nimport type { DocumentValue } from \"../json.ts\";\n\nimport {\n compareScalar,\n deepEqualDocumentValue,\n formatPath,\n sameComparableType,\n} from \"./_internals.ts\";\nimport type { PredicateClause, PredicateWire } from \"./wire.ts\";\n\ninterface FieldGroup {\n readonly eqs: DocumentValue[];\n readonly ins: ReadonlyArray<DocumentValue>[];\n lo?: { value: DocumentValue; inclusive: boolean };\n hi?: { value: DocumentValue; inclusive: boolean };\n}\n\nconst groupByField = (wire: PredicateWire): Map<string, FieldGroup> => {\n const out = new Map<string, FieldGroup>();\n for (const clause of wire.clauses) {\n let group = out.get(clause.field);\n if (group === undefined) {\n group = { eqs: [], ins: [] };\n out.set(clause.field, group);\n }\n applyClause(group, clause.field, clause);\n }\n return out;\n};\n\nconst applyClause = (group: FieldGroup, field: string, clause: PredicateClause): void => {\n switch (clause.op) {\n case \"eq\": {\n group.eqs.push(clause.value as DocumentValue);\n return;\n }\n case \"in\": {\n group.ins.push(clause.value as ReadonlyArray<DocumentValue>);\n return;\n }\n case \"gt\": {\n tightenLower(group, field, clause.value as DocumentValue, false);\n return;\n }\n case \"gte\": {\n tightenLower(group, field, clause.value as DocumentValue, true);\n return;\n }\n case \"lt\": {\n tightenUpper(group, field, clause.value as DocumentValue, false);\n return;\n }\n case \"lte\": {\n tightenUpper(group, field, clause.value as DocumentValue, true);\n return;\n }\n }\n};\n\nconst tightenLower = (\n group: FieldGroup,\n field: string,\n value: DocumentValue,\n inclusive: boolean,\n): void => {\n if (group.lo === undefined) {\n group.lo = { value, inclusive };\n return;\n }\n if (!sameComparableType(group.lo.value, value)) {\n // Type-incompatible bounds on the same field — the user wrote\n // (say) `q.gt(\"x\", 1).gt(\"x\", \"a\")`. Range matching is type-\n // strict at evaluation time so this is always-miss; surface\n // eagerly as `UnsatisfiablePredicate`.\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has type-incompatible lower bounds (${JSON.stringify(group.lo.value)} vs ${JSON.stringify(value)}).`,\n );\n }\n const c = compareScalar(group.lo.value, value);\n // Stryker disable next-line ConditionalExpression: two sub-expression-to-true mutants are\n // equivalent. (1) `inclusive === false → true`: fires when c=0, existing=inclusive,\n // new=inclusive — tighten updates lo to {value, inclusive=true}, identical to the existing\n // {same value, inclusive=true}; no observable change. (2) `group.lo.inclusive === true → true`:\n // fires when c=0, new=exclusive, existing=exclusive — tighten updates lo to {value, false},\n // identical to existing {same value, false}; no observable change.\n if (c < 0 || (c === 0 && inclusive === false && group.lo.inclusive === true)) {\n group.lo = { value, inclusive };\n }\n};\n\nconst tightenUpper = (\n group: FieldGroup,\n field: string,\n value: DocumentValue,\n inclusive: boolean,\n): void => {\n if (group.hi === undefined) {\n group.hi = { value, inclusive };\n return;\n }\n if (!sameComparableType(group.hi.value, value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has type-incompatible upper bounds (${JSON.stringify(group.hi.value)} vs ${JSON.stringify(value)}).`,\n );\n }\n const c = compareScalar(group.hi.value, value);\n // Stryker disable next-line ConditionalExpression: two sub-expression-to-true mutants are\n // equivalent. (1) `inclusive === false → true`: fires when c=0, existing=inclusive,\n // new=inclusive — tighten updates hi to {value, inclusive=true}, same as existing; no change.\n // (2) `group.hi.inclusive === true → true`: fires when c=0, new=exclusive, existing=exclusive —\n // tighten updates hi to {value, false}, same as existing; no observable change.\n if (c > 0 || (c === 0 && inclusive === false && group.hi.inclusive === true)) {\n group.hi = { value, inclusive };\n }\n};\n\nconst intersectInSets = (\n sets: ReadonlyArray<ReadonlyArray<DocumentValue>>,\n): ReadonlyArray<DocumentValue> => {\n // Stryker disable ConditionalExpression,BlockStatement,ArrayDeclaration: dead-code guard\n // — callers only invoke intersectInSets when group.ins.length > 1 (i.e., sets.length >= 2),\n // so sets.length === 0 is unreachable in production. Any mutation here is an equivalent mutant.\n if (sets.length === 0) {\n return [];\n }\n // Stryker restore ConditionalExpression,BlockStatement,ArrayDeclaration\n let acc: ReadonlyArray<DocumentValue> = sets[0]!;\n for (let i = 1; i < sets.length; i++) {\n const next: DocumentValue[] = [];\n for (const a of acc) {\n for (const b of sets[i]!) {\n if (deepEqualDocumentValue(a, b)) {\n next.push(a);\n break;\n }\n }\n }\n acc = next;\n }\n return acc;\n};\n\n/**\n * Check that every per-field clause group on `wire` is jointly\n * satisfiable. Throws `BaerlyError{code:\"UnsatisfiablePredicate\"}`\n * (or `\"InvalidConfig\"` for conflicting `eq` clauses) on the\n * first contradiction. Returns `void` on success.\n */\nexport const assertWireSatisfiable = (wire: PredicateWire): void => {\n const groups = groupByField(wire);\n for (const [field, group] of groups) {\n // Multiple `eq` clauses on the same field must agree.\n // Stryker disable next-line EqualityOperator,ConditionalExpression: equivalent — the inner\n // loop starts at i=1, so with 0 or 1 eqs the loop body never executes regardless of whether\n // we enter the outer if. `>= 1` enters with 1 eq (0 loop iterations); `true` enters with 0\n // eqs (0 loop iterations). Both are observationally identical to `> 1`.\n if (group.eqs.length > 1) {\n for (let i = 1; i < group.eqs.length; i++) {\n if (!deepEqualDocumentValue(group.eqs[0]!, group.eqs[i]!)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Conflicting equality clauses on field ${formatPath([field])} (${JSON.stringify(group.eqs[0]!)} vs ${JSON.stringify(group.eqs[i]!)}). Predicate chains must agree on shared equality.`,\n );\n }\n }\n }\n const eq = group.eqs[0];\n // Range interval must be non-empty.\n if (\n group.lo !== undefined &&\n group.hi !== undefined &&\n sameComparableType(group.lo.value, group.hi.value)\n ) {\n const c = compareScalar(group.lo.value, group.hi.value);\n if (c > 0 || (c === 0 && (!group.lo.inclusive || !group.hi.inclusive))) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has empty interval (lo=${JSON.stringify(group.lo.value)} ${group.lo.inclusive ? \"gte\" : \"gt\"}, hi=${JSON.stringify(group.hi.value)} ${group.hi.inclusive ? \"lte\" : \"lt\"}).`,\n );\n }\n }\n // `eq` outside the residual interval / membership set.\n if (eq !== undefined) {\n if (group.lo !== undefined) {\n if (!sameComparableType(eq, group.lo.value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} (${typeof eq}) is type-incompatible with lower bound ${JSON.stringify(group.lo.value)} (${typeof group.lo.value}); range ops require matching primitive types.`,\n );\n }\n const c = compareScalar(eq, group.lo.value);\n if (c < 0 || (c === 0 && !group.lo.inclusive)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} excluded by lower bound ${JSON.stringify(group.lo.value)} (${group.lo.inclusive ? \"gte\" : \"gt\"}).`,\n );\n }\n }\n if (group.hi !== undefined) {\n if (!sameComparableType(eq, group.hi.value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} (${typeof eq}) is type-incompatible with upper bound ${JSON.stringify(group.hi.value)} (${typeof group.hi.value}); range ops require matching primitive types.`,\n );\n }\n const c = compareScalar(eq, group.hi.value);\n if (c > 0 || (c === 0 && !group.hi.inclusive)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} excluded by upper bound ${JSON.stringify(group.hi.value)} (${group.hi.inclusive ? \"lte\" : \"lt\"}).`,\n );\n }\n }\n // Stryker disable next-line EqualityOperator,ConditionalExpression: equivalent — the for-of\n // loop over group.ins is a no-op when group.ins is empty, so `>= 0` (always true) and\n // `true` (always enter) produce identical behavior: zero iterations when ins is empty,\n // same iterations as `> 0` when ins is non-empty.\n if (group.ins.length > 0) {\n for (const set of group.ins) {\n let found = false;\n for (const m of set) {\n if (deepEqualDocumentValue(eq, m)) {\n found = true;\n break;\n }\n }\n if (!found) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} not present in in() set.`,\n );\n }\n }\n }\n }\n // Multiple `in` sets must intersect non-empty.\n // Stryker disable next-line EqualityOperator: equivalent — intersectInSets([single_set])\n // returns that set unchanged; since validateWire rejects empty in-arrays, the single set\n // is always non-empty, so isect.length === 0 is false and no throw occurs. `>= 1` (entering\n // with 1 in-set) behaves identically to `> 1` (skipping for 1 in-set).\n if (group.ins.length > 1) {\n const isect = intersectInSets(group.ins);\n if (isect.length === 0) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has empty in() intersection across multiple clauses.`,\n );\n }\n }\n }\n};\n","/**\n * Wire predicate validator. Walks a {@link PredicateWire} and throws\n * on a structurally bad clause (`BaerlyError{code:\"InvalidConfig\"}`)\n * or a per-field clause group that contradicts itself\n * (`BaerlyError{code:\"UnsatisfiablePredicate\"}`).\n *\n * The object-form normaliser at `./normalize.ts` enforces shape on\n * the way in (rejecting `$`-keys / non-scalars / null / undefined);\n * the callback builder at `./builder.ts` enforces shape via the\n * type system. This validator is the wire-arrival check: it runs\n * over already-normalised clauses, defending against raw-`fetch`\n * callers who bypass the typed seam and submit arbitrary JSON.\n *\n * Companion modules: `./matches.ts` (evaluator), `./merge.ts`\n * (AND-merge). Shared helpers live in `./_internals.ts`.\n */\n\nimport { BaerlyError } from \"../errors.ts\";\n\nimport { assertWireSatisfiable } from \"./satisfiable.ts\";\nimport type { PredicateClause, PredicateOpName, PredicateWire } from \"./wire.ts\";\n\nconst OP_NAMES: ReadonlyArray<PredicateOpName> = [\"eq\", \"gt\", \"gte\", \"lt\", \"lte\", \"in\"];\nconst RANGE_OPS: ReadonlyArray<PredicateOpName> = [\"gt\", \"gte\", \"lt\", \"lte\"];\n\n/**\n * Validate a normalised predicate wire. Throws\n * `BaerlyError{code:\"InvalidConfig\"}` on a structurally bad clause,\n * or `BaerlyError{code:\"UnsatisfiablePredicate\"}` when a clause\n * group on one field contradicts itself.\n *\n * Returns the wire unchanged on success — callers can thread the\n * validated wire forward.\n *\n * @example\n * ```ts\n * validateWire({ clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] }); // ok\n * validateWire({ clauses: [{ op: \"in\", field: \"priority\", value: [] }] }); // throws UnsatisfiablePredicate\n * validateWire({ clauses: [{ op: \"eq\", field: \"_id\", value: \"x\" }] }); // throws InvalidConfig (top-level _id)\n * ```\n */\nexport const validateWire = (wire: PredicateWire): PredicateWire => {\n if (\n wire === null ||\n typeof wire !== \"object\" ||\n !Array.isArray((wire as { clauses?: unknown }).clauses)\n ) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate wire must be an object with a \"clauses\" array.`,\n );\n }\n for (let i = 0; i < wire.clauses.length; i++) {\n validateClause(wire.clauses[i]!, i);\n }\n assertWireSatisfiable(wire);\n return wire;\n};\n\nconst validateClause = (clause: PredicateClause, index: number): void => {\n if (clause === null || typeof clause !== \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} must be an object — got ${JSON.stringify(clause)}.`,\n );\n }\n const { op, field, value } = clause;\n // Stryker disable next-line ConditionalExpression: `typeof op !== \"string\"` is redundant —\n // OP_NAMES contains only string literals; Array.prototype.includes uses SameValueZero\n // (effectively ===), so any non-string op is already rejected by the `!includes` half.\n // The early string-type check is a readability guard, not an observable branch.\n if (typeof op !== \"string\" || !(OP_NAMES as ReadonlyArray<string>).includes(op)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} has unsupported op ${JSON.stringify(op)} — supported: ${OP_NAMES.join(\" / \")}.`,\n );\n }\n if (typeof field !== \"string\" || field.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} has empty / non-string field.`,\n );\n }\n // Reject `_id` AND any nested `_id.<path>` — `Path<T>` excludes both\n // (`\"_id\" | \\`_id.${string}\\``), so a raw-wire caller (the threat this\n // validator names) must not slip a dotted `_id.x` past a check that\n // only matched the exact root field.\n if (field === \"_id\" || field.startsWith(\"_id.\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n 'Predicates may not key on \"_id\"; use .get(id) / .update(id, patch) / .replace(id, doc) / .delete(id) instead.',\n );\n }\n if (op === \"in\") {\n if (!Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} (op=\"in\", field=${JSON.stringify(field)}) must carry an array value.`,\n );\n }\n if (value.length === 0) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate clause at index ${index} (op=\"in\", field=${JSON.stringify(field)}) has empty value array — no document can match.`,\n );\n }\n for (let i = 0; i < value.length; i++) {\n validateMemberValue(value[i], field, index, i);\n }\n return;\n }\n if (Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} (op=${JSON.stringify(op)}, field=${JSON.stringify(field)}) must carry a primitive value, got an array — only op=\"in\" accepts arrays.`,\n );\n }\n if ((RANGE_OPS as ReadonlyArray<string>).includes(op)) {\n validateRangeBound(value, field, index);\n return;\n }\n validateScalar(value, field, index);\n};\n\nconst validateMemberValue = (\n value: unknown,\n field: string,\n clauseIndex: number,\n memberIndex: number,\n): void => {\n // Stryker disable next-line ConditionalExpression: `|| value === undefined` is redundant —\n // undefined falls through to `typeof value` = \"undefined\", which is caught by the\n // `t !== \"string\" && t !== \"number\" && t !== \"boolean\"` check below with the same\n // InvalidConfig code. The early check gives a more descriptive \"undefined\" message\n // but no input can distinguish the two code paths via the public error code alone.\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is ${value === null ? \"null\" : \"undefined\"} — members must be string / number / boolean / nested object.`,\n );\n }\n if (Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is an array — members must be string / number / boolean / nested object.`,\n );\n }\n const t = typeof value;\n if (t === \"object\") {\n return;\n }\n if (t !== \"string\" && t !== \"number\" && t !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n\nconst validateScalar = (value: unknown, field: string, clauseIndex: number): void => {\n // Stryker disable next-line ConditionalExpression: `|| value === undefined` is redundant —\n // undefined falls through to `typeof value` = \"undefined\", caught by the\n // `t !== \"string\" && t !== \"number\" && t !== \"boolean\"` check with the same code.\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value is ${value === null ? \"null\" : \"undefined\"} — terminal values must be string / number / boolean / nested object.`,\n );\n }\n const t = typeof value;\n if (t === \"object\") {\n // Equality clauses against nested objects survive only via callback\n // form (the normaliser flattens object-form sub-predicates to\n // dotted-path eq clauses). Keep the structural recursion light —\n // values are sealed from the typed seam.\n return;\n }\n if (t !== \"string\" && t !== \"number\" && t !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n\nconst validateRangeBound = (value: unknown, field: string, clauseIndex: number): void => {\n // Stryker disable next-line ConditionalExpression: `|| value === undefined` is redundant —\n // undefined falls through to `typeof value` = \"undefined\", caught by `t !== \"string\" && t !== \"number\"`\n // with the same InvalidConfig code.\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is ${value === null ? \"null\" : \"undefined\"} — range bounds must be string or finite number.`,\n );\n }\n const t = typeof value;\n if (t === \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is a boolean — range bounds must be string or finite number (booleans are not ordered).`,\n );\n }\n if (t === \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is a nested object — range bounds must be string or finite number.`,\n );\n }\n if (t !== \"string\" && t !== \"number\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) has unsupported type ${JSON.stringify(t)} — must be string or finite number.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n","import type { ContentVersionId } from \"./types.ts\";\n\n/**\n * Width of the {@link ContentVersionId} hex strings produced by\n * {@link versionFromContent}. 32 hex chars = 128 bits, matching the\n * information content of a v4 UUID. Birthday-bound collision probability\n * at N=10⁹ writes is ~1.5 × 10⁻²¹ (≈ N² / 2¹²⁹); ample for a\n * content-addressed version id. A collision is not detected at runtime —\n * two distinct bodies that share a truncated hash would alias to the same\n * content key, so a reader could observe the wrong body. The bound above\n * is the sole guard, and it sits far below any plausible write volume.\n *\n * @see docs/spec/log-entry-shape.md §\"Content body layout\"\n */\nconst VERSION_HEX_LENGTH = 32;\n\n/**\n * Content-addressed {@link ContentVersionId}: SHA-256 of `body`,\n * lowercase hex, truncated to {@link VERSION_HEX_LENGTH}. Same body\n * bytes ⇒ same ContentVersionId — scoped to **single-writer idempotent\n * replay** (a crash-recovery rewrite of the same in-memory value by the\n * same writer reproduces the content key the manifest already\n * referenced). `body` is non-canonical (`JSON.stringify`, insertion\n * key order — see `encodeJsonBytes`), so this is NOT cross-writer\n * content dedup: different key order ⇒ different key for an equal value.\n *\n * Async because {@link crypto.subtle.digest} returns an `ArrayBuffer`\n * via Promise. Workers and browsers both expose `crypto.subtle`\n * synchronously enough that the await fits naturally in the write\n * pipeline.\n *\n * @see docs/spec/log-entry-shape.md §\"Content body layout\"\n */\nexport const versionFromContent = async (body: Uint8Array): Promise<ContentVersionId> => {\n // Copy via fresh ArrayBuffer: tsgo narrows `Uint8Array` to\n // `Uint8Array<ArrayBufferLike>`, which `crypto.subtle.digest` rejects\n // (wants `ArrayBufferView<ArrayBuffer>`). See microsoft/TypeScript#61375.\n const view = new Uint8Array(body.byteLength);\n view.set(body);\n const digest = await crypto.subtle.digest(\"SHA-256\", view);\n const bytes = new Uint8Array(digest);\n let hex = \"\";\n for (let i = 0; i < bytes.length; i++) {\n hex += bytes[i]!.toString(16).padStart(2, \"0\");\n }\n return hex.slice(0, VERSION_HEX_LENGTH) as ContentVersionId;\n};\n","/**\n * Log-object key construction — a zero-import leaf module.\n *\n * Kept separate from `log.ts` on purpose: `log.ts` carries the heavier\n * `lsn` parsing runtime (`lsnParts`, the LSN regex, `str2uintDesc`).\n * Routing `gc` / `writer` / `log-walk` through a key helper that lived in\n * `log.ts` dragged that whole module into the `maintenance.js` bundle\n * closure (+3.8 KB raw). This module imports nothing, so consumers that\n * only need the key shape pull only the key shape.\n */\n\n/** S3 path segment for log entries, under the manifest prefix. */\nexport const LOG_KEY_PREFIX = \"log\";\n\n/**\n * The single constructor for a log-object key:\n * `<manifestPrefix>/log/<seq>.json`. `manifestPrefix` is the\n * `<…>/manifests/<collection>` segment — this helper adds `/log/`.\n * Route all callers here so the key shape lives in one place.\n */\nexport const logObjectKey = (manifestPrefix: string, seq: number): string =>\n `${manifestPrefix}/${LOG_KEY_PREFIX}/${seq}.json`;\n","/**\n * SHA-256 of `bytes` as a 64-char lowercase hex string. Used to seal\n * snapshot filenames so a crashed mid-PUT can't produce a body that\n * readers consume as truth: the filename embeds the hash; readers\n * recompute on load and reject any mismatch as \"file missing.\"\n *\n * Distinct from {@link versionFromContent} (truncated to 32 chars for\n * content keys) — snapshot bodies are larger and longer-lived;\n * 256-bit collision resistance matters here.\n */\nexport const snapshotHash = async (bytes: Uint8Array): Promise<string> => {\n // Copy via fresh ArrayBuffer: tsgo narrows `Uint8Array` to\n // `Uint8Array<ArrayBufferLike>`, which `crypto.subtle.digest` rejects\n // (wants `ArrayBufferView<ArrayBuffer>`). See microsoft/TypeScript#61375\n // and `versionFromContent` in ./hashing.ts for the same workaround.\n const view = new Uint8Array(bytes.byteLength);\n view.set(bytes);\n const digest = await crypto.subtle.digest(\"SHA-256\", view);\n const out = new Uint8Array(digest);\n let hex = \"\";\n for (let i = 0; i < out.length; i++) {\n hex += out[i]!.toString(16).padStart(2, \"0\");\n }\n return hex;\n};\n","/**\n * Tolerant forward-probe for the true committed log tail. The strict\n * `[log_seq_start, hint)` range is dense (a hole is corruption, owned\n * by `walkLogRange`); this owns only the tolerant `[hint, ∞)` probe,\n * where `hint` is a lower bound — the real tail may sit at or past it.\n */\n\nimport {\n type LogEntry,\n type Storage,\n BaerlyError,\n decodeJsonBytes,\n LOG_FORWARD_PROBE_CAP,\n logObjectKey,\n} from \"@baerly/protocol\";\n\n/**\n * Discover the true committed tail and fold entries in `[hint, tail)`.\n * `tail` is the first empty seq (>= hint); `entries` are the\n * LogEntries in `[hint, tail)` in seq order. `cap` bounds the walk;\n * exhausting it THROWS `Internal` (never silently truncates) — see\n * the cap-exhaustion comment below.\n */\nexport const probeTailFrom = async (\n storage: Storage,\n logPrefix: string,\n hint: number,\n opts?: { signal?: AbortSignal; cap?: number },\n): Promise<{ tail: number; entries: LogEntry[] }> => {\n const cap = opts?.cap ?? LOG_FORWARD_PROBE_CAP;\n const getOpts = opts?.signal !== undefined ? { signal: opts.signal } : undefined;\n const entries: LogEntry[] = [];\n for (let i = 0; i < cap; i++) {\n const seq = hint + i;\n const key = logObjectKey(logPrefix, seq);\n const got = await storage.get(key, getOpts);\n if (got === null) {\n return { tail: seq, entries };\n }\n try {\n entries.push(decodeJsonBytes<LogEntry>(got.body));\n } catch (error) {\n // A malformed body at an occupied slot is a protocol violation —\n // surface it as InvalidResponse (the same code readLogEntry uses)\n // rather than a raw SyntaxError leaking out of the probe.\n throw new BaerlyError(\n \"InvalidResponse\",\n `probeTailFrom: malformed log entry at ${key}: ${(error as Error).message}`,\n { cause: error },\n );\n }\n }\n // Cap exhausted without hitting a 404 — the true tail is past `cap`.\n // Returning `hint+cap` here would silently truncate every downstream\n // read (since.ts / query.ts / GC / export / rebuild-index), so we\n // THROW instead, mirroring `findLogTail`'s cap-exhaustion guard. With\n // the maintenance tick keeping `tail_hint` within\n // `MAINTENANCE_TAIL_HINT_REFRESH_WRITES` of the true tail (HR-2), this\n // is a pure runaway alarm — a >cap gap means maintenance is\n // broken/disabled (a graduation/operator concern), never normal\n // operation. No partial-accept escape hatch: no caller legitimately\n // needs to walk past the cap.\n throw new BaerlyError(\n \"Internal\",\n `probeTailFrom: forward probe exceeded ${cap} from hint ${hint} on ${logPrefix}`,\n );\n};\n\n/**\n * First empty log seq at/after `hint` — the slot a new commit creates —\n * found by galloping search (`O(log gap)` GETs vs `probeTailFrom`'s\n * `O(gap)`). Used by the writer's per-commit tail-find, where `tail_hint`\n * can lag the true tail. Position only; no bodies.\n *\n * PRECONDITION: occupancy MUST be a dense prefix from `hint` (galloping\n * assumes monotone occupied→empty; a hole ABOVE `hint` would be skipped\n * and the gallop could return a tail past live entries). Contrast\n * `probeTailFrom`, which stops at the first 404 and is hole-tolerant.\n */\nexport const findLogTail = async (\n storage: Storage,\n logPrefix: string,\n hint: number,\n opts?: { signal?: AbortSignal },\n): Promise<number> => {\n const getOpts = opts?.signal !== undefined ? { signal: opts.signal } : undefined;\n const exists = async (seq: number): Promise<boolean> =>\n (await storage.get(logObjectKey(logPrefix, seq), getOpts)) !== null;\n if (!(await exists(hint))) {\n return hint;\n }\n // Gallop to bracket the tail in `(lo, hi]` (lo occupied, hi empty).\n let lo = hint;\n let step = 1;\n let hi = hint + step;\n while (await exists(hi)) {\n lo = hi;\n step *= 2;\n hi = lo + step;\n if (step > LOG_FORWARD_PROBE_CAP) {\n throw new BaerlyError(\n \"Internal\",\n `findLogTail: galloping probe exceeded ${LOG_FORWARD_PROBE_CAP} from hint ${hint} on ${logPrefix}`,\n );\n }\n }\n while (hi - lo > 1) {\n const mid = lo + Math.floor((hi - lo) / 2);\n if (await exists(mid)) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n return hi;\n};\n","import { BaerlyError } from \"@baerly/protocol\";\n\n/** Reject names in the system-reserved leading-\"_\" namespace. See docs/adr/003-layout-versioning-cordon.md. */\nexport const assertNameNotReserved = (name: string, context: string): void => {\n if (name.startsWith(\"_\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${context}: \"${name}\" is reserved — names beginning with \"_\" are reserved for system use. See docs/adr/003-layout-versioning-cordon.md.`,\n );\n }\n};\n","/**\n * Snapshot file shape + parse. Lifted out of `./compactor.ts` so that\n * the kernel barrel (`packages/server/src/index.ts`) — which re-exports\n * these four symbols — does not transitively pull `withObservability`\n * via `compact()`. `./compactor.ts` imports its own snapshot primitives\n * back from this module; the public API surface is unchanged.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\n\nimport {\n BaerlyError,\n decodeJsonBytes,\n type DocumentData,\n encodeJsonBytes,\n snapshotHash,\n SNAPSHOT_SCHEMA_VERSION,\n type Storage,\n} from \"@baerly/protocol\";\n\n/**\n * Single-level snapshot at L9; the level prefix is forward-compatible\n * with future L0..L9 rolling merges without a wire change.\n */\nconst SNAPSHOT_LEVEL = 9 as const;\n\n/**\n * `minSeq` and `maxSeq` are padded to {@link SEQ_DIGITS} digits so\n * `list(prefix)` returns snapshots in seq order without needing to\n * parse the filename. 12 digits caps at ~10^12 entries per collection;\n * a real bucket hits S3's per-prefix QPS ceiling long before that.\n */\nconst SEQ_DIGITS = 12 as const;\n\nconst MAX_SEQ = 10 ** SEQ_DIGITS - 1;\n\n/**\n * Build the on-bucket key for a snapshot file. `sha256` must be the\n * lowercase hex digest of the canonical body\n * ({@link encodeSnapshotBody}); the filename embeds it so a crashed\n * mid-PUT body that doesn't match its own filename hash is rejected\n * by readers as \"missing.\"\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `minSeq`/`maxSeq` are\n * out of range or `sha256` is not 64 hex chars.\n */\nexport const snapshotKey = (\n collectionPrefix: string,\n minSeq: number,\n maxSeq: number,\n sha256: string,\n): string => {\n if (minSeq < 0 || maxSeq < 0 || minSeq > maxSeq || maxSeq > MAX_SEQ) {\n throw new BaerlyError(\"InvalidConfig\", `snapshotKey: invalid range [${minSeq}, ${maxSeq})`);\n }\n if (!/^[0-9a-f]{64}$/.test(sha256)) {\n throw new BaerlyError(\"InvalidConfig\", \"snapshotKey: sha256 must be 64 hex chars\");\n }\n const pad = (n: number): string => n.toString().padStart(SEQ_DIGITS, \"0\");\n return `${collectionPrefix}/snapshot/L${SNAPSHOT_LEVEL}/${pad(minSeq)}-${pad(maxSeq)}-${sha256}.json`;\n};\n\n/**\n * On-bucket body of a snapshot file. The reader recomputes the SHA-256\n * over the canonical serialisation ({@link encodeSnapshotBody}) and\n * rejects any mismatch with the filename hash.\n *\n * `docs` is sorted by `_id` for deterministic byte output — two\n * compactions over the same fold produce byte-identical snapshots,\n * which means same filename, which means an idempotent re-run never\n * leaves an orphan.\n */\nexport interface SnapshotBody {\n readonly schema_version: typeof SNAPSHOT_SCHEMA_VERSION;\n readonly min_seq: number;\n readonly max_seq: number;\n readonly collection: string;\n readonly docs: ReadonlyArray<{\n readonly _id: string;\n readonly body: DocumentData;\n }>;\n}\n\n/**\n * Canonical byte encoding of a {@link SnapshotBody}. Only the\n * compactor produces snapshots, and only this function does the\n * serialisation — so the byte output is deterministic for a given\n * `SnapshotBody` (identical input ⇒ identical bytes ⇒ identical\n * filename hash).\n */\nexport const encodeSnapshotBody = (s: SnapshotBody): Uint8Array => encodeJsonBytes(s);\n\n/**\n * Load a snapshot file as a `Map<_id, DocumentData>`. Verifies the\n * body hash against the filename, checks the schema version, and\n * cross-checks `body.collection` against the caller's expectation.\n *\n * @example\n * ```ts\n * import { loadSnapshotAsMap } from \"@gusto/baerly-storage\";\n *\n * const map =\n * srcCurrent.snapshot === null\n * ? new Map<string, DocumentData>()\n * : await loadSnapshotAsMap(src.storage, srcCurrent.snapshot, \"tickets\");\n * ```\n *\n * @throws BaerlyError code=\"Internal\" — pointer resolves to no body,\n * or the body's SHA-256 doesn't match the hash embedded in the\n * filename. (Protocol invariant violation; a corrupted snapshot\n * the reader cannot continue past.)\n * @throws BaerlyError code=\"InvalidResponse\" — body isn't valid JSON,\n * isn't an object, has an unsupported `schema_version`, or carries a\n * `collection` that doesn't match `expectedCollection`.\n */\nexport const loadSnapshotAsMap = async (\n storage: Storage,\n key: string,\n expectedCollection: string,\n signal?: AbortSignal,\n): Promise<Map<string, DocumentData>> => {\n const got = await storage.get(key, signal !== undefined ? { signal } : undefined);\n if (got === null) {\n throw new BaerlyError(\n \"Internal\",\n `compact: snapshot pointer ${key} resolves to no body; protocol violation`,\n );\n }\n // Verify hash: the filename shape is\n // `<...>/snapshot/L<n>/<min>-<max>-<sha256>.json`. The sha256 is\n // the segment after the LAST `-` (the two seq fields don't contain\n // dashes), with `.json` stripped.\n const filename = key.slice(key.lastIndexOf(\"/\") + 1).replace(/\\.json$/, \"\");\n const lastDash = filename.lastIndexOf(\"-\");\n const expectedHash = filename.slice(lastDash + 1);\n const actualHash = await snapshotHash(got.body);\n if (actualHash !== expectedHash) {\n throw new BaerlyError(\n \"Internal\",\n `compact: snapshot ${key} body hash mismatch (got ${actualHash}); protocol violation`,\n );\n }\n let parsed: unknown;\n try {\n parsed = decodeJsonBytes(got.body);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} body is not valid JSON`,\n error,\n );\n }\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `compact: snapshot ${key} body is not an object`);\n }\n const body = parsed as SnapshotBody;\n if (body.schema_version !== SNAPSHOT_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} has unsupported schema_version ${String(body.schema_version)}`,\n );\n }\n if (body.collection !== expectedCollection) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} carries collection ${body.collection}, expected ${expectedCollection}`,\n );\n }\n if (!Array.isArray(body.docs)) {\n throw new BaerlyError(\"InvalidResponse\", `compact: snapshot ${key} body.docs is not an array`);\n }\n const out = new Map<string, DocumentData>();\n for (const row of body.docs) {\n out.set(row._id, row.body);\n }\n return out;\n};\n","/**\n * Secondary indexes — declarative collection-config-driven\n * index entries that the writer emits inside the same CAS fence as\n * the log entry and content body.\n *\n * The {@link IndexDefinition} TYPE lives in `@baerly/protocol`\n * (cross-platform). This module owns the runtime helpers that\n * operate on that shape:\n *\n * - {@link validateIndexDefinition} — synchronous schema check\n * for path-segment safety; thrown at `Writer` construction.\n * - {@link encodeIndexValue} — value-order-preserving base-32 of a\n * type-tagged byte stream (null/bool tag-only, numbers as sortable\n * IEEE 754, strings as raw UTF-8, objects as `JSON.stringify`\n * bytes for equality only).\n * - {@link indexKeyFor} / {@link indexKeyPrefix} — the wire-key\n * shape consumed by the writer's index PUTs and the rebuild\n * command's idempotent reconciliation.\n * - {@link projectIndexValues} / {@link allIndexKeysFor} — pure\n * projections from a doc body to the set of index keys it\n * produces under a collection's declared indexes.\n *\n * Wire shape (single-field):\n *\n * `<logPrefix>/index/<indexName>/<value-b32>/<docId>.json`\n *\n * Wire shape (composite):\n *\n * `<logPrefix>/index/<indexName>/<a-b32>/<b-b32>/<docId>.json`\n *\n * Body is zero bytes. Each entry is a fact (\"doc `<docId>` has\n * `<field> = <value>`\"), not data. Readers list the prefix, extract\n * the doc id from each key, then issue a content GET on each.\n *\n * Encoding is RFC-4648 base-32 (lowercase alphabet `[0-9a-v]`,\n * matching `packages/protocol/src/log.ts:str2uintDesc` style) on a\n * type-tagged byte stream (see {@link encodeIndexValue}) so that:\n *\n * - String \"5\" and number 5 produce distinct encodings\n * (type-tag prefix keeps the slots disjoint).\n * - Equal-by-value inputs produce byte-equal segments.\n * - Lex order under storage `list(prefix)` matches value order:\n * `null < false < true < number < string < object`, with\n * numeric values ordered by IEEE 754 magnitude (range walks\n * and `$in` walks over numeric fields are first-class — no\n * planner fall-back to full-scan).\n *\n * Composite read routing is left-anchored. The planner may consume an\n * equality prefix plus a range / `$in` tail slot; predicates that do\n * not match a routable prefix fall back to the snapshot+log fold.\n *\n * @see docs/spec/sync-protocol.md — index emission is hybrid around\n * the commit: additive (new) keys are PUT before the committing\n * `log/<seq>` create, and stale-key DELETEs land after it.\n */\n\nimport {\n BaerlyError,\n type DocumentData,\n encodeJsonBytes,\n type IndexDefinition,\n matchesWire,\n validateWire,\n} from \"@baerly/protocol\";\nimport { assertNameNotReserved } from \"./names.ts\";\n\nexport type { IndexDefinition };\n\n/** Path-safe segment name. */\nconst INDEX_NAME_RE = /^[a-z][a-z0-9_]*$/;\n\n/**\n * Lowercase base-32 alphabet, RFC 4648 variant matching the\n * `packages/protocol/src/log.ts:str2uintDesc` style (`[0-9a-v]`).\n * Lex-order-preserving under storage `list(prefix)` semantics.\n */\nconst B32_ALPHABET = \"0123456789abcdefghijklmnopqrstuv\";\n\n/**\n * Reject malformed {@link IndexDefinition} shapes synchronously, at\n * writer construction. See docs/adr/003-layout-versioning-cordon.md.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — reserved leading-`_` `name`.\n * @throws BaerlyError code=\"SchemaError\" — `name` fails the regex, or `on` is empty.\n */\nexport const validateIndexDefinition = (def: IndexDefinition): void => {\n assertNameNotReserved(def.name, \"index.name\");\n if (!INDEX_NAME_RE.test(def.name)) {\n throw new BaerlyError(\n \"SchemaError\",\n `index.name must match /^[a-z][a-z0-9_]*$/; got ${JSON.stringify(def.name)}`,\n );\n }\n if (typeof def.on === \"string\") {\n if (def.on.length === 0) {\n throw new BaerlyError(\"SchemaError\", `index ${def.name}.on must be non-empty`);\n }\n } else if (def.on.length === 0) {\n throw new BaerlyError(\"SchemaError\", `index ${def.name}.on must be non-empty array`);\n }\n if (def.predicate !== undefined) {\n try {\n validateWire(def.predicate);\n } catch (error) {\n // Surface as SchemaError so the failure mode matches the rest\n // of validateIndexDefinition (writer-construction-time bail-out,\n // not query-time).\n if (error instanceof BaerlyError) {\n throw new BaerlyError(\n \"SchemaError\",\n `index ${def.name}.predicate is invalid: ${error.message}`,\n error,\n );\n }\n throw error;\n }\n }\n};\n\n/**\n * Type-tag bytes for the value-order-preserving wire format. The\n * tag is the LEADING byte of the encoded payload; the values are\n * picked so the type order under byte-wise lex is\n * `null < false < true < number < string < object`.\n *\n * | Type | Byte-prefix | Payload |\n * |---------|-------------|----------------------------------------------------|\n * | null | 0x10 | (none) |\n * | false | 0x20 | (none) |\n * | true | 0x21 | (none) |\n * | number | 0x30 | 8-byte sortable big-endian IEEE 754 |\n * | string | 0x40 | UTF-8 bytes of the string (no quotes, no escapes) |\n * | object | 0x50 | UTF-8 bytes of `JSON.stringify(v)` |\n *\n * Local to the encoder by design — these are wire shape, not\n * cross-package protocol constants (see `CLAUDE.md` § \"Magic\n * values\").\n */\nconst TYPE_NULL = 0x10;\nconst TYPE_FALSE = 0x20;\nconst TYPE_TRUE = 0x21;\nconst TYPE_NUMBER = 0x30;\nconst TYPE_STRING = 0x40;\nconst TYPE_OBJECT = 0x50;\n\n/**\n * Encode a JS double as an 8-byte big-endian sortable IEEE 754\n * payload. Byte-wise lex order on the result matches numeric order\n * across all finite doubles plus `±Infinity`:\n *\n * 1. Get the 8-byte big-endian view of the double.\n * 2. If the sign bit is `0` (zero or positive), flip the sign bit\n * (XOR `0x80` on byte 0) so positives sort above negatives.\n * 3. If the sign bit is `1` (negative), flip every bit in all 8\n * bytes so more-negative sorts lower.\n *\n * `NaN` has no order-preserving slot and is rejected — see the\n * `encodeIndexValue` JSDoc for the wire-contract rationale.\n * `-0` and `+0` collapse because the `n === 0 ? 0 : n` coercion below\n * forces both into the positive-zero branch before `setFloat64`.\n */\nconst encodeNumberPayload = (n: number): Uint8Array => {\n if (Number.isNaN(n)) {\n throw new BaerlyError(\n \"SchemaError\",\n `encodeIndexValue: NaN is not indexable (the byte encoding has no order-preserving slot for it)`,\n );\n }\n // Coerce `-0` to `+0` so both share the positive-zero serialisation\n // (`setFloat64(-0)` would produce `0x80 00...00` and take the\n // negative-branch all-bits-flip below, collapsing to a *different*\n // byte string than `+0`). Coercing up front keeps the wire stable.\n const buf = new ArrayBuffer(8);\n new DataView(buf).setFloat64(0, n === 0 ? 0 : n, false); // big-endian\n const bytes = new Uint8Array(buf);\n if ((bytes[0]! & 0x80) === 0) {\n // Positive (or +0): flip sign bit so positives sort above negatives.\n bytes[0] = bytes[0]! ^ 0x80;\n } else {\n // Negative: flip all bits so more-negative sorts lower.\n for (let i = 0; i < 8; i++) {\n bytes[i] = bytes[i]! ^ 0xff;\n }\n }\n return bytes;\n};\n\n/**\n * Compose the typed byte stream for one value. The leading byte is\n * the type tag (see {@link TYPE_NULL} et al.); the payload shape is\n * type-dependent. Strings are emitted as their raw UTF-8 bytes (no\n * JSON quoting / escaping) so byte-wise lex order on encoded strings\n * matches byte-wise lex order on the source UTF-8. Objects fall back\n * to `JSON.stringify` for equality only.\n */\nconst encodeBytes = (v: unknown): Uint8Array => {\n if (v === null || v === undefined) {\n return new Uint8Array([TYPE_NULL]);\n }\n if (v === false) {\n return new Uint8Array([TYPE_FALSE]);\n }\n if (v === true) {\n return new Uint8Array([TYPE_TRUE]);\n }\n if (typeof v === \"number\") {\n const payload = encodeNumberPayload(v);\n const out = new Uint8Array(1 + payload.length);\n out[0] = TYPE_NUMBER;\n out.set(payload, 1);\n return out;\n }\n if (typeof v === \"string\") {\n const utf8 = new TextEncoder().encode(v);\n const out = new Uint8Array(1 + utf8.length);\n out[0] = TYPE_STRING;\n out.set(utf8, 1);\n return out;\n }\n // Objects: equality only; insertion-order dependent (matches today's\n // contract on `JSON.stringify`-based equality).\n const utf8 = encodeJsonBytes(v);\n const out = new Uint8Array(1 + utf8.length);\n out[0] = TYPE_OBJECT;\n out.set(utf8, 1);\n return out;\n};\n\n/**\n * Encode an arbitrary `DocumentValue` value as a path-safe segment.\n *\n * Type-tagged byte stream, base-32-encoded for path safety. Lex\n * order on encoded bytes matches:\n *\n * - **Type order**: `null < false < true < number < string < object`.\n * - **Within numbers**: IEEE 754 numeric order (sortable\n * big-endian payload, sign-bit-flipped or all-bits-flipped).\n * `-Infinity` sorts lowest, `+Infinity` highest.\n * - **Within strings**: UTF-8 byte order.\n * - **Within objects**: byte-equality only (still\n * `JSON.stringify`-insertion-order dependent).\n *\n * Numbers ARE range-safe under this encoder — `9` sorts below `10`\n * as expected. The query planner's old\n * `numeric-range-on-byte-encoder` guard has been removed; range\n * walks and `$in` walks over numeric fields are routed normally.\n *\n * `NaN` throws `BaerlyError{code:\"SchemaError\"}` at write time —\n * the byte encoding has no order-preserving slot for it, and a\n * silent collapse to the `null` key (as the prior\n * `JSON.stringify`-based encoder did, since\n * `JSON.stringify(NaN) === \"null\"`) is a worse failure mode than\n * a loud reject.\n *\n * `-0` and `+0` collapse to the same encoding.\n *\n * Equal-by-value inputs (e.g. two `{a:1, b:2}` objects with the\n * same key insertion order) produce byte-equal segments;\n * structurally-different but visually-similar inputs (`\"5\"` vs `5`)\n * are kept apart by the type-tag prefix.\n *\n * String ranges remain safe: `\"2026-05-13\" < \"2026-05-14\"`\n * byte-wise matches semantic order. ISO 8601 timestamps,\n * alphabetical priorities like `\"p1\"/\"p2\"/\"p3\"`, and any\n * fixed-width string encoding are usable as range-walked indexed\n * fields.\n */\nexport const encodeIndexValue = (v: unknown): string => {\n const bytes = encodeBytes(v);\n let out = \"\";\n let bits = 0;\n let value = 0;\n for (const b of bytes) {\n value = (value << 8) | b;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n out += B32_ALPHABET[(value >> bits) & 0x1f];\n }\n }\n if (bits > 0) {\n out += B32_ALPHABET[(value << (5 - bits)) & 0x1f];\n }\n // The type-prefix guarantees the byte stream is non-empty for every\n // input, so the \"empty → '0'\" fallback that the old encoder needed\n // is dead. Encoder output is always non-empty under the new contract.\n return out;\n};\n\n/**\n * Storage `list(prefix)` boundary for every entry under one index\n * of a collection: `<logPrefix>/index/<name>/`. Used by the rebuild\n * command's reconciliation walk and by the read-path index hint.\n */\nexport const indexKeyPrefix = (logPrefix: string, indexName: string): string =>\n `${logPrefix}/index/${indexName}/`;\n\n/**\n * Build the per-doc index key for one `(def, values, docId)`.\n *\n * Single-field: `<logPrefix>/index/<name>/<v0-b32>/<docId>.json`.\n * Composite: `<logPrefix>/index/<name>/<v0-b32>/<v1-b32>/.../<docId>.json`.\n *\n * Composite entries are read-path routable when the planner can consume\n * a left-anchored prefix of the indexed tuple.\n */\nexport const indexKeyFor = (\n logPrefix: string,\n def: IndexDefinition,\n values: readonly unknown[],\n docId: string,\n): string => {\n const segments = values.map(encodeIndexValue).join(\"/\");\n return `${logPrefix}/index/${def.name}/${segments}/${docId}.json`;\n};\n\n/**\n * Project the value tuple a doc body produces under one index\n * definition. Returns `undefined` when any indexed field is\n * null / undefined / missing — no index entry for that doc under\n * that index (SQL \"NULL values don't enter the index\" semantics).\n *\n * @throws BaerlyError code=\"SchemaError\" — `on` contains a dotted\n * path, or the indexed field's value is an array. Both restrictions\n * are current 0.x limitations; multi-value (array) indexes are a follow-up.\n */\nexport const projectIndexValues = (\n def: IndexDefinition,\n body: DocumentData | undefined,\n): readonly unknown[] | undefined => {\n if (body === undefined) {\n return undefined;\n }\n const fields = typeof def.on === \"string\" ? [def.on] : def.on;\n const values: unknown[] = [];\n for (const field of fields) {\n // Today we only support top-level fields. Dotted paths land in\n // a follow-up; throw loudly so a config typo doesn't silently\n // produce empty values.\n if (field.includes(\".\")) {\n throw new BaerlyError(\n \"SchemaError\",\n `index ${def.name}: dotted-path \"on\" fields not yet supported (got ${JSON.stringify(field)})`,\n );\n }\n const v = body[field];\n // null/undefined are skipped — no index entry. Mirrors SQL\n // \"NULL values don't go into a regular index\" semantics.\n if (v === null || v === undefined) {\n return undefined;\n }\n // Array values are valid in documents (RFC 7386 replacement\n // semantics) but multi-value indexes aren't supported yet — the\n // prefix-tree encoder produces one key per doc, not one per\n // element. Throw loudly so a user indexing a tag list gets a\n // clear error instead of garbage keys.\n if (Array.isArray(v)) {\n throw new BaerlyError(\n \"SchemaError\",\n `index ${def.name}: cannot index array field \"${field}\" — multi-value indexes are not supported yet`,\n );\n }\n values.push(v);\n }\n return values;\n};\n\n/**\n * Compute the full index-key set a single doc produces under every\n * declared index of its collection. Skips indexes whose projection\n * yields `undefined` (null/missing indexed field). Used by both\n * the writer (to PUT new keys) and the rebuild command (to compute\n * the expected key set across the live doc map).\n *\n * Filter-aware (T4): when `def.predicate !== undefined`, the doc\n * must satisfy `matchesWire(def.predicate, body)` or the def contributes\n * zero keys. The writer's diff `oldKeys` vs `newKeys` then covers\n * all four U-quadrants automatically — see the JSDoc on\n * `writer.ts` above the index-emission block. `body ===\n * undefined` short-circuits ahead of the filter check (no keys for\n * an unknown pre-image, regardless of filter), preserving the prior\n * D-quadrant behaviour.\n */\nexport const allIndexKeysFor = (\n logPrefix: string,\n defs: ReadonlyArray<IndexDefinition>,\n body: DocumentData | undefined,\n docId: string,\n): string[] => {\n const keys: string[] = [];\n for (const def of defs) {\n if (def.predicate !== undefined && body !== undefined) {\n if (!matchesWire(def.predicate, body)) {\n continue;\n }\n }\n const values = projectIndexValues(def, body);\n if (values !== undefined) {\n keys.push(indexKeyFor(logPrefix, def, values, docId));\n }\n }\n return keys;\n};\n","/**\n * Shared log-walk primitives consumed by the read path (`query.ts`),\n * the compactor (`compactor.ts`), and the optional integrity walk in\n * `Writer.#singleAttemptCommit` (`writer.ts`).\n *\n * Two operations: read one log entry, or walk a contiguous range of\n * log entries with bounded parallelism. Each kernel call site\n * previously inlined the same range-build + unbounded `Promise.all`\n * pattern; on a free-tier collection where the compactor lags the\n * tail to 50-100 entries, that fans out 50-100 concurrent GETs per\n * call — and a contended writer multiplies that by the CAS retry\n * budget. `walkLogRange` caps concurrency at\n * {@link MAX_PARALLEL_LOG_READS} so a single call costs at most that\n * many simultaneous GETs against the storage backend.\n *\n * Order invariant: results are returned in seq order regardless of\n * resolution order. The read-side fold is order-sensitive (`U` then\n * `D` on the same doc must apply in that order); callers may iterate\n * the returned array as-is.\n *\n * Signal invariant: when the caller's `AbortSignal` fires, no further\n * chunks dispatch. In-flight reads see the signal via the underlying\n * `Storage.get` call.\n */\n\nimport {\n type DocumentData,\n type LogEntry,\n type Storage,\n BaerlyError,\n decodeJsonBytes,\n logObjectKey,\n MAX_PARALLEL_LOG_READS,\n} from \"@baerly/protocol\";\n\n/**\n * Fetch a single log entry. Centralises the \"missing entry inside the\n * visible log range is a protocol-invariant violation\" rule used by\n * every caller.\n *\n * @throws BaerlyError code=\"Internal\" when the key resolves to no\n * body — a hole inside `[log_seq_start, tail_hint)` is a corruption\n * the kernel can't continue past.\n * @throws BaerlyError code=\"InvalidResponse\" when the body isn't\n * valid JSON.\n */\nexport const readLogEntry = async (\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<LogEntry> => {\n const got = await readLogEntryWithBytes(storage, key, opts);\n return got.entry;\n};\n\n/**\n * Like {@link readLogEntry}, but also surfaces `bytes` — the\n * byteLength of the STORED log-object body exactly as it was GET back\n * from storage (`got.body.byteLength`).\n *\n * The compactor uses this to sum the byte cost of the folded slice.\n * The stored body byteLength IS what the writer PUT for each entry,\n * so summing `got.body.byteLength` over the folded range yields the\n * exact cost — no re-encode, no round-trip assumption (a re-encode\n * of the parsed `LogEntry` could drift if key-order/whitespace ever\n * diverged from what was PUT).\n *\n * Same error semantics as {@link readLogEntry}.\n */\nconst readLogEntryWithBytes = async (\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<{ entry: LogEntry; bytes: number }> => {\n const got = await storage.get(\n key,\n opts?.signal !== undefined ? { signal: opts.signal } : undefined,\n );\n if (got === null) {\n throw new BaerlyError(\n \"Internal\",\n `log-walk: missing log entry at ${key}; protocol invariant violation`,\n );\n }\n try {\n return { entry: decodeJsonBytes<LogEntry>(got.body), bytes: got.body.byteLength };\n } catch (error) {\n throw new BaerlyError(\"InvalidResponse\", `log-walk: malformed log entry at ${key}`, error);\n }\n};\n\n/**\n * Walk `[fromSeq, toSeqExclusive)` of `${logPrefix}/log/<seq>.json`\n * in chunks of {@link MAX_PARALLEL_LOG_READS} concurrent GETs.\n * Returns the materialised entries in seq order.\n *\n * Empty range (`fromSeq >= toSeqExclusive`) returns `[]` and issues\n * zero GETs.\n *\n * Same error semantics as {@link readLogEntry}: a missing entry\n * throws `Internal`, a malformed body throws `InvalidResponse`.\n */\nexport const walkLogRange = async (\n storage: Storage,\n logPrefix: string,\n fromSeq: number,\n toSeqExclusive: number,\n opts?: { signal?: AbortSignal },\n): Promise<LogEntry[]> => {\n const withBytes = await walkLogRangeWithBytes(storage, logPrefix, fromSeq, toSeqExclusive, opts);\n return withBytes.map((r) => r.entry);\n};\n\n/**\n * Like {@link walkLogRange}, but each element also carries `bytes` —\n * the STORED log-object body byteLength (see {@link readLogEntryWithBytes}).\n * Same seq-order, empty-range, error, and bounded-parallelism\n * ({@link MAX_PARALLEL_LOG_READS}) guarantees as {@link walkLogRange};\n * this is the bytes-aware core `walkLogRange` is implemented on top of.\n *\n * The compactor consumes this so it gets BOTH the parsed entries (for\n * the fold) AND the exact byte sum (for `mean_entry_bytes` stamping) from a\n * single walk.\n */\nexport const walkLogRangeWithBytes = async (\n storage: Storage,\n logPrefix: string,\n fromSeq: number,\n toSeqExclusive: number,\n opts?: { signal?: AbortSignal },\n): Promise<Array<{ entry: LogEntry; bytes: number }>> => {\n if (fromSeq >= toSeqExclusive) {\n return [];\n }\n const total = toSeqExclusive - fromSeq;\n const out: Array<{ entry: LogEntry; bytes: number }> = Array.from({ length: total });\n for (let chunkStart = 0; chunkStart < total; chunkStart += MAX_PARALLEL_LOG_READS) {\n opts?.signal?.throwIfAborted();\n const chunkEnd = Math.min(chunkStart + MAX_PARALLEL_LOG_READS, total);\n const promises: Array<Promise<{ entry: LogEntry; bytes: number }>> = [];\n for (let i = chunkStart; i < chunkEnd; i++) {\n const seq = fromSeq + i;\n promises.push(readLogEntryWithBytes(storage, logObjectKey(logPrefix, seq), opts));\n }\n const results = await Promise.all(promises);\n for (let i = 0; i < results.length; i++) {\n out[chunkStart + i] = results[i]!;\n }\n }\n return out;\n};\n\n/**\n * Fold a sequence of `LogEntry` records onto a doc-id-keyed map,\n * applying the protocol's per-doc-replace semantics:\n *\n * - `I` / `U`: when `entry.after !== undefined`, set\n * `map.set(entry.doc_id, entry.after)`. Entries with `after ===\n * undefined` (the partial-merge writer's future patch-only shape)\n * are ignored — today's writer always emits `after`, so this is a\n * forward-compat guard, not a live branch.\n * - `D`: tombstone — `map.delete(entry.doc_id)`.\n *\n * Entries whose `collection` does not match `opts.collection`, or\n * whose `doc_id` is `undefined`, are skipped. When\n * `opts.docIdFilter` is provided, only entries whose `doc_id` is\n * present in the filter set are folded — used by the index-walk\n * read path to scope the fold to the docs the planner already\n * resolved.\n *\n * This is the canonical fold used by the read path\n * (`query.ts`) and the index reconciler (`rebuild-index.ts`).\n * Centralising it keeps the\n * \"straight `set` on I/U; tombstone on D\" protocol invariant in one place.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\nexport const foldLogEntriesOnto = <T extends DocumentData>(\n map: Map<string, T>,\n entries: Iterable<LogEntry>,\n opts: {\n readonly collection: string;\n readonly docIdFilter?: ReadonlySet<string>;\n },\n): void => {\n const { collection, docIdFilter } = opts;\n for (const entry of entries) {\n if (entry.collection !== collection) {\n continue;\n }\n if (entry.doc_id === undefined) {\n continue;\n }\n if (docIdFilter !== undefined && !docIdFilter.has(entry.doc_id)) {\n continue;\n }\n switch (entry.op) {\n case \"I\":\n case \"U\": {\n if (entry.after === undefined) {\n continue;\n }\n map.set(entry.doc_id, entry.after as T);\n break;\n }\n case \"D\": {\n map.delete(entry.doc_id);\n break;\n }\n }\n }\n};\n","/* 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: 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-storage 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 SNAPSHOT_SCHEMA_VERSION,\n snapshotHash,\n type Storage,\n type StoragePutOptions,\n} from \"@baerly/protocol\";\nimport { walkLogRangeWithBytes } from \"./log-walk.ts\";\nimport { probeTailFrom } from \"./log-tail.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 /**\n * @internal SNAPSHOT-axis byte ceiling. The rebuilt snapshot body\n * (NOT snapshot + tail) must be `<= ceilingBytes` or the fold is\n * DEFERRED before the PUT. `undefined ⇒ no ceiling` (`Infinity`).\n * The write-tick runner threads its pre-fold-projection `C` here as\n * a Node-side belt-and-suspenders; on a CPU-killable CF isolate the\n * kill lands during walk+encode (before this check), so the decisive\n * CF guard is the runner's pre-fold projection, not this.\n */\n readonly ceilingBytes?: number;\n\n /**\n * @internal SNAPSHOT-axis row ceiling. The rebuilt snapshot row count\n * (`base.size`, NOT including the tail) must be `<= ceilingEntries`\n * or the fold is DEFERRED before the PUT. `undefined ⇒ no ceiling`\n * (`Infinity`). Catches the tiny-doc case where bytes stay small but\n * row count balloons.\n */\n readonly ceilingEntries?: number;\n\n /**\n * @internal A fresh tail LOWER BOUND the caller already observed (the\n * write-tick runner threads the writer's in-memory `observedTail`,\n * `seq + 1`). When present it raises the ceiling-probe FLOOR to\n * `max(log_seq_start, tail_hint, knownTail)`, so on a stale-low stored\n * `tail_hint` the forward probe walks only \"commits since this writer's\n * commit\" instead of re-walking the whole gap from the stale hint\n * (which could blow the CF subrequest budget — B4). The compactor still\n * discovers the TRUE tail by probing UP from this floor (small gap).\n * Absent on the scheduled path ⇒ probe from `max(log_seq_start,\n * tail_hint)` as before.\n */\n readonly knownTail?: 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\" | \"deferred\";\n /** `true` on the over-ceiling rebuild-defer path (`skippedReason === \"deferred\"`). */\n readonly deferred?: boolean;\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 // Each ceiling: `undefined ⇒ no ceiling` (treated as `Infinity`).\n const ceilingBytes = internal.ceilingBytes ?? Number.POSITIVE_INFINITY;\n const ceilingEntries = internal.ceilingEntries ?? Number.POSITIVE_INFINITY;\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 // Forward-probe the TRUE tail (uncapped) and stamp it as the new\n // `tail_hint` (Step 7). Ordinary writer commits never advance\n // `tail_hint` under single-write commit; compaction folds are the\n // primary durable advancer, with maintenance defer/disable refreshes\n // and explicit operator/import paths as the other writers. The\n // compactor still discovers the true tail to keep the writer's\n // per-commit tail-find cheap (a tracking hint ⇒ small gap). The\n // compactor's O(gap) probe is amortized O(1) per write across the\n // fold cadence; it's Class-A-active, not idle-reader-bound.\n // Raise the probe floor to any fresh tail lower bound the caller passed\n // (the write-tick `knownTail` = writer's observed `seq + 1`) so a\n // stale-low stored `tail_hint` doesn't force an O(gap) re-walk (B4).\n const probeFloor = Math.max(logSeqStartBefore, current.tail_hint, internal.knownTail ?? 0);\n const probe = await probeTailFrom(storage, collectionPrefix, probeFloor, {\n ...(options.signal !== undefined && { signal: options.signal }),\n });\n const discoveredTail = probe.tail;\n const nextSeq = discoveredTail;\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 // Bytes-aware variant: we need BOTH the parsed entries (for the fold)\n // AND the exact STORED body byteLength per object (to compute the\n // folded slice's mean entry size for `mean_entry_bytes`).\n const fetched = await walkLogRangeWithBytes(\n storage,\n collectionPrefix,\n logSeqStartBefore,\n foldEnd,\n { signal: options.signal },\n );\n\n // Sum the STORED body bytes over ALL fetched objects in\n // `[logSeqStartBefore, foldEnd)` — NOT only the entries the fold loop\n // keeps. This sum / entry count gives `mean_entry_bytes`, the\n // compactor-stamped basis for the derived live-tail estimate the\n // maintenance trigger reads. The byte sum is independent of the\n // fold-apply filter below.\n const foldedSliceBytes = fetched.reduce((sum, f) => sum + f.bytes, 0);\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.after` as the full post-image, see\n // packages/protocol/src/log.ts). D tombstones.\n for (const { entry } of fetched) {\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.after !== undefined) {\n base.set(entry.doc_id, entry.after);\n }\n break;\n }\n case \"D\": {\n // Tombstone purge: the numbered log serializes committed\n // mutations by `seq`, so no later entry in the folded prefix can\n // be missed. Dropping the row here IS the tombstone purge.\n base.delete(entry.doc_id);\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: SNAPSHOT_SCHEMA_VERSION,\n min_seq: 0,\n max_seq: foldEnd,\n collection: collectionName,\n docs: sortedDocs,\n };\n const bodyBytes = encodeSnapshotBody(snapshotBody);\n\n // ── Step 5b. SNAPSHOT-axis ceiling — check BEFORE the PUT. ───────\n // The ceiling is on the SNAPSHOT being rebuilt (`bodyBytes.byteLength`\n // / `base.size`), NOT snapshot + tail — the tail is bounded\n // separately by `maxEntriesPerRun`. This is a Node-side\n // belt-and-suspenders: on a CPU-killable CF isolate the kill lands\n // during the walk + encode above, BEFORE this check, so the decisive\n // CF guard is the runner's pre-fold projection (see maintenance.ts\n // `runBoundedMaintenance`). When over ceiling we DEFER: no PUT, no\n // CAS, no current.json mutation.\n if (bodyBytes.byteLength > ceilingBytes || base.size > ceilingEntries) {\n ctxMetrics().counter(\"db.compaction.deferred_total\", 1, {\n collection: collectionName,\n dimension: bodyBytes.byteLength > ceilingBytes ? \"bytes\" : \"rows\",\n });\n return {\n written: false,\n skippedReason: \"deferred\",\n deferred: true,\n previousSnapshotKey: current.snapshot,\n logSeqStartBefore,\n logSeqStartAfter: logSeqStartBefore,\n entriesFolded: 0,\n };\n }\n\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 entriesFolded = foldEnd - logSeqStartBefore;\n const next: CurrentJson = {\n ...current,\n snapshot: newKey,\n log_seq_start: foldEnd,\n // Stamp the discovered tail back as the new lower bound (monotone:\n // never lower the stored hint).\n tail_hint: Math.max(current.tail_hint, discoveredTail),\n snapshot_bytes: bodyBytes.byteLength,\n snapshot_rows: base.size,\n // Mean folded-entry byte size for live-tail estimation. Preserve a prior\n // mean on a zero-entry fold (no divide-by-zero, no clobber-with-0).\n mean_entry_bytes:\n entriesFolded > 0\n ? Math.round(foldedSliceBytes / entriesFolded)\n : (current.mean_entry_bytes ?? 0),\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 //\n // Emit the cas-lost metric HERE so it covers ALL callers\n // (write-tick runner, runScheduledMaintenance, direct tests). A\n // lost fold is EXPECTED contention, not an error. (The runner\n // must NOT also emit it — that would double-count.)\n ctxMetrics().counter(\"db.compaction.cas_lost_total\", 1, { collection: collectionName });\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 metrics = ctxMetrics();\n metrics.histogram(\"db.compact.entries_folded\", entriesFolded, { collection: collectionName });\n metrics.gauge(\"db.manifest.lag_window_depth\", discoveredTail - 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.after` 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. Because\n * content keys are hash-named (random lex order) and live content\n * is never deleted, a bounded pass cannot rely on deletion to\n * advance its LIST window the way `stale-log` does — so the\n * orphan-content LIST carries a persisted rotation cursor\n * (`content_scan_cursor` in `gc/pending.json`): each bounded pass\n * resumes `startAfter` the prior pass's last examined key and wraps\n * at end-of-keyspace, so the whole `content/` keyspace is swept\n * over a rotation within the per-pass `maxMarksPerRun` budget.\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 MAX_PARALLEL_LOG_READS,\n BaerlyError,\n casUpdateGcPending,\n createGcPending,\n decodeJsonBytes,\n encodeJsonBytes,\n logObjectKey,\n logSeqStartOf,\n mergeGcPending,\n noopMetricsRecorder,\n readCurrentJson,\n readGcPending,\n versionFromContent,\n} from \"@baerly/protocol\";\nimport { loadSnapshotAsMap } from \"./snapshot.ts\";\nimport { probeTailFrom } from \"./log-tail.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, tail_hint)\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 // Rotation cursor: resume the content LIST after the last key we\n // examined last pass. Bounded passes (`maxMarks` < keyspace) thus\n // sweep the whole `content/` keyspace over a rotation instead of\n // re-scanning the same lexicographic-first window forever — content\n // keys are hash-named (random lex order) and live content is never\n // deleted, so a fixed first-`maxMarks` window can be all-live and\n // never reach orphan content past it. See `content_scan_cursor`.\n const cursor = pending.json.content_scan_cursor;\n const contentPrefix = `${collectionPrefix}/content/`;\n let markedOrphanContent = 0;\n let examinedThisPass = 0;\n let lastExaminedKey: string | undefined;\n const listOpts: { startAfter?: string; maxKeys: number; signal?: AbortSignal } = {\n maxKeys: maxMarks,\n ...(cursor !== undefined && { startAfter: cursor }),\n ...(signal !== undefined && { signal }),\n };\n for await (const entry of storage.list(contentPrefix, listOpts)) {\n // The cursor advances by EXAMINED keys (not marked), so an\n // all-live window still moves the window forward to fresh keys\n // next pass.\n examinedThisPass++;\n lastExaminedKey = entry.key;\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 // New cursor: if the LIST yielded FEWER than `maxKeys` keys it\n // reached the end of the keyspace ⇒ WRAP (next pass starts from the\n // beginning, cursor cleared). The unbounded reconcile path\n // (maxMarks ≈ MAX_SAFE_INTEGER) always yields < maxKeys, so it lists\n // the whole keyspace in one pass, marks every orphan, and wraps —\n // behavior unchanged. Otherwise carry the last examined key.\n const reachedEnd = examinedThisPass < maxMarks;\n const nextContentCursor = reachedEnd ? undefined : lastExaminedKey;\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 // MERGE this pass's results INTO the latest stored value rather than\n // overwriting with a precomputed set: `casUpdateGcPending` re-reads\n // `latest` and hands it to `mergeGcPending`, so a concurrent pass's\n // candidates (marked between our read and our write) survive. Writing\n // a precomputed `merged` would silently overwrite them — the If-Match\n // would succeed (fresh etag), so NO conflict is raised and the marks\n // are lost. The mutator is pure + the DELETEs are idempotent + already\n // performed, so the helper safely retries the merge on conflict.\n const sweptKeys = new Set(toSweep.map((c) => c.key));\n // `\"\"` when this pass swept nothing — sourcing the no-sweep truth from\n // `latest` (via the merge's \"take later\" rule) rather than our stale\n // read. With no contention this is observably identical: `latest`\n // equals our read, so the later-of-the-two is the same value.\n const lastSweptAt = toSweep.length > 0 ? now().toISOString() : \"\";\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 (latest) =>\n mergeGcPending(latest, {\n sweptKeys,\n newCandidates,\n lastSweptAt,\n nextContentCursor,\n maxCandidates: GC_MAX_PENDING_CANDIDATES,\n }),\n signalOpts,\n );\n pendingDepth = updated.json.candidates.length;\n } catch (error) {\n // CAS-lost on pending.json after exhausting the bounded retry:\n // another GC pass kept landing concurrently. The DELETEs we issued\n // are durable; the next pass picks up any marks we couldn't persist.\n // Surface success — re-throwing here would mask the work we DID\n // 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.after` in `[logSeqStart, tail_hint)` 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, bounded to the TRUE tail (probe past a stale-low\n // hint) so GC never treats a committed post-image as dead. Floor the\n // probe at `max(log_seq_start, tail_hint)` — entries below\n // `log_seq_start` are folded and never scanned by the loop below. The\n // loop 404-tolerates misses, so over-bounding to `tail` is safe.\n const { tail } = await probeTailFrom(\n storage,\n collectionPrefix,\n Math.max(logSeqStart, current.tail_hint),\n { signal },\n );\n // Read every live entry in `[logSeqStart, tail)`, but cap the\n // simultaneous in-flight log GETs at MAX_PARALLEL_LOG_READS. A raw\n // `Promise.all` over the whole range fans out up to\n // LOG_FORWARD_PROBE_CAP (100_000) concurrent GETs when a backlogged\n // tail makes the range large — which blows the Cloudflare Workers\n // ~50-concurrent-subrequest cap. The walk is COMPLETE (every seq is\n // visited): this is a concurrency bound, never a partial scan. Unlike\n // the shared `walkLogRange` helper, this scan is 404-tolerant (a\n // missing `log/<seq>` past a stale-low hint is skipped, not fatal)\n // and tolerant of a malformed entry, so it keeps its own bounded loop\n // rather than borrowing the throwing walker.\n const ingestLogEntry = async (s: number): Promise<void> => {\n const got = await storage.get(logObjectKey(collectionPrefix, s), getOpts);\n if (got === null) {\n return;\n }\n let entry: { after?: unknown };\n try {\n entry = decodeJsonBytes<{ after?: 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.after === undefined) {\n return;\n }\n const bodyBytes = encodeJsonBytes(entry.after);\n hashes.add(await versionFromContent(bodyBytes));\n };\n for (let chunkStart = logSeqStart; chunkStart < tail; chunkStart += MAX_PARALLEL_LOG_READS) {\n signal?.throwIfAborted();\n const chunkEnd = Math.min(chunkStart + MAX_PARALLEL_LOG_READS, tail);\n const chunk: Array<Promise<void>> = [];\n for (let s = chunkStart; s < chunkEnd; s++) {\n chunk.push(ingestLogEntry(s));\n }\n await Promise.all(chunk);\n }\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 hybrid index emission path this command\n * 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\";\nimport { probeTailFrom } from \"./log-tail.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, tail_hint)`).\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 hint = read.json.tail_hint;\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`: strict dense walk `[log_seq_start, tail_hint)` plus a\n // tolerant forward-probe `[tail_hint, tail)` — `tail_hint` is only a\n // lower bound under single-write commit (compactor-advanced).\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, hint);\n foldLogEntriesOnto(live, entries, { collection });\n const probeOpts = opts.signal !== undefined ? { signal: opts.signal } : undefined;\n const probe = await probeTailFrom(\n storage,\n collectionPrefix,\n Math.max(logSeqStart, hint),\n probeOpts,\n );\n foldLogEntriesOnto(live, probe.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 {\n type CurrentJson,\n type MetricsRecorder,\n type Storage,\n BaerlyError,\n casUpdateCurrentJson,\n GC_STARVATION_GUARD,\n MAINTENANCE_COLD_START_ENTRY_BYTES,\n MAINTENANCE_MIN_LIVE_BYTES,\n MAINTENANCE_PROFILE_CF_FREE,\n MAINTENANCE_PROFILE_CF_PAID,\n MAINTENANCE_TAIL_HINT_REFRESH_WRITES,\n MAINTENANCE_TARGET_RATIO,\n MAINTENANCE_WARN_INTERVAL_WRITES,\n noopMetricsRecorder,\n readCurrentJson,\n WRITE_TICK_MIN_ENTRIES_TO_COMPACT,\n} 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\";\nimport { probeTailFrom } from \"./log-tail.ts\";\nimport { getCurrentContext } from \"./observability/context.ts\";\n\nconst ctxMetrics = (): MetricsRecorder => getCurrentContext()?.recorder ?? noopMetricsRecorder;\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/** The six host-agnostic write-tick budgets (`maxFoldBytes`=`C`, `maxFoldRows`=`E`). Canonical shape; mirrors the protocol constants (typed there to avoid a cycle). */\nexport interface MaintenanceProfile {\n readonly gcInterval: number;\n readonly gcMaxMarks: number;\n readonly gcMaxSweeps: number;\n readonly maxFoldEntriesPerPass: number;\n readonly maxFoldBytes: number;\n readonly maxFoldRows: number;\n}\n\nexport {\n MAINTENANCE_PROFILE_CF_FREE,\n MAINTENANCE_PROFILE_CF_PAID,\n MAINTENANCE_PROFILE_NODE,\n} from \"@baerly/protocol\";\n\n// Snapshot ceilings aren't part of the scheduled cap surface; omitted.\nconst profileToScheduledOptions = (profile: MaintenanceProfile): InternalMaintenanceOptions => ({\n compact: {\n maxEntriesPerRun: profile.maxFoldEntriesPerPass,\n minEntriesToCompact: WRITE_TICK_MIN_ENTRIES_TO_COMPACT,\n },\n gc: { maxMarksPerRun: profile.gcMaxMarks, maxSweepsPerRun: profile.gcMaxSweeps },\n});\n\n/**\n * Tuning profile for the 50-subrequest Cloudflare free-tier budget,\n * derived from {@link MAINTENANCE_PROFILE_CF_FREE} (one source of truth).\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 */\nexport const CLOUDFLARE_FREE_TIER: MaintenanceOptions = profileToScheduledOptions(\n MAINTENANCE_PROFILE_CF_FREE,\n);\n\n/**\n * Tuning profile for the 10,000-subrequest Cloudflare paid-tier budget,\n * derived from {@link MAINTENANCE_PROFILE_CF_PAID} (one source of truth).\n * Keeps the single-phase CPU-killable shape but affords Node-tier per-pass\n * throughput (compact ≈ 3+200, gc ≈ 6+200+100 — far under the 10k cap).\n *\n * To honour `BAERLY_MAINTENANCE_PROFILE=cf-paid` on the cron path, pass this\n * constant to `runScheduledMaintenance` inside your\n * {@link WorkerScheduledHandler}; the worked recipe lives in the `scheduled`\n * handler docstring of `baerlyWorker` (`@gusto/baerly-storage/cloudflare`).\n */\nexport const CLOUDFLARE_PAID_TIER: MaintenanceOptions = profileToScheduledOptions(\n MAINTENANCE_PROFILE_CF_PAID,\n);\n\n// =====================================================================\n// Write-tick (in-band) maintenance — `runBoundedMaintenance`.\n//\n// This is the runner the writer hook dispatches after a successful\n// commit. It is intentionally a thin, bounded composition over the\n// EXISTING `compact()` / `runGc()` primitives. The fold-viability\n// decision is made HERE (a pre-fold projection over `current.json`'s\n// `snapshot_bytes` / `snapshot_rows`) rather than inside `compact()`:\n// on a CPU-killable Cloudflare isolate the kill would land mid-rebuild,\n// before any post-rebuild size check could fire, so the only safe gate\n// is one that never starts an over-ceiling fold.\n//\n// §8.3 of docs/superpowers/plans/2026-05-29-just-a-bucket-maintenance.md.\n// =====================================================================\n\n/**\n * Floor-based GC-cadence boundary crossing. Every commit advances the\n * writer-observed tail by one logical slot; `tail_hint` remains a\n * lower bound and may be refreshed later by maintenance. The floor test\n * trips on any interval boundary inside `(prevSeq, nextSeq]`, so it\n * stays correct whether the observed/probed tail advances by one or\n * catches up by a larger step.\n */\nexport const crossesGcBoundary = (prevSeq: number, nextSeq: number, interval: number): boolean =>\n Math.floor(prevSeq / interval) !== Math.floor(nextSeq / interval);\n\n/**\n * Derived live-tail byte size — the ratio TRIGGER input that replaces the\n * formerly-stored exact byte count. `(observedTail − log_seq_start) ×\n * mean_entry_bytes`. `observedTail` is a param so write-tick callers can\n * pass the writer-observed tail and scheduled callers can pass a\n * probe-discovered true tail. Cold-start (no mean yet) falls back to\n * {@link MAINTENANCE_COLD_START_ENTRY_BYTES}, never 0 (see that constant).\n * TRIGGER-only — structurally barred from `foldViable` (the exact-bytes CPU-kill\n * ceiling).\n */\nexport const estimateTailBytes = (current: CurrentJson, observedTail: number): number =>\n Math.max(0, observedTail - current.log_seq_start) *\n (current.mean_entry_bytes ?? MAINTENANCE_COLD_START_ENTRY_BYTES);\n\n/**\n * The cheap DISPATCH gate the writer calls after a commit — zero\n * storage ops; it reads the post-commit {@link CurrentJson} already in\n * scope. Ratio-OR-boundary, WITHOUT the entry floor (the floor is part\n * of the fold-trigger Gate 1 checked inside {@link runBoundedMaintenance}).\n * Returning `false` lets the writer skip the dispatch entirely. Ratio\n * numerator is the DERIVED {@link estimateTailBytes};\n * `observedTail` threads from the caller (the writer's in-memory observed\n * tail `seq+1` under single-write commit). Both the boundary check and the\n * ratio key off `observedTail`, since the stored `tail_hint` is now only a\n * non-authoritative lower bound (compactor-advanced).\n */\nexport const shouldFireMaintenance = (\n current: CurrentJson,\n prevSeq: number,\n gcInterval: number,\n observedTail: number,\n): boolean =>\n crossesGcBoundary(prevSeq, observedTail, gcInterval) ||\n estimateTailBytes(current, observedTail) /\n Math.max(current.snapshot_bytes, MAINTENANCE_MIN_LIVE_BYTES) >=\n MAINTENANCE_TARGET_RATIO;\n\n/** Per-tier caps for {@link runBoundedMaintenance}, threaded by the adapter. */\nexport interface BoundedMaintenanceOptions {\n /** Host budgets, threaded by the adapter. Absent ⇒ {@link MAINTENANCE_PROFILE_CF_FREE} (CF-free-safe default; keeps a bare `Db.create()` maintaining). */\n readonly profile?: MaintenanceProfile;\n /** Gate-1 minimum live-tail length. Default {@link WRITE_TICK_MIN_ENTRIES_TO_COMPACT}. */\n readonly minEntriesToCompact?: number;\n /**\n * How many phases this tick may run. `\"single\"` (CF-free-safe\n * default) runs at most one of fold / GC per tick; `\"both\"` lets a\n * capable host run a fold AND a GC in one tick.\n */\n readonly phasesPerTick?: \"single\" | \"both\";\n /**\n * @internal — test seam. Forwarded into the runner's `runGc` call as\n * `graceMillis`. Default `undefined` ⇒ `runGc`'s 7-day\n * {@link GC_GRACE_PERIOD_MILLIS}. The drain-rate test sets `0` so a\n * single pass marks AND sweeps, making the steady-state object-count\n * trajectory observable without an 8-day clock advance. Production\n * never sets this.\n */\n readonly gcGraceMillis?: number;\n /**\n * @internal — test seam. Forwarded into the runner's `runGc` call as\n * the clock `now`. Default `undefined` ⇒ `runGc`'s `() => new Date()`.\n * Production never sets this.\n */\n readonly now?: () => Date;\n readonly signal?: AbortSignal;\n}\n\n/**\n * The write-tick maintenance runner: a bounded, single-attempt\n * composition of {@link compact} and {@link runGc} for one collection,\n * sized to fit a CPU-killable Cloudflare free-tier isolate by default.\n *\n * INVARIANT: a {@link MaintenanceProfile} changes only maintenance rate +\n * defer threshold — never data/API/query/wire/correctness; reads stay pure.\n * See `maintenance-profile-equivalence.test.ts`.\n *\n * Never throws — the write-tick caller must never see a maintenance\n * failure. Expected signals (CAS contention, an over-ceiling deferral)\n * are swallowed quietly; unexpected throws bump\n * `db.maintenance.unexpected_error_total`, log a stack, and are\n * swallowed.\n *\n * Control flow (fold-priority with a stateless GC-starvation guard):\n * 0. `disabled` → skip fold/GC, but still allow the rate-limited\n * tail_hint refresh that bounds read/write forward-probes.\n * 1. Read `current.json` once.\n * 2. Hard-GC starvation boundary (`\"single\"` only) → GC slice, skip fold.\n * 3. Gate 1 (ratio AND entry floor) trips → fold if viable, else\n * defer (and metric); on `\"single\"` a successful fold attempt is\n * this tick's one phase.\n * 4. Otherwise (or on `\"both\"`) → GC iff the cadence boundary crossed.\n */\nexport const runBoundedMaintenance = async (\n args: {\n storage: Storage;\n currentJsonKey: string;\n /** The pre-commit observed tail — the GC cadence baseline. */\n prevSeq: number;\n /**\n * Writer's in-memory observed tail (`seq + 1`). Given on the\n * write-tick path so the runner's Gate-1 ratio + GC cadence key off\n * the true tail without an O(gap) re-probe (the stored `tail_hint` is\n * only a lower bound). Absent on a scheduled tick ⇒ the runner probes.\n */\n observedTail?: number;\n /** `C` override (from `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`). */\n maxFoldBytes?: number;\n /** From `BAERLY_MAINTENANCE_DISABLE`: disable fold/GC phases, not tail_hint refresh. */\n disabled?: boolean;\n },\n options?: BoundedMaintenanceOptions,\n): Promise<void> => {\n const { storage, currentJsonKey, prevSeq } = args;\n // Resolve the profile ONCE (the runner's single CF-free-safe default,\n // preserving the bare-`Db.create()` promise); all six budgets read off it.\n const profile = options?.profile ?? MAINTENANCE_PROFILE_CF_FREE;\n const { maxFoldEntriesPerPass, gcMaxMarks, gcMaxSweeps, gcInterval } = profile;\n const minEntriesToCompact = options?.minEntriesToCompact ?? WRITE_TICK_MIN_ENTRIES_TO_COMPACT;\n const phasesPerTick = options?.phasesPerTick ?? \"single\";\n const signal = options?.signal;\n // `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` (args.maxFoldBytes) overrides `C`.\n const C = args.maxFoldBytes ?? profile.maxFoldBytes;\n const E = profile.maxFoldRows;\n\n // Derive the collection label the same way compact()/runGc() do.\n const collectionPrefix = currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"));\n const collection = collectionPrefix.slice(collectionPrefix.lastIndexOf(\"/\") + 1);\n\n const gcOpts = {\n maxMarksPerRun: gcMaxMarks,\n maxSweepsPerRun: gcMaxSweeps,\n ...(signal !== undefined && { signal }),\n // @internal test seams — undefined in production, so `runGc` falls\n // back to its 7-day grace and wall-clock `now`.\n ...(options?.gcGraceMillis !== undefined && { graceMillis: options.gcGraceMillis }),\n ...(options?.now !== undefined && { now: options.now }),\n } as InternalRunGcOptions;\n\n try {\n // ── Step 1. Read current.json once. ──────────────────────────────\n const read = await readCurrentJson(\n storage,\n currentJsonKey,\n signal !== undefined ? { signal } : undefined,\n );\n if (read === null) {\n return; // nothing to maintain yet\n }\n const current = read.json;\n const snapshotBytes = current.snapshot_bytes;\n const snapshotRows = current.snapshot_rows;\n const logSeqStart = current.log_seq_start;\n // Tail for THIS tick's Gate-1 ratio + GC cadence. Under single-write\n // commit `tail_hint` is only a lower bound (compactor-advanced), so the\n // tick can't read the true tail off `current.json`. Two sources:\n // - write-tick: use the writer's in-memory `observedTail` directly\n // (no re-probe — keeps the hot path off an O(gap) forward walk).\n // - scheduled (no `observedTail`): forward-probe the true tail here\n // (affordable at cron cadence).\n // Both floor at `max(log_seq_start, tail_hint)`.\n const probeFloor = Math.max(logSeqStart, current.tail_hint);\n let nextSeq: number;\n if (args.observedTail !== undefined) {\n nextSeq = Math.max(args.observedTail, probeFloor);\n } else {\n const probed = await probeTailFrom(\n storage,\n collectionPrefix,\n probeFloor,\n signal !== undefined ? { signal } : undefined,\n );\n nextSeq = probed.tail;\n }\n // Ratio TRIGGER numerator = DERIVED estimate (formerly exact stored field).\n const tailBytesEst = estimateTailBytes(current, nextSeq);\n\n const ratio = tailBytesEst / Math.max(snapshotBytes, MAINTENANCE_MIN_LIVE_BYTES);\n const gate1 = ratio >= MAINTENANCE_TARGET_RATIO && nextSeq - logSeqStart >= minEntriesToCompact;\n // SAFETY ceiling (CF CPU-kill guard) — EXACT snapshot_bytes/rows, NEVER the estimate.\n // Conservative by design: the row arm gates on POTENTIAL post-fold rows\n // (`snapshotRows + maxFoldEntriesPerPass`), so an update/delete-only fold\n // that would actually land under E can be deferred near the ceiling. We\n // can't know the insert-vs-update/delete mix without pre-scanning the\n // range, so we fail closed. Cost is a liveness edge for large near-E\n // collections, not a correctness bug.\n const foldViable = snapshotBytes <= C && snapshotRows + maxFoldEntriesPerPass <= E;\n const gcDue = crossesGcBoundary(prevSeq, nextSeq, gcInterval);\n\n const refreshTailHintIfNeeded = async (): Promise<void> => {\n if (nextSeq - current.tail_hint < MAINTENANCE_TAIL_HINT_REFRESH_WRITES) {\n return;\n }\n try {\n await casUpdateCurrentJson(\n storage,\n currentJsonKey,\n (c) => ({ ...c, tail_hint: Math.max(c.tail_hint, nextSeq) }),\n signal !== undefined ? { signal } : undefined,\n );\n } catch {\n // Swallow — Conflict (compactor/another isolate advanced first) or\n // any transient error. A missed advance just means the next tick\n // catches up; never throw out of write-tick maintenance.\n }\n };\n\n // ── Step 0. Phase disable. ───────────────────────────────────────\n // `BAERLY_MAINTENANCE_DISABLE` suppresses fold/GC work, but it must\n // not let `(true_tail - tail_hint)` grow past the read/write\n // forward-probe cap. Keep the same bounded, best-effort hint refresh\n // used by deferring collections; reads stay pure because this path\n // only runs from write-tick maintenance.\n if (args.disabled === true) {\n await refreshTailHintIfNeeded();\n return;\n }\n\n // ── Step 2. Hard-GC starvation guard (\"single\" only). ────────────\n // A long fold-heavy drain would otherwise starve GC on every\n // ratio-tripping tick. A COARSE cadence the fold may NOT preempt\n // guarantees ~1 GC tick per GC_STARVATION_GUARD intervals.\n const hardGc = crossesGcBoundary(prevSeq, nextSeq, gcInterval * GC_STARVATION_GUARD);\n if (phasesPerTick === \"single\" && hardGc) {\n await runGc({ storage, currentJsonKey }, gcOpts);\n return;\n }\n\n // ── Step 3. Fold-priority. ───────────────────────────────────────\n if (gate1) {\n if (foldViable) {\n // Thread the same `C` / `E` ceilings the pre-fold projection\n // above used into compact() as a Node-side belt-and-suspenders.\n // compact() emits `db.compaction.cas_lost_total` itself on a\n // lost CAS, so the runner does NOT (avoids double-count).\n await compact({ storage, currentJsonKey }, {\n maxEntriesPerRun: maxFoldEntriesPerPass,\n minEntriesToCompact,\n ceilingBytes: C,\n ceilingEntries: E,\n // B4: on the write-tick path the runner already knows a fresh\n // tail lower bound (`nextSeq`, derived from the writer's\n // `observedTail`). Pass it as the compactor's probe floor so the\n // ceiling probe is bounded by commits since this writer's commit,\n // not by an O(gap) re-walk from a stale stored `tail_hint`. On\n // the scheduled path (no `observedTail`) `nextSeq` is itself the\n // freshly-probed tail, so it's still a valid (tight) floor.\n knownTail: nextSeq,\n ...(signal !== undefined && { signal }),\n } as InternalCompactOptions);\n if (phasesPerTick === \"single\") {\n return; // this tick's one phase was the fold (attempt)\n }\n // \"both\": fall through to GC.\n } else {\n // DEFER: snapshot over the ceiling (bytes OR rows).\n // Graduation-pending. A deferring bucket MUST still GC, so we\n // fall through.\n ctxMetrics().counter(\"db.compaction.deferred_total\", 1, {\n collection,\n dimension: snapshotBytes > C ? \"bytes\" : \"rows\",\n });\n // HR-2: advance `tail_hint` toward the observed tail even though\n // we're NOT folding. A deferring collection never reaches the\n // compactor's Step-7 fold CAS, so without this bounded refresh\n // the gap `(true_tail − tail_hint)`\n // grows without bound and every READ re-walks the whole live tail\n // via `probeTailFrom` (and eventually throws at the cap, B3).\n // Rate-limited by `MAINTENANCE_TAIL_HINT_REFRESH_WRITES` so this is\n // NOT a per-commit `current.json` write (which single-write commit\n // removed); a deferring collection's read-walk stays bounded to\n // ≤ that interval. Best-effort / conflict-swallowing: a lost CAS\n // (e.g. against a concurrent compactor's fold CAS, or another\n // deferring isolate) just means someone else advanced it — the\n // stamp is monotone (`Math.max`) so a lost race never lowers it.\n // This is a WRITE-TICK action; reads stay pure.\n await refreshTailHintIfNeeded();\n // Advisory graduation warn, rate-limited off the SHARED\n // current.json.last_warned_seq (NOT a per-isolate Set — a fresh\n // isolate must honour the same rate-limit). Fires only when at\n // least MAINTENANCE_WARN_INTERVAL_WRITES writes have accrued\n // since the last warn, then best-effort CASes the stamp forward.\n if (nextSeq - (current.last_warned_seq ?? 0) >= MAINTENANCE_WARN_INTERVAL_WRITES) {\n console.warn(\n `baerly-storage: collection \"${collection}\" is deferring compaction — its ` +\n `snapshot exceeds the fold ceiling (${snapshotBytes > C ? `${C} bytes` : `${E} rows`}), ` +\n `so the tail keeps growing and read amplification will climb. The dataset has ` +\n `outgrown the maintenance envelope. On paid Cloudflare / Node you can raise ` +\n `BAERLY_MAINTENANCE_MAX_FOLD_BYTES — but on Cloudflare a cap above what a single ` +\n `isolate can fold makes folds get CPU-killed mid-flight and silently not land ` +\n `(no clean metric — watch snapshot age / object count); see docs/about/graduation.md. ` +\n `Otherwise, move to a database service (D1 / Postgres).`,\n );\n // SEPARATE best-effort CAS — explicitly NOT folded into any\n // commit CAS. A lost stamp just means another isolate warns\n // slightly sooner/later; it must never throw out of the runner\n // nor block the GC fall-through below.\n try {\n await casUpdateCurrentJson(\n storage,\n currentJsonKey,\n (c) => ({ ...c, last_warned_seq: nextSeq }),\n signal !== undefined ? { signal } : undefined,\n );\n } catch {\n // Swallow — Conflict (another isolate stamped first) or any\n // transient error. The warn already fired; GC must still run.\n }\n }\n }\n }\n\n // ── Step 4. GC phase — cadence-gated. ────────────────────────────\n // Reaching here on \"single\" means we did NOT fold (gate1 false, or\n // deferred). Run GC iff the cadence boundary was crossed.\n if (gcDue) {\n await runGc({ storage, currentJsonKey }, gcOpts);\n }\n } catch (error) {\n // CAS contention (Conflict) thrown by compact()/runGc() is an\n // EXPECTED signal — swallow without the unexpected-error counter.\n if (error instanceof BaerlyError && error.code === \"Conflict\") {\n return;\n }\n // Anything else is unexpected: count it, log the stack, swallow.\n ctxMetrics().counter(\"db.maintenance.unexpected_error_total\", 1, { collection });\n // The one intentional console sink in the runner — surface the stack for\n // operators, since the write-tick caller swallows the throw and emits no\n // canonical line for a post-response (waitUntil) maintenance pass.\n console.error(error);\n }\n};\n\n/**\n * Default maintenance dispatcher: run the task inline and await it.\n * Adapters that can keep running after the response (Cloudflare:\n * `ctx.waitUntil`) override this with a fire-and-forget variant that\n * returns `void`.\n */\nexport const dispatchInlineAwaited = (task: () => Promise<void>): void | Promise<void> => task();\n\n/**\n * Per-request maintenance dispatch config, set by the adapter onto the\n * observability context (NOT `Db.create`). It rides the per-request ALS\n * context because `dispatch = ctx.waitUntil` is inherently per-request,\n * and routing it through `Db.create` would widen that surface past its\n * locked four fields. The writer reads it at the post-commit dispatch\n * point via `getCurrentContext()?.maintenance`.\n *\n * Absent ⇒ inline dispatch + CF-free-safe caps (the defaults inside\n * {@link runBoundedMaintenance}), so a bare `Db.create(...)` maintains\n * out of the box once enough writes accrue.\n */\nexport interface MaintenanceDispatch {\n /** How to run the maintenance task. Default {@link dispatchInlineAwaited}. CF sets `ctx.waitUntil`. */\n readonly dispatch?: (task: () => Promise<void>) => void | Promise<void>;\n /** From `BAERLY_MAINTENANCE_DISABLE`: disables fold/GC phases while preserving tail_hint refresh. */\n readonly disabled?: boolean;\n /** `C` override, from `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`. */\n readonly maxFoldBytes?: number;\n /** Per-tier caps forwarded to {@link runBoundedMaintenance}. */\n readonly options?: BoundedMaintenanceOptions;\n}\n\n/**\n * Parse the two host-agnostic ops-plane env vars into the\n * {@link MaintenanceDispatch} overrides. Shared by every host adapter so the\n * cross-host contract has one source of truth: `maxFoldBytes` (`C`) is the\n * finite `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` or undefined; `disabled` is\n * `BAERLY_MAINTENANCE_DISABLE` truthy (set, non-empty, not `\"0\"`/`\"false\"`).\n */\nexport const parseMaintenanceEnv = (\n readEnv: (key: string) => string | undefined,\n): { maxFoldBytes?: number; disabled: boolean } => {\n const rawFoldBytes = readEnv(\"BAERLY_MAINTENANCE_MAX_FOLD_BYTES\");\n const parsedFoldBytes =\n rawFoldBytes !== undefined && rawFoldBytes !== \"\" ? Number(rawFoldBytes) : Number.NaN;\n const maxFoldBytes = Number.isFinite(parsedFoldBytes) ? parsedFoldBytes : undefined;\n\n const rawDisable = readEnv(\"BAERLY_MAINTENANCE_DISABLE\");\n const disabled =\n rawDisable !== undefined &&\n rawDisable !== \"\" &&\n rawDisable !== \"0\" &&\n rawDisable.toLowerCase() !== \"false\";\n\n return {\n ...(maxFoldBytes !== undefined && { maxFoldBytes }),\n disabled,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiGA,MAAa,gBAAgB,OAC3B,SACA,KACA,SACkC;CAClC,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AEnD,SAAS,OAAO;EAGd,IAAI,iBAAiB,eAAe,MAAM,SAAS,YACjD;EAGF,WAAW,CAAC,CAAC,QAAQ,yCAAyC,GAAG,EAAE,WAAW,CAAC;EAI/E,QAAQ,MAAM,KAAK;CACrB;AACF;;;;;;;AAQA,MAAa,yBAAyB,SAAoD,KAAK;;;;;;;;AAgC/F,MAAa,uBACX,YACiD;CACjD,MAAM,eAAe,QAAQ,mCAAmC;CAChE,MAAM,kBACJ,iBAAiB,KAAA,KAAa,iBAAiB,KAAK,OAAO,YAAY,IAAI;CAC7E,MAAM,eAAe,OAAO,SAAS,eAAe,IAAI,kBAAkB,KAAA;CAE1E,MAAM,aAAa,QAAQ,4BAA4B;CACvD,MAAM,WACJ,eAAe,KAAA,KACf,eAAe,MACf,eAAe,OACf,WAAW,YAAY,MAAM;CAE/B,OAAO;EACL,GAAI,iBAAiB,KAAA,KAAa,EAAE,aAAa;EACjD;CACF;AACF"}
@@ -1,5 +1,5 @@
1
- import { d as IndexDefinition } from "./app-config-BIzyAKzy.js";
2
- import { h as Storage, p as CurrentJson } from "./index-DW7GT6M2.js";
1
+ import { d as IndexDefinition } from "./app-config-DyiFK3_k.js";
2
+ import { d as CurrentJson, p as Storage } from "./index-BYk9oCNf.js";
3
3
  //#region packages/server/src/compactor.d.ts
4
4
  /**
5
5
  * Public configuration knobs for {@link compact}. All optional; the
@@ -374,11 +374,23 @@ interface MaintenanceProfile {
374
374
  * the 50 cap combined. The Cloudflare scheduled handler therefore
375
375
  * alternates phases per tick (even minute → compact, odd minute →
376
376
  * GC) by calling `compact()` / `runGc()` directly instead of
377
- * `runScheduledMaintenance`; the `maintenance.budget.test.ts`
377
+ * `runScheduledMaintenance`; the `maintenance-budget.test.ts`
378
378
  * worst-case test proves each phase in isolation sits under 50 ops
379
379
  * with these bounds.
380
380
  */
381
381
  declare const CLOUDFLARE_FREE_TIER: MaintenanceOptions;
382
+ /**
383
+ * Tuning profile for the 10,000-subrequest Cloudflare paid-tier budget,
384
+ * derived from {@link MAINTENANCE_PROFILE_CF_PAID} (one source of truth).
385
+ * Keeps the single-phase CPU-killable shape but affords Node-tier per-pass
386
+ * throughput (compact ≈ 3+200, gc ≈ 6+200+100 — far under the 10k cap).
387
+ *
388
+ * To honour `BAERLY_MAINTENANCE_PROFILE=cf-paid` on the cron path, pass this
389
+ * constant to `runScheduledMaintenance` inside your
390
+ * {@link WorkerScheduledHandler}; the worked recipe lives in the `scheduled`
391
+ * handler docstring of `baerlyWorker` (`@gusto/baerly-storage/cloudflare`).
392
+ */
393
+ declare const CLOUDFLARE_PAID_TIER: MaintenanceOptions;
382
394
  /**
383
395
  * Floor-based GC-cadence boundary crossing. Every commit advances the
384
396
  * writer-observed tail by one logical slot; `tail_hint` remains a
@@ -509,6 +521,17 @@ interface MaintenanceDispatch {
509
521
  /** Per-tier caps forwarded to {@link runBoundedMaintenance}. */
510
522
  readonly options?: BoundedMaintenanceOptions;
511
523
  }
524
+ /**
525
+ * Parse the two host-agnostic ops-plane env vars into the
526
+ * {@link MaintenanceDispatch} overrides. Shared by every host adapter so the
527
+ * cross-host contract has one source of truth: `maxFoldBytes` (`C`) is the
528
+ * finite `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` or undefined; `disabled` is
529
+ * `BAERLY_MAINTENANCE_DISABLE` truthy (set, non-empty, not `"0"`/`"false"`).
530
+ */
531
+ declare const parseMaintenanceEnv: (readEnv: (key: string) => string | undefined) => {
532
+ maxFoldBytes?: number;
533
+ disabled: boolean;
534
+ };
512
535
  //#endregion
513
- export { compact as C, CompactResult as S, rebuildIndex as _, MaintenanceDispatch as a, runGc as b, MaintenanceResult as c, estimateTailBytes as d, runBoundedMaintenance as f, RebuildIndexResult as g, RebuildIndexOptions as h, MaintenanceArgs as i, crossesGcBoundary as l, shouldFireMaintenance as m, CLOUDFLARE_FREE_TIER as n, MaintenanceOptions as o, runScheduledMaintenance as p, InternalMaintenanceOptions as r, MaintenanceProfile as s, BoundedMaintenanceOptions as t, dispatchInlineAwaited as u, RunGcOptions as v, CompactOptions as x, RunGcResult as y };
514
- //# sourceMappingURL=maintenance-BkhUr72A.d.ts.map
536
+ export { CompactOptions as C, runGc as S, compact as T, RebuildIndexOptions as _, MaintenanceArgs as a, RunGcOptions as b, MaintenanceProfile as c, dispatchInlineAwaited as d, estimateTailBytes as f, shouldFireMaintenance as g, runScheduledMaintenance as h, InternalMaintenanceOptions as i, MaintenanceResult as l, runBoundedMaintenance as m, CLOUDFLARE_FREE_TIER as n, MaintenanceDispatch as o, parseMaintenanceEnv as p, CLOUDFLARE_PAID_TIER as r, MaintenanceOptions as s, BoundedMaintenanceOptions as t, crossesGcBoundary as u, RebuildIndexResult as v, CompactResult as w, RunGcResult as x, rebuildIndex as y };
537
+ //# sourceMappingURL=maintenance-B_e0T99L.d.ts.map