@gusto/baerly-storage 0.5.0 → 0.7.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 (215) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -511
  3. package/dist/CHANGELOG.md +1148 -307
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +38 -39
  53. package/dist/dev-vite.js +67 -36
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
  68. package/dist/gcs.d.ts +30 -0
  69. package/dist/gcs.js +1 -0
  70. package/dist/goog4-signer-CeLIABoE.js +331 -0
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +130 -142
  103. package/dist/node.js +4 -3
  104. package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/sha256-4FfGQNPw.js +22 -0
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/sigv4-sign-5IUflUD_.js +507 -0
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +96 -69
  152. package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
  153. package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
  154. package/dist/bytes-BXdamO3L.js +0 -11
  155. package/dist/bytes-BXdamO3L.js.map +0 -1
  156. package/dist/cloudflare-DzKBrUlg.js.map +0 -1
  157. package/dist/config-1tv0-Yzm.js +0 -2693
  158. package/dist/config-1tv0-Yzm.js.map +0 -1
  159. package/dist/constants-CfeMWQWk.js +0 -222
  160. package/dist/constants-CfeMWQWk.js.map +0 -1
  161. package/dist/context-DRZ3tZ5l.js.map +0 -1
  162. package/dist/cost-DSMIVqzL.js +0 -203
  163. package/dist/cost-DSMIVqzL.js.map +0 -1
  164. package/dist/current-json-C6nhPOm1.js.map +0 -1
  165. package/dist/db-DsPkOVEH.d.ts +0 -254
  166. package/dist/deploy-DonTr-CV.js.map +0 -1
  167. package/dist/doctor-DSIyCDg_.js +0 -346
  168. package/dist/doctor-DSIyCDg_.js.map +0 -1
  169. package/dist/dump-Bh5k26VQ.js +0 -94
  170. package/dist/dump-Bh5k26VQ.js.map +0 -1
  171. package/dist/errors-Dfa3p78c.js +0 -78
  172. package/dist/errors-Dfa3p78c.js.map +0 -1
  173. package/dist/export-DtF5tDIM.js +0 -401
  174. package/dist/export-DtF5tDIM.js.map +0 -1
  175. package/dist/fsck-D_djMO5D.js +0 -279
  176. package/dist/fsck-D_djMO5D.js.map +0 -1
  177. package/dist/http-DGd5tbNs.js.map +0 -1
  178. package/dist/index-0rZcMBwy.d.ts +0 -115
  179. package/dist/index-BNRh23K9.d.ts +0 -162
  180. package/dist/index-BYk9oCNf.d.ts +0 -1112
  181. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  182. package/dist/inspect-6WZ-pC7-.js +0 -133
  183. package/dist/inspect-6WZ-pC7-.js.map +0 -1
  184. package/dist/log-tail-D98U1JBo.js +0 -522
  185. package/dist/log-tail-D98U1JBo.js.map +0 -1
  186. package/dist/maintenance-B4Dki6Ig.js +0 -2157
  187. package/dist/maintenance-B4Dki6Ig.js.map +0 -1
  188. package/dist/maintenance-B_e0T99L.d.ts +0 -537
  189. package/dist/maintenance-C7coQp4c.js +0 -1418
  190. package/dist/maintenance-C7coQp4c.js.map +0 -1
  191. package/dist/normalize-rjnZLwS4.js +0 -133
  192. package/dist/normalize-rjnZLwS4.js.map +0 -1
  193. package/dist/observability-BmflLCdF.js.map +0 -1
  194. package/dist/plan-a7PJHBCy.js.map +0 -1
  195. package/dist/query-rAtXNQQB.js +0 -1773
  196. package/dist/query-rAtXNQQB.js.map +0 -1
  197. package/dist/rebuild-index-BVzQSZlm.js +0 -81
  198. package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
  199. package/dist/request-u0M51mhJ.js +0 -72
  200. package/dist/request-u0M51mhJ.js.map +0 -1
  201. package/dist/restore-R-4rbciV.js +0 -778
  202. package/dist/restore-R-4rbciV.js.map +0 -1
  203. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  204. package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
  205. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  206. package/dist/src-BL_JoPTn.js.map +0 -1
  207. package/dist/src-CYHFDrKz.js +0 -536
  208. package/dist/src-CYHFDrKz.js.map +0 -1
  209. package/dist/src-DYZ4H1aF.js +0 -392
  210. package/dist/src-DYZ4H1aF.js.map +0 -1
  211. package/dist/subcommand-DoDA-K7d.js.map +0 -1
  212. package/dist/time-DUqvFMHq.js.map +0 -1
  213. package/dist/usage-DBV1eQHC.js.map +0 -1
  214. package/dist/validate-DtljsCh1.js.map +0 -1
  215. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"maintenance-Dd-Yakqj.js","names":[],"sources":["../packages/protocol/src/coordination/gc-pending.ts","../packages/protocol/src/metrics.ts","../packages/server/src/option-guards.ts","../packages/server/src/observability/context.ts","../packages/server/src/collection-key.ts","../packages/server/src/snapshot-projection.ts","../packages/server/src/compactor.ts","../packages/server/src/log-retention.ts","../packages/server/src/gc.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()` is the single\n * writer that adds and removes entries. Stays small in steady state\n * because every candidate is eventually resolved out of the ledger.\n *\n * \"Mark\" appends candidates with a future `due_at`; \"sweep\" revalidates\n * due candidates and either DELETEs the named object or resolves the\n * entry out of the ledger without one. Both run in the same GC pass, not\n * separate passes.\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, isWriteConflict } from \"../errors.ts\";\nimport { unsupportedSchemaVersionMessage } from \"./schema-version.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. Removing an optional,\n * ignored field can also remain schema v1 — old ledgers may carry it,\n * readers ignore it, and a later write may omit it. Renaming or removing\n * a required or semantically interpreted field is breaking and requires\n * bumping {@link GC_PENDING_SCHEMA_VERSION} to `2`; readers MUST reject\n * unknown major versions with `BaerlyError{code:\"InvalidResponse\"}`.\n */\nexport interface GcPending {\n /** Schema version. Today `1`. Readers MUST reject unknown majors. */\n schema_version: 1;\n /**\n * Candidate ledger entries. `runGc()` keeps this list bounded through\n * `mergeGcPending`, independently of its per-run mark and sweep caps.\n */\n candidates: ReadonlyArray<GcCandidate>;\n /**\n * Server-clock ISO-8601 timestamp of the last successful sweep\n * completion. Drives the `db.gc.entries_swept_per_second` metric.\n * Empty string `\"\"` before the first sweep.\n */\n last_swept_at: string;\n}\n\n/**\n * One pending ledger entry. The `runGc()` mark phase appends these with\n * a future `due_at`. Once due, the sweep gate either authorises an object\n * DELETE or resolves the entry without one, because generation/liveness\n * revalidation failed.\n */\nexport interface GcCandidate {\n /** Full bucket-relative key of the candidate artifact. */\n key: string;\n /** ISO-8601 server-clock time after which sweep may authorise a DELETE. */\n due_at: string;\n /**\n * Why the key is a candidate. `\"orphan-snapshot\"` is the only reason the\n * mark phase still emits; the other two survive in the union — and in\n * `VALID_REASONS` — because dropping either would make a v0.6\n * `gc/pending.json` fail to decode, stalling that collection's GC\n * entirely. They are not equivalent at sweep time:\n *\n * - `\"orphan-content\"` is **decode-only**: a v0.6.0 node can still emit\n * one during a mixed rollout, and the sweep gate evicts any it finds\n * *without* deleting the object.\n * - `\"stale-log\"` is **decode-and-sweep**: no current build marks one —\n * sub-floor log objects are reclaimed by computed-range retirement\n * (`packages/server/src/log-retention.ts`) — but a legacy entry that\n * clears the canonicality, generation, and liveness arms is still\n * DELETEd. That path advances no `log_delete_floor`, so it certifies\n * nothing; it is one-shot, since nothing re-marks the category.\n */\n reason: \"stale-log\" | \"orphan-snapshot\" | \"orphan-content\";\n /**\n * The `current.json` `generation` this candidate was marked under, if\n * the manifest carried one. The sweep drops — never deletes — a\n * candidate whose generation no longer matches the live manifest. That\n * stops a mark decision taken under one incarnation of a collection\n * from executing against a different one up to\n * `GC_GRACE_PERIOD_MILLIS` later.\n *\n * Optional and additive — an older reader ignores it — so\n * {@link GC_PENDING_SCHEMA_VERSION} is unchanged and a ledger written\n * by an older build stays valid. Absent decodes to `NO_GENERATION` on\n * both sides of the comparison, so a bucket whose manifest carries no\n * generation keeps reclaiming normally rather than fencing everything\n * off.\n */\n generation?: string;\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 * The single constructor for a `gc/pending.json` key:\n * `<collectionPrefix>/gc/pending.json`. `collectionPrefix` is the\n * `<…>/manifests/<collection>` segment — this helper adds the ledger's\n * relative path. Route all callers here so the key shape lives in one\n * place, mirroring {@link logObjectKey} in `log-key.ts` for the sibling\n * `log/<seq>.json` shape.\n */\nexport const gcPendingKey = (collectionPrefix: string): string =>\n `${collectionPrefix}/gc/pending.json`;\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(\"InvalidResponse\", `gc/pending.json at ${key}: body is not valid JSON`, {\n cause: 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:\"WriteConflict\"} — 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 `WriteConflict` (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 `WriteConflict`.\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:\"WriteConflict\"} — another writer kept landing a\n * write between this function's read and write for every\n * attempt, OR `key` does not exist. The missing-key case is a\n * CAS precondition failure, not a separate class of fault: the\n * pre-read is an optimisation, and a bare\n * `If-Match: <etag>` PUT against a key another actor deleted\n * would have surfaced `412` → `WriteConflict` from the storage layer\n * anyway. It is deliberately NOT retried — a deleted ledger\n * stays deleted until someone calls {@link createGcPending},\n * which the next `runGc` pass does. `baerly admin restore`\n * deletes `gc/pending.json` on both reseed branches, so a\n * concurrent pass reaches this routinely; `runGc` treats\n * `WriteConflict` as benign best-effort.\n * @throws BaerlyError{code:\"InvalidResponse\"} — the stored body doesn't\n * parse or fails the shape guard. Kept distinct from the\n * missing-key case on purpose: a caller that tolerates\n * `WriteConflict` as a race must not thereby swallow a corrupt\n * ledger, which fails identically on every future pass.\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 // `WriteConflict`, not `InvalidResponse`: the object was there when the\n // caller decided to update it and is not there now, which is the\n // If-Match precondition failing — the same 412 the storage layer\n // would have raised had this helper skipped its pre-read. Callers\n // that already tolerate a lost CAS therefore tolerate a ledger\n // deleted out from under them (`baerly admin restore`) without\n // also having to tolerate `InvalidResponse`, which stays reserved\n // for a body that is present but broken.\n throw new BaerlyError(\n \"WriteConflict\",\n `gc/pending.json at ${key} does not exist; it was deleted concurrently, or was never created — see createGcPending`,\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 `WriteConflict` is retryable — re-read latest and re-merge.\n // Anything else (AccessDenied, InvalidResponse, …) is terminal.\n if (!isWriteConflict(translated)) {\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 RESOLVED (`sweptKeys` carries both object DELETEs\n * and ledger-only drops/evictions), then APPEND every fresh mark whose\n * key is not already present AND was not itself resolved this pass. A\n * `graceMillis: 0` pass can mark-and-sweep a key in one go; re-adding a\n * terminal key would be wrong. Dedup also drops a key a concurrent pass\n * already marked. Capped at `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 */\nexport const mergeGcPending = (\n latest: GcPending,\n pass: {\n readonly sweptKeys: ReadonlySet<string>;\n readonly newCandidates: ReadonlyArray<GcCandidate>;\n readonly lastSweptAt: string;\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 resolved (DELETE, drop, or eviction)\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 return {\n schema_version: GC_PENDING_SCHEMA_VERSION,\n candidates,\n last_swept_at: lastSweptAt,\n };\n};\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\n/**\n * Accepted `reason` values. Only `\"orphan-snapshot\"` is still emitted; the\n * other two are legacy-ledger inputs with different sweep fates — see\n * {@link GcCandidate.reason}.\n */\nconst VALID_REASONS = new Set<GcCandidate[\"reason\"]>([\n // No longer emitted — sub-floor log objects are reclaimed by\n // computed-range retirement. Still accepted so a legacy ledger decodes,\n // and a legacy entry is still SWEPT (with a DELETE), not evicted.\n \"stale-log\",\n \"orphan-snapshot\",\n // Legacy-only AND decode-only: evicted without a DELETE.\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 unsupportedSchemaVersionMessage(\n `gc/pending.json at ${key}`,\n r[\"schema_version\"],\n GC_PENDING_SCHEMA_VERSION,\n ),\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 // Optional: absent is valid and means \"marked under a manifest with\n // no generation\". Present-but-not-a-string is a producer bug, and\n // this guard runs inside\n // `readGcPending` — GC's step-2 read — so rejecting here stalls the\n // collection's GC rather than letting a malformed candidate reach\n // the sweep gate, where a non-string would compare unequal to every\n // real generation and be silently dropped forever.\n if (cr[\"generation\"] !== undefined && typeof cr[\"generation\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json at ${key}: candidates[${String(i)}].generation must be a string when present`,\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 // `log_scan_cursor` is deprecated: stale log objects are now reclaimed\n // by a sequence window (see `log-retention.ts`) rather than a LIST/mark/cursor.\n // Retained for decode compatibility with legacy ledgers; dropped on merge.\n if (r[\"log_scan_cursor\"] !== undefined && typeof r[\"log_scan_cursor\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `gc/pending.json at ${key}: log_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. `WriteConflict` (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 (isWriteConflict(e)) {\n return new BaerlyError(\"WriteConflict\", `gc/pending.json CAS lost at ${key}: ${e.message}`, {\n cause: e,\n });\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 { cause: e },\n );\n};\n","/**\n * `MetricsRecorder` — internal emission contract for the load-bearing\n * kernel metrics. Writer / compactor / GC emit through\n * an instance of this interface; in production the instance is the\n * per-request `RequestScopedMetricsRecorder` on the active\n * `ObservabilityContext`, and emissions flow onto the canonical line\n * via `summarize()`. Tests use a local `InMemoryMetricsRecorder` and\n * wrap their workload in `runWithContext` to attach it.\n *\n * Operators do not wire a custom sink against this interface — the\n * operator's view of kernel emissions is the canonical line on\n * stdout (one JSON object per HTTP request).\n *\n * **Naming convention** matches the load-bearing metrics:\n * - `db.write.class_a_ops_per_logical_write` — histogram (recommend p99 alert ~5; not gated).\n * The committing log create, 1 per commit. Idle-reader cost is unchanged.\n * - `db.r2.put.412_total` — counter (CAS conflict / If-Match-or-None-Match loss)\n * - `db.r2.put.429_total` — counter (R2 prefix-partition rate-limit)\n * - `db.write.ambiguous_commit_total` — counter, labelled by `collection`\n * and `cleanup` (`deleted` / `failed`). A committing create won at a\n * sequence already certified deleted, so the commit failed with\n * `AmbiguousCommit` rather than acknowledging a mutation whose\n * visibility cannot be determined.\n * `cleanup` reports whether the phantom log object was reclaimed. Any\n * sustained rate means writers are pausing across a fold plus a\n * retirement pass; a `failed` rate leaves behind sub-floor objects that\n * leak permanently — they sit below `log_delete_floor`, where\n * computed-range retirement starts, so nothing revisits them\n * - `db.write.delete_floor_check_skipped_total` — counter, labelled by\n * `collection`. The post-create re-read of `current.json` inside\n * `Writer#assertCommitAboveDeleteFloor` failed with a non-abort error, so\n * the delete-floor check was skipped for that commit rather than\n * evaluated. A sustained rate means the check is not covering the writes\n * it exists to protect, even though no individual commit is rejected.\n * - `db.write.post_commit_refused_total` — counter, labelled by\n * `collection` and `phase` (`delete-floor-check`, the only post-commit\n * step). The request ledger refused a storage call of a step that runs\n * after a known commit; the step was skipped and the commit stands. The\n * floor check runs inside the commit's ledger hold, so a count means a call outside every hold, or a\n * platform cap below the ledger's limit, cut into it.\n * - `db.write.unresolved_create_total` — counter, labelled by\n * `collection`. A rejected committing create could not be resolved by\n * readback, so the commit failed with `AmbiguousCommit`.\n * - `db.write.maintenance_dispatch_failed_total` — counter, labelled by\n * `collection`. The maintenance dispatcher threw or rejected after a\n * durable commit, so that write's maintenance tick did not run.\n * - `db.write.insert_replayed_total` — counter, labelled by `collection`.\n * An SDK-minted insert (`mintedId`) found its identical row already\n * stored and returned it as the original success, committing nothing.\n * A rate tracks clients retransmitting inserts after lost responses.\n * - `db.read.decoded_entries_total` / `db.read.live_documents_total` /\n * `db.read.returned_rows_total` — counters, labelled by `collection`,\n * emitted together by every collection read (a read terminal, or a\n * write verb's pre-commit read). Units:\n * - decoded entries: snapshot rows plus log entries the fold decoded,\n * before predicate and limit. Entries, not documents: an `_id`\n * updated twice since the last fold counts three times, and a\n * deleted row still counts its `I` and its `D`.\n * - live documents: distinct documents live once the fold completes,\n * before predicate, order and limit.\n * - returned rows: rows left after predicate, order and limit — the\n * rows a read returns, the rows `count()` counts, or the rows a write\n * verb's read matched.\n * A never-provisioned collection reports zeros. A point read still\n * folds the whole collection, so a large decoded count beside one\n * returned row is that read's actual work. No threshold or cap attaches.\n * - `db.manifest.lag_window_depth` — gauge (alert at >100)\n * - `db.gc.entries_swept_per_second` — gauge (livelock indicator when <writes/s)\n * - `db.orphan.candidate_count` — gauge (`gc/pending.json` depth)\n * - `db.compact.entries_folded` — histogram (entries folded per run)\n * - `db.compaction.deferred_total` — counter, labelled by `collection`,\n * `dimension` (`bytes` / `rows`) and `gate` (`pre-fold` / `rebuild`).\n * The write-tick fold hit the snapshot ceiling (`C` / `E`) and did not\n * run: `log_seq_start` and log retention are frozen until it folds again.\n * Emitted once per deferral by the write-tick runner, never by compact().\n * - `db.compaction.deferred_bytes_total` / `db.compaction.deferred_rows_total`\n * — the same event under a per-dimension name, labelled by `collection`\n * and `gate`, because the canonical line keys counters by name and drops\n * labels\n * - `db.gc.swept_total` — counter (labelled by reason)\n * - `db.gc.dropped_total` — counter (labelled by cause: `stale-generation`\n * / `still-live`). Candidates resolved out of the ledger WITHOUT a\n * DELETE because the sweep gate re-checked them and found them no\n * longer eligible. A drop frees no bytes, so this is deliberately\n * not folded into `db.gc.swept_total` — a pass that reclaimed\n * nothing must not read as productive. One `stale-generation` spike\n * per restore or upgrade is expected; a sustained `still-live` rate\n * means the mark phase is misjudging liveness\n *\n * Names follow `db.<subsystem>.<metric>`, dot-separated, all-lowercase\n * snake_case segments. Labels are flat\n * `Readonly<Record<string, string>>` — no numbers, no nested objects.\n *\n * Metric emissions never throw on the hot path; the default\n * `noopMetricsRecorder` cannot throw.\n */\nexport interface MetricsRecorder {\n /** Monotonically-incrementing event count. */\n counter(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Point-in-time value. */\n gauge(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Distribution sample. */\n histogram(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n}\n\n/**\n * No-op recorder. Safe default when no operator sink is wired —\n * emission sites that read `getCurrentContext()?.recorder` fall\n * back to this outside an active `runWithContext` scope.\n */\nexport const noopMetricsRecorder: MetricsRecorder = {\n counter: (): void => {},\n gauge: (): void => {},\n histogram: (): void => {},\n};\n","/**\n * Shared pre-I/O validation for the internal maintenance option seams\n * (`InternalCompactOptions`, `InternalRunGcOptions`).\n *\n * Those seams are unvalidated by construction — reached by JS callers,\n * in-repo casts, and the `_internal/testing` subpath — yet their values\n * feed seq arithmetic and range bounds. A non-finite value must fail\n * before the first storage operation, so a rejected run costs nothing\n * durable. `compactor.ts` explains the specific NaN corruption at stake.\n *\n * Zero-import leaf beyond `BaerlyError`: both maintenance entry points\n * already carry that import, so consolidating here removes duplication\n * without widening either closure.\n */\n\nimport { BaerlyError } from \"@baerly/protocol\";\n\n/**\n * Throw `InvalidConfig` unless `value` is an integer at or above `min`.\n * `min` is `0` for a seq-shaped or count-shaped option (zero is a\n * meaningful \"do nothing\" bound) and `1` for one that must make at least\n * one unit of progress to be well-defined.\n *\n * Callers own the `undefined ⇒ default` decision before calling; this\n * guard rejects rather than defaults, so passing an absent option is a\n * caller bug, not a silently-tolerated input.\n */\nexport const requireIntegerOption = (\n fnName: string,\n collectionName: string,\n optionName: string,\n value: number,\n min: 0 | 1,\n): void => {\n if (!Number.isInteger(value) || value < min) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${fnName}(${collectionName}): ${optionName} must be a ${\n min === 0 ? \"non-negative\" : \"positive\"\n } integer, got ${String(value)}`,\n );\n }\n};\n","/**\n * Per-request observability context.\n *\n * One `ObservabilityContext` is created at the entry of each unit-of-\n * work (HTTP request, maintenance tick, GC sweep, rebuild run) and\n * carried through the call tree via {@link runWithContext} /\n * {@link getCurrentContext}, which delegates to a single module-level\n * `AsyncLocalStorage` instance.\n *\n * The context is intentionally tiny: an externally-set\n * {@link request_id}, a high-resolution `started_at`, and a mutable\n * {@link fields} bag used to accumulate canonical-line attributes\n * during the unit's lifecycle.\n *\n * The context shape is `readonly` everywhere it can be — only the\n * contents of `fields` are intended to mutate during a request. The\n * {@link fields} map itself is not `readonly` because callers (the\n * canonical-line emitter, middleware, the collection API once Dispatch\n * 3+ wires it up) need to set entries.\n *\n * The context carries no sampling state — every unit-of-work emits\n * one canonical line unconditionally; there is nothing to gate.\n *\n * ## Time source\n *\n * `started_at` uses `performance.now()` so durations can be\n * computed without worrying about wall-clock skew (NTP step,\n * leap-second smearing). `performance.now()` is part of both Node\n * 18+ and the Workers Runtime; we don't fall back to `Date.now()`.\n *\n * @example\n * ```ts\n * const ctx = createObservabilityContext({});\n * await runWithContext(ctx, async () => {\n * const inner = getCurrentContext();\n * inner?.fields.set(\"collection\", \"tickets\");\n * await doWork();\n * });\n * ```\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n type MetricsRecorder,\n noopMetricsRecorder,\n type RequestHold,\n type RequestLedger,\n setRequestHoldResolver,\n setRequestLedgerResolver,\n} from \"@baerly/protocol\";\n// Type-only import — `maintenance.ts` imports this module's runtime\n// values (`getCurrentContext`), so a value import here would form a\n// runtime cycle. A type-only edge erases at build time, so tsc /\n// rolldown see no cycle.\nimport type { MaintenanceDispatch } from \"../maintenance.ts\";\nimport type { ReadEnvelope } from \"../read-admission.ts\";\nimport { RequestScopedMetricsRecorder } from \"./recorder.ts\";\n\n/** Read-mostly per-request observability state. */\nexport interface ObservabilityContext {\n /** Externally-correlatable request identifier (UUID-ish). */\n readonly request_id: string;\n /** Monotonic `performance.now()` reading captured at construction. */\n readonly started_at: number;\n /**\n * Mutable bag for canonical-line attributes. Callers `obs.fields.set(\"k\", v)`;\n * the canonical-line flusher spreads this onto the emitted properties at\n * end-of-request.\n */\n readonly fields: Map<string, unknown>;\n /**\n * Per-request metrics bag. Lives on the context so adapters can\n * reach it from inside the `Db`'s `MetricsRecorder` callback via\n * `getCurrentContext()?.recorder` — no parallel `AsyncLocalStorage`\n * lookup. The canonical-line flusher reads its `summarize()` at\n * end-of-request and spreads the result onto the emitted line.\n */\n readonly recorder: RequestScopedMetricsRecorder;\n /**\n * The invocation's storage request budget. Set by the adapter that owns\n * the invocation (an HTTP request, a Workers cron tick) with its host's\n * limits. Every storage attempt run inside this context, `waitUntil`\n * work included, is charged to it by `retryStorageCall`, and one that\n * does not fit is refused before it is sent. Absent ⇒ nothing is charged.\n */\n readonly ledger?: RequestLedger;\n /**\n * A hold on `ledger` that storage calls in this context draw on first.\n * Set only by the writer, on a child context scoped to one commit slot's\n * calls (`Writer#withCommitHold`); work dispatched from outside that\n * scope never sees it.\n */\n readonly hold?: RequestHold;\n}\n\n/**\n * {@link ObservabilityContext} plus the adapter-set host wiring the kernel\n * reads: the write-tick maintenance dispatch and the read envelope. The\n * kernel's {@link createObservabilityContext} / {@link getCurrentContext}\n * use this type; the published `/observability` entry re-exports them\n * typed with the narrower public context.\n *\n * @internal\n */\nexport interface InternalObservabilityContext extends ObservabilityContext {\n /**\n * Per-request write-tick maintenance dispatch config. Set by the\n * adapter (NOT `Db.create`) so the inherently-per-request\n * `dispatch = ctx.waitUntil` and the env-var-derived caps ride the\n * same scope the kernel write-tick reads from. The `Writer`\n * consults `getCurrentContext()?.maintenance` at the post-commit\n * dispatch point. Absent ⇒ inline dispatch + CF-free-safe caps.\n */\n readonly maintenance?: MaintenanceDispatch;\n /**\n * The host's read envelope, set by the adapter with its host's bounds.\n * A read whose staged work falls outside it is refused whole with\n * `CapacityExceeded` (see `read-admission.ts`). Absent ⇒ reads are\n * bounded by the ledger alone.\n */\n readonly readEnvelope?: ReadEnvelope;\n}\n\n/**\n * Optional construction inputs. All fields are optional so callers in\n * unit-of-work entry middleware (HTTP router, maintenance scheduler)\n * can pass only what they have. Defaults:\n *\n * - `request_id`: a fresh `crypto.randomUUID()`. Pass an externally-\n * supplied id (`X-Request-Id` header, scheduler-supplied tag) to\n * propagate correlation downstream.\n * - `recorder`: a fresh {@link RequestScopedMetricsRecorder}. Tests can\n * pass an externally-constructed recorder to assert on its\n * `snapshot()` after the unit-of-work completes; production callers\n * should accept the default.\n */\nexport interface ObservabilityContextInit {\n readonly request_id?: string;\n readonly recorder?: RequestScopedMetricsRecorder;\n /** Storage request budget. See {@link ObservabilityContext.ledger}. */\n readonly ledger?: RequestLedger;\n}\n\n/**\n * {@link ObservabilityContextInit} plus the adapter-set host wiring of\n * {@link InternalObservabilityContext}.\n *\n * @internal\n */\nexport interface InternalObservabilityContextInit extends ObservabilityContextInit {\n /** Write-tick maintenance dispatch config. See {@link InternalObservabilityContext.maintenance}. */\n readonly maintenance?: MaintenanceDispatch;\n /** Read envelope. See {@link InternalObservabilityContext.readEnvelope}. */\n readonly readEnvelope?: ReadEnvelope;\n}\n\n/**\n * Factory for {@link ObservabilityContext}. We use a factory rather\n * than a class so consumers can structural-type the result and so\n * the `AsyncLocalStorage` slot type stays a plain interface — no\n * surprises around `instanceof` across realms (Workers vs Node).\n */\nexport const createObservabilityContext = (\n init: InternalObservabilityContextInit = {},\n): InternalObservabilityContext => ({\n request_id: init.request_id ?? crypto.randomUUID(),\n started_at: performance.now(),\n fields: new Map(),\n recorder: init.recorder ?? new RequestScopedMetricsRecorder(),\n ...(init.maintenance !== undefined && { maintenance: init.maintenance }),\n ...(init.ledger !== undefined && { ledger: init.ledger }),\n ...(init.readEnvelope !== undefined && { readEnvelope: init.readEnvelope }),\n});\n\n/**\n * Module-level slot. One instance per process — the Workers\n * Runtime's `nodejs_compat` flag wires `node:async_hooks` to a\n * per-request scope, so cross-request bleed is impossible there.\n */\nconst als = new AsyncLocalStorage<InternalObservabilityContext>();\n\n// Adapters import only `@baerly/protocol`, so `retryStorageCall` finds the\n// active invocation's ledger through this resolver.\nsetRequestLedgerResolver(() => als.getStore()?.ledger);\nsetRequestHoldResolver(() => als.getStore()?.hold);\n\n/**\n * Run `fn` with `ctx` active as the current observability context.\n * Inside `fn` (and any `await`-chained continuation rooted in `fn`),\n * {@link getCurrentContext} returns `ctx`. Outside, it returns the\n * previously-active context (or `undefined`).\n *\n * `runWithContext` is async-safe via `AsyncLocalStorage`; it propagates\n * through `await`, `Promise.all`, `setTimeout`, and `queueMicrotask`.\n *\n * Returns `fn`'s return value verbatim — including its promise\n * identity, so callers can `await` or chain off it without extra\n * indirection.\n */\nexport const runWithContext = <T>(\n ctx: ObservabilityContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> => als.run(ctx, fn);\n\n/** Returns the currently-active context, or `undefined` outside one. */\nexport const getCurrentContext = (): InternalObservabilityContext | undefined => als.getStore();\n\n/** The active context's recorder, or the no-op recorder outside one. */\nexport const ctxMetrics = (): MetricsRecorder =>\n getCurrentContext()?.recorder ?? noopMetricsRecorder;\n","/**\n * Splits a `current.json` key (`<collectionPrefix>/current.json`) into the\n * collection's key prefix and its trailing name segment. `compact()`,\n * `runGc()`, `retireLogRange()` and the maintenance runner all take the\n * key and derive these the same way.\n */\nexport const collectionFromCurrentJsonKey = (\n currentJsonKey: string,\n): { prefix: string; name: string } => {\n const prefix = currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"));\n return { prefix, name: prefix.slice(prefix.lastIndexOf(\"/\") + 1) };\n};\n","/**\n * Byte-exact projection of the snapshot a fold rebuilds, entry by entry,\n * as the compactor encodes it. Shared by the growth-refusal check\n * (`./capacity.ts`) and the compactor's bytes cut (`./compactor.ts`), so\n * the two agree on where a fold can stop; a module of its own because the\n * compactor cannot import `./capacity.ts` without a cycle through\n * `./maintenance.ts`.\n */\n\nimport {\n type CurrentJson,\n type DocumentData,\n encodeJsonBytes,\n SNAPSHOT_SCHEMA_VERSION,\n} from \"@baerly/protocol\";\nimport { encodeSnapshotBody } from \"./snapshot.ts\";\n\n/** Encoded size of one snapshot row: the `{ _id, body }` element the compactor writes. */\nexport const rowBytes = (docId: string, body: DocumentData): number =>\n encodeJsonBytes({ _id: docId, body }).byteLength;\n\n/** Separators between `rows` elements of the snapshot's `docs` array. */\nconst separators = (rows: number): number => Math.max(rows - 1, 0);\n\n/**\n * Encoded size of an empty snapshot body for `collection` whose header\n * records `max_seq`. Rows add their own bytes plus one separator between\n * each pair, inside the `docs` array.\n */\nconst headerBytes = (collection: string, maxSeq: number): number =>\n encodeSnapshotBody({\n schema_version: SNAPSHOT_SCHEMA_VERSION,\n min_seq: 0,\n max_seq: maxSeq,\n collection,\n docs: [],\n }).byteLength;\n\n/** Running projection of a snapshot as log entries fold onto it. */\nexport interface SnapshotProjection {\n /** Fold one entry onto the projection. */\n apply(op: \"I\" | \"U\" | \"D\", docId: string, after: DocumentData | undefined): void;\n /** Whether folding this entry would add a row (an `I` / `U` with a post-image for an absent row). */\n addsRow(op: \"I\" | \"U\" | \"D\", docId: string, after: DocumentData | undefined): boolean;\n readonly rows: number;\n /** Encoded size with the header the projection currently carries. */\n readonly bytes: number;\n /** Encoded size of the snapshot a fold ending at `maxSeq` writes: exact. */\n bytesAt(maxSeq: number): number;\n /** Largest `rows` / `bytes` seen at any prefix, the starting state included. */\n readonly peakRows: number;\n readonly peakBytes: number;\n /**\n * Restart the peaks at the current state, as once everything applied so\n * far has folded through `maxSeq`, which the header then records.\n */\n settle(maxSeq: number): void;\n}\n\n/**\n * Project the snapshot a fold would build from `head`'s stored figures and\n * its rows (`base`), one entry at a time, byte for byte as the compactor\n * encodes it: each row, one separator between rows, and the header, whose\n * `max_seq` is the fold's end. A stored snapshot's `max_seq` is\n * `log_seq_start` (the compactor writes both from the same fold end); a\n * never-folded collection (`snapshot_bytes === 0`) starts empty at 0.\n *\n * `bytes` keeps the stored header, so a growth check made now does not\n * know the `max_seq` its fold will record; `CAPACITY_BYTES_MARGIN` covers\n * that header growth. `bytesAt` is exact for a fold whose end is known.\n *\n * @internal — exported for `capacity.test.ts`.\n */\nexport const projectSnapshot = (\n head: Pick<CurrentJson, \"snapshot_rows\" | \"snapshot_bytes\" | \"log_seq_start\">,\n base: ReadonlyMap<string, DocumentData>,\n collection: string,\n): SnapshotProjection => {\n // Current encoded size of each row touched so far; `null` = absent.\n const overlay = new Map<string, number | null>();\n const sizeOf = (docId: string): number | undefined => {\n const known = overlay.get(docId);\n if (known !== undefined) {\n return known ?? undefined;\n }\n const body = base.get(docId);\n return body === undefined ? undefined : rowBytes(docId, body);\n };\n const folded = head.snapshot_bytes !== 0;\n let header = headerBytes(collection, folded ? head.log_seq_start : 0);\n let rows = head.snapshot_rows;\n // Encoded rows without separators.\n let rowSum = folded ? head.snapshot_bytes - header - separators(rows) : 0;\n const sizeNow = (): number => header + rowSum + separators(rows);\n let peakRows = rows;\n let peakBytes = sizeNow();\n return {\n get rows() {\n return rows;\n },\n get bytes() {\n return sizeNow();\n },\n get peakRows() {\n return peakRows;\n },\n get peakBytes() {\n return peakBytes;\n },\n bytesAt(maxSeq: number): number {\n return headerBytes(collection, maxSeq) + rowSum + separators(rows);\n },\n addsRow(op: \"I\" | \"U\" | \"D\", docId: string, after: DocumentData | undefined): boolean {\n return op !== \"D\" && after !== undefined && sizeOf(docId) === undefined;\n },\n apply(op: \"I\" | \"U\" | \"D\", docId: string, after: DocumentData | undefined): void {\n // An `I` / `U` with no post-image is skipped, as the fold skips it.\n if (op !== \"D\" && after === undefined) {\n return;\n }\n const before = sizeOf(docId);\n if (op === \"D\" || after === undefined) {\n if (before !== undefined) {\n rows -= 1;\n rowSum -= before;\n }\n overlay.set(docId, null);\n return;\n }\n const next = rowBytes(docId, after);\n if (before === undefined) {\n rows += 1;\n }\n rowSum += next - (before ?? 0);\n overlay.set(docId, next);\n peakRows = Math.max(peakRows, rows);\n peakBytes = Math.max(peakBytes, sizeNow());\n },\n settle(maxSeq: number): void {\n header = headerBytes(collection, maxSeq);\n peakRows = rows;\n peakBytes = sizeNow();\n },\n };\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 assertCurrentJsonTransition,\n COMPACT_FOLD_WRITE_REQUESTS,\n encodeJsonBytes,\n type LogEntry,\n logSeqStartOf,\n isWriteConflict,\n readCurrentJson,\n SNAPSHOT_SCHEMA_VERSION,\n snapshotHash,\n type Storage,\n type StoragePutOptions,\n} from \"@baerly/protocol\";\nimport { requireIntegerOption } from \"./option-guards.ts\";\nimport { walkLogRangeWithBytes } from \"./log-walk.ts\";\nimport { probeTailChunk, probeTailFrom, type TailProbeChunk } from \"./log-tail.ts\";\nimport { ctxMetrics, getCurrentContext } from \"./observability/context.ts\";\nimport { collectionFromCurrentJsonKey } from \"./collection-key.ts\";\nimport {\n encodeSnapshotBody,\n loadSnapshotAsMap,\n type SnapshotBody,\n snapshotKey,\n} from \"./snapshot.ts\";\nimport { isOwnCollection } from \"./collection-alias.ts\";\nimport { projectSnapshot } from \"./snapshot-projection.ts\";\n\n/**\n * Base options for {@link compact}, unpublished like `compact` itself. 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. A snapshot-producing run's I/O profile includes the\n * current read, bounded tail probe, optional prior snapshot read, folded\n * log reads, and two writes (snapshot PUT plus `current.json` CAS). A\n * probe-budget checkpoint instead writes only the `current.json` CAS.\n * The default is effectively unbounded (`Number.MAX_SAFE_INTEGER`).\n */\n readonly maxEntriesPerRun?: number;\n\n /**\n * @internal Maximum consecutive log GETs spent discovering the tail\n * during one compaction run. Inside an invocation whose request ledger\n * has less left, the probe is lowered further so the fold it certifies\n * still fits (see {@link COMPACT_FOLD_WRITE_REQUESTS}). An exhausted\n * budget checkpoints the certified lower bound in `current.json` so the\n * next run resumes from there. Must be a positive integer. When omitted,\n * the default path uses the strict protocol-capped probe, which throws\n * rather than accepting a partial result.\n */\n readonly maxTailProbeGets?: number;\n\n /**\n * @internal SNAPSHOT-axis byte ceiling. The fold applies the longest\n * prefix of the range whose rebuilt snapshot body (NOT snapshot + tail)\n * stays `<= ceilingBytes`, sized entry by entry as the body encodes. A\n * range with no such prefix, or a body over the ceiling once encoded\n * (a stale `snapshot_bytes`), is DEFERRED before the PUT.\n * `undefined ⇒ no ceiling` (`Infinity`). The write-tick runner threads\n * `C` here; on a CPU-limited CF isolate an invocation terminated during\n * walk+encode never reaches this, so the decisive CF guard is the\n * runner's pre-fold gate on the stored snapshot.\n */\n readonly ceilingBytes?: number;\n\n /**\n * @internal SNAPSHOT-axis row ceiling. The fold applies the longest\n * prefix of the range whose rebuilt row count stays `<= ceilingEntries`:\n * it stops before the first entry that would add a row once the\n * snapshot holds `ceilingEntries` rows, so updates and deletes keep\n * folding at the ceiling. A prefix that folds nothing, or a rebuilt\n * snapshot still over the ceiling (the stored snapshot was already\n * larger), 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 probes\n * UP from this floor and, within `maxTailProbeGets`, either discovers the\n * exact tail or certifies an exclusive lower bound that it checkpoints;\n * the latter is not the exact tail. Absent on the scheduled path ⇒ probe\n * from `max(log_seq_start, 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 /**\n * Reason `written === false`. `\"probe-budget-checkpointed\"` means the\n * explicitly budgeted tail probe could not finish: no snapshot was\n * published, but the certified tail lower bound was durably checkpointed\n * in `current.json`. A later scheduled `compact()` invocation resumes\n * probing from that checkpoint.\n */\n readonly skippedReason?:\n | \"below-min-threshold\"\n | \"current-json-missing\"\n | \"cas-lost\"\n | \"deferred\"\n | \"probe-budget-checkpointed\";\n /** `true` on the over-ceiling rebuild-defer path (`skippedReason === \"deferred\"`). */\n readonly deferred?: boolean;\n /**\n * Present iff `skippedReason === \"deferred\"`: which ceiling the rebuilt\n * snapshot tripped and its measured size. Nothing was written.\n */\n readonly deferral?: {\n readonly dimension: \"bytes\" | \"rows\";\n /** Encoded byte length of the rebuilt (unwritten) snapshot body. */\n readonly snapshotBytes: number;\n /** Row count of the rebuilt (unwritten) snapshot. */\n readonly snapshotRows: number;\n };\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\n/**\n * {@link CompactResult} plus the storage keys of the snapshot objects the\n * run read and wrote. Returned by {@link compactInternal}; surfaced via\n * the `@baerly/server/_internal/testing` subpath. The public\n * {@link compact} return type omits these so the published result stays\n * independent of the snapshot object layout.\n *\n * @internal\n */\nexport interface InternalCompactResult extends CompactResult {\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}\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\"}` — 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=\"InvalidConfig\" — `maxEntriesPerRun` or\n * `knownTail` (the `InternalCompactOptions` seam) is not a\n * non-negative integer, or `maxTailProbeGets` is not a positive\n * integer. Checked before any I/O: a non-finite value would otherwise\n * slip the range guards and write an unreadable `current.json`.\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 \"@baerly/server/_internal/maintenance\";\n *\n * const res = await compact(\n * { storage, currentJsonKey: \"app/x/tenant/t/manifests/tickets/current.json\" },\n * { minEntriesToCompact: 100 },\n * );\n * if (res.written) console.log(\"folded\", res.entriesFolded, \"entries\");\n * ```\n */\nexport const compact: (\n args: {\n storage: Storage;\n /** Full bucket-relative key of the CAS pointer. */\n currentJsonKey: string;\n },\n options?: CompactOptions,\n) => Promise<CompactResult> = (args, options) => compactInternal(args, options);\n\n/**\n * {@link compact}, typed to return the {@link InternalCompactResult}\n * snapshot keys. Tests and in-repo tooling reach it via the\n * `@baerly/server/_internal/testing` subpath.\n *\n * @internal\n */\nexport const compactInternal = async (\n args: {\n storage: Storage;\n /** Full bucket-relative key of the CAS pointer. */\n currentJsonKey: string;\n },\n options: CompactOptions = {},\n): Promise<InternalCompactResult> => {\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 maxTailProbeGets = internal.maxTailProbeGets;\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 { prefix: collectionPrefix, name: collectionName } =\n collectionFromCurrentJsonKey(currentJsonKey);\n\n // Validate the options that feed seq arithmetic, before any I/O.\n // `InternalCompactOptions` is an unvalidated seam — reached by JS\n // callers, in-repo casts, and the `_internal/testing` subpath. A\n // non-finite value must never reach the fold: NaN slips\n // every `<`/`>` guard below (`Math.min(nextSeq, NaN)` is NaN), lands a\n // snapshot at a `…-00000000000NaN-…` key, and CASes\n // `log_seq_start: null` — JSON.stringify renders NaN as null — after\n // which every read path throws InvalidResponse, including\n // `admin restore --force`, which reads `current.json` before reaching\n // its own floor exemption. Nothing shipped can repair that.\n //\n // Validating here rather than leaning on the Step 7 floor guard also\n // buys the monotonicity invariant outright: with `maxPerRun >= 0` and\n // `nextSeq >= logSeqStartBefore` (guaranteed by `probeFloor`),\n // `foldEnd >= logSeqStartBefore` holds by construction, so that guard\n // never fires — and a rejected run costs no orphan snapshot, because\n // nothing has been written yet. The ceilings are deliberately\n // not checked: a NaN there fails the viability comparisons closed\n // (defer), which is the safe direction.\n const requireSeqOption = (name: string, value: number): void =>\n requireIntegerOption(\"compact\", collectionName, name, value, 0);\n requireSeqOption(\"maxEntriesPerRun\", maxPerRun);\n requireSeqOption(\"knownTail\", internal.knownTail ?? 0);\n if (maxTailProbeGets !== undefined) {\n requireIntegerOption(\"compact\", collectionName, \"maxTailProbeGets\", maxTailProbeGets, 1);\n }\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 a bounded chunk of the tail and stamp the certified\n // lower bound (or exact tail) as the new `tail_hint` (Step 7).\n // Ordinary writer commits never advance `tail_hint` under single-write\n // commit; compaction folds are the primary durable advancer, with\n // maintenance defer/disable refreshes and explicit operator/import paths\n // as the other writers. An exhausted probe budget checkpoints its lower\n // bound before a below-threshold return, so a future run resumes there.\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 let probe: TailProbeChunk;\n if (maxTailProbeGets === undefined) {\n const exact = await probeTailFrom(storage, collectionPrefix, probeFloor, {\n ...(options.signal !== undefined && { signal: options.signal }),\n });\n probe = { kind: \"exact\", ...exact, complete: true };\n } else {\n // Size the probe from the invocation's request ledger, net of the fold\n // it may certify: the prior-snapshot GET, `maxPerRun` log GETs and the\n // two fold writes. Without this, a probe of `maxTailProbeGets` behind a\n // stale `tail_hint` certifies a fold the ledger then refuses mid-walk,\n // before anything is written, and every later pass repeats it. Room\n // for no probe at all leaves the stored hint as the lower bound.\n const foldReserve =\n (current.snapshot === null ? 0 : 1) + maxPerRun + COMPACT_FOLD_WRITE_REQUESTS;\n const requestsLeft = getCurrentContext()?.ledger?.storageRemaining() ?? Infinity;\n probe = await probeTailChunk(storage, collectionPrefix, probeFloor, {\n ...(options.signal !== undefined && { signal: options.signal }),\n cap: Math.max(0, Math.min(maxTailProbeGets, requestsLeft - foldReserve)),\n });\n }\n const tailIsExact = probe.kind === \"exact\";\n const discoveredTail = probe.kind === \"exact\" ? probe.tail : probe.lowerBound;\n const nextSeq = discoveredTail;\n const available = nextSeq - logSeqStartBefore;\n if (available < minToCompact) {\n if (!tailIsExact && discoveredTail <= current.tail_hint) {\n // The ledger left no probe: nothing new to checkpoint.\n return {\n written: false,\n skippedReason: \"probe-budget-checkpointed\",\n previousSnapshotKey: current.snapshot,\n logSeqStartBefore,\n logSeqStartAfter: logSeqStartBefore,\n entriesFolded: 0,\n };\n }\n if (!tailIsExact) {\n const checkpoint: CurrentJson = {\n ...current,\n tail_hint: Math.max(current.tail_hint, discoveredTail),\n };\n assertCurrentJsonTransition(current, checkpoint, currentJsonKey);\n const checkpointBody = encodeJsonBytes(checkpoint);\n const checkpointCasOpts: StoragePutOptions = {\n ifMatch: baseEtag,\n contentType: APPLICATION_JSON,\n ...(options.signal !== undefined && { signal: options.signal }),\n };\n try {\n await storage.put(currentJsonKey, checkpointBody, checkpointCasOpts);\n } catch (error) {\n if (isWriteConflict(error)) {\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 logSeqStartBefore,\n logSeqStartAfter: logSeqStartBefore,\n entriesFolded: 0,\n };\n }\n throw error;\n }\n return {\n written: false,\n skippedReason: \"probe-budget-checkpointed\",\n previousSnapshotKey: current.snapshot,\n logSeqStartBefore,\n logSeqStartAfter: logSeqStartBefore,\n entriesFolded: 0,\n };\n }\n // Observable by contract, not just by return value: a caller that\n // discards the result (a cron loop, an admin route) must still be able\n // to tell \"folded nothing because nothing was foldable\" apart from\n // \"folded nothing for months because the floor sat above the tail\".\n // Idle (`available === 0`) is not a dead zone — after floor 1 the\n // default scheduled path only skips when idle, so counting that would\n // make the playbook counter mean \"the cron fired\". Emit only when a\n // live tail was left under the floor.\n if (available > 0) {\n ctxMetrics().counter(\"db.compaction.below_min_total\", 1, { collection: collectionName });\n }\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 // `foldEnd >= logSeqStartBefore` by construction: `maxPerRun` is a\n // validated non-negative integer and `nextSeq >= logSeqStartBefore`\n // via `probeFloor`. Step 7's CAS can't route through\n // `casUpdateCurrentJson` (it must If-Match the etag we folded from),\n // so it calls `assertCurrentJsonTransition` directly before its PUT —\n // that check is what enforces monotonicity here; the construction\n // above is why it never fires.\n let 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 // ── Step 4. Choose the fold end, then 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 //\n // Row ceiling: stop before the first entry that would add a row to a\n // snapshot already holding `ceilingEntries` rows, and fold only the\n // prefix before it. Counting real rows (not entries) lets an\n // update/delete tail fold a full pass at the ceiling, and the count is\n // taken against the `current.json` this run read, so no caller's stale\n // estimate can push the rebuild past the ceiling.\n //\n // Byte ceiling: of that prefix, fold the longest one whose rebuilt\n // snapshot stays `<= ceilingBytes`, sized entry by entry exactly as\n // Step 5 encodes it (`projectSnapshot`, the projection the growth\n // refusal check runs). Whether a prefix fits depends only on the log up\n // to its end, so a byte-heavy entry no longer pins a whole pass: the\n // prefix before it folds, and the next pass starts at that entry, where\n // a delete or shrink behind it can bring the snapshot back within `C`.\n // Step 5b still checks the encoded body exactly before the PUT.\n const own = (entry: LogEntry): entry is LogEntry & { doc_id: string } =>\n isOwnCollection(entry.collection, collectionName) && entry.doc_id !== undefined;\n let applied = fetched.length;\n let rowsStopped = false;\n if (ceilingBytes !== Number.POSITIVE_INFINITY || ceilingEntries !== Number.POSITIVE_INFINITY) {\n // Row count from the loaded body itself, as the apply loop below sees it.\n const projection = projectSnapshot(\n { ...current, snapshot_rows: base.size },\n base,\n collectionName,\n );\n let rowsEnd = 0;\n let fits = 0;\n for (const { entry } of fetched) {\n if (own(entry)) {\n // `!(<)`, not `>=`: a NaN ceiling stops the fold (fails closed).\n if (\n projection.addsRow(entry.op, entry.doc_id, entry.after) &&\n !(projection.rows < ceilingEntries)\n ) {\n rowsStopped = true;\n break;\n }\n projection.apply(entry.op, entry.doc_id, entry.after);\n }\n rowsEnd++;\n // `<=` so a NaN ceiling never fits (fails closed).\n if (projection.bytesAt(logSeqStartBefore + rowsEnd) <= ceilingBytes) {\n fits = rowsEnd;\n }\n }\n applied = fits;\n // Nothing fits. Defer before spending the apply + sort + encode; the\n // rebuilt snapshot would be the stored one. `rows` when the first\n // entry adds a row at the ceiling, else `bytes`: every prefix the row\n // ceiling allows rebuilds past `C` (reported at its longest).\n if (applied === 0 && fetched.length > 0) {\n const byRows = rowsStopped && rowsEnd === 0;\n return {\n written: false,\n skippedReason: \"deferred\",\n deferred: true,\n deferral: {\n dimension: byRows ? \"rows\" : \"bytes\",\n snapshotBytes: byRows\n ? current.snapshot_bytes\n : projection.bytesAt(logSeqStartBefore + rowsEnd),\n snapshotRows: byRows ? base.size : projection.rows,\n },\n previousSnapshotKey: current.snapshot,\n logSeqStartBefore,\n logSeqStartAfter: logSeqStartBefore,\n entriesFolded: 0,\n };\n }\n }\n for (const { entry } of fetched.slice(0, applied)) {\n if (!own(entry)) {\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 foldEnd = logSeqStartBefore + applied;\n // Sum the STORED body bytes over every fetched object in the folded\n // prefix `[logSeqStartBefore, foldEnd)`, including entries the loop\n // skipped (other collections, no `doc_id`). This sum / entry count gives\n // `mean_entry_bytes`, the compactor-stamped basis for the derived\n // live-tail estimate the maintenance trigger reads.\n const foldedSliceBytes = fetched.slice(0, applied).reduce((sum, f) => sum + f.bytes, 0);\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`. Step 4 already stopped the fold at\n // the row ceiling, so the rows arm here only trips when the STORED\n // snapshot was over it (folded on a larger host) and the prefix did not\n // shrink it back. Step 4 also cut the fold at the byte ceiling from the\n // projection, so the bytes arm only trips if `snapshot_bytes` disagrees\n // with the stored body; it is the exact check on what would be\n // published. On a CPU-limited CF isolate an invocation terminated during\n // the walk + encode above never reaches either, so the decisive CF guard\n // is the runner's pre-fold gate (see maintenance.ts\n // `runBoundedMaintenance`). When over ceiling we DEFER: no PUT, no\n // CAS, no current.json mutation.\n //\n // No metric here: the caller that threaded the ceilings (the write-tick\n // runner) owns the one deferral signal for both gates, so a deferral\n // counts once. `deferral` carries the rebuilt figures it reports.\n // Written as `!(<=)` so a NaN ceiling defers (fails closed).\n const bytesFit = bodyBytes.byteLength <= ceilingBytes;\n if (!(bytesFit && base.size <= ceilingEntries)) {\n return {\n written: false,\n skippedReason: \"deferred\",\n deferred: true,\n deferral: {\n dimension: bytesFit ? \"rows\" : \"bytes\",\n snapshotBytes: bodyBytes.byteLength,\n snapshotRows: base.size,\n },\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 assertCurrentJsonTransition(current, next, currentJsonKey);\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 (isWriteConflict(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 // `entriesFolded` on cas-lost is the count attempted\n // (`foldEnd - logSeqStartBefore`), not zero. The snapshot was built and\n // written before publication lost its CAS; deferred folds read no range.\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 if (tailIsExact) {\n metrics.gauge(\"db.manifest.lag_window_depth\", discoveredTail - foldEnd, {\n collection: collectionName,\n });\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 * Sequence-based log retention.\n *\n * Log keys are derivable, so retirement uses a half-open sequence range rather\n * than LIST-based discovery. This module computes the range and owns the\n * CAS-then-delete retirement pass. Every maintenance trigger runs it through\n * the shared `retireLogs` helper in `maintenance.ts`: `runScheduledMaintenance`\n * after its GC phase, and `runBoundedMaintenance` on the hard-GC early-return\n * path and as its final step.\n */\n\nimport {\n BaerlyError,\n casUpdateCurrentJson,\n certifiedDeleteFloor,\n type CurrentJson,\n LOG_RETENTION_MAX_DELETES_PER_TICK,\n LOG_RETENTION_SEQ_WINDOW,\n logDeleteFloorOf,\n logObjectKey,\n logSeqStartOf,\n readCurrentJson,\n type Storage,\n} from \"@baerly/protocol\";\nimport { collectionFromCurrentJsonKey } from \"./collection-key.ts\";\n\n/** A half-open `[start, end)` sequence range. Empty when equal. */\nexport interface RetirableRange {\n readonly start: number;\n readonly end: number;\n}\n\n/** Compute the budgeted prefix of the currently retirable log range. */\nexport const computeRetirableRange = (\n current: CurrentJson,\n opts?: { window?: number; maxDeletes?: number },\n): RetirableRange => {\n const window = opts?.window ?? LOG_RETENTION_SEQ_WINDOW;\n const maxDeletes = opts?.maxDeletes ?? LOG_RETENTION_MAX_DELETES_PER_TICK;\n const liveFloor = logSeqStartOf(current);\n const start = certifiedDeleteFloor(current);\n const boundary = Math.min(liveFloor - window, liveFloor); // clamps a negative window seam only\n const end = Math.max(start, Math.min(boundary, start + maxDeletes));\n return { start, end };\n};\n\n/** Outcome of one budgeted {@link retireLogRange} call. */\nexport interface RetireLogRangeResult {\n /**\n * Count of DELETEs issued this call — the authorized range's width. An\n * already-absent target is not an error (idempotent under crash-repeat, per\n * the {@link Storage} DELETE contract), so this is a request count, not a\n * count of objects that were physically present.\n *\n * This does NOT cover the call's full storage-call cost: an active pass also\n * issues 2 GETs (the advisory gate read, then {@link casUpdateCurrentJson}'s\n * own read) + 1 PUT (the floor CAS), and a no-op pass (empty gate) still\n * costs 1 GET. A caller budgeting a tick against a per-invocation request\n * limit (the combined GC-sweep + fold + retirement total that\n * {@link LOG_RETENTION_MAX_DELETES_PER_TICK}'s JSDoc derives) must add those\n * manifest round-trips itself; `deleted` alone undercounts.\n *\n * Two states make {@link computeRetirableRange} return an empty range, so\n * the pass no-ops until a fold advances `log_seq_start` past the stored\n * floor plus the window: a raised window whose boundary drops below the\n * certified floor (the stored floor is at most `log_seq_start` here — the\n * transition validator throws `Internal` on anything above it), and a\n * stored floor genuinely above `log_seq_start`, reachable only via a\n * `restore --force` reseed or a legacy/hand-edited manifest, which\n * `certifiedDeleteFloor` clamps to `log_seq_start` per\n * `docs/spec/sync-protocol.md` invariant 12. Both are temporary stalls,\n * not permanent wedges — the next fold that clears the window unblocks\n * them.\n */\n readonly deleted: number;\n}\n\n/**\n * Delete a budgeted, computed slice of the stale log prefix and advance\n * `log_delete_floor` to match. Sequence-based: log keys are derivable, so this\n * never LISTs.\n *\n * **The authorized range is computed inside the CAS mutator, against the state\n * the CAS validates — do not hoist it out.** {@link casUpdateCurrentJson}\n * performs its own read and CASes against *that* etag, so a range computed from\n * an earlier read is a plan the CAS never validated. Computing it in the mutator\n * makes plan and validation atomic: whatever floor this call publishes is the\n * floor its own DELETEs are authorized by. If the fresh state yields an empty\n * range (a `restore --force` reseed lowered `log_seq_start` — the one writer\n * allowed to, `restore.ts:191-206`), the pass aborts with `WriteConflict` and zero\n * DELETEs rather than publishing a floor above the live one.\n *\n * **CAS before deleting, never after.** Every floor this function publishes\n * satisfies `end <= log_seq_start - window`, where `window` is the *effective*\n * window — {@link LOG_RETENTION_SEQ_WINDOW} by default, or `opts.window` when\n * a caller overrides it (via {@link computeRetirableRange}, which also clamps\n * a malformed stored floor per `docs/spec/sync-protocol.md` invariant 12).\n * That bound holds only at the default window: `opts.window` is a test seam\n * that can shrink or erase the folded entries the window keeps readable for\n * a windowed commit and steepen the retirement rate it limits (this module's\n * own `{window: 0}` tests push the floor to `log_seq_start` exactly).\n * `log_delete_floor` is monotone under the transition validator regardless of\n * `window`. So by the time a slot is physically deleted, a durable\n * certificate that it is gone already exists — which is what makes\n * `log_delete_floor` usable as a witness of \"reclaimed\" rather than \"folded\".\n * A crash between the CAS and the end of the DELETE loop leaks the remaining\n * slice permanently below the newly-advanced floor: deliberate, and the\n * fail-safe direction this program picked — leak, never corruption.\n *\n * The writer-side counterpart lives on the commit path, not here.\n * {@link LOG_RETENTION_SEQ_WINDOW} is a cost margin and a rate limit, never a\n * fence — see its JSDoc. What stops a paused or uncertain writer's create from\n * being acknowledged in a slot this pass has already retired is\n * `Writer#assertCommitAboveDeleteFloor`, which re-reads the manifest after the\n * committing create resolves and fails a sub-floor `seq` with\n * `BaerlyError{code:\"AmbiguousCommit\"}`. See\n * `docs/adr/002-ephemeral-coordination.md` § Closed paths for the two\n * approaches that were tried and rejected, and why that check is what remains.\n *\n * @param opts.signal Threaded to every storage call this makes (the gate\n * read, the CAS's own read + write, and each DELETE in the loop) — an\n * already-aborted signal, or one aborted mid-call, rejects the in-flight\n * {@link Storage} operation.\n * @param opts.window Test seam that overrides {@link LOG_RETENTION_SEQ_WINDOW}.\n * NOT a production tuning knob — do not promote this to an env var the way\n * `BAERLY_MAINTENANCE_*` tunes the fold/GC budgets. Shrinking it (this\n * module's own tests use `{window: 0}`) erases the pre-image reach and\n * steepens the retirement rate described above; production call sites\n * should omit it and take the default.\n * @param opts.maxDeletes Test seam that overrides\n * {@link LOG_RETENTION_MAX_DELETES_PER_TICK}. Same caveat as `opts.window`:\n * a scoped override for exercising the budget boundary in tests, not a\n * knob meant to reach a config surface.\n * @throws BaerlyError{code:\"WriteConflict\"} if the floor CAS loses to another\n * `current.json` writer, or if the fresh state authorizes nothing. The\n * maintenance call sites' shared `retireLogs` helper (`maintenance.ts`)\n * swallows exactly this code and re-throws everything else, matching how\n * `WriteConflict` from `compact()` / `runGc()` is treated at every call site;\n * returning it unwrapped here is what keeps that policy in one place.\n * @throws BaerlyError{code:\"Internal\"} if the floor CAS completes without\n * having authorized the range it published — a wiring tripwire, not a\n * runtime state. `retireLogs` re-throws it into `runBoundedMaintenance`'s\n * outer catch (`db.maintenance.unexpected_error_total`), so the failure is\n * observable rather than silent.\n */\nexport async function retireLogRange(\n storage: Storage,\n currentJsonKey: string,\n opts?: { signal?: AbortSignal; window?: number; maxDeletes?: number },\n): Promise<RetireLogRangeResult> {\n const readOpts = opts?.signal !== undefined ? { signal: opts.signal } : undefined;\n const read = await readCurrentJson(storage, currentJsonKey, readOpts);\n if (read === null) {\n return { deleted: 0 };\n }\n // Advisory gate only: skip the CAS's PUT when there is provably nothing to\n // do. The authorized range is the one computed in the mutator below.\n const gate = computeRetirableRange(read.json, opts);\n if (gate.start >= gate.end) {\n return { deleted: 0 };\n }\n\n let authorized: RetirableRange | undefined;\n const cas = await casUpdateCurrentJson(\n storage,\n currentJsonKey,\n (current: CurrentJson): CurrentJson => {\n // The mutator runs exactly once per call (see casUpdateCurrentJson's\n // JSDoc), so `authorized` after the await is the range this CAS just\n // validated — the assertion below trips on any wiring that lets the\n // CAS complete without one, rather than deleting unvalidated.\n authorized = computeRetirableRange(current, opts);\n if (authorized.start >= authorized.end) {\n throw new BaerlyError(\n \"WriteConflict\",\n `retireLogRange: ${currentJsonKey} authorizes no retirable range at CAS time; a concurrent writer moved log_seq_start`,\n );\n }\n return { ...current, log_delete_floor: authorized.end };\n },\n readOpts,\n );\n // Tripwire, not a runtime state: when the wiring is intact this is a\n // tautology (the mutator just returned `{...current, log_delete_floor:\n // authorized.end}`), but if it ever rots — a hoisted range computation, a\n // retry loop around the CAS — the DELETE loop below must not fall back to\n // the unvalidated advisory-gate range. Fail observable (`retireLogs`\n // re-throws this into the runner's unexpected-error counter) instead.\n if (authorized === undefined || logDeleteFloorOf(cas.json) !== authorized.end) {\n const published = logDeleteFloorOf(cas.json);\n const authorizedEnd = authorized === undefined ? \"none\" : String(authorized.end);\n throw new BaerlyError(\n \"Internal\",\n `retireLogRange: ${currentJsonKey}: the floor CAS published ${String(published)} against authorized end ${authorizedEnd}; refusing to DELETE a range the CAS never validated`,\n );\n }\n const range = authorized;\n\n // Idempotent DELETE on every in-tree Storage impl — a 404 is a no-op —\n // so a crash-leaked slot below the already-advanced floor stays leaked\n // regardless of ordering (leak, never corruption — the deliberate\n // fail-safe above). Parallel via Promise.all for the same reason the GC\n // sweep is: the DELETEs are independent, so serialization only adds\n // round-trip latency — up to `maxDeletes` serial trips on the Node\n // write-tick path, where the retirement pass runs inline on the commit\n // ack. One failure rejects the aggregate while the landed DELETEs stay\n // durable; the floor already authorizes every slot in the range.\n const { prefix: collectionPrefix } = collectionFromCurrentJsonKey(currentJsonKey);\n await Promise.all(\n Array.from({ length: range.end - range.start }, (_, i) =>\n storage.delete(logObjectKey(collectionPrefix, range.start + i), readOpts),\n ),\n );\n return { deleted: range.end - range.start };\n}\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 snapshot prefix and\n * classifying each key.\n * 3. Rescues candidates proven live, then sweeps due candidates that\n * are safe to classify.\n * 4. CAS-writes the updated `gc/pending.json`.\n *\n * Two-phase by design: each mark sits in `gc/pending.json` for a grace\n * period (default 7 days, see {@link GC_GRACE_PERIOD_MILLIS}) before\n * sweep may delete it. The grace bounds the worst plausible writer-retry\n * window — a paused-process writer that resumes hours later still finds\n * its idempotency anchor on the bucket. Sweep can also resolve a\n * candidate OUT of the ledger without deleting it, when a generation or\n * liveness recheck fails.\n *\n * **A pass is bounded by the grace it relies on.** Sweep DELETEs go out\n * in batches of {@link GC_SWEEP_DELETE_BATCH_KEYS}. Before each batch,\n * a pass whose sweep-gate `current.json` read is older than\n * {@link GC_PASS_GRACE_FRACTION} of the grace issues no further DELETEs;\n * the unissued candidates stay pending, still due, for a later pass.\n * That bounds how stale a DELETE's liveness proof can be (sync-protocol\n * invariant 14) without a lease or a scheduler.\n *\n * Stale log objects are reclaimed by a sequence window rather than a\n * timed mark-and-sweep. See `log-retention.ts` for the computed-range\n * deletion path.\n *\n * Unbounded by default — the run marks and sweeps the entire eligible\n * set in one pass. Callers on a per-invocation request limit (Cloudflare\n * Workers) opt INTO caps via the `CLOUDFLARE_FREE_TIER` /\n * `CLOUDFLARE_PAID_TIER` profiles' mark and sweep knobs\n * (`InternalRunGcOptions`, not on the public `RunGcOptions`); the\n * per-pass worst cases are on `CLOUDFLARE_FREE_TIER`.\n *\n * One category of orphan:\n * - `orphan-snapshot`: a canonical\n * `<collectionPrefix>/snapshot/L9/...` key not equal to\n * `current.snapshot`. Each compactor run replaces the pointer; the\n * prior file becomes unreferenced. Discovery is scoped to this\n * binary's owned `snapshot/L9/` namespace. Future L0-L8 layouts\n * stay opaque to this binary and do not consume the bounded mark\n * window. Opaque L9 keys are ignored during mark and evicted from\n * legacy ledgers without a DELETE; no current writer emits one.\n *\n * **Mark window rule.** Every pass LISTs `snapshot/L9/` from the\n * lexicographic start — no persisted cursor, so no orphan can sit\n * behind a position the scan never revisits (a restore that deletes the\n * ledger, a stale-generation drop, or a lost CAS simply re-marks on the\n * next pass). The window is `maxMarks` plus every key the pass will\n * certainly skip: the snapshot keys already in `gc/pending.json` and the\n * one live `current.snapshot`. The loop stops after `maxMarks` NEW\n * marks. Without the widening, older keys sort first and a cohort\n * waiting out its 7-day grace fills a `maxMarks`-key window, capping\n * marking at `maxMarks` per grace while folds keep orphaning snapshots.\n * The widening is capped at {@link GC_MARK_LIST_PAGE_KEYS} (one full\n * provider page) and never shrinks the window below `maxMarks`, so it\n * adds no LIST page request beyond what `maxMarks` alone costs: one\n * request per 1000 keys, more only if the provider truncates a page\n * short. Marking only adds ledger entries; deletion authority stays with\n * the sweep gate below.\n *\n * Progress: within the protocol-written L9 keyspace at most ONE key is\n * permanently unmarkable (the live `current.snapshot`), so for any\n * `maxMarks >= 1` a pass whose ledger has room marks an unpending orphan\n * if one exists in the window. Opaque L9 keys (non-canonical names) are\n * skipped but still occupy window slots; no current writer emits one.\n *\n * Ceiling: `GC_MAX_PENDING_CANDIDATES` (1000) bounds the in-flight\n * cohort, so a collection reclaims at most ~1000 replaced snapshots per\n * 7-day grace — about 143 folds/day. At the cap the window holds only\n * pending keys and `mergeGcPending` drops appends past the cap, so\n * marking stops until the oldest cohort comes due and is swept; a\n * collection folding faster than that accumulates the excess.\n *\n * **`content/` is deliberately NOT a category.** Legacy\n * `<collectionPrefix>/content/<sha>.json` side objects — written by\n * v0.6.0, and still written by a v0.6.0 node during a mixed rollout —\n * are inert: no current writer creates one, no reader opens one. GC\n * never LISTs, reads, or deletes under that prefix, so they cost storage\n * and nothing else, and an operator who wants the bytes back deletes the\n * prefix directly (`docs/guide/backups.md`). An `orphan-content` entry\n * found in a legacy ledger is EVICTED, not swept — see the sweep gate's\n * legacy arm.\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 * **Not fault-isolated, by design.** Every storage call in Steps 1-5 —\n * the `current.json`/`gc/pending.json` reads, the mark-phase `LIST`s,\n * the sweep DELETEs — is uncaught within `runGc` itself; a throw from\n * any of them aborts the whole pass. That's a deliberate fail-safe, not\n * a gap to close with a `try`/`catch` around one call: Steps 3-4 re-LIST\n * from scratch every pass rather than trusting partial progress, sweep\n * DELETEs are idempotent, and the pending-ledger CAS in Step 5 hasn't\n * happened yet when an earlier step throws — so an abort mid-pass loses\n * no durable state and deletes nothing it shouldn't. This is fuzz-tested\n * directly: `maintenance-crash-fuzz.test.ts` aborts the K-th storage op\n * inside `runGc` and asserts the reader still returns every live row.\n */\n\nimport {\n type GcCandidate,\n type GcPending,\n type Storage,\n GC_GRACE_PERIOD_MILLIS,\n GC_MARK_LIST_PAGE_KEYS,\n GC_MAX_PENDING_CANDIDATES,\n GC_PASS_GRACE_FRACTION,\n GC_PENDING_SCHEMA_VERSION,\n GC_SWEEP_DELETE_BATCH_KEYS,\n NO_GENERATION,\n isWriteConflict,\n casUpdateGcPending,\n createGcPending,\n gcPendingKey,\n logObjectKey,\n logSeqStartOf,\n mergeGcPending,\n readCurrentJson,\n readGcPending,\n} from \"@baerly/protocol\";\nimport { ctxMetrics } from \"./observability/context.ts\";\nimport { collectionFromCurrentJsonKey } from \"./collection-key.ts\";\n\n/**\n * Base options for {@link runGc}, unpublished like `runGc` itself. 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; a zero grace also\n * lifts the {@link GC_PASS_GRACE_FRACTION} bound on the 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 as one isolated\n * GC phase for one collection, alternated with a separate direct\n * `compact()` invocation. The default is effectively unbounded\n * (`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 every candidate's `due_at`), at sweep time (to compare\n * against candidate `due_at`), and around the `current.json` reads and\n * DELETE batches (to enforce {@link GC_PASS_GRACE_FRACTION}).\n */\n readonly now?: () => Date;\n\n /**\n * @internal Monotonic clock injection for tests, in milliseconds.\n * Defaults to `() => performance.now()`. The grace bound takes the\n * larger of this clock's elapsed time and `now`'s, so a backward\n * wall-clock correction cannot make a stalled pass look younger, and a\n * suspend the monotonic clock does not count still shows on the wall\n * clock.\n */\n readonly monotonicNow?: () => number;\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 orphan_snapshot: number;\n };\n /** Number of keys deleted in this pass. */\n readonly swept: number;\n /**\n * Per-cause counts of candidates RESOLVED OUT of the ledger without\n * being deleted, because the sweep gate re-checked them and found\n * them no longer eligible: `stale_generation` when the manifest that\n * authorised the mark has been replaced, `still_live` when the key\n * reads live now.\n *\n * A drop frees no bytes, so it drives neither {@link swept} nor\n * `last_swept_at`. It is nonetheless the healthy outcome — dropping\n * is what keeps a permanently-live candidate from wedging the ledger\n * against `GC_MAX_PENDING_CANDIDATES`, which keeps the FIRST N\n * entries. Also emitted as `db.gc.dropped_total`, labelled by cause.\n */\n readonly dropped: {\n readonly stale_generation: number;\n readonly still_live: number;\n };\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\n/** One instant on the wall clock and the monotonic clock, in milliseconds. */\ninterface PassStamp {\n readonly wall: number;\n readonly mono: number;\n}\n\nconst DEFAULT_MAX_MARKS = Number.MAX_SAFE_INTEGER;\nconst DEFAULT_MAX_SWEEPS = Number.MAX_SAFE_INTEGER;\nconst zeroGcResult = (): RunGcResult => ({\n marked: { orphan_snapshot: 0 },\n swept: 0,\n dropped: { stale_generation: 0, still_live: 0 },\n pendingDepth: 0,\n});\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 \"@baerly/server/_internal/maintenance\";\n *\n * const r = await runGc({ storage, currentJsonKey });\n * console.log(`marked ${r.marked.orphan_snapshot} orphan snapshots, 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 monotonicNow = internal.monotonicNow ?? ((): number => performance.now());\n /** Both clocks at one instant; see {@link elapsedSince}. */\n const stamp = (): PassStamp => ({ wall: now().getTime(), mono: monotonicNow() });\n /** The larger of the two clocks' elapsed times, so neither can understate it. */\n const elapsedSince = (from: PassStamp): number =>\n Math.max(now().getTime() - from.wall, monotonicNow() - from.mono);\n const { prefix: collectionPrefix, name: collectionName } =\n collectionFromCurrentJsonKey(currentJsonKey);\n const pendingKey = gcPendingKey(collectionPrefix);\n const signal = options.signal;\n const signalOpts = signal !== undefined ? { signal } : undefined;\n\n // ── Step 1. Read current.json (skip silently if absent). ────────\n // Stamped BEFORE the GET: the body reflects some instant after the\n // request left, so the stamp can only overstate the read's age.\n const currentReadAt = stamp();\n const cur = await readCurrentJson(storage, currentJsonKey, signalOpts);\n if (cur === null) {\n return zeroGcResult();\n }\n const current = cur.json;\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 WriteConflict.\n let pending = await readGcPending(storage, pendingKey, 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, pendingKey, initial, signalOpts);\n } catch (error) {\n if (isWriteConflict(error)) {\n pending = await readGcPending(storage, pendingKey, 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 // Stamped onto every candidate this pass marks, so the sweep gate can\n // tell \"still the collection I judged this against\" from \"a different\n // incarnation wearing the same key\". Spread rather than assigned so a\n // manifest with no generation writes no field at all — absent is the\n // legacy-compatible spelling, and it decodes to `NO_GENERATION` on\n // both sides of the later comparison.\n const markGeneration: { generation?: string } =\n current.generation !== undefined ? { generation: current.generation } : {};\n\n // ── Step 3. Mark orphan snapshots. ──────────────────────────────\n const newCandidates: GcCandidate[] = [];\n let markedOrphanSnapshot = 0;\n // Uncursored on purpose — every pass scans from the lexicographic\n // start, so no key can hide behind a position. The window is widened\n // past the keys this pass already knows it will skip (see\n // `markWindowKeys` and the module JSDoc), and the loop stops at\n // `maxMarks` NEW marks.\n const snapshotPrefix = `${collectionPrefix}/snapshot/L9/`;\n const pendingSnapshotKeys = pending.json.candidates.filter((c) =>\n c.key.startsWith(snapshotPrefix),\n ).length;\n for await (const entry of storage.list(\n snapshotPrefix,\n listWindow(markWindowKeys(maxMarks, pendingSnapshotKeys), undefined, signal),\n )) {\n if (markedOrphanSnapshot >= maxMarks) {\n break;\n }\n // Liveness starts with exact key equality with the active pointer,\n // never a parsed key range — a snapshot installed directly by\n // `admin restore` or by a replacement fold is live whatever its seq\n // fields say, and one whose name parses as \"current-looking\" is\n // still dead if `current.snapshot` does not name it.\n if (entry.key === current.snapshot) {\n continue;\n }\n // Only the exact key shape emitted by `snapshotKey` can ever carry\n // deletion authority. Leave opaque objects on the bucket without\n // spending bounded-ledger capacity on an entry that sweep cannot classify.\n if (parseMaxSeqFromCanonicalSnapshotKey(entry.key, collectionPrefix) === null) {\n continue;\n }\n if (known.has(entry.key)) {\n continue;\n }\n newCandidates.push({\n key: entry.key,\n due_at: computeDueAt(now, grace),\n reason: \"orphan-snapshot\",\n ...markGeneration,\n });\n markedOrphanSnapshot++;\n }\n\n // ── Step 4. Rescue live candidates, then sweep due candidates. ──\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 // Snapshot classification used the initial manifest so stale work remains\n // monotone and deterministic. Re-read only when a due snapshot could be\n // deleted, as late as possible before DELETE. The fresh pointer rescues a\n // candidate it names; every other due snapshot still needs a strict\n // generation-floor proof below before it may enter `toSweep`.\n const hasDueSnapshot = sweepCandidates.some(\n (candidate) => candidate.reason === \"orphan-snapshot\" && Date.parse(candidate.due_at) <= nowMs,\n );\n const freshReadAt = hasDueSnapshot ? stamp() : currentReadAt;\n const freshCurrent = hasDueSnapshot\n ? await readCurrentJson(storage, currentJsonKey, signalOpts)\n : undefined;\n // The freshest manifest this pass holds. `freshCurrent` exists only\n // when a due snapshot forced the re-read above; otherwise this is the\n // step-1 read. Either way it costs no additional op, and preferring\n // the fresher one narrows — never widens — the window between the\n // read a decision rests on and the DELETE it authorises.\n const fenceCurrent = freshCurrent?.json ?? current;\n // When the read behind `fenceCurrent` was taken; the sweep's grace\n // bound is measured from here.\n const fenceReadAt = freshCurrent?.json !== undefined ? freshReadAt : currentReadAt;\n const fenceGeneration = fenceCurrent.generation ?? NO_GENERATION;\n const fenceFloor = logSeqStartOf(fenceCurrent);\n const rescuedKeys = new Set<string>();\n const staleGenerationKeys = new Set<string>();\n const evictedKeys = new Set<string>();\n for (const candidate of sweepCandidates) {\n // Arm 0 — legacy eviction. A v0.6-era `orphan-content` candidate names a\n // `content/<sha>.json` side object this build cannot classify and never\n // deletes (module header). Resolve it OUT of the ledger, object untouched.\n //\n // Eviction is load-bearing, not a courtesy to old buckets:\n // `mergeGcPending` keeps the FIRST `GC_MAX_PENDING_CANDIDATES` entries,\n // so a ledger head full of content candidates would silently discard\n // every new `orphan-snapshot` mark — the only category this build\n // emits — forever.\n //\n // Ordered BEFORE the generation fence on purpose. Most legacy candidates\n // would fail that fence too, and counting them there fires an alertable\n // `db.gc.dropped_total{cause=\"stale-generation\"}` spike on a legacy\n // bucket's first post-upgrade pass. Eviction frees no bytes and signals\n // nothing wrong, so it drives no counter at all.\n if (candidate.reason === \"orphan-content\") {\n evictedKeys.add(candidate.key);\n continue;\n }\n // Arm 1 — stale-log deletion authority. No current build marks\n // `stale-log`: sub-floor log objects are reclaimed by computed-range\n // retirement (`log-retention.ts`), which CASes `log_delete_floor`\n // before it deletes, so invariant 5's commit-path check covers every\n // slot it reclaims. This arm exists for the legacy residual — a\n // v0.6.0-era ledger can still carry `stale-log` candidates, and a\n // canonical, same-generation, sub-floor one is still DELETEd here\n // WITHOUT advancing the floor, so those deletions certify nothing.\n // One-shot and self-extinguishing: nothing re-marks the category, so\n // the residual drains with the ledger.\n //\n // A persisted candidate authorizes DELETE only when its key is the\n // exact canonical `log/<seq>.json` for THIS collection; the ledger\n // decoder has no collection context, so malformed, mislabeled,\n // noncanonical, and cross-prefix keys reach here. Resolve them without\n // DELETE — waiting for `due_at` would let an invalid entry wedge the\n // bounded first-N ledger for no safety gain. Ordered before the\n // generation fence so invalid authority does not masquerade as a\n // stale-generation event.\n if (\n candidate.reason === \"stale-log\" &&\n parseSeqFromCanonicalLogKey(candidate.key, collectionPrefix) === null\n ) {\n evictedKeys.add(candidate.key);\n continue;\n }\n // Arm 2 — snapshot deletion authority. Unknown levels, malformed names,\n // inverted ranges, and cross-prefix keys provide no floor proof, so GC\n // never deletes the object they name. Resolve legacy ledger entries\n // immediately: retaining an opaque candidate would let a full first-N\n // ledger discard every later useful mark indefinitely.\n if (\n candidate.reason === \"orphan-snapshot\" &&\n parseMaxSeqFromCanonicalSnapshotKey(candidate.key, collectionPrefix) === null\n ) {\n evictedKeys.add(candidate.key);\n continue;\n }\n // Arm 3 — the generation fence, checked before liveness and for\n // every reason. A candidate marked under a manifest that has since\n // been replaced was judged against a keyspace that no longer\n // exists: `baerly admin restore --force` truncates the log, reseeds\n // `log_seq_start` from the surviving objects (which can move the\n // floor DOWN), and re-mints `generation`. A `log/K` that was\n // provably dead under the old floor can be a live entry of the new\n // incarnation, at the same key. Absent compares equal to absent, so\n // a bucket whose manifest never carried a generation is unaffected.\n if ((candidate.generation ?? NO_GENERATION) !== fenceGeneration) {\n staleGenerationKeys.add(candidate.key);\n continue;\n }\n if (candidate.reason === \"orphan-snapshot\" && candidate.key === freshCurrent?.json.snapshot) {\n rescuedKeys.add(candidate.key);\n continue;\n }\n // Arm 4 — a stale-log candidate that reads live again. Same\n // generation, so this is not a reseed; the floor can still have\n // been rewound by a `--force` that reused the nonce, and a mark\n // taken `GC_GRACE_PERIOD_MILLIS` ago is stale enough to be worth\n // re-deriving from the floor rather than trusted. Arm 1 has already\n // resolved every non-canonical key, so `null` here is unreachable.\n if (candidate.reason === \"stale-log\") {\n const seq = parseSeqFromCanonicalLogKey(candidate.key, collectionPrefix);\n if (seq !== null && seq >= fenceFloor) {\n rescuedKeys.add(candidate.key);\n }\n continue;\n }\n }\n // All five arms resolve a candidate OUT of the ledger without deleting\n // anything. That is what stops the ledger starving: `mergeGcPending`\n // keeps the FIRST `GC_MAX_PENDING_CANDIDATES` entries, so a\n // permanently-live candidate — or an unclassifiable legacy one — at the\n // head would otherwise wedge it forever and silently discard every later\n // mark.\n const droppedKeys = new Set([...staleGenerationKeys, ...rescuedKeys, ...evictedKeys]);\n const toSweep: GcCandidate[] = [];\n const remaining: GcCandidate[] = [];\n for (const cand of sweepCandidates) {\n if (droppedKeys.has(cand.key)) {\n continue;\n }\n if (toSweep.length < maxSweeps && Date.parse(cand.due_at) <= nowMs) {\n if (cand.reason === \"orphan-snapshot\") {\n const maxSeq = parseMaxSeqFromCanonicalSnapshotKey(cand.key, collectionPrefix);\n // A compactor may publish this candidate after the fresh manifest GET\n // but before DELETE. The manifest floor is monotone, so only a\n // canonical snapshot wholly below that observed floor is already\n // obsolete in every later generation. Equality stays pending: the\n // internal zero-entry fold seam may publish `[floor, floor)`.\n if (maxSeq === null || maxSeq >= (freshCurrent?.json.log_seq_start ?? 0)) {\n remaining.push(cand);\n continue;\n }\n }\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. Each batch is parallel via Promise.all; one failure aborts\n // the rest, but the per-key DELETEs that landed are durable.\n //\n // Bounded by the grace it relies on: before each batch, a pass whose\n // `fenceCurrent` read is older than `GC_PASS_GRACE_FRACTION` of the\n // grace stops deleting. The unissued candidates stay in the ledger,\n // still due, for a pass that re-reads the manifest. A zero grace (tests\n // only) has no window to keep a fraction of, so it is not bounded.\n const sweepBudgetMillis = grace * GC_PASS_GRACE_FRACTION;\n const swept: GcCandidate[] = [];\n for (let start = 0; start < toSweep.length; start += GC_SWEEP_DELETE_BATCH_KEYS) {\n if (grace > 0 && elapsedSince(fenceReadAt) > sweepBudgetMillis) {\n break;\n }\n const batch = toSweep.slice(start, start + GC_SWEEP_DELETE_BATCH_KEYS);\n await Promise.all(batch.map((c) => storage.delete(c.key, signalOpts)));\n swept.push(...batch);\n }\n const abandonedCount = toSweep.length - swept.length;\n\n // ── Step 5. 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 // `mergeGcPending` drops terminal keys via its existing `sweptKeys`\n // merge input. Positively-live rescues are terminal ledger resolutions too,\n // but only `swept` (the DELETEs actually issued) drives result counts,\n // timestamps, and metrics.\n const sweptKeys = new Set([...swept.map((candidate) => candidate.key), ...droppedKeys]);\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 = swept.length > 0 ? now().toISOString() : \"\";\n const markedSummary = {\n orphan_snapshot: markedOrphanSnapshot,\n };\n let pendingDepth: number;\n try {\n const updated = await casUpdateGcPending(\n storage,\n pendingKey,\n (latest) =>\n mergeGcPending(latest, {\n sweptKeys,\n newCandidates,\n lastSweptAt,\n maxCandidates: GC_MAX_PENDING_CANDIDATES,\n }),\n signalOpts,\n );\n pendingDepth = updated.json.candidates.length;\n } catch (error) {\n // `WriteConflict` covers two benign races, and the DELETEs we issued are\n // durable in both:\n // - CAS-lost on pending.json after exhausting the bounded retry —\n // another GC pass kept landing concurrently;\n // - the ledger VANISHED between step 2 and here. `baerly admin\n // restore` deletes `gc/pending.json` on both reseed branches, so\n // this is routine rather than exceptional.\n // `casUpdateGcPending` reports it as `WriteConflict` because it IS a\n // CAS precondition failure — an `If-Match` PUT against the\n // deleted key would have 412'd.\n // Either way the next pass re-marks whatever we couldn't persist,\n // bootstrapping a fresh ledger if there isn't one. Surface success —\n // re-throwing would mask the work we DID complete, and on the\n // `runScheduledMaintenance` path (documented \"Errors propagate\")\n // would surface a routine restore to an operator's cron.\n // `InvalidResponse` — a ledger body that is present but corrupt — is\n // deliberately NOT in this arm and still escapes.\n if (isWriteConflict(error)) {\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 + abandonedCount;\n } else {\n throw error;\n }\n }\n\n // ── Step 6. 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\", swept.length, labels);\n if (swept.length > 0) {\n const byReason = new Map<GcCandidate[\"reason\"], number>();\n for (const c of swept) {\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 // Separate from `db.gc.swept_total` on purpose: a drop frees no bytes,\n // so folding the two would make a pass that reclaimed nothing look\n // productive. A `stale-generation` spike is expected exactly once\n // after a restore or an upgrade and is alertable if it persists; a\n // sustained `still-live` rate means the mark phase is misjudging\n // liveness, which is the failure this gate exists to contain.\n if (staleGenerationKeys.size > 0) {\n metrics.counter(\"db.gc.dropped_total\", staleGenerationKeys.size, {\n collection: collectionName,\n cause: \"stale-generation\",\n });\n }\n if (rescuedKeys.size > 0) {\n metrics.counter(\"db.gc.dropped_total\", rescuedKeys.size, {\n collection: collectionName,\n cause: \"still-live\",\n });\n }\n\n return {\n marked: markedSummary,\n swept: swept.length,\n dropped: {\n stale_generation: staleGenerationKeys.size,\n still_live: rescuedKeys.size,\n },\n pendingDepth,\n };\n};\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\n/**\n * `Storage.list` options for one bounded rotation window: at most\n * `maxKeys` keys, resuming strictly after `cursor` when the ledger\n * carries one. `maxKeys` is a hard cross-page total on every adapter\n * (`docs/spec/storage-compatibility.md`), which is what makes\n * \"yielded fewer than we asked for ⇒ end of keyspace\" a sound wrap\n * test. `startAfter` is strict-greater on the key VALUE, so a cursor\n * naming a key this pass already deleted still resumes correctly —\n * never probe whether it still exists.\n */\nconst listWindow = (\n maxKeys: number,\n cursor: string | undefined,\n signal: AbortSignal | undefined,\n): { startAfter?: string; maxKeys: number; signal?: AbortSignal } => ({\n maxKeys,\n ...(cursor !== undefined && { startAfter: cursor }),\n ...(signal !== undefined && { signal }),\n});\n\n/**\n * `maxKeys` for the orphan-snapshot mark LIST: `maxMarks` plus every key\n * the pass is certain to skip without marking — the `pendingSnapshotKeys`\n * already in the ledger under `snapshot/L9/` and the one live\n * `current.snapshot`. Without the widening, a ledger cohort waiting out\n * its grace fills the lex-first window and marking stalls at `maxMarks`\n * per grace period.\n *\n * Capped at {@link GC_MARK_LIST_PAGE_KEYS} so the widening never adds a\n * full LIST page: a pass with `maxMarks` at or under one page fits one\n * page request unless the provider truncates short. The cap is never\n * below `maxMarks`, so a bounded pass scans at least what it always did.\n */\nconst markWindowKeys = (maxMarks: number, pendingSnapshotKeys: number): number =>\n Math.max(maxMarks, Math.min(maxMarks + pendingSnapshotKeys + 1, GC_MARK_LIST_PAGE_KEYS));\n\n/**\n * Parse the exact canonical `log/<seq>.json` key for this collection.\n * Returns `null` for another prefix, malformed or noncanonical decimal,\n * or a sequence outside JavaScript's safe-integer range.\n */\nconst parseSeqFromCanonicalLogKey = (key: string, collectionPrefix: string): number | null => {\n const logPrefix = `${collectionPrefix}/log/`;\n if (!key.startsWith(logPrefix)) {\n return null;\n }\n const match = /^(\\d+)\\.json$/.exec(key.slice(logPrefix.length));\n if (match === null) {\n return null;\n }\n const seq = Number(match[1]);\n return Number.isSafeInteger(seq) && seq >= 0 && logObjectKey(collectionPrefix, seq) === key\n ? seq\n : null;\n};\n\n/**\n * Parse the exclusive `max_seq` from the exact key shape emitted by\n * `snapshotKey`. Unknown levels/layouts and invalid ranges stay opaque: GC\n * never deletes the object and never retains its candidate in the bounded\n * ledger.\n */\nconst parseMaxSeqFromCanonicalSnapshotKey = (\n key: string,\n collectionPrefix: string,\n): number | null => {\n const snapshotPrefix = `${collectionPrefix}/snapshot/L9/`;\n if (!key.startsWith(snapshotPrefix)) {\n return null;\n }\n const match = /^(\\d{12})-(\\d{12})-[0-9a-f]{64}\\.json$/.exec(key.slice(snapshotPrefix.length));\n if (match === null) {\n return null;\n }\n const minSeq = Number(match[1]);\n const maxSeq = Number(match[2]);\n // Twelve decimal digits are always safely below MAX_SAFE_INTEGER.\n return minSeq <= maxSeq ? maxSeq : null;\n};\n\n/**\n * Anchor `due_at` on the MARK: `now() + graceMs`. Grace measures the\n * writer-retry window from when we judged a key dead, which is\n * unrelated to when the object was written.\n *\n * Never anchor on the object's own timestamp. Doing so made the\n * effective grace `max(0, graceMs − object age)` — zero past the\n * 7-day default, for exactly the old objects GC marks. It read a\n * `lastModified` that only the S3/GCS/R2 adapters populated, so the\n * suite's backends showed a full window and no test could see it.\n * `StorageListEntry` no longer carries a timestamp; `gc.test.ts`\n * still pins the behaviour against an entry that fakes one.\n *\n * Called per candidate, not hoisted per pass, so the local-clock\n * backends keep their exact previous horizon.\n */\nconst computeDueAt = (now: () => Date, graceMs: number): string =>\n new Date(now().getTime() + graceMs).toISOString();\n","/**\n * Maintenance passes over one collection. `runScheduledMaintenance` is the\n * published opt-in scheduled pass (addressed by collection, sized by host\n * tier); `runMaintenancePass` is the internal composition it resolves to,\n * which the adapters, CLI, bench and tests drive with per-phase knobs;\n * `runBoundedMaintenance` is the in-band write-tick runner.\n *\n * Every pass is a single attempt: `compact()` and `runGc()` are\n * CAS-protected, so a pass cut short is retried safely by the next one.\n * The caller schedules the next pass; nothing here loops or retries.\n */\n\nimport {\n type CurrentJson,\n type Storage,\n BaerlyError,\n isWriteConflict,\n casUpdateCurrentJson,\n CF_FREE_COMPACT_TAIL_PROBE_GETS,\n CF_PAID_COMPACT_TAIL_PROBE_GETS,\n GC_STARVATION_GUARD,\n LOG_RETENTION_MAX_DELETES_PER_TICK,\n MAINTENANCE_COLD_START_ENTRY_BYTES,\n MAINTENANCE_FOLD_BASE_REQUESTS,\n MAINTENANCE_GC_BASE_REQUESTS,\n MAINTENANCE_MIN_LIVE_BYTES,\n MAINTENANCE_PROFILE_CF_FREE,\n MAINTENANCE_PROFILE_CF_PAID,\n MAINTENANCE_PROFILE_NODE,\n MAINTENANCE_RETIRE_PRE_FLOOR_REQUESTS,\n MAINTENANCE_TAIL_HINT_REFRESH_REQUESTS,\n MAINTENANCE_TAIL_HINT_REFRESH_WRITES,\n MAINTENANCE_TARGET_RATIO,\n MAINTENANCE_WARN_INTERVAL_WRITES,\n readCurrentJson,\n SCHEDULED_MIN_ENTRIES_TO_COMPACT,\n STORAGE_RETRY_MAX_ATTEMPTS,\n WRITE_TICK_MIN_ENTRIES_TO_COMPACT,\n} from \"@baerly/protocol\";\nimport { compact, type CompactResult, type InternalCompactOptions } from \"./compactor.ts\";\nimport { runGc, type InternalRunGcOptions, type RunGcResult } from \"./gc.ts\";\nimport type {\n InternalBoundedMaintenanceOptions,\n InternalMaintenanceOptions,\n LogRetentionOptions,\n MaintenanceOptions,\n MaintenanceResult,\n MaintenanceTarget,\n} from \"./maintenance-options.ts\";\nimport { collectionFromCurrentJsonKey } from \"./collection-key.ts\";\nimport { assertNameSegment } from \"./path-segment.ts\";\nimport { probeTailFrom } from \"./log-tail.ts\";\nimport { retireLogRange } from \"./log-retention.ts\";\nimport { ctxMetrics, getCurrentContext } from \"./observability/context.ts\";\n\nexport { type CompactOptions, type CompactResult, compact } from \"./compactor.ts\";\nexport { type RunGcOptions, type RunGcResult, runGc } from \"./gc.ts\";\n\n/** The internal pass's target: one collection, addressed by its `current.json` key. */\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\n/** Per-phase results of one {@link runMaintenancePass}. */\nexport interface MaintenancePassResult {\n readonly compact: CompactResult;\n readonly gc: RunGcResult;\n /** Log objects retired. */\n readonly retired: number;\n}\n\n/**\n * One log-retirement pass: run {@link retireLogRange} and emit its\n * counter. Shared by every maintenance trigger that retires stale logs\n * (`runScheduledMaintenance` and both retirement points inside\n * `runBoundedMaintenance`), so the metric name, option threading, and\n * error policy cannot drift between call sites.\n *\n * Error policy — deliberately NOT a bare swallow: `WriteConflict` (the floor\n * CAS lost to another writer, or a concurrent fold moved `log_seq_start`)\n * is routine contention, swallowed here and retried by the next pass.\n * Anything else is re-thrown for the caller's own error path, matching\n * how `compact()` / `runGc()` failures are treated at every call site:\n * `runBoundedMaintenance`'s outer catch counts\n * `db.maintenance.unexpected_error_total` and logs the stack, and\n * `runScheduledMaintenance` propagates per its documented \"errors\n * propagate\" contract. Retirement is the only mechanism bounding the\n * steady-state log-object count — a persistent unexpected failure must\n * not fail silently while objects accumulate unbounded.\n */\nconst retireLogs = async (\n storage: Storage,\n currentJsonKey: string,\n opts?: { logRetention?: LogRetentionOptions; signal?: AbortSignal },\n): Promise<number> => {\n const { name: collection } = collectionFromCurrentJsonKey(currentJsonKey);\n try {\n const retired = await retireLogRange(storage, currentJsonKey, {\n ...opts?.logRetention,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n });\n ctxMetrics().counter(\"db.log_retention.deleted_total\", retired.deleted, {\n collection,\n });\n return retired.deleted;\n } catch (error) {\n if (isWriteConflict(error)) {\n return 0; // routine CAS contention — the next pass retries\n }\n throw error;\n }\n};\n\n/**\n * One maintenance pass over one collection, addressed by its `current.json`\n * key: `compact()` then `runGc()` (in that order; the compactor's advance\n * of `log_seq_start` produces the stale-log candidates the GC then marks),\n * then log retirement. With {@link CLOUDFLARE_FREE_TIER} the whole pass is\n * at most 94 storage calls, 282 with every call retried, which fits the 900\n * a Workers Free invocation may spend through the R2 binding but not the 45\n * it may spend through `fetch` (see {@link CLOUDFLARE_FREE_TIER}). The\n * request ledger refuses any call past the invocation's limit before it is\n * sent, so a pass never exceeds the limit.\n *\n * `minEntriesToCompact` defaults to {@link SCHEDULED_MIN_ENTRIES_TO_COMPACT}\n * (1) here, deliberately NOT `compact()`'s own default (100) or the\n * write-tick floor ({@link WRITE_TICK_MIN_ENTRIES_TO_COMPACT}, 50), both of\n * which exist to keep an in-band write from thrashing snapshot rewrites. A\n * scheduler that fires has already decided it is time to work, so the\n * scheduled path drains the live tail to zero rather than parking it in a\n * dead zone between a count floor and the per-entry GET cost every read\n * pays. An explicit `options.compact.minEntriesToCompact` suppresses this\n * default; {@link CLOUDFLARE_FREE_TIER} carries 20, which keeps\n * `minEntriesToCompact <= P` for its bounded tail probe.\n *\n * Errors propagate; `WriteConflict` from retirement is swallowed as\n * routine contention (see `retireLogs`).\n *\n * @internal\n */\nexport const runMaintenancePass = async (\n args: MaintenanceArgs,\n options: InternalMaintenanceOptions = {},\n): Promise<MaintenancePassResult> => {\n const compactRes = await compactPhase(args, options);\n const gcRes = await gcPhase(args, options);\n // Retire stale log objects. Cheap and bounded — a computed key range,\n // no LIST — and placed after GC so it runs on every whole pass.\n const retired = await retireLogs(args.storage, args.currentJsonKey, {\n logRetention: options.logRetention,\n ...(options.signal !== undefined && { signal: options.signal }),\n });\n return { compact: compactRes, gc: gcRes, retired };\n};\n\n/** The pass's `compact()` call, with the scheduled fold floor. */\nconst compactPhase = (\n args: MaintenanceArgs,\n options: InternalMaintenanceOptions,\n): Promise<CompactResult> =>\n compact(args, {\n ...options.compact,\n ...(options.compact?.minEntriesToCompact === undefined && {\n minEntriesToCompact: SCHEDULED_MIN_ENTRIES_TO_COMPACT,\n }),\n ...(options.signal !== undefined && { signal: options.signal }),\n });\n\n/** The pass's `runGc()` call. */\nconst gcPhase = (\n args: MaintenanceArgs,\n options: InternalMaintenanceOptions,\n): Promise<RunGcResult> =>\n runGc(args, { ...options.gc, ...(options.signal !== undefined && { signal: options.signal }) });\n\n/** 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.\n// Default fold floor is the scheduled drain (1), not the write-tick 50:\n// a library-provided scheduled profile exists for per-pass caps, and\n// inheriting the in-band floor parks a 1–49 entry tail forever.\nconst profileToScheduledOptions = (\n profile: MaintenanceProfile,\n compactMaxTailProbeGets?: number,\n minEntriesToCompact: number = SCHEDULED_MIN_ENTRIES_TO_COMPACT,\n): InternalMaintenanceOptions => ({\n compact: {\n maxEntriesPerRun: profile.maxFoldEntriesPerPass,\n minEntriesToCompact,\n ...(compactMaxTailProbeGets !== undefined && {\n maxTailProbeGets: compactMaxTailProbeGets,\n }),\n },\n gc: {\n maxMarksPerRun: profile.gcMaxMarks,\n maxSweepsPerRun: profile.gcMaxSweeps,\n },\n});\n\n/**\n * Tuning profile for Cloudflare Workers Free, derived from\n * {@link MAINTENANCE_PROFILE_CF_FREE} (one source of truth): fold slice\n * N=20, compact tail probe P=25 ({@link CF_FREE_COMPACT_TAIL_PROBE_GETS}),\n * GC sweeps S=10, marks 20.\n *\n * **These caps are ceilings, not the budget.** Every storage call is\n * charged to the invocation's request ledger, which refuses a call past\n * the host's limit before sending it: 900 calls through the R2 binding\n * (`CF_FREE_INTERNAL_REQUEST_LIMIT`), 45 through `fetch`\n * (`CF_FREE_EXTERNAL_REQUEST_LIMIT`). The caps bound one pass's work so\n * that it fits those limits; they do not need to stay under a 50 of their\n * own. The in-band write tick (`runBoundedMaintenance`) also sizes each\n * phase from what the ledger has left, net of commit holds: a fold that\n * does not fit is skipped, and a GC slice or retirement pass runs with a\n * smaller DELETE cap.\n *\n * Budget arithmetic (worst case, one storage call per GET, PUT, DELETE or\n * LIST page):\n * compact: 1 current GET + P tail-probe GETs + 1 optional prior-snapshot\n * GET + N folded-log GETs + 1 snapshot PUT + 1 `current.json` CAS PUT\n * = 4 + N + P.\n * GC, maximally contended: 1 current GET + 3 pending-bootstrap-conflict\n * operations + 1 `snapshot/` LIST page (the mark window never exceeds\n * one page) + 1 conditional fresh-current GET before a due snapshot\n * sweep + S DELETEs + all three final pending CAS attempts (3 GETs +\n * 3 PUTs) = 12 + S.\n * retirement: 1 advisory-gate GET + 1 CAS GET + 1 CAS PUT + up to\n * `LOG_RETENTION_MAX_DELETES_PER_TICK` (20) DELETEs = 23.\n *\n * At these caps, fault-free / with every call retried\n * `STORAGE_RETRY_MAX_ATTEMPTS` (3) times:\n *\n * | Pass | Calls | Retried |\n * | --- | --- | --- |\n * | compaction | 49 | 147 |\n * | GC | 22 | 66 |\n * | write-tick GC (runner GET + GC + `tail_hint` refresh GET+PUT + retirement gate GET) | 26 | 78 |\n * | retirement | 23 | 69 |\n * | write-tick GC + retirement | 48 | 144 |\n * | scheduled compact + GC + retirement | 94 | 282 |\n *\n * Every row fits 900, so on Free with the R2 binding one whole\n * {@link runScheduledMaintenance} pass per invocation is safe. Free CPU is\n * the tighter limit there (about 0.25 ms per binding call against a 10 ms\n * budget), which is why the caps stay at their measured values. Through\n * `fetch` (an unsupported Free host) a whole pass does not fit 45 calls;\n * the compaction row alone does, because `compact()` lowers its tail probe to\n * what the ledger has left after its `current.json` GET, net of the fold\n * it may certify (prior-snapshot GET + N log GETs +\n * `COMPACT_FOLD_WRITE_REQUESTS`): 45 − 1 − 23 = 21 probe GETs, so a pass\n * behind a stale `tail_hint` folds N entries in at most 45 calls. A ledger\n * with less left probes less; a pass whose probe then certifies fewer than\n * `minEntriesToCompact` entries checkpoints its lower bound (reported as\n * `deferred: { reason: \"budget\" }`) and the next pass probes on from it.\n *\n * `minEntriesToCompact` is `maxFoldEntriesPerPass` (20) here, passed\n * explicitly (not the scheduled helper default of 1), because a bounded\n * probe changes what \"available\" can even mean. `compact()` measures\n * `available = discoveredTail − log_seq_start`, and a P-capped probe\n * certifies at most `probeFloor + P`, so\n * a threshold above P is only reachable after several passes have each spent\n * P GETs to ratchet `tail_hint` forward — every one of them returning\n * `probe-budget-checkpointed` without folding. Holding 50 against P=25 also\n * pairs a threshold with a smaller per-pass fold cap (N=20), which folds 20\n * of an accumulated 50 and then waits for the remainder to climb back to 50.\n * Keeping the threshold at N makes a pass fold exactly when one pass's worth\n * of work exists. Any future edit must keep `minEntriesToCompact <= P`.\n *\n * `maintenance-budget.test.ts` pins the per-phase counts exactly and checks\n * each against the Free limit with retries.\n */\nexport const CLOUDFLARE_FREE_TIER: InternalMaintenanceOptions = profileToScheduledOptions(\n MAINTENANCE_PROFILE_CF_FREE,\n CF_FREE_COMPACT_TAIL_PROBE_GETS,\n MAINTENANCE_PROFILE_CF_FREE.maxFoldEntriesPerPass,\n);\n\n/**\n * Tuning profile for Cloudflare Workers Paid, derived from\n * {@link MAINTENANCE_PROFILE_CF_PAID} (one source of truth): Node-tier\n * per-pass fold, GC classification, and sweep budgets, and a compact tail\n * probe of {@link CF_PAID_COMPACT_TAIL_PROBE_GETS} (`P` = 1,000) GETs.\n *\n * Worst cases, with the {@link CLOUDFLARE_FREE_TIER} formulas at N=200,\n * P=1,000, S=100 (fault-free / every call retried\n * `STORAGE_RETRY_MAX_ATTEMPTS` = 3 times): compaction `4 + N + P` =\n * 1,204 / 3,612; GC `12 + S` = 112 / 336; retirement 23 / 69; one\n * scheduled compact + GC + retirement pass 1,339 / 4,017. All fit the Paid\n * request ledger limit of 9,000 (`CF_PAID_REQUEST_LIMIT`). The bounded\n * probe is what makes the compaction figure finite: unbounded, a pass\n * behind a stale `tail_hint` could need up to `LOG_FORWARD_PROBE_CAP`\n * GETs, which the ledger refuses before the fold lands.\n *\n * Fold floor is {@link SCHEDULED_MIN_ENTRIES_TO_COMPACT} (1): this object\n * exists for per-pass caps (`maxEntriesPerRun: 200`, GC bounds), not for\n * an in-band count floor: under `tier: \"cf-paid\"` a live tail of any\n * length folds, sliced by those caps.\n *\n * @see packages/server/src/maintenance-budget.test.ts\n */\nexport const CLOUDFLARE_PAID_TIER: InternalMaintenanceOptions = profileToScheduledOptions(\n MAINTENANCE_PROFILE_CF_PAID,\n CF_PAID_COMPACT_TAIL_PROBE_GETS,\n);\n\nconst TIER_OPTIONS: Readonly<Record<string, InternalMaintenanceOptions>> = {\n \"cf-free\": CLOUDFLARE_FREE_TIER,\n \"cf-paid\": CLOUDFLARE_PAID_TIER,\n node: {},\n};\n\n/**\n * Run one opt-in scheduled maintenance pass over one collection: fold its\n * recent writes, delete data nothing references any more, and retire old\n * log entries. Optional: every write already runs bounded maintenance in\n * band, so a collection that takes writes maintains itself. A schedule is\n * for collections served mostly read-only, or to keep folding ahead of\n * the write tick.\n *\n * One call does a bounded amount of work and returns; it never loops or\n * retries, and it is safe to run concurrently with writes and with other\n * passes. The caller schedules the next pass. Run one collection per\n * Cloudflare invocation: shard the cron schedule or persist a collection\n * cursor instead of looping tenants or collections in one invocation.\n *\n * `tier` sizes the pass for its host, in the `BAERLY_MAINTENANCE_PROFILE`\n * vocabulary: `\"cf-free\"` fits one Workers Free invocation through the R2\n * binding, `\"cf-paid\"` one Workers Paid invocation, and `\"node\"` (the\n * default) is unbounded. S3 storage on Workers needs Paid, with\n * `\"cf-paid\"`.\n *\n * Errors propagate; log them from the cron handler. On Cloudflare an\n * uncaught error reaches the Workers dashboard.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `app`, `tenant` or\n * `collection` is not a name `Db.create` / `db.collection` accepts, or\n * `tier` is not one of the listed values, or when an option this\n * release no longer accepts is passed.\n *\n * @example\n * ```ts\n * import { runScheduledMaintenance } from \"@gusto/baerly-storage/maintenance\";\n *\n * const target = { storage, app: \"helpdesk\", tenant: \"acme\", collection: \"tickets\" };\n *\n * // Node: one unbounded pass.\n * const res = await runScheduledMaintenance(target);\n * console.log(\"folded\", res.folded, \"deleted\", res.gcDeleted);\n *\n * // Cloudflare: one bounded pass per invocation.\n * await runScheduledMaintenance(target, { tier: \"cf-paid\" });\n * ```\n */\nexport const runScheduledMaintenance = async (\n target: MaintenanceTarget,\n options: MaintenanceOptions = {},\n): Promise<MaintenanceResult> => {\n const { storage, app, tenant, collection } = target;\n assertNameSegment(app, \"app\", \"runScheduledMaintenance\");\n assertNameSegment(tenant, \"tenant\", \"runScheduledMaintenance\");\n assertNameSegment(collection, \"collection\", \"runScheduledMaintenance\");\n const { tier = \"node\", signal } = options;\n const tierOptions = Object.hasOwn(TIER_OPTIONS, tier) ? TIER_OPTIONS[tier] : undefined;\n if (tierOptions === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `runScheduledMaintenance: tier must be \"cf-free\", \"cf-paid\" or \"node\", got ${JSON.stringify(tier)}`,\n );\n }\n // Removed in 0.7; refuse it so an untyped caller does not silently get\n // a different pass than it asked for.\n if ((options as { readonly phase?: unknown }).phase !== undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"runScheduledMaintenance: `phase` was removed in 0.7; each invocation runs one whole maintenance pass — remove the option\",\n );\n }\n // The same key layout `Db` writes under (`db-read-seams.ts`).\n const args = {\n storage,\n currentJsonKey: `app/${app}/tenant/${tenant}/manifests/${collection}/current.json`,\n };\n const passOptions = { ...tierOptions, ...(signal !== undefined && { signal }) };\n return summarize(await runMaintenancePass(args, passOptions));\n};\n\n/**\n * Compaction skips that leave available work unfolded. The scheduled\n * tiers set no snapshot ceiling, so the over-ceiling `\"deferred\"` skip\n * cannot occur on this path.\n */\nconst DEFERRAL_REASONS: Readonly<\n Record<string, NonNullable<MaintenanceResult[\"deferred\"]>[\"reason\"]>\n> = {\n \"cas-lost\": \"contention\",\n \"probe-budget-checkpointed\": \"budget\",\n};\n\n/** Format-neutral summary of one whole pass. */\nconst summarize = ({\n compact: compactRes,\n gc: gcRes,\n retired,\n}: MaintenancePassResult): MaintenanceResult => {\n const reason = DEFERRAL_REASONS[compactRes.skippedReason ?? \"\"];\n return {\n // A lost CAS reports the entries it would have folded; none landed.\n folded: compactRes.written ? compactRes.entriesFolded : 0,\n ...(reason !== undefined && { deferred: { reason } }),\n gcDeleted: gcRes.swept + retired,\n pending: gcRes.pendingDepth,\n };\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-limited Cloudflare isolate an invocation terminated mid-rebuild\n// would never reach a post-rebuild size check, so the gate is one that\n// never starts an over-ceiling fold.\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 * The write-tick runner's pre-fold projection off STORED figures: the\n * snapshot it would load is within `C` bytes and `E` rows. It does not\n * project the pass: `compact()` counts real rows as it applies the range\n * and folds the longest prefix that stays within `E`, so an update/delete\n * tail keeps folding at the ceiling and only an entry that would add a row\n * past `E` stops it. The runner, `baerly inspect` and the backlog bench\n * share this predicate. Both comparisons are written so a NaN ceiling\n * fails closed.\n */\nexport const isFoldViable = (\n snapshotBytes: number,\n snapshotRows: number,\n ceilings: Pick<MaintenanceProfile, \"maxFoldBytes\" | \"maxFoldRows\">,\n): boolean => snapshotBytes <= ceilings.maxFoldBytes && snapshotRows <= ceilings.maxFoldRows;\n\n/** The fold ceilings `C` (`maxFoldBytes`) and `E` (`maxFoldRows`) a host folds within. */\nexport type FoldCeilings = Pick<MaintenanceProfile, \"maxFoldBytes\" | \"maxFoldRows\">;\n\n/**\n * Resolve the serving host's fold ceilings: `profile` (absent ⇒\n * {@link MAINTENANCE_PROFILE_CF_FREE}) with `C` overridden by\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` (`maxFoldBytes`). `E` has no\n * override. The write-tick runner and growth refusal (`capacity.ts`) both\n * resolve through here, so a refusal and a fold never see different\n * ceilings.\n */\nexport const resolveFoldCeilings = (\n profile: MaintenanceProfile | undefined,\n maxFoldBytes: number | undefined,\n): FoldCeilings => {\n const resolved = profile ?? MAINTENANCE_PROFILE_CF_FREE;\n return {\n maxFoldBytes: maxFoldBytes ?? resolved.maxFoldBytes,\n maxFoldRows: resolved.maxFoldRows,\n };\n};\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 fold\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/** Derived live-tail bytes over the snapshot's bytes (floored at {@link MAINTENANCE_MIN_LIVE_BYTES}). */\nconst tailRatio = (current: CurrentJson, observedTail: number): number =>\n estimateTailBytes(current, observedTail) /\n Math.max(current.snapshot_bytes, MAINTENANCE_MIN_LIVE_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 tailRatio(current, observedTail) >= 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 /**\n * @internal — test seam. Log retention options (window size, max deletes).\n * Production callers should omit it and take the defaults.\n */\n readonly logRetention?: LogRetentionOptions;\n readonly signal?: AbortSignal;\n}\n\n/** Which fold gate closed: the runner's pre-fold projection, or compact()'s post-rebuild check. */\ntype FoldGate = \"pre-fold\" | \"rebuild\";\n\n/**\n * Structured fields of one fold-wall deferral — the `fold_deferred`\n * LogTape record carries these plus `detail`, the\n * {@link foldDeferredWarning} rendering of them for humans. `snapshot_*` are the stored figures on a\n * `pre-fold` defer and the rebuilt (unwritten) figures on a `rebuild` one.\n */\n// A `type` (not `interface`) so it is assignable to the `warn` sink's\n// `Readonly<Record<string, unknown>>` parameter.\ntype FoldDeferredFields = {\n readonly collection: string;\n readonly dimension: \"bytes\" | \"rows\";\n readonly gate: FoldGate;\n readonly snapshot_bytes: number;\n readonly snapshot_rows: number;\n /** `C`, after any `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` override. */\n readonly ceiling_bytes: number;\n /** `E` — per host profile, no env override. */\n readonly ceiling_rows: number;\n readonly live_log_tail: number;\n readonly log_seq_start: number;\n};\n\n/**\n * Human-readable line for a fold-wall deferral. Names both ceilings, which\n * arm tripped, that `log_seq_start` and log retention are frozen, and the\n * remedy that actually applies to that arm — the bytes override does\n * nothing for rows.\n */\nconst foldDeferredWarning = (f: FoldDeferredFields): string => {\n const which = f.gate === \"rebuild\" ? \"rebuilt\" : \"stored\";\n const rowsTripped =\n f.gate === \"rebuild\"\n ? `the rows arm tripped (the next log entry adds a row past E, or the rebuilt snapshot is over E)`\n : `the rows arm tripped (snapshot_rows > E)`;\n const tripped =\n f.dimension === \"bytes\" ? `the bytes arm tripped (snapshot_bytes > C)` : rowsTripped;\n const remedy =\n f.dimension === \"bytes\"\n ? `On Workers Paid set BAERLY_MAINTENANCE_PROFILE=cf-paid (C=${MAINTENANCE_PROFILE_CF_PAID.maxFoldBytes}); ` +\n `on paid Cloudflare / Node you can also raise BAERLY_MAINTENANCE_MAX_FOLD_BYTES — but on ` +\n `Cloudflare a cap above the configured default may exceed an invocation's CPU or ` +\n `memory resources, so such folds may not land. Otherwise, move to a database service (D1 / Postgres).`\n : `E has no env override, and BAERLY_MAINTENANCE_MAX_FOLD_BYTES does not apply to rows. ` +\n `On Cloudflare, move to Workers Paid and set BAERLY_MAINTENANCE_PROFILE=cf-paid ` +\n `(E=${MAINTENANCE_PROFILE_CF_PAID.maxFoldRows}); on Node (E=${MAINTENANCE_PROFILE_NODE.maxFoldRows}) ` +\n `or past the paid ceiling, split the collection or move to a database service (D1 / Postgres).`;\n return (\n `baerly-storage: collection \"${f.collection}\" has stopped compacting — the ${which} ` +\n `snapshot is ${f.snapshot_bytes} bytes / ${f.snapshot_rows} rows against this host's fold ` +\n `ceiling C=${f.ceiling_bytes} bytes, E=${f.ceiling_rows} rows, and ${tripped}. Until it ` +\n `folds again log_seq_start stays at ${f.log_seq_start}, log retention is paused, the live ` +\n `tail (${f.live_log_tail} entries) and the bucket grow without bound, and every read ` +\n `replays the tail. ${remedy} See docs/about/graduation.md.`\n );\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 by default to a conservative Cloudflare free-tier CPU budget.\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. CAS contention is swallowed quietly, and so is a call the\n * invocation's request ledger refused (each phase is sized from the\n * ledger's remainder first; see the request-budget note inside, and\n * `docs/spec/sync-protocol.md` \"Per-invocation request budget\"); an over-ceiling deferral\n * is not an error but is signalled loudly (see `signalFoldDeferred`\n * inside); 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, or a forced tick) trips → fold if the pre-fold\n * projection is viable, else defer and signal. On `\"single\"` a fold\n * attempt is this tick's one phase — including one that compact()\n * deferred after rebuilding, which signals the same way and ends the\n * tick. A pre-fold defer falls through to Step 4.\n * 4. Otherwise (or on `\"both\"`) → GC iff the cadence boundary crossed.\n *\n * Steps 0, 2, 3-defer, and 4 all take the rate-limited `tail_hint`\n * refresh, but the tick publishes the hint AT MOST ONCE — a landed fold\n * (Step-7 CAS) and the refresh itself both count as that publication.\n * Ordering matters: Step 3's defer refreshes and then falls through to\n * Step 4, so without the shared guard that one tick would CAS\n * `current.json` twice with identical bytes.\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 * Forced tick (main-10 G6): the writing verb found the collection at\n * its growth-refusal point, so Gate 1's ratio trigger and entry floor\n * are bypassed and any pending tail folds. Every other step is\n * unchanged: the pre-fold ceiling check, the hard-GC guard, and the\n * per-pass budget (`maxFoldEntriesPerPass`).\n */\n forceFold?: 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 phase budgets read off it.\n const profile = options?.profile ?? MAINTENANCE_PROFILE_CF_FREE;\n const { maxFoldEntriesPerPass, gcMaxMarks, gcMaxSweeps, gcInterval } = profile;\n const forceFold = args.forceFold === true;\n // A forced tick folds whatever is pending: one entry clears the floor.\n const minEntriesToCompact = forceFold\n ? 1\n : (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 ceilings = resolveFoldCeilings(profile, args.maxFoldBytes);\n const C = ceilings.maxFoldBytes;\n const E = ceilings.maxFoldRows;\n\n // Derive the collection label the same way compact()/runGc() do.\n const { prefix: collectionPrefix, name: collection } =\n collectionFromCurrentJsonKey(currentJsonKey);\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 // Request budget. On a host with a per-invocation request cap the tick\n // shares the ledger of the write that dispatched it (`ctx.waitUntil` work\n // included), so each phase is sized at its start from what that ledger\n // has left on the pool the storage charges, net of active holds\n // (`storageRemaining()`). A tick dispatched while a multi-row write runs\n // sits outside every commit hold, so it sizes against the room the later\n // rows' commit-resolution reserves leave. A phase whose common-path\n // cost does not fit is skipped, and a GC slice or retirement pass that\n // fits only in part runs with a smaller DELETE cap. The profile's caps\n // stay the ceilings. A call that still overruns (a retry, a tail a\n // concurrent writer lengthened) is refused by the ledger before it is\n // sent; the tick ends there and the next one resumes.\n const ledger = getCurrentContext()?.ledger;\n const requestsLeft = (): number => ledger?.storageRemaining() ?? Infinity;\n const skipForBudget = (phase: \"fold\" | \"gc\" | \"retire\" | \"tail_hint\"): void => {\n ctxMetrics().counter(\"db.maintenance.request_budget_skipped_total\", 1, { collection, phase });\n };\n\n const retireWithinBudget = async (): Promise<void> => {\n // Unlike the other phases, sized for every attempt: the floor CAS lands\n // before the DELETEs, so a DELETE refused after it leaks for good.\n const deletes = Math.floor(\n (requestsLeft() - MAINTENANCE_RETIRE_PRE_FLOOR_REQUESTS) / STORAGE_RETRY_MAX_ATTEMPTS,\n );\n if (deletes < 1) {\n skipForBudget(\"retire\");\n return;\n }\n const logRetention = options?.logRetention;\n const maxDeletes = logRetention?.maxDeletes ?? LOG_RETENTION_MAX_DELETES_PER_TICK;\n await retireLogs(storage, currentJsonKey, {\n logRetention: deletes < maxDeletes ? { ...logRetention, maxDeletes: deletes } : logRetention,\n ...(signal !== undefined && { signal }),\n });\n };\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 ratio = tailRatio(current, nextSeq);\n const foldAtTailEntries = (options as InternalBoundedMaintenanceOptions | undefined)\n ?.foldAtTailEntries;\n const gate1 =\n forceFold ||\n (foldAtTailEntries !== undefined && nextSeq - logSeqStart >= foldAtTailEntries) ||\n (ratio >= MAINTENANCE_TARGET_RATIO && nextSeq - logSeqStart >= minEntriesToCompact);\n // SAFETY ceiling (conservative CF CPU/memory budget) — EXACT snapshot_bytes/rows, NEVER the estimate.\n // The pass is not projected: compact() stops at the first entry that\n // would add a row past E, against the current.json it folds from.\n const foldViable = isFoldViable(snapshotBytes, snapshotRows, ceilings);\n const gcDue = crossesGcBoundary(prevSeq, nextSeq, gcInterval);\n\n // ONE `tail_hint` publication per tick, whoever performs it: this\n // helper's own CAS, or a fold that landed (compact()'s Step-7 stamps\n // `max(stored, discoveredTail)` with a probe floor including\n // `knownTail = nextSeq`).\n //\n // The rate limit alone cannot enforce this. It tests the in-memory\n // `current`, which `casUpdateCurrentJson` never writes back, so a\n // second call on a >= REFRESH_INTERVAL gap still reads as due and\n // rewrites byte-identical bytes. Every path that reaches GC after\n // already publishing — a landed fold on `\"both\"`, and the Step-3\n // DEFER refresh that falls through — would otherwise spend a second\n // GET+PUT for no state change.\n let tailHintPublished = false;\n\n // `stampWarnedSeq` rides the deferral warn's `last_warned_seq` stamp on\n // the SAME CAS as the hint refresh, so a warning defer costs one\n // GET+PUT, not two. A single-phase rebuild-gate defer tick then costs\n // 26 ops — runner GET 1 + deferred compact() 23 (current.json GET,\n // `knownTail` probe, snapshot GET, 20 log GETs) + this CAS 2; pinned in\n // `maintenance-budget.test.ts`.\n const refreshTailHintIfNeeded = async (stampWarnedSeq = false): Promise<void> => {\n if (!stampWarnedSeq) {\n if (tailHintPublished) {\n return;\n }\n if (nextSeq - current.tail_hint < MAINTENANCE_TAIL_HINT_REFRESH_WRITES) {\n return;\n }\n }\n // Set before the CAS, so this counts publication ATTEMPTS: a lost\n // CAS means a peer advanced the hint (the stamp is monotone, so it\n // is published either way) and a transient error is caught by the\n // next tick. Retrying inside one tick would reintroduce the extra\n // ops this guard exists to bound.\n tailHintPublished = true;\n if (requestsLeft() < MAINTENANCE_TAIL_HINT_REFRESH_REQUESTS) {\n skipForBudget(\"tail_hint\");\n return;\n }\n try {\n await casUpdateCurrentJson(\n storage,\n currentJsonKey,\n (c) => ({\n ...c,\n tail_hint: Math.max(c.tail_hint, nextSeq),\n ...(stampWarnedSeq && { last_warned_seq: nextSeq }),\n }),\n signal !== undefined ? { signal } : undefined,\n );\n } catch {\n // Swallow — WriteConflict (compactor/another isolate advanced first) or\n // any transient error. A missed advance just means the next tick\n // catches up; a lost warn stamp just means another isolate warns\n // slightly sooner/later. Never throw out of write-tick maintenance.\n }\n };\n\n /**\n * The one fold-wall deferral signal, shared by both gates so a\n * deferral counts once and reads the same wherever it closed:\n *\n * - `db.compaction.deferred_total` (labels `collection`, `dimension`,\n * `gate`) plus `db.compaction.deferred_{bytes,rows}_total` — distinct\n * names, because the canonical line keys counters by name alone and\n * drops labels.\n * - A `fold_deferred` structured warning through the adapter's\n * {@link MaintenanceDispatch.warn} sink, carrying the human text as\n * `detail` — or, with no sink or one that throws, that text as a\n * `console.warn` line. Rate-limited by the SHARED `current.json.last_warned_seq` (not a\n * per-isolate Set — a fresh isolate must honour it). A collection\n * that has never warned warns on its first deferral. On Cloudflare\n * the tick runs in `ctx.waitUntil` after the canonical line flushed,\n * so the log record is the only signal an operator sees.\n * - The bounded `tail_hint` refresh (HR-2): a deferring collection\n * never reaches compact()'s Step-7 CAS, so without it every read\n * would re-walk the whole growing tail. Write-tick only; reads stay\n * pure.\n */\n const signalFoldDeferred = async (d: {\n gate: FoldGate;\n dimension: \"bytes\" | \"rows\";\n snapshotBytes: number;\n snapshotRows: number;\n }): Promise<void> => {\n const metrics = ctxMetrics();\n metrics.counter(\"db.compaction.deferred_total\", 1, {\n collection,\n dimension: d.dimension,\n gate: d.gate,\n });\n metrics.counter(\n d.dimension === \"bytes\"\n ? \"db.compaction.deferred_bytes_total\"\n : \"db.compaction.deferred_rows_total\",\n 1,\n { collection, gate: d.gate },\n );\n // A collection that has never warned warns on its FIRST deferral, so a\n // young collection does not sit silent until seq 1000.\n const warnDue =\n current.last_warned_seq === undefined ||\n nextSeq - current.last_warned_seq >= MAINTENANCE_WARN_INTERVAL_WRITES;\n if (warnDue) {\n const fields: FoldDeferredFields = {\n collection,\n dimension: d.dimension,\n gate: d.gate,\n snapshot_bytes: d.snapshotBytes,\n snapshot_rows: d.snapshotRows,\n ceiling_bytes: C,\n ceiling_rows: E,\n live_log_tail: nextSeq - logSeqStart,\n log_seq_start: logSeqStart,\n };\n const detail = foldDeferredWarning(fields);\n const sink = getCurrentContext()?.maintenance?.warn;\n let delivered = false;\n if (sink !== undefined) {\n // A throwing custom sink must not skip the stamp + hint refresh\n // below (or GC after it), so its failure is contained here.\n try {\n sink(\"fold_deferred\", { ...fields, detail });\n delivered = true;\n } catch {\n // Fall through to the console line.\n }\n }\n // The human line goes to the console only when no sink took the\n // record — a bare `Db.create()` (no adapter, or `observability:\n // false`) or a sink that threw — so an adapter logs one line per\n // deferral, not two.\n if (!delivered) {\n console.warn(detail);\n }\n }\n await refreshTailHintIfNeeded(warnDue);\n };\n\n const runGcAndRefreshTailHint = async (): Promise<void> => {\n const sweeps = requestsLeft() - MAINTENANCE_GC_BASE_REQUESTS;\n if (sweeps < 0) {\n skipForBudget(\"gc\");\n } else {\n await runGc(\n { storage, currentJsonKey },\n sweeps < gcMaxSweeps ? { ...gcOpts, maxSweepsPerRun: sweeps } : gcOpts,\n );\n }\n await refreshTailHintIfNeeded();\n };\n\n // Every tick that is due takes the rate-limited refresh, whichever way\n // it exits: a single-phase fold that published nothing returns early,\n // and with zero adapter retries one 503 throws out of compact() or\n // runGc(). A skipped refresh leaves the writer's `findLogTail` galloping\n // over the lag on every commit. `tailHintPublished` makes this a no-op\n // once a landed fold or an earlier refresh published the hint, so the\n // tick still publishes at most once.\n try {\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 runGcAndRefreshTailHint();\n // Retire stale logs after GC even on the early-return path.\n // Non-WriteConflict errors re-throw into the outer catch below\n // (unexpected_error_total + stack log), like every other phase.\n await retireWithinBudget();\n return;\n }\n\n // ── Step 3. Fold-priority. ───────────────────────────────────────\n // A fold folds at most one pass of the tail the runner sees. It is not\n // shortened to fit: the growth refusal (`capacity.ts`) models passes\n // of exactly `maxFoldEntriesPerPass` seqs, so a shorter pass could\n // rebuild past `C` where the modelled one lands. One that does not\n // fit is skipped and falls through to GC like a pre-fold defer.\n const foldFits =\n requestsLeft() >=\n MAINTENANCE_FOLD_BASE_REQUESTS +\n Math.min(maxFoldEntriesPerPass, Math.max(0, nextSeq - logSeqStart));\n if (gate1 && foldViable && !foldFits) {\n skipForBudget(\"fold\");\n } else 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 const foldRes = await compact({ storage, currentJsonKey }, {\n maxEntriesPerRun: maxFoldEntriesPerPass,\n // compact() re-checks the floor against the tail it discovers,\n // so it must accept whichever Gate-1 arm tripped.\n minEntriesToCompact:\n foldAtTailEntries === undefined\n ? minEntriesToCompact\n : Math.min(minEntriesToCompact, foldAtTailEntries),\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 // A `written` fold stamped `max(stored, discoveredTail)` at or past\n // `nextSeq` via Step-7. Every other outcome reachable here (failed,\n // skipped, deferred, CAS-lost) published nothing, so it takes the\n // closing refresh. The one skip that does publish,\n // `probe-budget-checkpointed`, needs `maxTailProbeGets`, which this\n // runner never passes.\n if (foldRes.written) {\n tailHintPublished = true;\n }\n // REBUILD-GATE DEFER: the stored snapshot passed the pre-fold gate,\n // but no prefix of this pass rebuilds within `C` / `E` (compact()\n // folds the longest one that does). Two ways here: log entries the\n // capacity check never saw (another host's writes, a direct\n // `Writer` commit), or a tail that ends in a run of entries over\n // `C` shorter than a pass, which the check leaves open so a delete\n // or shrink can end it, holding the writes it accepted behind the\n // over-`C` entry until one does. Same signal as the pre-fold defer\n // below.\n if (foldRes.deferral !== undefined) {\n await signalFoldDeferred({\n gate: \"rebuild\",\n dimension: foldRes.deferral.dimension,\n snapshotBytes: foldRes.deferral.snapshotBytes,\n snapshotRows: foldRes.deferral.snapshotRows,\n });\n }\n if (phasesPerTick === \"single\") {\n // This tick's one phase was the fold attempt. A rebuild defer\n // already spent a full compact() walk, so it must NOT also GC:\n // runner GET (1) + deferred compact (23) + the one signal CAS (2)\n // is 26 ops, and a GC slice on top would spend request budget the\n // write's own route needs on Free over `fetch`. An unpublished\n // fold takes the closing refresh in the `finally` below; after a\n // rebuild defer the signal already took it, so that is a no-op.\n return;\n }\n // \"both\": fall through to GC.\n } else {\n // PRE-FOLD DEFER: stored snapshot over the ceiling (bytes OR rows).\n // A deferring bucket MUST still GC, so we fall through.\n await signalFoldDeferred({\n gate: \"pre-fold\",\n dimension: snapshotBytes > C ? \"bytes\" : \"rows\",\n snapshotBytes,\n snapshotRows,\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 runGcAndRefreshTailHint();\n }\n\n // ── Step 5. Retire stale log objects. ──────────────────────────────\n // Cheap and bounded — a computed key range, no LIST — and placed\n // after GC so it runs on every maintenance pass. `WriteConflict` is\n // swallowed inside `retireLogs`; anything unexpected re-throws into\n // this runner's outer catch (counter + stack log), never out of the\n // write-tick path.\n await retireWithinBudget();\n } finally {\n await refreshTailHintIfNeeded();\n }\n } catch (error) {\n // CAS contention (WriteConflict) thrown by compact()/runGc() is an\n // EXPECTED signal — swallow without the unexpected-error counter.\n if (isWriteConflict(error)) {\n return;\n }\n // So is a call refused before it was sent (`cause.refused`: the request\n // ledger, or the platform's subrequest limit): the tick spent this\n // invocation's request budget, and the next tick resumes. Any other\n // CapacityExceeded is unexpected here.\n if (\n error instanceof BaerlyError &&\n error.code === \"CapacityExceeded\" &&\n (error.cause as { refused?: boolean } | undefined)?.refused === true\n ) {\n ctxMetrics().counter(\"db.maintenance.request_budget_refused_total\", 1, { collection });\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 * Dispatch one write-tick {@link runBoundedMaintenance} through the\n * request's {@link MaintenanceDispatch}: inline and awaited by default,\n * `ctx.waitUntil` on Cloudflare. Never throws: the tick swallows its own\n * failures, and a failing dispatcher bumps\n * `db.write.maintenance_dispatch_failed_total`. The writer calls it after\n * a commit; a write refused with `MaintenancePending` calls it with\n * `forceFold` and nothing committed (`prevSeq === observedTail`).\n */\nexport const dispatchWriteTick = async (args: {\n storage: Storage;\n currentJsonKey: string;\n collection: string;\n prevSeq: number;\n observedTail: number;\n forceFold?: boolean;\n}): Promise<void> => {\n const maint = getCurrentContext()?.maintenance;\n const dispatch = maint?.dispatch ?? dispatchInlineAwaited;\n // `await dispatch(...)`: `dispatchInlineAwaited` returns the task's\n // promise (awaited inline — deterministic for tests + correct for\n // serverful Node). A `ctx.waitUntil`-style dispatch returns void\n // (fire-and-forget off the ack); `await void` is a no-op. The\n // `.then(() => {}, () => {})` is belt-and-suspenders:\n // `runBoundedMaintenance` already swallows internally, but this\n // guarantees a dispatched task can NEVER reject the caller even if a\n // future change makes it throw.\n try {\n await dispatch(() =>\n runBoundedMaintenance(\n {\n storage: args.storage,\n currentJsonKey: args.currentJsonKey,\n prevSeq: args.prevSeq,\n // The in-memory observed tail keys the runner's Gate-1 ratio +\n // GC cadence off the true tail without an O(gap) re-probe (the\n // stored `tail_hint` is only a lower bound).\n observedTail: args.observedTail,\n // `disabled` disables fold/GC phases inside the runner but still\n // permits the bounded tail_hint refresh that prevents a\n // maintenance-off collection from drifting past the probe cap.\n ...(maint?.disabled === true && { disabled: true }),\n ...(maint?.maxFoldBytes !== undefined && { maxFoldBytes: maint.maxFoldBytes }),\n ...(args.forceFold === true && { forceFold: true }),\n },\n maint?.options,\n ).then(\n () => {},\n () => {},\n ),\n );\n } catch {\n // Dispatch is optional work. Its own failure must not surface: after\n // a commit it would make a durable mutation appear safely retriable,\n // and a refused write's refusal stands either way.\n ctxMetrics().counter(\"db.write.maintenance_dispatch_failed_total\", 1, {\n collection: args.collection,\n });\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 * Structured warning sink for maintenance events — today only\n * `fold_deferred`, whose properties are the `collection` / `dimension`\n * / `gate` / `snapshot_*` / `ceiling_*` / `live_log_tail` /\n * `log_seq_start` fields an operator alerts on, plus the human-readable\n * `detail` line naming the remedy. Adapters bind it to LogTape's\n * `[\"baerly\", \"maintenance\"]` category; the kernel never imports\n * LogTape, which keeps the observability subgraph out of the\n * `index.js` / `maintenance.js` bundles. Absent, or throwing ⇒ the\n * runner writes `detail` as a `console.warn` line instead; a throw is\n * contained and never skips the rest of the tick.\n */\n readonly warn?: (event: string, properties: Readonly<Record<string, unknown>>) => void;\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.\n *\n * `maxFoldBytes` (`C`) is `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` written as a\n * plain positive decimal integer (`/^[1-9][0-9]*$/`, at most\n * `Number.MAX_SAFE_INTEGER`), or undefined when unset or `\"\"` (the active\n * profile's default applies). Anything else throws, untrimmed: `\" 1024\"`,\n * `\"0x400\"`, `\"1e6\"`, `\"1.5\"`, `\"8mb\"`. A unit-suffixed or mistyped value\n * would otherwise run silently at the default ceiling; zero or negative\n * would make `snapshot_bytes <= C` false forever, so the fold would defer\n * on every tick and the live tail would grow unbounded.\n *\n * `disabled` reads `BAERLY_MAINTENANCE_DISABLE`, untrimmed, against a closed,\n * case-insensitive vocabulary: unset, `\"\"`, `\"0\"`, `\"false\"` → `false`;\n * `\"1\"`, `\"true\"` → `true`; anything else throws. The prior truthy-if-\n * non-empty parsing silently disabled maintenance on `\"no\"` / `\"off\"` —\n * the two most natural ways an operator would try to spell \"don't disable\".\n *\n * @throws {BaerlyError} `InvalidConfig` for a\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` that is not a plain positive decimal\n * integer, or a `BAERLY_MAINTENANCE_DISABLE`\n * value outside the closed vocabulary above.\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 let maxFoldBytes: number | undefined;\n if (rawFoldBytes !== undefined && rawFoldBytes !== \"\") {\n const parsedFoldBytes = Number(rawFoldBytes);\n if (!/^[1-9][0-9]*$/.test(rawFoldBytes) || !Number.isSafeInteger(parsedFoldBytes)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `BAERLY_MAINTENANCE_MAX_FOLD_BYTES must be unset, \"\", or a positive decimal integer byte count no greater than ${Number.MAX_SAFE_INTEGER}, got ${JSON.stringify(rawFoldBytes)}`,\n );\n }\n maxFoldBytes = parsedFoldBytes;\n }\n\n const rawDisable = readEnv(\"BAERLY_MAINTENANCE_DISABLE\");\n const normalizedDisable = rawDisable?.toLowerCase();\n let disabled: boolean;\n if (\n rawDisable === undefined ||\n normalizedDisable === \"\" ||\n normalizedDisable === \"0\" ||\n normalizedDisable === \"false\"\n ) {\n disabled = false;\n } else if (normalizedDisable === \"1\" || normalizedDisable === \"true\") {\n disabled = true;\n } else {\n throw new BaerlyError(\n \"InvalidConfig\",\n `BAERLY_MAINTENANCE_DISABLE must be one of \"\", \"0\", \"false\", \"1\", \"true\" (case-insensitive), got ${JSON.stringify(rawDisable)}`,\n );\n }\n\n return {\n ...(maxFoldBytes !== undefined && { maxFoldBytes }),\n disabled,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuHA,MAAa,gBAAgB,qBAC3B,GAAG,iBAAiB;;;;;;;;;AAUtB,MAAa,gBAAgB,OAC3B,SACA,KACA,SACkC;CAClC,MAAM,MAAM,MAAM,QAAQ,IAAI,KAAK,IAAI;CACvC,IAAI,QAAQ,MACV,OAAO;CAET,IAAI;CACJ,IAAI;EACF,SAAS,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