@gusto/baerly-storage 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +3 -2
  2. package/dist/API.md +59 -7
  3. package/dist/{app-config-Dj_nGBfj.d.ts → app-config-C0Bbw_Z6.d.ts} +9 -9
  4. package/dist/app-config.d.ts +1 -1
  5. package/dist/auth.d.ts +1 -1
  6. package/dist/baerly.js +10 -10
  7. package/dist/baerly.js.map +1 -1
  8. package/dist/bytes-BXdamO3L.js +11 -0
  9. package/dist/bytes-BXdamO3L.js.map +1 -0
  10. package/dist/{client-CC5yVs1S.d.ts → client-DYZfoZb9.d.ts} +3 -3
  11. package/dist/client-react.d.ts +3 -3
  12. package/dist/client.d.ts +3 -3
  13. package/dist/cloudflare.d.ts +31 -4
  14. package/dist/cloudflare.js +72 -6
  15. package/dist/cloudflare.js.map +1 -1
  16. package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
  17. package/dist/config-DVfDGyw1.js.map +1 -0
  18. package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
  19. package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
  20. package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
  21. package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
  22. package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
  23. package/dist/current-json-C-EyJqs0.js.map +1 -0
  24. package/dist/{db-aRMK_0R0.d.ts → db-BM3y2JQw.d.ts} +3 -3
  25. package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
  26. package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
  27. package/dist/dev-vite.d.ts +3 -3
  28. package/dist/dev-vite.js +3 -3
  29. package/dist/dev.d.ts +1 -1
  30. package/dist/dev.js +1 -1
  31. package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
  32. package/dist/doctor-Db-hzPmE.js.map +1 -0
  33. package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
  34. package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
  35. package/dist/errors-DOdL95kK.js.map +1 -1
  36. package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
  37. package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
  38. package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
  39. package/dist/fsck-CPPZWt9p.js.map +1 -0
  40. package/dist/{http-DeJEeUcO.js → http-Cw8p6y5b.js} +5 -5
  41. package/dist/{http-DeJEeUcO.js.map → http-Cw8p6y5b.js.map} +1 -1
  42. package/dist/http.d.ts +3 -3
  43. package/dist/http.js +1 -1
  44. package/dist/{index-m6pY8iRU.d.ts → index-C3JAH1Yo.d.ts} +14 -2
  45. package/dist/{index-5lX_5NxZ.d.ts → index-DSvwEUeF.d.ts} +63 -54
  46. package/dist/{index-DPaQhAro.d.ts → index-DwDTWPSU.d.ts} +2 -2
  47. package/dist/{index-spCBsIwm.d.ts → index-cUY-36AN.d.ts} +3 -3
  48. package/dist/index.d.ts +5 -5
  49. package/dist/index.js +3 -3
  50. package/dist/{indexes-BIH73Uv4.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
  51. package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
  52. package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
  53. package/dist/maintenance-BRrThz8V.d.ts +449 -0
  54. package/dist/maintenance-BvOv6BMM.js +1295 -0
  55. package/dist/maintenance-BvOv6BMM.js.map +1 -0
  56. package/dist/maintenance-ClzBC1Vv.js +1895 -0
  57. package/dist/maintenance-ClzBC1Vv.js.map +1 -0
  58. package/dist/maintenance.d.ts +2 -323
  59. package/dist/maintenance.js +2 -2
  60. package/dist/node.d.ts +20 -79
  61. package/dist/node.js +2 -2
  62. package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
  63. package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
  64. package/dist/observability.d.ts +2 -2
  65. package/dist/observability.js +2 -2
  66. package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
  67. package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
  68. package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
  69. package/dist/query-BmiQy328.js.map +1 -0
  70. package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
  71. package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
  72. package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
  73. package/dist/restore-C6IcmLeA.js.map +1 -0
  74. package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
  75. package/dist/snapshot-SS8USDUF.js.map +1 -0
  76. package/dist/{src-Cr9C7_tT.js → src-DU1sCMlr.js} +315 -278
  77. package/dist/src-DU1sCMlr.js.map +1 -0
  78. package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
  79. package/dist/src-QQ7jDeL2.js.map +1 -0
  80. package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
  81. package/dist/src-zhEAmmF7.js.map +1 -0
  82. package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
  83. package/dist/subcommand-DZcHcsYp.js.map +1 -0
  84. package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
  85. package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
  86. package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
  87. package/dist/validate-DCq_0DIn.js.map +1 -0
  88. package/package.json +13 -6
  89. package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
  90. package/dist/config-Bsg8wgwo.js.map +0 -1
  91. package/dist/current-json-BkatBzF7.js.map +0 -1
  92. package/dist/doctor-B8h9GCN9.js.map +0 -1
  93. package/dist/fsck-DEz9lyCy.js.map +0 -1
  94. package/dist/indexes-BXn7a06a.js +0 -297
  95. package/dist/indexes-BXn7a06a.js.map +0 -1
  96. package/dist/log-walk-DIru96UT.js.map +0 -1
  97. package/dist/maintenance-Bn6ul9aV.js +0 -758
  98. package/dist/maintenance-Bn6ul9aV.js.map +0 -1
  99. package/dist/query-DcSbFLJt.js.map +0 -1
  100. package/dist/rebuild-index-C5gTXryd.js +0 -119
  101. package/dist/rebuild-index-C5gTXryd.js.map +0 -1
  102. package/dist/restore-CbKVMMpm.js.map +0 -1
  103. package/dist/snapshot-D7C4_FSl.js +0 -71
  104. package/dist/snapshot-D7C4_FSl.js.map +0 -1
  105. package/dist/snapshot-z_N9hpTe.js +0 -917
  106. package/dist/snapshot-z_N9hpTe.js.map +0 -1
  107. package/dist/src-Chafbw8r.js.map +0 -1
  108. package/dist/src-Cr9C7_tT.js.map +0 -1
  109. package/dist/src-n0Te1r98.js.map +0 -1
  110. package/dist/subcommand-BWs6K7zb.js +0 -110
  111. package/dist/subcommand-BWs6K7zb.js.map +0 -1
  112. package/dist/validate-DhH1lO8I.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-BmiQy328.js","names":["#storage","#currentJsonKey","#maxRetries","#initialBackoffMs","#random","#indexes","#verifyLogIntegrityOnCommit","#singleAttemptCommit","#backoff","#verifyFenceUnchanged","#emitWriteMetrics","#provisionCurrentJson","#walkLog","#observe429","#readPreImage"],"sources":["../packages/protocol/src/json.ts","../packages/protocol/src/query/merge.ts","../packages/protocol/src/types.ts","../packages/protocol/src/time.ts","../packages/protocol/src/log.ts","../packages/server/src/log-conflict-adoption.ts","../packages/server/src/writer.ts","../packages/server/src/query-planner-implies.ts","../packages/server/src/query-planner.ts","../packages/server/src/schema.ts","../packages/server/src/query.ts"],"sourcesContent":["import { FORBIDDEN_MERGE_KEYS } from \"./constants.ts\";\n\n/**\n * The shape constraint for documents stored in a {@link Collection}.\n *\n * Plain JSON object: string-keyed; values are strings, numbers,\n * booleans, nested {@link DocumentData}, or arrays of\n * {@link DocumentValue}.\n *\n * The document **body** itself must be an object (not an array) —\n * Baerly's writer is built on JSON Merge Patch (RFC 7386), which\n * is only defined over object documents. Array *values* at any\n * nested level are fine; per RFC 7386, an array in a patch\n * replaces the target array wholesale (Baerly has no array-merge\n * semantics).\n */\nexport type DocumentData = { [x: string]: DocumentValue };\n\n/**\n * A single field value inside a {@link DocumentData}. The recursive\n * type that backs {@link DocumentData}, also used by predicate and\n * order-spec types in `@baerly/protocol/query`.\n *\n * Arrays are valid values; they are replaced (not merged) on patch.\n */\nexport type DocumentValue = string | number | boolean | DocumentData | Array<DocumentValue>;\n\nexport type JSONObject = { [x: string]: JSONValue };\nexport type JSONValue = string | number | boolean | null | JSONObject | Array<JSONValue>;\n\nconst isPlainObject = (value: DocumentValue | undefined): value is DocumentData =>\n // Stryker disable next-line ConditionalExpression: `value !== null` is a defensive guard — null\n // is not in DocumentValue; null patches are caught by the `patch === null` early-return before\n // isPlainObject is called. Replacing `value !== null` with `true` is equivalent for all\n // reachable call sites: genuine dead-branch equivalence.\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * JSON Merge Patch (RFC 7386).\n *\n * Update `target` with a merge patch. Plain-object values recurse\n * key-by-key; primitives, arrays, and type-mismatched values replace\n * the target wholesale. A `null` value in `patch` deletes the key.\n *\n * RFC 7386 explicitly treats arrays as opaque values: an array in a\n * patch replaces the target array — there is no element-wise merge.\n */\nexport function merge<T extends DocumentValue>(\n target: T | undefined,\n patch: Partial<T> | null | undefined,\n): T | undefined {\n if (patch === undefined) {\n return target;\n }\n if (patch === null) {\n return undefined;\n }\n\n // Patch is primitive or an array → replace target wholesale.\n if (!isPlainObject(patch as DocumentValue)) {\n return patch as T;\n }\n // Patch is a plain object but target isn't → replace.\n if (!isPlainObject(target)) {\n return patch as T;\n }\n\n const combined = { ...(target as DocumentData) } as T;\n for (const key of Object.keys(patch) as Array<Extract<keyof T, string>>) {\n // Object.keys returns own enumerable string keys — but `__proto__`\n // is an own property when patches arrive via JSON.parse (HTTP PATCH\n // bodies hit this path through query.ts:runUpdate). Guard remains\n // load-bearing. See predicate.test.ts for the same vector.\n if (FORBIDDEN_MERGE_KEYS.has(key)) {\n continue;\n }\n if (patch[key] === null) {\n delete combined[key];\n } else {\n combined[key] = merge(target[key] as DocumentValue, patch[key] as DocumentValue) as T[Extract<\n keyof T,\n string\n >];\n }\n }\n return combined as T;\n}\n","/**\n * AND-merge two validated wire predicates. Powers chained\n * `Query<T>.where(...).where(...)`: each new clause set AND's with\n * the existing wire by clause-list concatenation; the per-field\n * satisfiability check runs across the combined list.\n *\n * Companion modules: `./validate.ts`, `./matches.ts`, `./wire.ts`.\n */\n\nimport { assertWireSatisfiable } from \"./satisfiable.ts\";\nimport type { PredicateWire } from \"./wire.ts\";\n\n/**\n * AND-merge two validated wire predicates. The result accepts a\n * document iff both `a` and `b` would accept it.\n *\n * Wire-level: clause lists concatenate. The per-field satisfiability\n * check runs across the combined list, surfacing\n * `BaerlyError{code:\"UnsatisfiablePredicate\"}` on empty residual\n * intervals / empty `in()` intersections / `eq` outside the merged\n * interval, and `BaerlyError{code:\"InvalidConfig\"}` on conflicting\n * `eq` clauses for the same field (mirrors the pre-redesign\n * conflict-on-shared-keys semantics).\n *\n * @example\n * ```ts\n * mergePredicateWires(\n * { clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] },\n * { clauses: [{ op: \"eq\", field: \"priority\", value: \"p1\" }] },\n * );\n * // → { clauses: [\n * // { op: \"eq\", field: \"status\", value: \"open\" },\n * // { op: \"eq\", field: \"priority\", value: \"p1\" },\n * // ] }\n *\n * mergePredicateWires(\n * { clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] },\n * { clauses: [{ op: \"eq\", field: \"status\", value: \"closed\" }] },\n * );\n * // throws BaerlyError{InvalidConfig}: conflicting equality clauses on \"status\"\n *\n * mergePredicateWires(\n * { clauses: [{ op: \"gt\", field: \"x\", value: 10 }] },\n * { clauses: [{ op: \"lt\", field: \"x\", value: 5 }] },\n * );\n * // throws BaerlyError{UnsatisfiablePredicate}: empty interval\n * ```\n */\nexport const mergePredicateWires = (a: PredicateWire, b: PredicateWire): PredicateWire => {\n const merged: PredicateWire = { clauses: [...a.clauses, ...b.clauses] };\n assertWireSatisfiable(merged);\n return merged;\n};\n","declare const brand: unique symbol;\ntype Brand<B> = { [brand]: B };\n\n/**\n * Nominal-typing helper. `Branded<string, \"UUID\">` is a `string` at\n * runtime but the type system rejects mixing it with a plain `string` or\n * a string branded as something else. Used to prevent confusion bugs at\n * protocol boundaries (UUIDs vs. content versions are both strings, but\n * using the wrong one corrupts the manifest log).\n *\n * Construct branded values via the helpers in this file (e.g. {@link uuid})\n * or with a tagged cast at a single, deliberate boundary — never `as string`\n * to widen one back. See `docs/contributing/conventions/src.md`.\n */\nexport type Branded<T, B> = T & Brand<B>;\n\n/**\n * A v4 UUID minted by this client. Used as session IDs and content\n * identifiers in non-versioned mode.\n */\nexport type UUID = Branded<string, \"UUID\">;\n\n/**\n * SHA-256 content digest, lowercase hex truncated to\n * `VERSION_HEX_LENGTH` (32 chars). Minted by\n * `versionFromContent` in `useVersioning=false` mode and used as\n * the `<key>@<version>` suffix in content keys.\n *\n * The synthetic `local-${op}` placeholder used for in-flight\n * optimistic updates also wears this brand — it never round-trips\n * to S3, only flows through the local manifest poll loop.\n */\nexport type ContentVersionId = Branded<string, \"ContentVersionId\">;\n\n/**\n * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle\n * `<UUID>crypto.randomUUID()` throughout the codebase.\n */\nexport const uuid = (): UUID => crypto.randomUUID() as UUID;\n\n/**\n * Mint a UUIDv7 — 48-bit Unix-millis prefix + 74 bits of randomness,\n * formatted as a standard 8-4-4-4-12 UUID string per RFC 9562 §5.7.\n * Lex-sortable by mint time, so it pairs well with object-storage\n * list semantics. Returns a branded {@link UUID}.\n *\n * Uses `crypto.getRandomValues` which is universally available\n * (Node 19+, Workerd, Bun, browsers).\n *\n * @example\n * ```ts\n * const id = uuidv7();\n * // e.g. \"01956cad-4cc8-7abc-9def-0123456789ab\"\n * ```\n */\nexport const uuidv7 = (): UUID => {\n const millis = Date.now();\n const rand = new Uint8Array(10);\n crypto.getRandomValues(rand);\n // Version nibble: top 4 bits of rand[0] = 0b0111 (v7). The byte\n // sits at the start of the \"version-and-rand-a\" group below.\n rand[0] = (rand[0]! & 0x0f) | 0x70;\n // Variant bits: top 2 bits of rand[2] = 0b10 (RFC 4122 variant).\n // This byte starts the \"variant-and-rand-b\" group below.\n rand[2] = (rand[2]! & 0x3f) | 0x80;\n const millisHex = millis.toString(16).padStart(12, \"0\");\n const b = Array.from(rand, (n) => n.toString(16).padStart(2, \"0\")).join(\"\");\n return `${millisHex.slice(0, 8)}-${millisHex.slice(8, 12)}-${b.slice(0, 4)}-${b.slice(4, 8)}-${b.slice(8, 20)}` as UUID;\n};\n\n/**\n * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).\n * `COUNT_BIT_WIDTH = 10` (matches `packages/protocol/src/log.ts:145`)\n * gives a 2-char descending base-32 string with a domain of 0..1023.\n *\n * Used together with {@link timestamp} (the descending base-32\n * encoding of millis-since-epoch). See {@link uint2strDesc} for the\n * lex-reversal property both rely on.\n */\nexport const countKey = (number: number): string => uint2strDesc(number, 10);\n\nexport const uint2str = (num: number, bits: number) => {\n const maxBase32Length = Math.ceil(bits / 5); // Change from 4 to 5 because log2(32) is roughly 5.\n const base32Representation = num.toString(32);\n return base32Representation.padStart(maxBase32Length, \"0\");\n};\n\nexport const str2uint = (str: string) => {\n return parseInt(str, 32); // Parse the string as base 32.\n};\n\n/**\n * Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.\n * Pads to `Math.ceil(bits/5)` chars so all values in the domain compare\n * lex against each other.\n *\n * **Order-reversal property:** for any pair of integers `a < b` (with\n * `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`\n * lexicographically. Composed into an LSN of shape\n * `<base32-time>_<session>_<seq>` (where both `<base32-time>` and\n * `<seq>` use this encoder), a forward `Storage.list(prefix)`\n * returns log entries in reverse-causal order — newer entries first.\n *\n * This is the structural property the read path leans on:\n * `ListObjectsV2` is forward-only on S3, but the descending encoding\n * makes \"fetch the K newest entries\" a single bounded LIST with\n * `maxKeys=K` instead of a full-population LIST + in-memory reverse.\n *\n * Behaviourally verified across randomized populations in\n * `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified\n * bytes-listed reduction is in\n * `docs/spec/attachments/lsn-reverse-walk-baseline.json`\n * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:\n * `docs/spec/sync-protocol.md` §\"Subtleties of the manifest key\".\n */\nexport const uint2strDesc = (num: number, bits: number): string => {\n const maxValue = Math.pow(2, bits) - 1;\n return uint2str(maxValue - num, bits);\n};\n\nexport const str2uintDesc = (str: string, bits: number): number => {\n const maxValue = Math.pow(2, bits) - 1;\n const num = parseInt(str, 32); // Convert base32 string to number\n return maxValue - num;\n};\n","import { TIMESTAMP_BIT_WIDTH } from \"./constants.ts\";\nimport { BaerlyError } from \"./errors.ts\";\nimport { uint2strDesc } from \"./types.ts\";\n\n/**\n * Encode an epoch-millis instant as a lexicographically-DEScending\n * base-32 key (newer sorts first). The load-bearing LSN ordering\n * primitive — see {@link uint2strDesc}.\n *\n * `epoch` is REQUIRED and validated. There is no default: an argless\n * call used to encode `0`, which descending-sorts as the most-ancient\n * instant and would silently invert ordering. A non-finite, negative,\n * or out-of-range `epoch` (e.g. a broken `Date.now()` returning `NaN`)\n * would corrupt the key silently rather than fail loud, so it throws\n * `Internal` instead — this is an invariant violation, not caller config\n * (the only legitimate argument is `Date.now()`).\n */\nexport const timestamp = (epoch: number): string => {\n if (!Number.isInteger(epoch) || epoch < 0 || epoch >= 2 ** TIMESTAMP_BIT_WIDTH) {\n throw new BaerlyError(\n \"Internal\",\n `timestamp(): epoch must be a non-negative integer < 2^${TIMESTAMP_BIT_WIDTH} (got ${epoch})`,\n );\n }\n return uint2strDesc(epoch, TIMESTAMP_BIT_WIDTH);\n};\n\n/**\n * Delay for `ms` milliseconds, with optional cancellation. If\n * `signal` aborts before the delay elapses, the returned promise\n * rejects with `signal.reason`. Used by `S3HttpStorage`'s retry\n * loop so shutdown can interrupt an in-flight backoff instead of\n * waiting for it to complete.\n */\nexport const delay = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(signal.reason);\n },\n // Stryker disable next-line BooleanLiteral,ObjectLiteral: `{ once: true }` removes the\n // listener after the first fire. AbortController fires `abort` only once per signal, so\n // `once: false` / `{}` produce identical observable behaviour — the listener stays attached\n // to an already-fired signal, but calling reject on a settled Promise is a no-op. The\n // BooleanLiteral (once:false) and ObjectLiteral ({}) mutations are genuine equivalences.\n { once: true },\n );\n });\n","import { BaerlyError } from \"./errors.ts\";\nimport type { DocumentData, JSONValue } from \"./json.ts\";\nimport { str2uintDesc } from \"./types.ts\";\n\n/**\n * Debezium-style JSON CDC envelope using pgoutput's message-tag (`I`/`U`/`D`) vocabulary. One per mutation.\n *\n * **Pre-launch: the shape may still narrow.** Once the first production\n * consumer ships, this becomes a frozen migration contract behind\n * `baerly export --target=postgres` — the keys will be public, consumers\n * ack on `lsn`, and any rename / removal will be a major-version\n * migration.\n *\n * Field requirement matrix:\n * - Always: `lsn`, `commit_ts`, `op`, `collection`, `session`,\n * `seq`.\n * - For I/U/D: `doc_id`.\n * - For I/U: `after` (full post-image).\n * - Optional: `before` (when `replica_identity === \"FULL\"`), `key_old`\n * (U/D when `replica_identity !== \"PATCH_ONLY\"`), `origin`.\n *\n * @see docs/spec/log-entry-shape.md\n */\nexport interface LogEntry {\n /**\n * Opaque, monotonic, lex-asc cursor. Shape is\n * `<base32-time>_<session>_<seq>` — minted inside\n * `Writer.commit` (see\n * `packages/server/src/writer.ts`) from `timestamp()` +\n * the per-commit `session` + `countKey(seq)`. Consumers ack and\n * resume from this string.\n *\n * When you have a `LogEntry` in hand, prefer the structured\n * `session` / `seq` fields below over parsing this string. The\n * one place that *does* need to crack it open is the\n * `/v1/since` boundary, where a client resumes from an opaque\n * `next_cursor` and no `LogEntry` is in scope — that path uses\n * `lsnParts` (the kernel-blessed parser) rather than ad-hoc\n * `split(\"_\")`.\n */\n lsn: string;\n\n /** ISO-8601 ms timestamp. Redundant with `lsn` but cheap. */\n commit_ts: string;\n\n /** Insert / Update / Delete. */\n op: \"I\" | \"U\" | \"D\";\n\n /**\n * Collection name — the pgoutput RELATION analogue. Today derived\n * from the path segment immediately under the manifest prefix\n * (the part of `ref.key` before the first `/`); falls back to\n * `ref.bucket` for flat keys with no separator. The table API\n * makes collections first-class.\n */\n collection: string;\n\n /**\n * The document key (`ref.key`). Required for every op — `op` is\n * `I | U | D` and all three carry it — so the wire type is required,\n * not optional, matching `log-entry-shape.md`.\n */\n doc_id: string;\n\n /** Required for I, U. The post-image (Debezium's `after`). */\n after?: DocumentData;\n\n /**\n * The pre-image (Debezium's `before`). Present iff the\n * collection's `replica_identity` is `FULL`. ~2× log size on\n * update-heavy collections; off by default.\n */\n before?: DocumentData;\n\n /**\n * Pre-image of the primary key. U/D always carry this when\n * `replica_identity` is not `PATCH_ONLY`. (For Baerly today,\n * `_id` is the only PK.)\n */\n key_old?: { readonly [pk: string]: JSONValue };\n\n /** ORIGIN analogue — the writer session id. */\n origin?: string;\n\n /**\n * Causal metadata (Baerly-only; no pgoutput analogue). The\n * session id that built the `lsn`. Surfaces here so consumers\n * can dedupe / order without parsing the cursor.\n */\n session: string;\n\n /** Per-session sequence number embedded in the `lsn`. */\n seq: number;\n}\n\n/**\n * Per-collection setting controlling how much pre-image data each\n * `U` / `D` entry carries.\n *\n * - `PATCH_ONLY` (default today, applied unconditionally): `U`\n * carries `{ after }`; no `before`, no `key_old`.\n * Bandwidth-cheap. SQL consumers rebuilding before-images need\n * to maintain a shadow table.\n * - `FULL`: `U` additionally carries `before` and `key_old`. ~2× log\n * size on update-heavy collections; buys true 1:1 logical\n * replication and \"previous value\" answerable from the log\n * alone.\n *\n * Per-collection opt-in is not yet wired; every collection is\n * currently `PATCH_ONLY`.\n */\nexport type ReplicaIdentity = \"PATCH_ONLY\" | \"FULL\";\n\n/**\n * S3 path segment for log entries (under the manifest prefix). The\n * full key shape is `<manifestPrefix>/log/<seq>.json` — composed\n * inline by callers (`writer`, `gc`, `rebuild-index`,\n * `http/since`) since the `<seq>` integer is the load-bearing\n * identifier and a one-arg helper would just hide the join.\n */\nexport const LOG_KEY_PREFIX = \"log\";\n\nconst COUNT_BIT_WIDTH = 10;\n\n/**\n * Extract the `session` and `seq` embedded in an `lsn` of shape\n * `<base32-time>_<session>_<seq>`. The seq portion is decoded as a\n * descending base-32 integer (matches `countKey` in `./types`).\n *\n * Use this at the `/v1/since` cursor-decoding boundary, where a\n * client resumes from an opaque `SinceResponse.next_cursor` and no\n * `LogEntry` is in scope. When iterating `LogEntry` records, read\n * `entry.session` / `entry.seq` directly instead.\n *\n * Throws on malformed input; callers should pass only lsns minted\n * by `Writer.commit` (see\n * `packages/server/src/writer.ts`).\n */\nexport const lsnParts = (lsn: string): { session: string; seq: number } => {\n const parts = lsn.split(\"_\");\n if (parts.length !== 3) {\n throw new BaerlyError(\"InvalidResponse\", `invalid lsn shape: ${lsn}`);\n }\n return {\n session: parts[1]!,\n seq: str2uintDesc(parts[2]!, COUNT_BIT_WIDTH),\n };\n};\n","/**\n * Self-session log-conflict adoption — the one decision that\n * distinguishes a retry of our own prior commit attempt from a\n * peer racing us at the same `seq`.\n *\n * Background. `Writer.#singleAttemptCommit` PUTs each log entry with\n * `If-None-Match: \"*\"`. A 412 on `/log/<seq>.json` can mean either\n *\n * (a) a peer wrote a DIFFERENT entry at the same seq — we lost\n * the race; the caller's CAS will also fail; or\n * (b) our OWN previous attempt landed the log PUT but lost the\n * subsequent `current.json` CAS-advance, and we're now\n * re-driving the same logical commit.\n *\n * This function makes the (a)/(b) call. It is callable, separately\n * testable, and patent-disclosable in isolation from the rest of the\n * commit path.\n *\n * ## Soundness invariant\n *\n * Adoption is sound iff all three hold:\n *\n * 1. **Same session.** `existing.session === self.session`. The\n * session id is a per-commit, in-RAM-only secret minted at\n * `Writer.commit` from `crypto.randomUUID().slice(0,\n * SESSION_ID_LENGTH)`; an adversary with bucket-write access\n * can forge any other field but cannot forge a value they\n * did not observe being PUT.\n * 2. **Matching seq.** `existing.seq === self.expectedSeq`. The\n * seq match is also implied by the key shape (the writer\n * reads `/log/<expectedSeq>.json`), but is re-asserted here\n * so the invariant is visible at the decision site.\n * 3. **Single-input commit.** `self.batchSize === 1`. Batches\n * surface a log-PUT 412 as `Conflict` immediately — the\n * caller (`Db.transaction`) decides whether to re-run the\n * body. Adoption inside a batch would require per-input\n * adoption decisions that don't compose with the\n * all-or-nothing CAS-advance on `current.json`.\n *\n * When any of (1)/(2)/(3) fails, the writer MUST throw\n * `BaerlyError{code:\"Conflict\"}` and let the caller's retry-or-\n * surface logic run.\n *\n * ## Threat model\n *\n * The adversary may (a) write arbitrary bytes to any key in the\n * bucket, (b) replay any PUT they previously observed on the wire,\n * (c) reorder or drop network packets between the writer and the\n * bucket. The adversary may NOT (d) read the writer's local RAM\n * and therefore cannot learn the per-commit `session` id before\n * observing the writer's own `/log/<seq>.json` PUT. Under these\n * constraints, conditions (1)+(2)+(3) close every attack path in\n * the adversarial-replay property test\n * (`tests/integration/log-conflict-adversarial.test.ts`).\n *\n * **Pinned by:** `tests/integration/log-conflict-forgery.test.ts`\n * exercises the session-id-unguessability claim under a\n * `ForgeryStorage` adversary that plants arbitrary entries at the\n * writer's expected log key. Property verified by default at\n * `numRuns: 1000`; `FC_NUM_RUNS=10000` for the hardening sweep.\n *\n * ## Prior art\n *\n * SlateDB's manifest-pivot writer protocol (rfcs/0001-manifest.md,\n * scenarios 1–4) is the closest published prior art on the broader\n * commit-protocol skeleton. SlateDB's scenario 3 — \"conflicting SST\n * has same `writer_epoch` as me\" — is explicitly labelled an\n * **illegal state that should panic**. The three-clause adoption\n * decision encoded here (same session ∧ matching seq ∧ single-input)\n * recognises that case as the writer's own prior in-flight attempt\n * and adopts it as success rather than aborting, closing the recovery\n * gap SlateDB leaves to operator intervention.\n *\n * Apache Iceberg and Delta Lake commits surface analogous failures as\n * `CommitFailedException` / commit-conflict retries; neither inspects\n * the conflicting object to determine ownership.\n *\n * See `docs/spec/prior-art.md` for the consolidated IDS-shaped\n * differentiation.\n *\n * @see docs/spec/sync-protocol.md §\"Self-session log-conflict adoption\"\n */\n\nimport type { LogEntry } from \"@baerly/protocol\";\n\n/**\n * Inputs to {@link tryAdoptOwnSessionLogEntry}. All fields are\n * required; the writer constructs this struct at the call site.\n */\nexport interface AdoptionContext {\n /**\n * The entry the writer just attempted to PUT. Carries the\n * writer's session, expected seq, and the rest of the LogEntry\n * shape minted in `Writer.#singleAttemptCommit` step 3.\n */\n readonly self: LogEntry;\n /**\n * The entry currently stored at `/log/<self.seq>.json`, as read\n * back after a 412. The caller is responsible for the GET (the\n * function is pure, no I/O).\n */\n readonly existing: LogEntry;\n /**\n * `inputs.length` for the parent commit attempt. `1` for\n * `Writer.commit`; `inputs.length` for `Writer.commitBatch`.\n * Adoption is only safe when this is exactly `1`.\n */\n readonly batchSize: number;\n}\n\n/**\n * Discriminated outcome of {@link tryAdoptOwnSessionLogEntry}.\n * `adopt: true` carries the existing entry (which by the\n * invariant is byte-identical to `self` modulo `commit_ts`); the\n * caller substitutes it for `self` so the returned `CommitResult`\n * matches what's actually stored. `adopt: false` carries a\n * machine-readable `reason` so callers and tests can discriminate\n * which clause of the invariant failed.\n */\nexport type AdoptionDecision =\n | { readonly adopt: true; readonly entry: LogEntry }\n | { readonly adopt: false; readonly reason: \"foreign-session\" | \"wrong-seq\" | \"batch\" };\n\n/**\n * Decide whether the entry already at `/log/<seq>.json` is the\n * writer's own prior in-flight attempt and may be adopted. Pure\n * function; no I/O. The caller performs the GET (when the log PUT\n * surfaces 412) and passes the read-back body in `ctx.existing`.\n *\n * @see {@link AdoptionDecision} for the return shape.\n * @see The soundness invariant in this module's header docstring.\n */\nexport const tryAdoptOwnSessionLogEntry = (ctx: AdoptionContext): AdoptionDecision => {\n // Clause (3) — single-input commit. Evaluated first so a batched\n // call short-circuits before any field comparison.\n if (ctx.batchSize !== 1) {\n return { adopt: false, reason: \"batch\" };\n }\n // Clause (1) — same session.\n if (ctx.existing.session !== ctx.self.session) {\n return { adopt: false, reason: \"foreign-session\" };\n }\n // Clause (2) — matching seq. The seq is also implied by the\n // key the caller read from, but re-asserted here for\n // patent-disclosure clarity.\n if (ctx.existing.seq !== ctx.self.seq) {\n return { adopt: false, reason: \"wrong-seq\" };\n }\n return { adopt: true, entry: ctx.existing };\n};\n","/**\n * `Writer` — stateless multi-instance write engine.\n *\n * Each {@link Writer.commit} call reads `current.json` FRESH from\n * the bucket, mints the next {@link LogEntry}, PUTs the content body\n * and the log entry, and CAS-advances `current.json` with `If-Match`.\n * Up to {@link S3_REQUEST_MAX_RETRIES} attempts on contention before\n * surfacing `BaerlyError{code:\"Conflict\"}`. The optional integrity\n * walk over the live log tail is gated by\n * {@link WriterOptions.verifyLogIntegrityOnCommit} (default off\n * — see the option's docstring).\n *\n * The instance carries no per-write cache: every commit re-reads\n * `current.json`, so N stateless server instances writing the same\n * tenant prefix contend at exactly one place — the conditional PUT\n * on `current.json` — and one loses cleanly with a 412.\n *\n * **Manifest-first ordering is REVERSED relative to the legacy\n * `src/syncer.ts` write loop.** Old loop: PUT manifest → PUT content\n * → CAS. New loop: PUT content → PUT log entry → CAS-advance\n * `current.json`. A crashed mid-loop writer leaves an unreferenced\n * content body (no log entry points at it), not an orphan log entry\n * with missing content. The compactor sweeps the orphan content\n * later.\n *\n * **`LogEntry` shape.** Emitted entries follow the contract in\n * `packages/protocol/src/log.ts` (see {@link LogEntry}) and\n * `docs/spec/log-entry-shape.md`. The on-bucket key is\n * `log/<seq>.json` (the integer `seq` is the load-bearing\n * identifier; the `lsn` string is schema-only).\n *\n * @see docs/spec/sync-protocol.md for the protocol invariants this\n * loop preserves.\n * @see docs/spec/log-entry-shape.md for the per-field contract.\n */\n\nimport {\n CURRENT_JSON_SCHEMA_VERSION,\n type CurrentJson,\n type CurrentJsonRead,\n type DocumentData,\n type LogEntry,\n type MetricsRecorder,\n createCurrentJson,\n decodeJsonBytes,\n encodeJsonBytes,\n logSeqStartOf,\n BaerlyError,\n noopMetricsRecorder,\n type Storage,\n type StoragePutOptions,\n type StoragePutResult,\n S3_REQUEST_MAX_RETRIES,\n SESSION_ID_LENGTH,\n WRITE_TICK_GC_INTERVAL,\n countKey,\n readCurrentJson,\n timestamp,\n uuid,\n versionFromContent,\n} from \"@baerly/protocol\";\nimport { allIndexKeysFor, type IndexDefinition, validateIndexDefinition } from \"./indexes.ts\";\nimport { readLogEntry, walkLogRange } from \"./log-walk.ts\";\nimport { tryAdoptOwnSessionLogEntry } from \"./log-conflict-adoption.ts\";\nimport {\n dispatchInlineAwaited,\n runBoundedMaintenance,\n shouldFireMaintenance,\n} from \"./maintenance.ts\";\nimport { getCurrentContext } from \"./observability/context.ts\";\n\nconst ctxMetrics = (): MetricsRecorder => getCurrentContext()?.recorder ?? noopMetricsRecorder;\n\n/**\n * Tunables for {@link Writer}. All optional; defaults match the\n * legacy retry budget so the new loop is a drop-in replacement.\n */\nexport interface WriterOptions {\n /**\n * Max CAS attempts on 412 before throwing `Conflict`. Default\n * {@link S3_REQUEST_MAX_RETRIES} (8). Override only in tests.\n */\n readonly maxRetries?: number;\n\n /** Initial backoff in ms; doubles per attempt, capped at 1500ms. Default 25. */\n readonly initialBackoffMs?: number;\n\n /**\n * Pure function returning a number in [0, 1). Used for jitter; tests\n * inject a deterministic generator. Defaults to `Math.random`.\n */\n readonly random?: () => number;\n\n /**\n * Optional. Indexes declared for the collection this writer\n * commits to. Each commit emits one zero-byte PUT per declared\n * index (when the indexed field is set on the doc) inside the\n * same fence as the log entry and content body. On U/D, the\n * writer reads the pre-image content body from the log (one\n * back-walk per indexed collection, NOT per index) to compute\n * the stale-key set; stale keys are DELETE'd inside the same\n * fence.\n *\n * Validated at construction via {@link validateIndexDefinition} —\n * an invalid def throws `BaerlyError{code:\"SchemaError\"}`\n * synchronously, before the first commit. Empty / undefined is\n * a no-op (writer behaves identically to the no-index path — no\n * extra GET, no extra PUTs).\n *\n * Note: `Writer` is per-collection (the `currentJsonKey`\n * is per-collection), so this array applies to one collection\n * only — adapters that serve multiple collections instantiate\n * one writer per collection.\n *\n * Emits one new metric when at least one index is declared:\n * - `db.write.index_ops_per_logical_write` (histogram,\n * labelled by `collection`) — `K (PUT) + L (DELETE)` per\n * successful commit.\n */\n readonly indexes?: ReadonlyArray<IndexDefinition>;\n\n /**\n * When `true`, every commit walks the live log range\n * `[log_seq_start, next_seq)` before minting a new entry, surfacing\n * a missing or malformed entry as `BaerlyError{code:\"Internal\"}`\n * (or `\"InvalidResponse\"` for parse failures). The walk is purely\n * observational — the per-doc fold lives in the read path\n * (`./query.ts`) and any hole inside the visible range would also\n * fire on the next read.\n *\n * Production callers default this OFF: under contention the walk\n * issues `O(tail)` Class-B GETs per CAS attempt and the retry\n * budget multiplies that by {@link S3_REQUEST_MAX_RETRIES}. Tests\n * that intentionally puncture bucket state to exercise the\n * invariant trigger opt in by passing `true`.\n *\n * Default `false`.\n */\n readonly verifyLogIntegrityOnCommit?: boolean;\n}\n\n/**\n * Single-doc mutation request. One `commit()` ↔ one {@link LogEntry}.\n */\nexport interface CommitInput {\n /** The mutation op. Maps directly to {@link LogEntry.op}. */\n readonly op: \"I\" | \"U\" | \"D\";\n\n /** The collection (table) name. Becomes {@link LogEntry.collection}. */\n readonly collection: string;\n\n /** The document primary key. Becomes {@link LogEntry.doc_id}. */\n readonly docId: string;\n\n /**\n * For `I` / `U`: the post-image. Becomes {@link LogEntry.after}. Must\n * be `undefined` for `op: \"D\"`.\n */\n readonly body?: DocumentData;\n\n /** Optional ISO-8601 origin marker; becomes {@link LogEntry.origin}. */\n readonly origin?: string;\n}\n\n/** Return shape of {@link Writer.commit}. */\nexport interface CommitResult {\n /** The committed `LogEntry`. Caller can ack on `entry.lsn`. */\n readonly entry: LogEntry;\n\n /** New ETag of `current.json` after the CAS-advance landed. */\n readonly currentEtag: string;\n\n /** How many CAS attempts it took (1 = first try won). */\n readonly attempts: number;\n}\n\n/** Return shape of {@link Writer.commitBatch}. */\nexport interface CommitBatchResult {\n /**\n * One emitted `LogEntry` per input, in input order.\n * `entries[i]` corresponds to `inputs[i]`. `entries.length ===\n * inputs.length`. On an empty input array `entries` is empty and\n * no I/O happened.\n */\n readonly entries: readonly LogEntry[];\n\n /**\n * New ETag of `current.json` after the CAS-advance landed.\n * `undefined` on an empty input array (the CAS step is skipped).\n */\n readonly currentEtag: string | undefined;\n}\n\nconst DEFAULT_INITIAL_BACKOFF_MS = 25;\nconst MAX_BACKOFF_MS = 1500;\nconst APPLICATION_JSON = \"application/json\";\n\n/**\n * Empty body for index entries. Each index entry is a fact (\"doc\n * `<docId>` has `<field> = <value>`\"), not data — readers list the\n * prefix, extract the doc id, then GET the content body separately.\n * Pre-allocated module-level constant so every index PUT shares one\n * zero-length buffer.\n */\nconst EMPTY_BODY = new Uint8Array(0);\n\n/**\n * Successful outcome of one full {@link Writer.#singleAttemptCommit}\n * attempt. Retryable failures (log-peer race, CAS 412) throw\n * `BaerlyError{code:\"Conflict\"}` directly; the caller catches via\n * {@link isPreconditionFailed} and decides whether to retry. Non-retryable\n * failures (fence bump, protocol-invariant violations, network errors)\n * also throw, but the caller verifies the fence OUTSIDE the catch arm so\n * the fence-bump `Conflict` propagates instead of being mistaken for a\n * retryable CAS loss.\n */\ninterface SingleAttemptSuccess {\n readonly entries: readonly LogEntry[];\n readonly currentEtag: string;\n readonly classAOps: number;\n readonly expectedEpoch: number;\n}\n\n/**\n * Stateless write engine for the multi-instance core.\n *\n * Construction is cheap and performs zero I/O — adapters build a\n * fresh `Writer` per request and discard it. All real work\n * happens in {@link commit}.\n *\n * @example\n * ```ts\n * import { Writer } from \"@gusto/baerly-storage\";\n * import { MemoryStorage } from \"@gusto/baerly-storage\";\n *\n * const writer = new Writer({\n * storage: new MemoryStorage(),\n * currentJsonKey: \"app/tickets/tenant/acme/manifests/tickets/current.json\",\n * });\n *\n * const result = await writer.commit({\n * op: \"I\",\n * collection: \"tickets\",\n * docId: \"doc-1\",\n * body: { _id: \"doc-1\", title: \"hello\" },\n * });\n * console.log(result.entry.seq, result.attempts);\n * ```\n */\nexport class Writer {\n readonly #storage: Storage;\n readonly #currentJsonKey: string;\n readonly #maxRetries: number;\n readonly #initialBackoffMs: number;\n readonly #random: () => number;\n readonly #indexes: ReadonlyArray<IndexDefinition>;\n readonly #verifyLogIntegrityOnCommit: boolean;\n\n constructor(opts: {\n storage: Storage;\n /**\n * Full bucket-relative key of the CAS pointer, e.g.\n * `app/tickets/tenant/acme/manifests/tickets/current.json`. The\n * collection-prefix half lives at\n * `currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"))` — the\n * log and content keys are derived from it.\n */\n currentJsonKey: string;\n options?: WriterOptions;\n }) {\n this.#storage = opts.storage;\n this.#currentJsonKey = opts.currentJsonKey;\n this.#maxRetries = opts.options?.maxRetries ?? S3_REQUEST_MAX_RETRIES;\n this.#initialBackoffMs = opts.options?.initialBackoffMs ?? DEFAULT_INITIAL_BACKOFF_MS;\n this.#random = opts.options?.random ?? Math.random;\n const indexes = opts.options?.indexes ?? [];\n for (const def of indexes) {\n validateIndexDefinition(def);\n }\n this.#indexes = indexes;\n this.#verifyLogIntegrityOnCommit = opts.options?.verifyLogIntegrityOnCommit ?? false;\n }\n\n /**\n * Atomically commit one mutation. Reads `current.json` fresh, mints\n * the next log entry at `seq = current.next_seq`, PUTs the content\n * body and the log entry, then CAS-advances `current.json` with\n * `If-Match`. Retries on conflict up to `maxRetries`.\n *\n * The hot-path cost under no contention is 1 GET + 3 PUTs (4 ops);\n * an in-flight peer write costs one extra GET + the backoff sleep\n * per retry.\n *\n * Idempotency: PUT content uses `If-None-Match: \"*\"`, so a retry of\n * the same logical write produces the same content key and the\n * second PUT no-ops. PUT log entry also uses `If-None-Match: \"*\"`,\n * so two writers racing the same `next_seq` cause exactly one PUT\n * to land — the loser falls into the CAS retry path.\n *\n * @throws BaerlyError code=\"Conflict\" when the retry budget is\n * exhausted (genuine high-contention case), or when the underlying\n * `current.json` CAS PUT lost.\n * @throws BaerlyError code=\"Conflict\" — the writer fence\n * (`current.json.writer_fence.epoch`) was bumped by a concurrent\n * `claimWriter` call between this commit's read of\n * `current.json` and its CAS-advance. The stale writer aborts\n * to honour the new authority — the kernel does NOT retry under\n * the old epoch. See {@link claimWriter} for the rotation\n * recipe.\n * @throws BaerlyError code=\"Internal\" when a log entry expected in\n * `[0, next_seq)` is missing — a protocol-invariant violation\n * (compactor bug or stale `current.json`).\n * @throws BaerlyError code=\"InvalidResponse\" when a log-entry body\n * isn't valid JSON.\n *\n * **Implicit provisioning.** When `current.json` does not exist at\n * `currentJsonKey` (fresh bucket, fresh collection), the writer\n * auto-creates it with a zero-state manifest before the commit\n * lands. The cost is one extra Class A PUT on the very first\n * commit per collection; steady-state cost is unchanged. A peer\n * racing the same first-write loses cleanly on the create CAS\n * and re-reads to pick up the winner's manifest.\n */\n async commit(input: CommitInput): Promise<CommitResult> {\n const session = uuid().slice(0, SESSION_ID_LENGTH);\n const logPrefix = this.#currentJsonKey.slice(0, this.#currentJsonKey.lastIndexOf(\"/\"));\n\n for (let attempt = 1; attempt <= this.#maxRetries; attempt++) {\n let success: SingleAttemptSuccess;\n try {\n success = await this.#singleAttemptCommit(\n [input],\n session,\n logPrefix,\n \"Writer\",\n /* adoptOwnSessionOnLogConflict */ true,\n );\n } catch (error) {\n // Only retryable conflicts (storage 412 on log PUT or\n // current.json CAS) come back as `Conflict`. The fence-bump\n // throw happens AFTER the helper returns, so it never\n // reaches this catch arm. Anything else propagates.\n if (!isPreconditionFailed(error)) {\n throw error;\n }\n await this.#backoff(attempt);\n continue;\n }\n // Fence verify lives in the caller so its `Conflict` propagates\n // past the retry-catch arm above. Bypasses the retry loop —\n // the stale writer must defer to the new authority.\n await this.#verifyFenceUnchanged(success.expectedEpoch, \"Writer\");\n // `success.classAOps` is the per-attempt base; add `(attempt\n // - 1)` to bill prior failed attempts as one PUT each (the\n // simple-and-test-locked cost model — not a precise replay\n // of every PUT in every dropped attempt).\n this.#emitWriteMetrics(input.collection, success.classAOps + (attempt - 1));\n return {\n entry: success.entries[0]!,\n currentEtag: success.currentEtag,\n attempts: attempt,\n };\n }\n\n // Retry budget exhausted.\n throw new BaerlyError(\n \"Conflict\",\n `Writer: CAS conflict on ${this.#currentJsonKey} after ${this.#maxRetries} attempts`,\n );\n }\n\n /**\n * Single-attempt batched commit. Reads `current.json` ONCE, mints\n * `inputs.length` log entries with contiguous `seq` numbers\n * starting at the current `next_seq`, PUTs each content body and\n * each log entry, then CAS-advances `current.json` from\n * `next_seq = N` to `next_seq = N + inputs.length` with\n * `If-Match`.\n *\n * NO retry on CAS loss. On `current.json` 412, throws\n * `BaerlyError{code:\"Conflict\"}` immediately — the caller (here:\n * `Db.transaction`) decides whether to retry by re-running the\n * body, or to surface to the app. Likewise on a log-entry 412\n * (a peer wrote our seq).\n *\n * Empty `inputs`: returns `{ entries: [], currentEtag: undefined }`\n * after zero storage operations.\n *\n * @throws BaerlyError code=\"Conflict\" — CAS lost on `current.json`,\n * or a log entry already exists at our seq (peer wrote ahead).\n * @throws BaerlyError code=\"Conflict\" — the writer fence\n * (`current.json.writer_fence.epoch`) was bumped by a concurrent\n * `claimWriter` call between this batch's read of\n * `current.json` and its CAS-advance. The stale writer aborts\n * to honour the new authority — the kernel does NOT retry under\n * the old epoch. See {@link claimWriter} for the rotation\n * recipe.\n * @throws BaerlyError code=\"Internal\" — protocol-invariant violation\n * (missing log entry inside `[0, next_seq)`).\n * @throws BaerlyError code=\"InvalidResponse\" — malformed log body.\n *\n * **Implicit provisioning.** Like {@link commit}, this path auto-\n * creates `current.json` with a zero-state manifest on a missing\n * read. Because `commitBatch` does NOT retry on CAS loss, a peer\n * racing the same first-write surfaces `Conflict` to the caller\n * (`Db.transaction` re-runs the body); the manifest is durable\n * regardless of which writer won the create.\n */\n async commitBatch(inputs: readonly CommitInput[]): Promise<CommitBatchResult> {\n if (inputs.length === 0) {\n return { entries: [], currentEtag: undefined };\n }\n\n const session = uuid().slice(0, SESSION_ID_LENGTH);\n const logPrefix = this.#currentJsonKey.slice(0, this.#currentJsonKey.lastIndexOf(\"/\"));\n\n // No retry — `#singleAttemptCommit`'s `Conflict` (log-peer race\n // or `current.json` CAS loss) propagates verbatim to the caller\n // (`Db.transaction` decides whether to re-run the body). The\n // fence-bump check sits AFTER the helper returns so its\n // `Conflict` propagates with the fence-bump message rather than\n // a generic CAS-loss one.\n const success = await this.#singleAttemptCommit(\n inputs,\n session,\n logPrefix,\n \"Writer.commitBatch\",\n /* adoptOwnSessionOnLogConflict */ false,\n );\n await this.#verifyFenceUnchanged(success.expectedEpoch, \"Writer.commitBatch\");\n // Pick the first input's collection as the batch label; in the\n // current `Db.transaction` model every input shares one\n // collection, so this is exact. If future tickets relax that\n // we'll need a per-collection split here.\n this.#emitWriteMetrics(inputs[0]!.collection, success.classAOps);\n return { entries: success.entries, currentEtag: success.currentEtag };\n }\n\n /**\n * One full commit attempt — the shared body of {@link commit} and\n * {@link commitBatch}. Reads `current.json`, walks the log, mints N\n * entries, PUTs content + indexes in parallel, PUTs log entries,\n * CAS-advances `current.json`. Returns the success payload + the\n * pre-commit fence epoch so the caller can run\n * {@link #verifyFenceUnchanged} outside the retry-catch arm.\n *\n * Retryable failures (a peer wrote our seq; a peer won the CAS on\n * `current.json`) throw `BaerlyError{code:\"Conflict\"}`. The caller\n * catches via {@link isPreconditionFailed} and either retries\n * (`commit`) or surfaces (`commitBatch`). Fence-bump and protocol-\n * invariant violations are NOT thrown from this helper — the fence\n * check lives in the caller so its `Conflict` propagates past the\n * retry-catch arm. Other thrown `BaerlyError`s (Internal,\n * InvalidResponse, NetworkError) bypass `isPreconditionFailed` and\n * propagate naturally.\n *\n * Crash safety invariant: content / index PUTs are awaited before\n * log PUTs, which are awaited before the CAS. A crashed mid-attempt\n * writer leaves orphan content / index entries (no log entry\n * references them) — the compactor sweeps the orphans. The\n * inverse — orphan log entry with missing content — is never\n * produced.\n */\n async #singleAttemptCommit(\n inputs: readonly CommitInput[],\n session: string,\n logPrefix: string,\n errorPrefix: string,\n adoptOwnSessionOnLogConflict: boolean,\n ): Promise<SingleAttemptSuccess> {\n // ── Step 1. Read current.json (fresh; carries the ETag). ────────\n // On a fresh bucket / fresh collection the manifest doesn't exist\n // yet. Auto-create it with a zero-state initial so `db.collection(x)\n // .insert(...)` works zero-shot. A peer racing the same create\n // loses cleanly on `If-None-Match: \"*\"`; we re-read to pick up\n // the winner's manifest. Cost: one extra Class A PUT on the very\n // first commit per collection, zero overhead thereafter.\n const read =\n (await readCurrentJson(this.#storage, this.#currentJsonKey)) ??\n (await this.#provisionCurrentJson());\n const current = read.json;\n const baseEtag = read.etag;\n const expectedEpoch = current.writer_fence.epoch;\n\n // ── Step 2. Optional integrity walk (`verifyLogIntegrityOnCommit`,\n // default off). Surfaces missing / malformed entries inside\n // `[log_seq_start, next_seq)` as `Internal` / `InvalidResponse`;\n // entries below `log_seq_start` are folded into the snapshot\n // by `compact()` and possibly swept by `runGc()`, so the walk is\n // bounded to the live tail. The read path catches the same\n // conditions on the next consult — production callers leave the\n // walk off to avoid `O(tail)` Class-B GETs per CAS attempt.\n if (this.#verifyLogIntegrityOnCommit) {\n await this.#walkLog(logPrefix, logSeqStartOf(current), current.next_seq);\n }\n\n // ── Step 3. Mint N LogEntries with contiguous seqs. ─────────────\n // All entries share `session` (one session per logical commit) and\n // a single commit instant: `lsn`'s timestamp and `commit_ts` are\n // derived from ONE clock read so they can't drift apart under skew\n // (a reader validates `commit_ts` against `LAG_WINDOW_MILLIS`, and\n // two independent reads could straddle that band). Intra-batch\n // ordering is by `seq` (the `countKey` lsn suffix), not the shared\n // timestamp, so one instant for the whole batch is correct.\n const commitNowMs = Date.now();\n const commitTs = new Date(commitNowMs).toISOString();\n const lsnTimestamp = timestamp(commitNowMs);\n const entries: LogEntry[] = [];\n for (let i = 0; i < inputs.length; i++) {\n const input = inputs[i]!;\n const seq = current.next_seq + i;\n const lsn = `${lsnTimestamp}_${session}_${countKey(seq)}`;\n const entry: LogEntry = {\n lsn,\n commit_ts: commitTs,\n op: input.op,\n collection: input.collection,\n doc_id: input.docId,\n session,\n seq,\n ...(input.op !== \"D\" && input.body !== undefined ? { after: input.body } : {}),\n ...(input.origin !== undefined ? { origin: input.origin } : {}),\n };\n entries.push(entry);\n }\n\n // ── Step 4. PUT content bodies + index entries in parallel. ─────\n // Content PUT: `ifNoneMatch: \"*\"` makes a same-hash re-write a\n // no-op (412 swallowed). Crash-recovery and same-body replay\n // both rely on this idempotency property.\n //\n // Index PUT: each declared index emits one zero-byte PUT per new\n // key. On `U` / `D` the pre-image is sourced from an earlier\n // same-`docId` input in this batch (if any) before falling back\n // to a log back-walk — preserves correctness when a transaction\n // does `[I, U]` or `[U, D]` on the same doc.\n //\n // Empty `#indexes` short-circuits the index block (including the\n // pre-image GET), preserving zero behaviour change for\n // collections without declared indexes.\n //\n // Filter-aware projection (T4): `allIndexKeysFor` short-circuits\n // on `def.predicate` miss. The writer's diff `oldKeys` vs\n // `newKeys` transparently covers all four U-quadrants without any\n // structural change here:\n //\n // match → match : both non-empty; diff PUTs/DELETEs as today.\n // match → miss : oldKeys non-empty, newKeys empty → DELETE all.\n // miss → match : oldKeys empty, newKeys non-empty → PUT all.\n // miss → miss : both empty → no-op for this def.\n //\n // All four quadrants are pinned by named tests in\n // `writer.test.ts` (\"Writer — filtered index\"). Do\n // not collapse them into one combined case — a regression in one\n // quadrant should fail exactly one named test so the bug is\n // localisable.\n let contentPutCount = 0;\n let indexClassA = 0;\n const parallelPuts: Array<Promise<unknown>> = [];\n // Per-docId in-batch image map: tracks the latest post-image\n // each input lays down so a later input on the same docId reads\n // the in-batch pre-image, not the on-disk one.\n const inBatchImage = new Map<string, DocumentData | undefined>();\n for (const input of inputs) {\n if (input.op !== \"D\" && input.body !== undefined) {\n contentPutCount++;\n const bytes = encodeJsonBytes(input.body);\n const version = await versionFromContent(bytes);\n const contentKey = `${logPrefix}/content/${version}.json`;\n parallelPuts.push(\n this.#storage\n .put(contentKey, bytes, { ifNoneMatch: \"*\", contentType: APPLICATION_JSON })\n .catch((error: unknown) => {\n this.#observe429(error, input.collection);\n if (isPreconditionFailed(error)) {\n return;\n }\n throw error;\n }),\n );\n }\n if (this.#indexes.length > 0) {\n let newKeys: readonly string[] = [];\n let staleKeys: readonly string[] = [];\n if (input.op === \"I\") {\n newKeys = allIndexKeysFor(logPrefix, this.#indexes, input.body, input.docId);\n } else if (input.op === \"U\") {\n const preImage = inBatchImage.has(input.docId)\n ? inBatchImage.get(input.docId)\n : await this.#readPreImage(logPrefix, input.collection, input.docId, current.next_seq);\n const oldKeys = allIndexKeysFor(logPrefix, this.#indexes, preImage, input.docId);\n newKeys = allIndexKeysFor(logPrefix, this.#indexes, input.body, input.docId);\n const newSet = new Set(newKeys);\n staleKeys = oldKeys.filter((k) => !newSet.has(k));\n } else {\n const preImage = inBatchImage.has(input.docId)\n ? inBatchImage.get(input.docId)\n : await this.#readPreImage(logPrefix, input.collection, input.docId, current.next_seq);\n staleKeys = allIndexKeysFor(logPrefix, this.#indexes, preImage, input.docId);\n }\n for (const k of newKeys) {\n parallelPuts.push(\n this.#storage\n .put(k, EMPTY_BODY, { ifNoneMatch: \"*\", contentType: APPLICATION_JSON })\n .catch((error: unknown) => {\n this.#observe429(error, input.collection);\n if (isPreconditionFailed(error)) {\n return;\n }\n throw error;\n }),\n );\n }\n for (const k of staleKeys) {\n // Storage.delete is contractually idempotent — no defensive catch.\n parallelPuts.push(this.#storage.delete(k));\n }\n indexClassA += newKeys.length + staleKeys.length;\n if (newKeys.length + staleKeys.length > 0) {\n ctxMetrics().histogram(\n \"db.write.index_ops_per_logical_write\",\n newKeys.length + staleKeys.length,\n { collection: input.collection },\n );\n }\n inBatchImage.set(input.docId, input.op === \"D\" ? undefined : input.body);\n }\n }\n await Promise.all(parallelPuts);\n\n // ── Step 5. PUT log entries. ────────────────────────────────────\n // `ifNoneMatch: \"*\"` per entry. On 412 we bump the counter and\n // record the rejection; the disposition (adopt vs surface) is\n // computed below from the aggregated results.\n //\n // Two cases on 412:\n // (a) a peer wrote a DIFFERENT entry at the same seq — we lost\n // the race; the caller's CAS will also fail.\n // (b) (single-input commit only) our OWN previous attempt\n // landed step 5 but lost step 6, and we're now re-driving\n // the same logical commit. Adopt it and proceed to CAS so\n // the advance gets a chance to commit.\n //\n // We discriminate by `session`: the random per-call id uniquely\n // identifies \"our own previous attempt.\" Adoption is only safe\n // when there's exactly one entry to compare (`commit`'s N=1 case);\n // batch commits surface log-PUT 412s as `Conflict` immediately.\n type LogPutOutcome = { readonly ok: true } | { readonly ok: false };\n const logPutOne = async (entry: LogEntry): Promise<LogPutOutcome> => {\n const logEntryKey = `${logPrefix}/log/${entry.seq}.json`;\n const logBytes = encodeJsonBytes(entry);\n try {\n await this.#storage.put(logEntryKey, logBytes, {\n ifNoneMatch: \"*\",\n contentType: APPLICATION_JSON,\n });\n return { ok: true };\n } catch (error) {\n this.#observe429(error, entry.collection);\n if (!isPreconditionFailed(error)) {\n throw error;\n }\n ctxMetrics().counter(\"db.r2.put.412_total\", 1, {\n collection: entry.collection,\n step: \"log-put\",\n });\n return { ok: false };\n }\n };\n const logPutResults = await Promise.all(entries.map(logPutOne));\n let committedEntries: readonly LogEntry[] = entries;\n const firstConflictIdx = logPutResults.findIndex((r) => !r.ok);\n if (firstConflictIdx !== -1) {\n const conflictedEntry = entries[firstConflictIdx]!;\n const logEntryKey = `${logPrefix}/log/${conflictedEntry.seq}.json`;\n if (adoptOwnSessionOnLogConflict) {\n const existing = await readLogEntry(this.#storage, logEntryKey);\n const decision = tryAdoptOwnSessionLogEntry({\n self: conflictedEntry,\n existing,\n batchSize: inputs.length,\n });\n if (decision.adopt) {\n committedEntries = [decision.entry];\n } else {\n throw new BaerlyError(\n \"Conflict\",\n `${errorPrefix}: log entry already exists at ${logEntryKey}; ${decision.reason}`,\n );\n }\n } else {\n throw new BaerlyError(\n \"Conflict\",\n `${errorPrefix}: log entry already exists at ${logEntryKey}; peer wrote our seq`,\n );\n }\n }\n\n // ── Step 6. CAS-advance current.json with If-Match. ─────────────\n // Bind to `baseEtag` from step 1 — re-reading would risk advancing\n // `next_seq` past a seq we never wrote a log entry for.\n //\n // Accumulate `tail_bytes` EXACTLY. The compactor later subtracts the\n // bytes of the log objects it folds, summed from the fetched object\n // bodies — i.e. exactly what the writer PUT per entry\n // (`encodeJsonBytes(entry)` in `logPutOne`). Counting the writer-add\n // and the compactor-subtract over the identical bytes keeps\n // `tail_bytes` exact under the full-fence CAS. Sum over\n // `committedEntries` (the source of truth for what's actually in the\n // tail — `entries` normally, or the single adopted entry on the\n // own-session-adoption path), NOT `inputs`.\n const batchLogBytes = committedEntries.reduce(\n (sum, e) => sum + encodeJsonBytes(e).byteLength,\n 0,\n );\n const next: CurrentJson = {\n ...current,\n next_seq: current.next_seq + inputs.length,\n tail_bytes: current.tail_bytes + batchLogBytes,\n };\n // Cadence-invariant assert (cheap, load-bearing). The GC write-tick\n // cadence keys off `next_seq` advancing by exactly the number of log\n // entries written. Today one input ⇒ one log entry, so `next_seq`\n // advances by `inputs.length` and `committedEntries.length ===\n // inputs.length` (the adoption path adopts the single in-flight\n // entry of a 1-input commit, preserving the identity). Pin it so a\n // future change that makes one input emit ≠1 entries fails LOUD here\n // instead of silently skewing the GC cadence.\n if (next.next_seq - current.next_seq !== inputs.length) {\n throw new BaerlyError(\n \"Internal\",\n `${errorPrefix}: GC-cadence invariant violated — next_seq advanced by ${\n next.next_seq - current.next_seq\n } but ${inputs.length} input(s) were committed on ${this.#currentJsonKey}`,\n );\n }\n const nextBody = encodeJsonBytes(next);\n const putOpts: StoragePutOptions = {\n ifMatch: baseEtag,\n contentType: APPLICATION_JSON,\n };\n let result: StoragePutResult;\n try {\n result = await this.#storage.put(this.#currentJsonKey, nextBody, putOpts);\n } catch (error) {\n this.#observe429(error, inputs[0]!.collection);\n if (isPreconditionFailed(error)) {\n ctxMetrics().counter(\"db.r2.put.412_total\", 1, {\n collection: inputs[0]!.collection,\n step: \"current-json-cas\",\n });\n throw new BaerlyError(\n \"Conflict\",\n `${errorPrefix}: CAS conflict on ${this.#currentJsonKey}`,\n );\n }\n throw error;\n }\n\n // ── Step 6b. Write-tick maintenance dispatch. ───────────────────\n // Single funnel site reached by BOTH `commit()` and `commitBatch()`\n // exactly once per logical commit (a CAS retry re-enters this helper\n // and dispatches once per successful attempt — but a successful CAS\n // ends the retry loop, so a logical commit dispatches once). Sits\n // BEFORE the caller's `#verifyFenceUnchanged` — a write that then\n // fails its fence check may have paid for one bounded maintenance\n // pass; that's the intended single funnel, bounded and safe.\n //\n // Config rides the per-request observability context\n // (`getCurrentContext()?.maintenance`), set by the adapter — NOT the\n // Writer constructor / `Db.create`. Absent ⇒ inline dispatch +\n // CF-free-safe caps, so a bare `Db.create(...).collection(...)\n // .insert(...)` maintains inline by default once enough writes\n // accrue.\n const prevSeq = current.next_seq; // pre-CAS seq, already in scope\n const maint = getCurrentContext()?.maintenance;\n if (maint?.disabled !== true) {\n const gcInterval = maint?.options?.gcInterval ?? WRITE_TICK_GC_INTERVAL;\n if (shouldFireMaintenance(next, prevSeq, gcInterval)) {\n const dispatch = maint?.dispatch ?? dispatchInlineAwaited;\n // `await dispatch(...)`: `dispatchInlineAwaited` returns the\n // task's promise (awaited inline — deterministic for tests +\n // correct for serverful Node). A `ctx.waitUntil`-style dispatch\n // returns void (fire-and-forget off the ack); `await void` is a\n // no-op. The `.then(() => {}, () => {})` is belt-and-suspenders:\n // `runBoundedMaintenance` already swallows internally, but this\n // guarantees a dispatched task can NEVER reject the commit even\n // if a future change makes it throw.\n await dispatch(() =>\n runBoundedMaintenance(\n {\n storage: this.#storage,\n currentJsonKey: this.#currentJsonKey,\n prevSeq,\n // `disabled` is intentionally NOT forwarded: the outer\n // `maint?.disabled !== true` gate already guarantees we only\n // reach here when maintenance is enabled, so passing it would\n // only ever forward `false` (a no-op) and imply a coupling\n // that doesn't exist.\n ...(maint?.maxFoldBytes !== undefined && { maxFoldBytes: maint.maxFoldBytes }),\n },\n maint?.options,\n ).then(\n () => {},\n () => {},\n ),\n );\n }\n }\n\n // Step 7 — the fence-verify GET — lives in the caller, not here.\n // Both fence-bump and a 412-driven CAS retry use\n // `BaerlyError{code:\"Conflict\"}`; keeping the fence check outside\n // this helper's body lets the caller's retry-catch arm\n // (`isPreconditionFailed`) match ONLY retryable conflicts thrown\n // from inside, while the fence-bump throw propagates.\n\n // Base class-A op count for this attempt: content PUTs (skipping\n // `op:\"D\"`) + log PUTs (= N) + index PUTs + index DELETEs + 1\n // current.json CAS. The fence-verify GET is Class B and excluded.\n // The caller of `commit()` adds `(attempt - 1)` for retry cost.\n const classAOps = contentPutCount + entries.length + indexClassA + 1;\n return {\n entries: committedEntries,\n currentEtag: result.etag,\n classAOps,\n expectedEpoch,\n };\n }\n\n /**\n * Read the pre-image content body for a doc by walking the live\n * log backwards from `currentNextSeq` looking for the\n * most-recent I/U entry on this `(collection, docId)`. Returns\n * `undefined` when:\n *\n * - the doc's most-recent op was `D` (tombstone — no live body);\n * - no entry for this doc lives inside the visible log range\n * `[log_seq_start, currentNextSeq)` (a fresh-insert race or\n * the doc has been folded into the snapshot but is no longer\n * referenced).\n *\n * Used ONLY by the index-emission path on `U` / `D` to compute\n * the stale-key set. Bounded by `log_seq_start`: entries below\n * have been folded into the snapshot and may already be swept\n * off the bucket — a snapshot fold is the rebuild command's job\n * (see `./rebuild-index.ts`), not the writer's.\n *\n * **Cost note:** linear walk, O(snapshot lag). For day-one Phase\n * 8 collections (helpdesk-shape: 100s of docs, <10k log entries)\n * this is fine — the compactor folds the live tail every ~100\n * entries (`packages/server/src/compactor.ts`). A follow-up ticket\n * caches per-doc index head in `current.json` for O(1) lookup.\n * The bound is documented; out of scope here.\n */\n /**\n * Auto-create the per-collection `current.json` at\n * `this.#currentJsonKey` with a zero-state initial manifest. Called\n * by `#singleAttemptCommit` when the read returned `null` (fresh\n * bucket / fresh collection).\n *\n * Concurrency: `createCurrentJson` uses `If-None-Match: \"*\"`. If a\n * peer raced us and won, the storage layer surfaces `Conflict`; we\n * recover by re-reading the now-present manifest. We do NOT retry\n * the create — a single recover-via-read covers every race that\n * could have produced our null read.\n *\n * The seed shape (`snapshot: null`, `next_seq: 0`, `log_seq_start:\n * 0`, `writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" }`)\n * matches `ensureTable` and `baerly deploy`'s pre-warm path, so an\n * operator who pre-provisions and a writer who auto-creates land\n * on byte-identical bytes.\n *\n * @throws BaerlyError code=\"InvalidResponse\" — the post-recover\n * re-read also returned null. Defensive guard; in practice\n * unreachable because the Conflict implies the key now exists.\n */\n async #provisionCurrentJson(): Promise<CurrentJsonRead> {\n const initial: CurrentJson = {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n next_seq: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" },\n tail_bytes: 0,\n snapshot_bytes: 0,\n snapshot_rows: 0,\n };\n try {\n return await createCurrentJson(this.#storage, this.#currentJsonKey, initial);\n } catch (error) {\n if (!(error instanceof BaerlyError) || error.code !== \"Conflict\") {\n throw error;\n }\n }\n const recovered = await readCurrentJson(this.#storage, this.#currentJsonKey);\n if (recovered === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `Writer: current.json missing at ${this.#currentJsonKey} after auto-create raced and recover read returned null`,\n );\n }\n return recovered;\n }\n\n async #readPreImage(\n logPrefix: string,\n collection: string,\n docId: string,\n currentNextSeq: number,\n ): Promise<DocumentData | undefined> {\n // Walk newest-to-oldest so we hit the most-recent op first.\n // `s = -1` is the natural empty-bucket sentinel.\n for (let s = currentNextSeq - 1; s >= 0; s--) {\n const logKey = `${logPrefix}/log/${s}.json`;\n const got = await this.#storage.get(logKey);\n if (got === null) {\n // A hole below the visible range — either we walked past\n // `log_seq_start` (the entry was folded + swept) or a peer\n // is mid-CAS on a write we don't see yet. Bail; the\n // rebuild command (`rebuildIndex`) handles holes by\n // re-projecting from the snapshot.\n continue;\n }\n let entry: LogEntry;\n try {\n entry = decodeJsonBytes<LogEntry>(got.body);\n } catch {\n // Malformed entry shouldn't propagate up the index-emission\n // path — let the outer commit's `#walkLog` (step 2) flag it\n // as the protocol violation. Skip.\n continue;\n }\n if (entry.collection !== collection || entry.doc_id !== docId) {\n continue;\n }\n if (entry.op === \"D\") {\n return undefined;\n } // last op was delete\n if ((entry.op === \"I\" || entry.op === \"U\") && entry.after !== undefined) {\n return entry.after;\n }\n }\n return undefined;\n }\n\n /**\n * Walk `log/<logSeqStart>.json` … `log/<nextSeq - 1>.json` with\n * bounded parallelism via `walkLogRange`. Materialised entries are\n * discarded — the walk's only job is to surface a hole or a\n * malformed body inside the visible range as\n * `BaerlyError{code:\"Internal\"}` / `\"InvalidResponse\"`.\n *\n * Gated on `verifyLogIntegrityOnCommit`; default off in production\n * because the per-doc fold already lives in the read path. See the\n * option's docstring for the rationale and the opt-in convention.\n *\n * `logSeqStart` is the boundary set by the compactor on\n * `current.json.log_seq_start`. Entries below it have been folded\n * into the snapshot and may have been swept off the bucket, so the\n * walk MUST NOT GET-require them.\n */\n async #walkLog(logPrefix: string, logSeqStart: number, nextSeq: number): Promise<void> {\n await walkLogRange(this.#storage, logPrefix, logSeqStart, nextSeq);\n }\n\n /**\n * Bump the `db.r2.put.429_total` counter when `err` looks like an\n * R2 prefix-partition rate-limit. Best-effort: detected via\n * `BaerlyError{code:\"NetworkError\"}` with a `429` token in the\n * message. Called from every PUT call site's catch arm; mutually\n * exclusive in practice with `isPreconditionFailed` (412 ≠ 429).\n */\n #observe429(err: unknown, collection: string): void {\n if (is429(err)) {\n ctxMetrics().counter(\"db.r2.put.429_total\", 1, { collection });\n }\n }\n\n /**\n * Emit the per-logical-write `class_a_ops_per_logical_write`\n * histogram shared by `commit` and `commitBatch`. `classAOps`\n * differs between the two paths (retry-budget vs batch shape),\n * so each caller computes it.\n */\n #emitWriteMetrics(collection: string, classAOps: number): void {\n ctxMetrics().histogram(\"db.write.class_a_ops_per_logical_write\", classAOps, { collection });\n }\n\n /**\n * Re-read `current.json` after a successful CAS and assert the\n * writer-fence epoch is still ours. The CAS only mutated `next_seq`\n * (the fence is preserved from `current`), so a post-write epoch\n * mismatch can only mean another writer claimed the fence between\n * our step-1 read and step-6 PUT — the exact split-brain\n * `WriterFence` prevents. Throws `Conflict`; no retry, since the\n * stale writer must defer to the new authority.\n *\n * The fence-verify GET is Class B and intentionally NOT counted in\n * `class_a_ops_per_logical_write`.\n */\n async #verifyFenceUnchanged(expectedEpoch: number, where: string): Promise<void> {\n const postRead = await readCurrentJson(this.#storage, this.#currentJsonKey);\n if (postRead === null) {\n return;\n }\n if (postRead.json.writer_fence.epoch === expectedEpoch) {\n return;\n }\n throw new BaerlyError(\n \"Conflict\",\n `${where}: writer fence bumped from epoch ${expectedEpoch} to ${postRead.json.writer_fence.epoch} during commit on ${this.#currentJsonKey}; stale writer aborting`,\n );\n }\n\n /**\n * Exponential backoff with full jitter. `25 * 2^(attempt-1)` capped\n * at 1500ms; uniform jitter in `[0, base)` keeps colliding peers\n * from re-racing in lockstep. Worst-case total wait across the\n * default 8 attempts is roughly 2.5 s — well under a typical\n * Worker request budget.\n */\n async #backoff(attempt: number): Promise<void> {\n const base = Math.min(this.#initialBackoffMs * 2 ** (attempt - 1), MAX_BACKOFF_MS);\n const sleepMs = base * this.#random();\n if (sleepMs <= 0) {\n return;\n }\n await new Promise<void>((r) => setTimeout(r, sleepMs));\n }\n}\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\n/**\n * `true` when the underlying storage surfaced a `PreconditionFailed`\n * 412 (or its non-S3 equivalents). Every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`.\n */\nconst isPreconditionFailed = (err: unknown): boolean =>\n err instanceof BaerlyError && err.code === \"Conflict\";\n\n/**\n * `true` when the underlying storage surfaced an R2 prefix-partition\n * rate-limit. {@link S3HttpStorage} stamps the upstream HTTP status\n * onto `BaerlyError.cause` as `{ status }`; we discriminate on that\n * structured field rather than regex-matching the message.\n */\nconst is429 = (err: unknown): boolean => {\n if (!(err instanceof BaerlyError) || err.code !== \"NetworkError\") {\n return false;\n }\n const cause = err.cause as { status?: number } | undefined;\n return cause?.status === 429;\n};\n","/**\n * Filtered-index implication checker — decides whether every\n * document accepted by a query predicate is also accepted by a\n * filtered index's predicate. The query planner uses the result to\n * rank candidate indexes; see {@link \"./query-planner.ts\".planQuery}.\n *\n * Pure-function module: no I/O, no `Db` / `Storage` imports. Lives\n * in `@baerly/server` (not in `@baerly/protocol`) because the\n * planner is the only caller.\n *\n * Operates on the wire form: both inputs are {@link PredicateWire}s\n * with clauses already grouped by `(op, field, value)`. The\n * normaliser at `@baerly/protocol`'s `./query/normalize.ts` has\n * already flattened nested literal sub-predicates into dotted-path\n * `eq` clauses, so there is no recursion on nested objects here.\n */\n\nimport {\n deepEqualDocumentValue,\n type DocumentValue,\n type PredicateClause,\n type PredicateWire,\n} from \"@baerly/protocol\";\n\n/**\n * One side of a range bound extracted from a clause group. The\n * `inclusive` flag distinguishes `gte` / `lte` (inclusive) from\n * `gt` / `lt` (exclusive). Private to {@link predicateImplies}.\n */\ninterface RangeInfo {\n readonly value: DocumentValue;\n readonly inclusive: boolean;\n}\n\n/**\n * Normalised view of one field's clause group. A field may carry an\n * `eq` clause, range bounds (`lo` / `hi`), and/or an `in` clause.\n * Multiple clauses on one field AND together; the validator has\n * already proved the group is internally consistent. An \"unknown\n * shape\" sentinel surfaces when the planner can't safely reason\n * about the group (e.g. two `in` clauses on one field — the\n * intersection requires set arithmetic we don't do at plan time).\n * Private to {@link predicateImplies}.\n */\ninterface OperatorBundle {\n readonly eq?: DocumentValue;\n readonly lo?: RangeInfo;\n readonly hi?: RangeInfo;\n readonly in?: ReadonlyArray<DocumentValue>;\n}\n\ntype DecodeResult = OperatorBundle | \"unknown-shape\";\n\n/**\n * Group a wire's clauses by `field` so the per-field implication\n * check can reason over one bundle at a time. Inlined small helper\n * (not exported) so the planner module doesn't need to expose its\n * grouping helper as a cross-module contract.\n */\nconst groupByField = (wire: PredicateWire): Map<string, ReadonlyArray<PredicateClause>> => {\n const groups = new Map<string, PredicateClause[]>();\n for (const clause of wire.clauses) {\n const bucket = groups.get(clause.field);\n if (bucket === undefined) {\n groups.set(clause.field, [clause]);\n } else {\n bucket.push(clause);\n }\n }\n return groups;\n};\n\n/**\n * Collapse a per-field clause list into an {@link OperatorBundle}.\n * Returns `\"unknown-shape\"` when the group has more than one `in`\n * clause (set-intersection at plan time is out of scope) or\n * unrecognised ops slipping through (defensive — the validator\n * already locked the op vocabulary). Multiple `eq` clauses on one\n * field: the validator proves they all agree, so we pick the first.\n * Multiple range clauses on one field: take the strictest bound\n * (tightest `lo` = numerically largest; tightest `hi` = numerically\n * smallest).\n */\nconst decodeGroup = (clauses: ReadonlyArray<PredicateClause>): DecodeResult => {\n const bundle: {\n eq?: DocumentValue;\n lo?: RangeInfo;\n hi?: RangeInfo;\n in?: ReadonlyArray<DocumentValue>;\n } = {};\n for (const clause of clauses) {\n const v = clause.value;\n if (clause.op === \"eq\") {\n // Validator: every eq on a field carries the same value.\n bundle.eq = v as DocumentValue;\n } else if (clause.op === \"gte\") {\n const next: RangeInfo = { value: v as DocumentValue, inclusive: true };\n bundle.lo = tightestLo(bundle.lo, next);\n } else if (clause.op === \"gt\") {\n const next: RangeInfo = { value: v as DocumentValue, inclusive: false };\n bundle.lo = tightestLo(bundle.lo, next);\n } else if (clause.op === \"lte\") {\n const next: RangeInfo = { value: v as DocumentValue, inclusive: true };\n bundle.hi = tightestHi(bundle.hi, next);\n } else if (clause.op === \"lt\") {\n const next: RangeInfo = { value: v as DocumentValue, inclusive: false };\n bundle.hi = tightestHi(bundle.hi, next);\n } else if (clause.op === \"in\") {\n if (bundle.in !== undefined) {\n // Multiple `in` clauses on one field: the validator already\n // proved the intersection is non-empty, but reasoning about\n // the intersection's containment at plan time is out of\n // scope — bail out to \"unknown-shape\" so the caller refuses\n // implication conservatively.\n return \"unknown-shape\";\n }\n if (!Array.isArray(v)) {\n return \"unknown-shape\";\n }\n bundle.in = v as ReadonlyArray<DocumentValue>;\n } else {\n return \"unknown-shape\";\n }\n }\n return bundle;\n};\n\nconst tightestLo = (existing: RangeInfo | undefined, next: RangeInfo): RangeInfo => {\n if (existing === undefined) {\n return next;\n }\n if (typeof existing.value !== typeof next.value) {\n // Mixed types — bail to existing; the validator already proves\n // the group is satisfiable, so this case is a defensive no-op.\n return existing;\n }\n if (next.value > existing.value) {\n return next;\n }\n if (next.value < existing.value) {\n return existing;\n }\n // Equal value — strictest inclusivity wins (exclusive > inclusive\n // for lo bounds).\n if (!next.inclusive && existing.inclusive) {\n return next;\n }\n return existing;\n};\n\nconst tightestHi = (existing: RangeInfo | undefined, next: RangeInfo): RangeInfo => {\n if (existing === undefined) {\n return next;\n }\n if (typeof existing.value !== typeof next.value) {\n return existing;\n }\n if (next.value < existing.value) {\n return next;\n }\n if (next.value > existing.value) {\n return existing;\n }\n if (!next.inclusive && existing.inclusive) {\n return next;\n }\n return existing;\n};\n\n/**\n * Does the query's lower bound `loQ` (`undefined` if none) prove that\n * every matching doc satisfies the filter's lower bound `loF`?\n *\n * `loF.inclusive` true → need doc ≥ loF.value; `loF.inclusive` false →\n * need doc > loF.value. A stricter `loQ` (numerically larger or with\n * tighter inclusivity) always implies a looser `loF`.\n */\nconst lowerBoundImplies = (loF: RangeInfo, loQ: RangeInfo | undefined): boolean => {\n if (loQ === undefined) {\n return false;\n }\n // Mixed types: comparison is `false` either way; refuse implication.\n if (typeof loF.value !== typeof loQ.value) {\n return false;\n }\n if (loQ.value > loF.value) {\n return true;\n }\n if (loQ.value < loF.value) {\n return false;\n }\n // Equal values: implies iff loQ.inclusive ⇒ loF.inclusive, OR loQ is\n // strictly stricter than loF (loQ exclusive, loF inclusive). Concretely:\n // loF inclusive + loQ inclusive → doc ≥ Q == F ≥ F → ok\n // loF inclusive + loQ exclusive → doc > Q == F > F-ε → doc > F ≥ F → ok\n // loF exclusive + loQ inclusive → doc ≥ Q == F → doc could be == F → NOT > F → fail\n // loF exclusive + loQ exclusive → doc > Q == F → ok\n if (loF.inclusive) {\n return true;\n } // inclusive filter is the loosest case\n return !loQ.inclusive; // strict filter needs strict query at equal bound\n};\n\n/** Mirror of lowerBoundImplies for upper bounds. */\nconst upperBoundImplies = (hiF: RangeInfo, hiQ: RangeInfo | undefined): boolean => {\n if (hiQ === undefined) {\n return false;\n }\n if (typeof hiF.value !== typeof hiQ.value) {\n return false;\n }\n if (hiQ.value < hiF.value) {\n return true;\n }\n if (hiQ.value > hiF.value) {\n return false;\n }\n if (hiF.inclusive) {\n return true;\n }\n return !hiQ.inclusive;\n};\n\n// Derive the tightest lower-bound the query enforces, preferring (in\n// order): an `eq` clamp, the smallest `in` value, an explicit `lo`.\n// Returns `undefined` when the query gives the planner nothing to lean\n// on — the implication check then fails fast.\nconst loFromQuery = (q: OperatorBundle): RangeInfo | undefined => {\n if (q.eq !== undefined) {\n return { value: q.eq, inclusive: true };\n }\n if (q.in !== undefined && q.in.length > 0) {\n return {\n value: q.in.reduce((acc, v) => (v < acc ? v : acc), q.in[0]!),\n inclusive: true,\n };\n }\n return q.lo;\n};\n\n// Mirror of {@link loFromQuery} for upper bounds.\nconst hiFromQuery = (q: OperatorBundle): RangeInfo | undefined => {\n if (q.eq !== undefined) {\n return { value: q.eq, inclusive: true };\n }\n if (q.in !== undefined && q.in.length > 0) {\n return {\n value: q.in.reduce((acc, v) => (v > acc ? v : acc), q.in[0]!),\n inclusive: true,\n };\n }\n return q.hi;\n};\n\n/**\n * Filtered-index implication checker — decides whether every document\n * accepted by `queryWire` is also accepted by `indexFilterWire`. When\n * `true`, a walk over an index declared with `predicate: indexFilterWire`\n * is **complete** for `queryWire`: no matching doc is missing\n * from the smaller key set, so the planner can prefer it.\n *\n * Implication on `eq`, `gt` / `gte`, `lt` / `lte`, and `in` is\n * sound and complete in pure operator form; combined shapes (e.g.\n * range-on-filter and `in`-on-query) follow the algebra in the body\n * JSDoc.\n *\n * Algorithm — group both wires by `field`, then for every field\n * present in `indexFilterWire`:\n *\n * 1. Decode the filter's clause group into an {@link OperatorBundle}.\n * \"unknown-shape\" → refuse implication conservatively.\n * 2. The query MUST have at least one clause on that field —\n * otherwise the query says nothing about that field and cannot\n * possibly imply the filter's constraint.\n * 3. Decode the query's clause group on the same field.\n * 4. For each non-empty slot of the filter bundle, the query bundle\n * must establish the constraint:\n * - `eq` → query establishes equality (via its own `eq`).\n * - `in` → query is contained in the set (via `eq` ∈ set or\n * `in` ⊆ set).\n * - `lo` / `hi` → query establishes the bound via `eq`, `in`\n * (then min/max of the set), or its own `lo`/`hi` with the\n * inclusivity rules in {@link lowerBoundImplies} /\n * {@link upperBoundImplies}.\n * Mixed types (e.g. number filter vs string query) refuse\n * implication conservatively.\n *\n * Returns `true` iff every clause was satisfied. An empty\n * `indexFilterWire` is vacuously implied by any `queryWire`.\n *\n * Soundness contract — when this function returns `true`,\n * `matchesWire(queryWire, doc) ⇒ matchesWire(indexFilterWire, doc)` for\n * any document `doc`. Tests pin this property; see\n * `./query-planner-implies.test.ts`.\n */\nexport const predicateImplies = (\n indexFilterWire: PredicateWire,\n queryWire: PredicateWire,\n): boolean => {\n const filterGroups = groupByField(indexFilterWire);\n const queryGroups = groupByField(queryWire);\n\n for (const [field, filterClauses] of filterGroups) {\n const filterBundle = decodeGroup(filterClauses);\n if (filterBundle === \"unknown-shape\") {\n return false;\n }\n\n const queryClauses = queryGroups.get(field);\n if (queryClauses === undefined) {\n return false;\n }\n const queryBundle = decodeGroup(queryClauses);\n if (queryBundle === \"unknown-shape\") {\n return false;\n }\n\n if (filterBundle.eq !== undefined) {\n // Filter pins an exact value. Query must establish equality.\n if (queryBundle.eq === undefined) {\n return false;\n }\n if (!deepEqualDocumentValue(queryBundle.eq, filterBundle.eq)) {\n return false;\n }\n continue;\n }\n if (filterBundle.in !== undefined) {\n const set = filterBundle.in;\n const contains = (v: DocumentValue): boolean => set.some((m) => deepEqualDocumentValue(m, v));\n if (queryBundle.eq !== undefined) {\n if (!contains(queryBundle.eq)) {\n return false;\n }\n } else if (queryBundle.in !== undefined) {\n for (const v of queryBundle.in) {\n if (!contains(v)) {\n return false;\n }\n }\n } else {\n return false; // range query against `in` filter — not a subset\n }\n // `in` filter clause forbids any extra range constraint on the\n // filter side (enforced upstream by `validateWire`); nothing\n // else to check.\n continue;\n }\n // Range filter (lo / hi). Both bounds (if set) must be implied.\n if (filterBundle.lo !== undefined) {\n if (!lowerBoundImplies(filterBundle.lo, loFromQuery(queryBundle))) {\n return false;\n }\n }\n if (filterBundle.hi !== undefined) {\n if (!upperBoundImplies(filterBundle.hi, hiFromQuery(queryBundle))) {\n return false;\n }\n }\n }\n return true;\n};\n","/**\n * Pure-function query planner. Picks a walk plan (or a full-scan\n * decision) from a predicate + the collection's declared indexes.\n *\n * Zero I/O, zero storage-encoding awareness, zero `Db`/`Storage`\n * imports. The planner sits between `runRead`'s predicate intake and\n * the executor that walks index entries; the executor handles every\n * storage-encoding boundary (`encodeIndexValue`, `Storage.list`,\n * etc.).\n *\n * T2 shipped equality-only walks — single-field, composite full,\n * and composite partial-prefix. T3 fills the `rangeOn` / `inOn`\n * slots reserved on {@link IndexWalkPlan} so range / `$in` clauses\n * on the LAST indexed field beyond the equality prefix get pushed\n * into the walk too. T4 adds the filtered-index cost bias.\n *\n * Numeric range / `$in` are routed normally; the encoder at\n * `./indexes.ts:encodeIndexValue` is value-order-preserving for\n * numbers.\n */\n\nimport { type DocumentValue, type PredicateWire } from \"@baerly/protocol\";\nimport type { IndexDefinition } from \"./indexes.ts\";\nimport { predicateImplies } from \"./query-planner-implies.ts\";\n\n/**\n * Tagged union returned by {@link planQuery}. The read path\n * routes on `kind` — `index-walk` invokes the executor, `full-scan`\n * falls through to the snapshot + log fold.\n */\nexport type QueryPlan = IndexWalkPlan | FullScanPlan;\n\n/**\n * Plan to satisfy the predicate by walking one declared index. The\n * executor encodes `equalityKeys` via `encodeIndexValue` at the I/O\n * boundary and lists `<collectionPrefix>/index/<indexName>/<v0>/.../<vN>/`.\n *\n * `rangeOn` and `inOn` are reserved for T3 — both `undefined` under\n * T2's equality-only routing. The executor re-applies the FULL\n * original wire via `matchesWire(...)` after fetching rows; that\n * single check is both the stale-index defence and the residue\n * consumer, so the planner does NOT emit a separate `postFilter`.\n */\nexport interface IndexWalkPlan {\n readonly kind: \"index-walk\";\n /** Name of the chosen IndexDefinition. */\n readonly indexName: string;\n /**\n * Left-anchored raw equality values, one per indexed field consumed.\n * Length ≥ 1. The executor encodes these via `encodeIndexValue` at\n * the I/O boundary; the planner stays storage-encoding-free.\n */\n readonly equalityKeys: ReadonlyArray<DocumentValue>;\n /**\n * T3 fills this slot. Range bound on the LAST indexed field beyond\n * the equality prefix. Mutually exclusive with `inOn`.\n */\n readonly rangeOn?: {\n readonly field: string;\n readonly lo?: DocumentValue;\n readonly hi?: DocumentValue;\n readonly loInclusive: boolean;\n readonly hiInclusive: boolean;\n };\n /**\n * T3 fills this slot. $in multi-walk on the LAST indexed field\n * beyond the equality prefix. Mutually exclusive with `rangeOn`.\n */\n readonly inOn?: {\n readonly field: string;\n readonly values: ReadonlyArray<DocumentValue>;\n };\n}\n\n/**\n * Plan to fall through to the snapshot + log fold. The `reason`\n * field is diagnostic only — it is NOT part of the public API and\n * is consumed by the planner's tests / future observability.\n */\nexport interface FullScanPlan {\n readonly kind: \"full-scan\";\n /** Diagnostic — not part of the public API. */\n readonly reason:\n | \"no-predicate\"\n | \"no-indexes-declared\"\n | \"no-matching-index\"\n | \"predicate-uses-operators-only\";\n}\n\n/**\n * `$in` fan-out threshold. `$in: [...]` with `values.length`\n * at or below this number emits an `inOn` walk plan; over this\n * number the planner falls back to `FullScanPlan` because N\n * parallel-fan-out LIST round-trips cost more than one snapshot+log\n * fold on every backend we benchmark (see `bench/load-harness/`).\n *\n * Hard-coded at the value that survives Cloudflare's 50-subrequest\n * budget. If the default proves wrong on cheap-LIST backends\n * (Minio / S3 / GCS), file a bug — the answer is \"good, let's tune\n * the default,\" not \"make it configurable.\"\n */\nexport const IN_FANOUT_THRESHOLD = 50;\n\n/**\n * Per-field range bound bundle decoded from a {@link PredicateWire}.\n * Mirrors the shape the executor consumes on the plan's `rangeOn`\n * slot.\n */\ninterface RangeOpInfo {\n readonly lo?: DocumentValue;\n readonly hi?: DocumentValue;\n readonly loInclusive: boolean;\n readonly hiInclusive: boolean;\n}\n\n/**\n * Choose a query plan over the wire predicate + declared indexes.\n * Pure function. The executor enforces the I/O semantics; the\n * planner's only contract is \"given these inputs, this is the\n * routing decision.\"\n *\n * Algorithm:\n * 1. `wire === undefined` or empty → `no-predicate`.\n * 2. `indexes.length === 0` → `no-indexes-declared`.\n * 3. Partition wire clauses per field into:\n * - `equality[f] = v` from `eq` clauses.\n * - `rangeOps[f] = {lo, hi, loInclusive, hiInclusive}` from\n * one or more of `gt`/`gte`/`lt`/`lte` clauses on `f`.\n * - `inOps[f] = [...]` from a single `in` clause on `f`.\n * - Defensive: any field whose clause group mixes op-channels\n * (mostly impossible post-validation) is marked unroutable\n * and skipped — the executor's full-wire `matchesWire(...)`\n * post-fetch catches the residue automatically.\n * 4. If no equality / range / `in` candidates exist →\n * `predicate-uses-operators-only`.\n * 5. For each `def`, walk `def.on` left-to-right consuming\n * equality clauses for each indexed field. On the FIRST field\n * where the equality clause is absent, check whether a range\n * or `in` clause is available for that field — if so, that's\n * the \"tail slot\" of the walk.\n * 6. Score candidates by `(equalityPrefixLen, hasTailExtension)`.\n * Longest prefix wins; tail-extension breaks ties. If no\n * candidate consumed at least one field (equality OR\n * range/`in`): `no-matching-index`.\n * 7. `in` FAN-OUT GUARD: if the chosen plan's `in` slot has\n * `values.length > IN_FANOUT_THRESHOLD`, fall back to\n * `FullScanPlan{reason:\"no-matching-index\"}` — N sequential\n * LISTs cost more than a snapshot+log fold.\n *\n * The planner deliberately treats `def.on` as the LITERAL tuple of\n * field names — top-level only. Dotted paths are out of scope here\n * (the projector at `indexes.ts:projectIndexValues` is top-level-\n * only too).\n *\n * **Range/`in` is allowed only on the LAST indexed field beyond the\n * equality prefix** — on a composite `[a, b]`, a range on `a` with\n * equality on `b` is NOT contiguous under the key encoding (the `b`\n * slot sits to the right of the varying `a` slot). Clauses landing\n * outside the tail slot are simply left for the executor's full-\n * predicate re-check.\n */\nexport const planQuery = (\n wire: PredicateWire | undefined,\n indexes: ReadonlyArray<IndexDefinition>,\n): QueryPlan => {\n if (wire === undefined || wire.clauses.length === 0) {\n return { kind: \"full-scan\", reason: \"no-predicate\" };\n }\n if (indexes.length === 0) {\n return { kind: \"full-scan\", reason: \"no-indexes-declared\" };\n }\n\n // Partition wire clauses per-field into:\n // - equality (one `eq` clause on a field)\n // - rangeOps (one or more of `gt`/`gte`/`lt`/`lte` on a field)\n // - inOps (one `in` clause on a field)\n // - \"unroutable\" fields are skipped — the executor re-applies the\n // FULL original wire via `matchesWire(...)` post-fetch, which\n // catches the residue automatically.\n //\n // Validator-guaranteed invariants we lean on:\n // - Single op per field is the common case; multi-eq + multi-range\n // are pre-collapsed to a satisfiable group.\n // - An `eq` clause never coexists with `in` on the same field.\n // - An `in` clause never coexists with other ops on the same field.\n //\n // Defensive posture for \"mixed eq+in\" or \"two `in` clauses\" (which\n // the validator does NOT explicitly forbid for routing's sake but\n // are not worth set-intersecting at plan time): mark the field as\n // unroutable and let the executor's full-wire post-filter cover\n // correctness.\n const equality = new Map<string, DocumentValue>();\n const rangeOps = new Map<string, RangeOpInfo>();\n const inOps = new Map<string, ReadonlyArray<DocumentValue>>();\n const unroutable = new Set<string>();\n\n // First pass: per field, accumulate the lo/hi bounds and detect\n // collisions between op channels.\n interface RangeAcc {\n lo?: DocumentValue;\n hi?: DocumentValue;\n loInclusive: boolean;\n hiInclusive: boolean;\n }\n const rangeAcc = new Map<string, RangeAcc>();\n for (const clause of wire.clauses) {\n const field = clause.field;\n if (unroutable.has(field)) {\n continue;\n }\n if (clause.op === \"eq\") {\n if (inOps.has(field) || rangeAcc.has(field)) {\n // Defensive: shouldn't happen post-validation, but keep the\n // executor's post-filter as the safety net.\n unroutable.add(field);\n equality.delete(field);\n inOps.delete(field);\n rangeAcc.delete(field);\n continue;\n }\n // Multiple `eq` on a field: the validator proves agreement; pick\n // the first observed (overwrite is fine — values agree).\n equality.set(field, clause.value as DocumentValue);\n } else if (clause.op === \"in\") {\n if (equality.has(field) || rangeAcc.has(field) || inOps.has(field)) {\n unroutable.add(field);\n equality.delete(field);\n inOps.delete(field);\n rangeAcc.delete(field);\n continue;\n }\n if (!Array.isArray(clause.value)) {\n unroutable.add(field);\n continue;\n }\n inOps.set(field, clause.value as ReadonlyArray<DocumentValue>);\n } else {\n // Range op (gt / gte / lt / lte).\n if (equality.has(field) || inOps.has(field)) {\n unroutable.add(field);\n equality.delete(field);\n inOps.delete(field);\n rangeAcc.delete(field);\n continue;\n }\n const acc: RangeAcc = rangeAcc.get(field) ?? { loInclusive: false, hiInclusive: false };\n const v = clause.value as DocumentValue;\n if (clause.op === \"gte\") {\n // Tighten lo upward.\n if (acc.lo === undefined || v > acc.lo) {\n acc.lo = v;\n acc.loInclusive = true;\n } else if (v === acc.lo && !acc.loInclusive) {\n // existing exclusive is stricter — keep it\n }\n } else if (clause.op === \"gt\") {\n if (acc.lo === undefined || v > acc.lo) {\n acc.lo = v;\n acc.loInclusive = false;\n } else if (v === acc.lo) {\n // Same value; exclusive wins.\n acc.loInclusive = false;\n }\n } else if (clause.op === \"lte\") {\n if (acc.hi === undefined || v < acc.hi) {\n acc.hi = v;\n acc.hiInclusive = true;\n }\n } else if (clause.op === \"lt\") {\n if (acc.hi === undefined || v < acc.hi) {\n acc.hi = v;\n acc.hiInclusive = false;\n } else if (v === acc.hi) {\n acc.hiInclusive = false;\n }\n }\n rangeAcc.set(field, acc);\n }\n }\n // Project the range accumulators into the final `RangeOpInfo` map.\n for (const [field, acc] of rangeAcc) {\n rangeOps.set(field, {\n ...(acc.lo !== undefined ? { lo: acc.lo } : {}),\n ...(acc.hi !== undefined ? { hi: acc.hi } : {}),\n loInclusive: acc.loInclusive,\n hiInclusive: acc.hiInclusive,\n });\n }\n\n if (equality.size === 0 && rangeOps.size === 0 && inOps.size === 0) {\n return { kind: \"full-scan\", reason: \"predicate-uses-operators-only\" };\n }\n\n // Enumerate every viable candidate over the declared indexes,\n // then sort with the T4 tie-break:\n //\n // (1) Implied filter — a filtered index whose\n // `predicateImplies(def.predicate, queryWire)` is `true`\n // outranks an unfiltered alternative (sparser key range →\n // smaller LIST). An unfiltered index outranks a filtered one\n // whose `predicateImplies` is `false` — walking the smaller\n // set would miss matching docs.\n // (2) Longest total consumed length wins among ties on (1).\n // (3) Definition order among ties on (1) and (2).\n interface Candidate {\n readonly def: IndexDefinition;\n readonly defIndex: number;\n readonly prefixLen: number;\n readonly equalityKeys: DocumentValue[];\n readonly tail?:\n | { kind: \"range\"; field: string; info: RangeOpInfo }\n | { kind: \"in\"; field: string; values: ReadonlyArray<DocumentValue> };\n }\n const candidates: Candidate[] = [];\n for (let defIndex = 0; defIndex < indexes.length; defIndex++) {\n const def = indexes[defIndex]!;\n const tuple: readonly string[] = typeof def.on === \"string\" ? [def.on] : def.on;\n const equalityKeys: DocumentValue[] = [];\n let tail: Candidate[\"tail\"] | undefined;\n for (let i = 0; i < tuple.length; i++) {\n const field = tuple[i]!;\n const v = equality.get(field);\n if (v !== undefined) {\n equalityKeys.push(v);\n continue;\n }\n // First field WITHOUT equality — this is the \"tail slot\"\n // candidate for range/$in. Range and $in are mutually\n // exclusive on a single walk; the partitioning above is\n // mutually exclusive per-field, so at most one applies.\n const range = rangeOps.get(field);\n if (range !== undefined) {\n tail = { kind: \"range\", field, info: range };\n } else {\n const inVals = inOps.get(field);\n if (inVals !== undefined) {\n tail = { kind: \"in\", field, values: inVals };\n }\n }\n break;\n }\n const candidateLen = equalityKeys.length + (tail !== undefined ? 1 : 0);\n if (candidateLen === 0) {\n continue;\n }\n candidates.push({\n def,\n defIndex,\n prefixLen: candidateLen,\n equalityKeys,\n ...(tail !== undefined ? { tail } : {}),\n });\n }\n if (candidates.length === 0) {\n return { kind: \"full-scan\", reason: \"no-matching-index\" };\n }\n\n // T4 cost-bias rank: 0 = filtered + implied (best), 1 = unfiltered\n // (mid), 2 = filtered + NOT implied (worst). A filtered candidate\n // whose filter is NOT implied is STILL eligible — but only as a\n // last resort. The post-fetch `matchesWire(wire, ...)` re-check\n // would still drop the rows that fall outside the filter, so the\n // index walk is unsound for the query (it would silently miss\n // matching rows that fell outside the filter), and only the\n // sort order keeps it last.\n const rank = (c: Candidate): number => {\n if (c.def.predicate === undefined) {\n return 1;\n }\n return predicateImplies(c.def.predicate, wire) ? 0 : 2;\n };\n candidates.sort((a, b) => {\n const aRank = rank(a);\n const bRank = rank(b);\n if (aRank !== bRank) {\n return aRank - bRank;\n }\n if (b.prefixLen !== a.prefixLen) {\n return b.prefixLen - a.prefixLen;\n }\n return a.defIndex - b.defIndex;\n });\n const best: Candidate = candidates[0]!;\n\n // `$in` fan-out guard. Over {@link IN_FANOUT_THRESHOLD}, N\n // sequential LISTs cost more than one snapshot+log fold on every\n // backend we benchmark — refuse routing. Full-scan is correct.\n if (best.tail !== undefined && best.tail.kind === \"in\") {\n if (best.tail.values.length > IN_FANOUT_THRESHOLD) {\n return { kind: \"full-scan\", reason: \"no-matching-index\" };\n }\n }\n\n // Residue (unconsumed wire clauses) is intentionally NOT\n // surfaced on the plan — the executor re-applies the FULL\n // original wire via `matchesWire(...)` post-fetch, which is\n // both the stale-index defence and the residue consumer. See\n // `query.ts` (\"simpler invariant\").\n const plan: IndexWalkPlan = {\n kind: \"index-walk\",\n indexName: best.def.name,\n equalityKeys: best.equalityKeys,\n ...(best.tail !== undefined && best.tail.kind === \"range\"\n ? {\n rangeOn: {\n field: best.tail.field,\n ...(best.tail.info.lo !== undefined ? { lo: best.tail.info.lo } : {}),\n ...(best.tail.info.hi !== undefined ? { hi: best.tail.info.hi } : {}),\n loInclusive: best.tail.info.loInclusive,\n hiInclusive: best.tail.info.hiInclusive,\n },\n }\n : {}),\n ...(best.tail !== undefined && best.tail.kind === \"in\"\n ? { inOn: { field: best.tail.field, values: best.tail.values } }\n : {}),\n };\n return plan;\n};\n","/**\n * Schema-validator runtime helper for `Db.insert` / `Query.update` /\n * `Collection.replace` boundary checks.\n *\n * The `SchemaValidator` / `SchemaIssue` TYPES live in\n * `@baerly/protocol` (cross-platform). This module owns the runtime\n * helper `validateOrThrow` that runs a validator and raises a\n * `BaerlyError{code:\"SchemaError\"}` on failure.\n *\n * @example\n * ```ts\n * import { z } from \"zod\";\n * import { defineConfig } from \"@gusto/baerly-storage/config\";\n *\n * const Ticket = z.object({\n * _id: z.string(),\n * status: z.enum([\"open\", \"closed\"]),\n * title: z.string().min(1),\n * });\n *\n * export default defineConfig({\n * collections: {\n * tickets: { schema: Ticket },\n * },\n * });\n * ```\n */\n\nimport { BaerlyError, type SchemaValidator } from \"@baerly/protocol\";\n\nexport type { SchemaIssue, SchemaValidator } from \"@baerly/protocol\";\n\n/**\n * Run a validator and throw `BaerlyError{code:\"SchemaError\"}` on failure.\n * On success returns the validator's output (which for transforming\n * validators may differ from the input).\n *\n * Field paths are normalised to `(string | number)[]` so the wire shape\n * is JSON-clean. Symbol keys (rare; StandardSchemaV1 permits them) are\n * coerced to `String(sym)` — we never emit `symbol` on the wire.\n *\n * The thrown error's `message` carries a one-line summary\n * (`\"<collection>.<verb>: <issuesCount> field(s) failed validation: <first>\"`)\n * for stderr-readable logs; the structured `issues` are on `.issues`.\n */\nexport const validateOrThrow = async <TIn, TOut>(\n schema: SchemaValidator<TIn, TOut>,\n candidate: unknown,\n context: { readonly collection: string; readonly verb: \"insert\" | \"update\" | \"replace\" },\n): Promise<TOut> => {\n const result = await schema[\"~standard\"].validate(candidate);\n if (result.issues === undefined) {\n return result.value;\n }\n const issues = result.issues.map((i) => ({\n path: (i.path ?? []).map((p) => {\n // StandardSchemaV1 permits `{ key: PropertyKey }` segments\n // (Zod 3.24+, Valibot 0.36+) alongside bare PropertyKeys.\n const raw = typeof p === \"object\" && p !== null && \"key\" in p ? p.key : p;\n return typeof raw === \"number\" ? raw : String(raw);\n }),\n message: i.message,\n }));\n const first = issues[0];\n const summary =\n first === undefined\n ? \"schema validation failed (no issues reported)\"\n : `${first.path.length === 0 ? \"<root>\" : first.path.join(\".\")}: ${first.message}`;\n throw new BaerlyError(\n \"SchemaError\",\n `${context.collection}.${context.verb}: ${issues.length} field${issues.length === 1 ? \"\" : \"s\"} failed validation: ${summary}`,\n undefined,\n issues,\n );\n};\n","/* eslint-disable no-underscore-dangle -- `_id` is the locked primary-key\n field on document shapes (see `@baerly/protocol/src/collection-api.ts`'s `Collection<T>` /\n `Query<T>` declarations); mutation verbs surface and route it by name. */\n\n/**\n * Read engine + mutation terminals: `Query<T>` builder, the\n * three read terminals (`first`, `all`, `count`) that fold the log\n * under a fresh `current.json` snapshot, and the four mutation\n * terminals (`insert`, `update`, `replace`, `delete`) that each\n * compile to one or more `Writer.commit()` round-trips.\n *\n * Every modifier (`.where` / `.order` / `.limit`) returns a NEW\n * `Query<T>` carrying merged frozen state — the input state is never\n * mutated. Identity inequality between the original and the returned\n * builder is intentional: callers cannot share a chain.\n *\n * `.where()` AND-merges through `mergePredicateWires` (clause-level\n * AND on the normalised wire form).\n * `.order()` and `.limit()` are last-call-wins (state replace).\n *\n * Each terminal reads `current.json` FRESH and walks `[0, next_seq)`\n * directly — no cache, no `list()` round-trip. Per the multi-\n * instance rules, every read sees a fresh CAS snapshot.\n *\n * Mutation terminals are SINGLE-ATTEMPT per call site. CAS contention\n * retries (up to 8 attempts) live inside `Writer.commit()`; the\n * verbs do NOT add their own retry loop. On retry-budget exhaustion\n * `commit()` throws `BaerlyError{code:\"Conflict\"}` and the verb\n * surfaces it unchanged — the caller's option is to wrap in\n * `db.transaction(...)`.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\n\nimport {\n type CurrentJson,\n type DocumentValue,\n type DocumentData,\n logSeqStartOf,\n MANIFEST_POINTER_EMPTY_SNAPSHOT,\n matchesWire,\n merge,\n mergePredicateWires,\n normalizePredicateArg,\n validateWire,\n BaerlyError,\n type OrderSpec,\n type PredicateWire,\n type Query,\n readCurrentJson,\n type Storage,\n uuidv7,\n} from \"@baerly/protocol\";\nimport { loadSnapshotAsMap } from \"./snapshot.ts\";\nimport type { TxContext } from \"./db.ts\";\nimport { encodeIndexValue, type IndexDefinition } from \"./indexes.ts\";\nimport { foldLogEntriesOnto, walkLogRange } from \"./log-walk.ts\";\nimport { type IndexWalkPlan, planQuery, type QueryPlan } from \"./query-planner.ts\";\nimport { type SchemaValidator, validateOrThrow } from \"./schema.ts\";\nimport { Writer } from \"./writer.ts\";\n\n/**\n * What a `Query<T>` needs to issue a read against the bucket. The\n * `Db` builds this once and hands it to `Collection` / `Query`; the chain\n * carries it forward unchanged.\n *\n * The `collectionPrefix` shape matches what `Writer` writes under —\n * e.g. `\"app/<app>/tenant/<tenant>/manifests/<name>\"`. Drift between\n * the reader and writer prefix is the most likely bug class; both\n * compose the same string from `app`/`tenant`/`name`.\n *\n * @internal\n */\nexport interface CollectionReadContext {\n readonly storage: Storage;\n /** Physical key prefix — already includes `app/<app>/tenant/<tenant>/manifests/<name>`. */\n readonly collectionPrefix: string;\n readonly collectionName: string;\n /**\n * When defined, mutation verbs (`Collection.insert`, `Query.update`,\n * `Collection.replace`, `Query.delete`) buffer a {@link BufferedMutation}\n * onto `txCtx.mutations` instead of calling `Writer.commit`\n * directly. Reads ignore `txCtx` entirely — they go through\n * `Storage` live, by design (no MVCC; see `Db.transaction`'s JSDoc\n * in `./db.ts`). Threaded in by `Db.transaction(...)`; `undefined`\n * outside a transaction.\n *\n * @internal\n */\n readonly txCtx?: TxContext;\n /**\n * Optional StandardSchemaV1-shaped validator for this collection.\n * When set, `runInsert`, `runUpdate`, and `runReplaceById` validate the\n * post-image before committing or buffering — invalid input throws\n * `BaerlyError{code:\"SchemaError\"}` carrying a `.issues` array of\n * `{ path, message }` entries. `undefined` means no validation\n * (today's behaviour — zero overhead).\n *\n * Threaded in by {@link Db.collectionReadContext} from the per-collection\n * map handed to {@link Db.create}; the boundary calls happen in\n * `query.ts`, not `writer.ts`, so schemas plug in at the\n * read/write API surface rather than at the writer layer.\n *\n * @internal\n */\n readonly schema?: SchemaValidator;\n /**\n * Per-collection {@link IndexDefinition}s threaded onto every\n * read. Consumed by `planQuery(...)` inside `runRead` to pick an\n * index-walk plan when the predicate's equality fields cover a\n * declared index's `on` tuple left-to-right. Empty array means\n * \"no indexes declared\" — every read falls through to the\n * snapshot + log fold path.\n *\n * Mirrors the shape callers build when flattening\n * `BaerlyConfig.collections[*].indexes` into a map keyed by name\n * before constructing the `Db`; we keep the `Db` itself library-\n * agnostic by accepting the pre-flattened map (not the full\n * `BaerlyConfig`).\n *\n * @internal\n */\n readonly indexes: ReadonlyArray<IndexDefinition>;\n}\n\n/**\n * What `runRead` hands back: the materialised rows plus the cursor\n * + freshness pair surfaced as `_meta` on read response envelopes\n * (see `contract.ts:HttpOkMeta`). The public `Query<T>` terminals\n * destructure and discard the cursor — only the in-router\n * `*WithMeta` helpers consume it.\n *\n * @internal\n */\nexport interface ReadResult<T extends DocumentData> {\n readonly rows: T[];\n readonly manifestPointer: string;\n readonly fresh: boolean;\n}\n\n/**\n * Serialise a {@link CurrentJson} head into the wire cursor format\n * `\"<snapshot>@<next_seq>\"`. `null` snapshots stringify as\n * {@link MANIFEST_POINTER_EMPTY_SNAPSHOT} so the cursor is never the\n * empty string.\n *\n * @internal — exported for `query.test.ts`.\n */\nexport const serializeManifestPointer = (json: CurrentJson): string =>\n `${json.snapshot ?? MANIFEST_POINTER_EMPTY_SNAPSHOT}@${json.next_seq}`;\n\n/**\n * Frozen state carried along a `Query<T>` chain. Every modifier\n * produces a fresh `QueryState<T>` via spread + `Object.freeze`; the\n * wire / order / limit fields are never mutated in place.\n *\n * The chain carries the normalised wire form ({@link PredicateWire})\n * — the public seam (`.where(p)` accepting `PredicateArg<T>`) routes\n * incoming object-form / callback-form predicates through\n * `normalizePredicateArg` before they reach this state, so every\n * downstream consumer (planner, executor, post-filter) reads the\n * same shape.\n *\n * @internal\n */\nexport interface QueryState<T extends DocumentData> {\n readonly wire: PredicateWire | undefined;\n readonly order: OrderSpec<T> | undefined;\n readonly limit: number | undefined;\n}\n\n/**\n * Returns the id iff `wire` carries exactly one clause and that\n * clause is `{op:\"eq\", field:\"_id\", value:<string>}` — the shape\n * `runRead` short-circuits to a single `Map.get`. Any other shape\n * (multi-clause, non-`eq` op, non-`_id` field, non-string value)\n * returns `undefined` and falls through to the scan path.\n *\n * Kernel-internal `_id`-shaped wires (built by `byId`,\n * `runByIdWithMeta`, `runInsert`) bypass the wire validator by\n * design (`_id` at the root is a wire-only rejection); this\n * recogniser matches the same shape so the fast-path stays\n * symmetric.\n *\n * @internal\n */\nexport const singleIdFromPredicate = (wire: PredicateWire | undefined): string | undefined => {\n if (wire === undefined) {\n return undefined;\n }\n if (wire.clauses.length !== 1) {\n return undefined;\n }\n const clause = wire.clauses[0]!;\n if (clause.op !== \"eq\" || clause.field !== \"_id\") {\n return undefined;\n }\n return typeof clause.value === \"string\" ? clause.value : undefined;\n};\n\n/**\n * Build a `Query<T>` from a context + frozen state. Every modifier\n * returns a NEW `Query<T>` carrying merged state — the input state\n * is never mutated. Identity inequality with the input chain is\n * intentional.\n *\n * Validation happens at the public seams — `Query.where(p)`\n * normalises + validates the incoming fragment before merging into\n * `state.wire`. By the time `makeQuery` is reached from elsewhere\n * (`Collection.where`, `runAllWithMeta`, kernel-internal `_id`-shaped\n * wires from `byId` / `runByIdWithMeta` / `runInsert`), the wire is\n * already trusted.\n *\n * @example\n * ```ts\n * const q = makeQuery<Ticket>(ctx, { wire: undefined, order: undefined, limit: undefined });\n * const open = await q.where({ status: \"open\" }).order({ created_at: \"desc\" }).limit(10).all();\n * ```\n *\n * @internal\n */\nexport const makeQuery = <T extends DocumentData>(\n ctx: CollectionReadContext,\n state: QueryState<T>,\n): Query<T> => {\n // Every modifier below produces a fresh spread; identity inequality\n // with `state` is intentional and load-bearing. A shallow `Object.freeze`\n // would only protect the top-level object (the chain never mutates it\n // anyway) and not nested wire / order objects — pure ceremony.\n return {\n where: (p) => {\n // Normalise + validate the incoming fragment before merge so\n // error messages pin the offender to `p`, not the merged whole.\n // The validator is the wire-arrival contract surface; running\n // it once per fragment is sufficient because `mergePredicateWires`\n // preserves the per-clause shape that `validateWire` already\n // approved.\n const incoming = normalizePredicateArg<T>(p);\n validateWire(incoming);\n return makeQuery<T>(ctx, {\n ...state,\n wire: state.wire === undefined ? incoming : mergePredicateWires(state.wire, incoming),\n });\n },\n order: (s) => makeQuery<T>(ctx, { ...state, order: s }),\n limit: (n) => makeQuery<T>(ctx, { ...state, limit: n }),\n first: async () => {\n const { rows } = await runRead<T>(ctx, { ...state, limit: 1 });\n return rows[0]; // undefined when rows.length === 0\n },\n all: async () => {\n const res = await runRead<T>(ctx, state);\n return res.rows;\n },\n count: async () => {\n const res = await runRead<T>(ctx, state);\n return res.rows.length;\n },\n update: (patch) => runUpdate<T>(ctx, state, patch),\n delete: () => runDelete<T>(ctx, state),\n };\n};\n\n/**\n * Server-internal read entry surfacing the manifest-pointer cursor\n * and freshness flag alongside the materialised rows. The HTTP\n * router calls this directly so the read-response handler can pack\n * `_meta` onto the envelope; the public `Query<T>` terminals\n * destructure the rows out and discard the cursor to keep the\n * locked interface signature. Single-row routes (`GET /v1/c/:collection/:id`)\n * call this with `limit:1` and pick `rows[0]`.\n *\n * `state.wire` is assumed already validated — the public seam\n * (`Query.where(p)` → `normalizePredicateArg` → `validateWire`) is\n * the wire-arrival contract surface. Router callers parsing\n * `?where=` run `validateWire` themselves inside `parseWhereParam`,\n * keeping a single validation pass per wire.\n *\n * @internal\n */\nexport const runAllWithMeta = <T extends DocumentData>(\n ctx: CollectionReadContext,\n state: QueryState<T>,\n): Promise<ReadResult<T>> => {\n return runRead<T>(ctx, state);\n};\n\n/**\n * By-id read entry surfacing the same `ReadResult<T>` shape as\n * {@link runAllWithMeta} so the HTTP router can preserve the\n * `_meta` wire envelope while routing through the PK-lookup\n * fast-path. Mirrors {@link runAllWithMeta}'s signature; the\n * wire is built internally as a single-clause `{op:\"eq\",\n * field:\"_id\", value:id}` shape (same form as the `byId` helper in\n * `./collection.ts` and the `runInsert` duplicate-collision check)\n * which routes through `runRead`'s `singleIdFromPredicate`\n * short-circuit automatically.\n *\n * Bypasses {@link validateWire} — the wire is kernel-constructed,\n * never wire-submitted, so it would always pass the structural\n * rules. Skipping the validator also keeps this helper usable\n * from kernel-internal sites (`Collection<T>.get` etc.) without\n * tripping the wire-only rule that bans top-level `_id`.\n *\n * @internal — router uses this to preserve `_meta` envelope;\n * mirrors {@link runAllWithMeta} and {@link Collection.get}.\n */\nexport const runByIdWithMeta = <T extends DocumentData>(\n ctx: CollectionReadContext,\n id: string,\n): Promise<ReadResult<T>> => {\n return runRead<T>(ctx, {\n wire: { clauses: [{ op: \"eq\", field: \"_id\", value: id }] },\n order: undefined,\n limit: 1,\n });\n};\n\n// ---------------------------------------------------------------------\n// Mutation terminals\n// ---------------------------------------------------------------------\n\n/**\n * Build a fresh `Writer` bound to this collection's `current.json`.\n * Construction is zero-I/O (writer.ts:160) so we mint one per\n * `commit()` rather than caching on the chain — same writer object\n * shared across N commits would inherit retry-budget state we want\n * fresh per call.\n */\nconst writerFor = (ctx: CollectionReadContext): Writer =>\n new Writer({\n storage: ctx.storage,\n currentJsonKey: `${ctx.collectionPrefix}/current.json`,\n options: {\n indexes: ctx.indexes,\n },\n });\n\n/**\n * `Collection.insert` / `Query.insert` implementation. Mints a UUIDv7 `_id`\n * when the caller omits it (or supplies an empty string); honours a\n * caller-supplied non-empty `_id`. On collision (the materialised\n * collection already carries that `_id`) throws\n * `BaerlyError{code:\"Conflict\"}` BEFORE issuing the writer round-trip\n * — matches the locked `Collection.insert` contract\n * (`packages/protocol/src/collection-api.ts:123–125`).\n *\n * The emitted `LogEntry` has `op:\"I\"` and `after === {...doc, _id}`\n * (today's per-doc-replace model).\n *\n * @throws BaerlyError code=\"Conflict\" — `_id` collision (pre-commit check) or\n * CAS retry budget exhausted inside `Writer.commit()`.\n * @throws BaerlyError code=\"SchemaError\" — from the per-collection\n * `SchemaValidator` threaded via {@link Db.collectionReadContext}.\n *\n * @internal — exported for `Collection.insert` in `./collection.ts` to delegate\n * without duplicating the auto-id / collision-check /\n * commit pipeline.\n */\nexport const runInsert = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n doc: Partial<T> & DocumentData,\n): Promise<{ _id: string }> => {\n // Auto-id semantics: caller-supplied non-empty `_id` wins; otherwise\n // mint a UUIDv7. The locked contract\n // (`packages/protocol/src/collection-api.ts:120–122`) names UUIDv7 as the\n // auto-id source.\n const supplied = doc[\"_id\"];\n const _id = typeof supplied === \"string\" && supplied.length > 0 ? supplied : uuidv7();\n // The locked input type `Partial<T> & DocumentData` is an\n // intersection of optional-keyed and required-keyed: at runtime the\n // DocumentData half is authoritative (Partial widens types\n // but doesn't add `undefined` to the runtime shape). Cast through\n // the runtime-authoritative half.\n const body: DocumentData = { ...(doc as DocumentData), _id };\n\n // Schema validation against the post-image. Runs BEFORE the\n // pre-commit collision check and before the writer round-trip so\n // a malformed doc never reaches the wire. Inside a transaction it\n // also runs before `txCtx.mutations.push` — a `SchemaError` thrown\n // here aborts the body, dropping every buffered mutation, before\n // the commit fires.\n if (ctx.schema !== undefined) {\n await validateOrThrow(ctx.schema, body, {\n collection: ctx.collectionName,\n verb: \"insert\",\n });\n }\n\n // Pre-commit `_id`-collision check. Costs one log walk; matches the\n // locked `Collection.insert` throws contract\n // (`packages/protocol/src/collection-api.ts:123–125`). Without it a caller-\n // supplied duplicate `_id` would land a second `I` entry that the\n // read fold collapses silently — a contract violation. The CAS\n // retry budget in `Writer` does not surface this case\n // (no `current.json` conflict; both writes succeed at different seqs).\n //\n // Inside a transaction the read sees LIVE state (no MVCC, no read-\n // your-writes); a buffered insert in the same transaction is NOT\n // visible here. The collision check still defends against a doc\n // ALREADY committed to the bucket.\n const existing = await runRead<DocumentData>(ctx, {\n wire: { clauses: [{ op: \"eq\", field: \"_id\", value: _id }] },\n order: undefined,\n limit: 1,\n });\n if (existing.rows.length > 0) {\n throw new BaerlyError(\n \"Conflict\",\n `Query.insert: _id ${JSON.stringify(_id)} already exists in collection ${JSON.stringify(ctx.collectionName)}`,\n );\n }\n\n if (ctx.txCtx !== undefined) {\n assertTxBindMatches(ctx);\n ctx.txCtx.mutations.push({ op: \"I\", docId: _id, body });\n return { _id };\n }\n\n // Single-attempt at the verb level; CAS retries are internal to\n // `Writer.commit()`. If `commit` throws `Conflict`, the\n // budget is exhausted and we surface unchanged.\n await writerFor(ctx).commit({\n op: \"I\",\n collection: ctx.collectionName,\n docId: _id,\n body,\n });\n\n return { _id };\n};\n\n/**\n * `Query.update` implementation. Materialises the predicate/order/\n * limit-filtered match set, applies RFC 7386 `merge(prev, patch)`\n * per row, and emits one `op:\"U\"` `LogEntry` per affected `doc_id`\n * — one `Writer.commit()` round-trip apiece.\n *\n * Atomicity is per row, not across the N-row batch. The locked\n * contract (`packages/protocol/src/collection-api.ts:178–184`) is explicit on\n * this: all-or-nothing across multiple rows is what\n * `db.transaction(...)` exists to deliver.\n *\n * `replica_identity` defaults to `PATCH_ONLY` for every collection\n * today — emitted `U` entries carry `{ after }` (the full post-image)\n * and neither `before` nor `key_old`. Consumers rebuilding pre-images\n * under `PATCH_ONLY` need to maintain a shadow table — see\n * `packages/protocol/src/log.ts:102–118`.\n *\n * @throws BaerlyError code=\"Conflict\" — any one row's CAS retry budget\n * exhausted inside `Writer.commit()`. The partial-progress\n * `modified` count is NOT returned in that case.\n * @throws BaerlyError code=\"SchemaError\" — `merge(prev, patch)` produced\n * `undefined` (defensive — `Partial<T>` cannot be `null` at the\n * root in the type system).\n */\nconst runUpdate = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n state: QueryState<T>,\n patch: Partial<T>,\n): Promise<{ modified: number }> => {\n const { rows } = await runRead<T>(ctx, state);\n const tx = ctx.txCtx;\n if (tx !== undefined) {\n assertTxBindMatches(ctx);\n }\n let modified = 0;\n for (const doc of rows) {\n const merged = merge(doc as DocumentData, patch as Partial<DocumentData>);\n if (merged === undefined) {\n // `merge(target, patch)` returns undefined only when patch is\n // null at the root. `Partial<T>` cannot be `null` at the type\n // level; defensive check for runtime caller misuse via cast.\n throw new BaerlyError(\n \"SchemaError\",\n `Query.update: merge produced undefined for doc ${JSON.stringify(doc[\"_id\"])}`,\n );\n }\n // Validate the merged post-image, not the incoming patch.\n // Patches are partial by design — validating the patch itself\n // would reject valid updates against schemas that require fields\n // the patch doesn't touch. The post-image is what the schema\n // actually models. Atomicity stays per-row: a violation on row\n // N aborts the batch without rolling back rows 0..N-1.\n if (ctx.schema !== undefined) {\n await validateOrThrow(ctx.schema, merged, {\n collection: ctx.collectionName,\n verb: \"update\",\n });\n }\n if (tx !== undefined) {\n tx.mutations.push({ op: \"U\", docId: String(doc[\"_id\"]), body: merged });\n } else {\n await writerFor(ctx).commit({\n op: \"U\",\n collection: ctx.collectionName,\n docId: String(doc[\"_id\"]),\n body: merged,\n });\n }\n modified++;\n }\n return { modified };\n};\n\n/**\n * `Collection.replace` implementation. Existence check via `runRead` over\n * a `byId`-shaped wire so the `singleIdFromPredicate` PK fast path\n * (`Map.get`) fires and any transaction-buffered insert of `id` is\n * visible. Missing row → `NotFound` directly (no Conflict-string\n * indirection through the router). Present row → emit a single\n * `op:\"U\"` `LogEntry` carrying `doc` as the post-image, with `_id`\n * forced to the requested `id` so doc identity is preserved across\n * replaces even if the supplied `doc._id` differs.\n *\n * @throws BaerlyError code=\"NotFound\" — no row exists at `id`.\n * @throws BaerlyError code=\"SchemaError\" — post-image rejected by\n * the collection's bound validator.\n * @throws BaerlyError code=\"Conflict\" — writer CAS retry budget\n * exhausted.\n */\nexport const runReplaceById = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n id: string,\n doc: T,\n): Promise<void> => {\n const wire: PredicateWire = {\n clauses: [{ op: \"eq\", field: \"_id\", value: id }],\n };\n const state: QueryState<T> = {\n wire,\n order: undefined,\n limit: undefined,\n };\n const { rows } = await runRead<T>(ctx, state);\n if (rows.length === 0) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n const body: DocumentData = { ...(doc as DocumentData), _id: id };\n // Schema validation runs against the post-image — same shape as\n // `runInsert`. Buffers in a transaction only after validation\n // passes; an invalid replace inside a tx aborts the body and\n // drops every previously-buffered mutation.\n if (ctx.schema !== undefined) {\n await validateOrThrow(ctx.schema, body, {\n collection: ctx.collectionName,\n verb: \"replace\",\n });\n }\n if (ctx.txCtx !== undefined) {\n assertTxBindMatches(ctx);\n ctx.txCtx.mutations.push({ op: \"U\", docId: id, body });\n return;\n }\n await writerFor(ctx).commit({\n op: \"U\",\n collection: ctx.collectionName,\n docId: id,\n body,\n });\n};\n\n/**\n * `Query.delete` implementation. Tombstones every matched row with a\n * single `op:\"D\"` `LogEntry` per `doc_id`. `replica_identity` defaults\n * to `PATCH_ONLY`, so emitted `D` entries carry no body fields\n * (no `after`, no `before`/`key_old`).\n * Consumers rebuilding pre-images under `PATCH_ONLY` need to\n * maintain a shadow table — see `packages/protocol/src/log.ts:102–118`.\n *\n * Atomicity is per row, not across the N-row batch — same shape as\n * `Query.update`. `db.transaction(...)` is where all-or-nothing\n * semantics live.\n *\n * @throws BaerlyError code=\"Conflict\" — any one row's CAS retry budget\n * exhausted. The partial-progress `deleted` count is NOT returned\n * in that case.\n */\nconst runDelete = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n state: QueryState<T>,\n): Promise<{ deleted: number }> => {\n const { rows } = await runRead<T>(ctx, state);\n const tx = ctx.txCtx;\n if (tx !== undefined) {\n assertTxBindMatches(ctx);\n }\n let deleted = 0;\n for (const doc of rows) {\n if (tx !== undefined) {\n tx.mutations.push({ op: \"D\", docId: String(doc[\"_id\"]) });\n } else {\n await writerFor(ctx).commit({\n op: \"D\",\n collection: ctx.collectionName,\n docId: String(doc[\"_id\"]),\n });\n }\n deleted++;\n }\n return { deleted };\n};\n\n/**\n * Runtime guard for the txCtx-Collection-name binding. The type system\n * already prevents the legitimate path (the body callback gets one\n * `Collection<T>`, no `Db`), so this only catches a bug where a stale\n * `Query<T>` outlives its `Collection<T>` and is somehow re-attached to a\n * transaction over a different collection.\n *\n * @throws BaerlyError code=\"Internal\" — txCtx ↔ Collection name mismatch.\n */\nconst assertTxBindMatches = (ctx: CollectionReadContext): void => {\n if (ctx.txCtx === undefined) {\n return;\n }\n if (ctx.txCtx.collection !== ctx.collectionName) {\n throw new BaerlyError(\n \"Internal\",\n `Transaction context bound to ${JSON.stringify(ctx.txCtx.collection)} but mutation issued on collection ${JSON.stringify(ctx.collectionName)}`,\n );\n }\n};\n\n/**\n * Load `current.json` fresh, walk `[0, next_seq)` in parallel, fold\n * per-`doc_id`, then apply predicate / order / limit in memory.\n *\n * Error mapping:\n * - `current.json` missing → empty result (collection not provisioned).\n * - `current.json` malformed → `InvalidResponse` (from `readCurrentJson`).\n * - log entry missing in `[0, next_seq)` → `Internal`.\n * - log entry malformed → `InvalidResponse`.\n */\nconst runRead = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n state: QueryState<T>,\n): Promise<ReadResult<T>> => {\n // ── Step 1. Read current.json. ────────────────────────────────────\n // Every read GETs `current.json` fresh — mirrors the multi-instance\n // rules: every read sees a fresh CAS snapshot, matching the writer's\n // per-commit GET.\n const currentJsonKey = `${ctx.collectionPrefix}/current.json`;\n const head = await readCurrentJson(ctx.storage, currentJsonKey);\n\n // Capture the wire cursor before the rest of the fold runs. A\n // not-found head (\"collection not yet provisioned\") still emits a\n // well-defined cursor so the wire shape never carries `\"\"`.\n const manifestPointer =\n head === null ? `${MANIFEST_POINTER_EMPTY_SNAPSHOT}@0` : serializeManifestPointer(head.json);\n // Every read is strong by construction — `fresh` reflects that.\n const fresh = true;\n\n // Not-found is \"collection not yet provisioned\" — return empty rather\n // than throw. Mirrors `Storage.get` returning null on miss.\n if (head === null) {\n return { rows: [], manifestPointer, fresh };\n }\n\n // ── Optional index-walk fast path. ──────────────────────────────\n // `planQuery` is a pure function over `(wire, indexes)`. It picks\n // the longest-prefix-matching index from the collection's declared\n // indexes and emits a `FullScanPlan` when nothing matches. We\n // route on `plan.kind`; the in-memory `matchesWire(...)` re-check\n // on every fetched doc defends against stale index entries AND\n // consumes the planner's residue (range clauses, unrelated\n // equality on non-indexed fields).\n const plan: QueryPlan = planQuery(state.wire, ctx.indexes);\n if (plan.kind === \"index-walk\") {\n let rows = await runIndexWalkPlan<T>(ctx, head.json, state, plan);\n if (state.order !== undefined) {\n rows = sortByOrderSpec(rows, state.order);\n }\n if (state.limit !== undefined && state.limit < rows.length) {\n rows = rows.slice(0, state.limit);\n }\n return { rows, manifestPointer, fresh };\n }\n // plan.kind === \"full-scan\" — fall through to the snapshot+log fold.\n\n // Load the snapshot, if any. `compact()` guarantees:\n // `snapshot !== null` iff `log_seq_start > 0`. The snapshot is\n // sealed by its filename hash; `loadSnapshotAsMap` recomputes on\n // load and throws `Internal` on mismatch. Entries with\n // `seq < log_seq_start` have been folded into the snapshot (or\n // dropped on truncation) and MUST NOT be GET-required here — the\n // bucket may have already swept them via `runGc()`.\n const nextSeq = head.json.next_seq;\n const logSeqStart = logSeqStartOf(head.json);\n const baseDocs: Map<string, DocumentData> =\n head.json.snapshot === null\n ? new Map()\n : await loadSnapshotAsMap(ctx.storage, head.json.snapshot, ctx.collectionName);\n\n // ── Step 2. Bounded parallel-fetch of [log_seq_start, next_seq). ──\n const entries = await walkLogRange(ctx.storage, ctx.collectionPrefix, logSeqStart, nextSeq);\n\n // ── Step 3. Fold per doc_id, seeded from the snapshot. ────────────\n // I / U: post-image overwrite. `entry.after` is the full post-image;\n // a straight `set` is correct (a `merge(prev, post)` would\n // carry forward keys the writer dropped).\n // D: tombstone — remove from the map.\n const docs = new Map<string, T>(baseDocs as Map<string, T>);\n foldLogEntriesOnto(docs, entries, { collection: ctx.collectionName });\n\n // ── Step 4. Apply predicate. ──────────────────────────────────────\n // PK fast-path: a single `eq` clause on `_id` short-circuits the\n // O(n) scan with a `Map.get` on the same snapshot — observable\n // contract unchanged.\n const fastId = singleIdFromPredicate(state.wire);\n let rows: T[];\n if (fastId !== undefined) {\n const hit = docs.get(fastId);\n rows = hit === undefined ? [] : [hit];\n } else {\n rows = Array.from(docs.values());\n if (state.wire !== undefined) {\n const w = state.wire;\n rows = rows.filter((d) => matchesWire(w, d));\n }\n }\n\n // ── Step 5. Apply order. ──────────────────────────────────────────\n if (state.order !== undefined) {\n rows = sortByOrderSpec(rows, state.order);\n }\n\n // ── Step 6. Apply limit. ──────────────────────────────────────────\n if (state.limit !== undefined && state.limit < rows.length) {\n rows = rows.slice(0, state.limit);\n }\n\n return { rows, manifestPointer, fresh };\n};\n\n/**\n * Range-walk exclusive-lower sentinel. `Storage.list({startAfter})`\n * is strict-greater; to position the cursor PAST every entry whose\n * value-segment equals `ENCODE(lo)`, append a character that\n * lex-sorts strictly greater than every base-32 character (the\n * encoder alphabet is `[0-9a-v]`, topping out at `v` = 0x76) AND\n * strictly greater than the path separator `/` (0x2F).\n *\n * `~` (0x7E) satisfies both. The cursor `${eqPrefix}${ENCODE(lo)}/~`\n * lex-sorts strictly greater than the LARGEST possible key under\n * the `lo` value bucket but strictly less than the smallest key\n * under any bucket with a larger value-segment. The next LIST\n * result is the first entry with value-segment strictly greater\n * than `ENCODE(lo)` — exactly the exclusive-lower semantics we\n * want.\n */\nconst RANGE_EXCLUSIVE_LOWER_SENTINEL = \"~\";\n\n/**\n * Bounded parallelism for `$in` multi-walk LISTs. Each batch of this\n * many `$in` values dispatches its `list()` calls concurrently; the\n * loop waits on the batch before starting the next.\n *\n * Picked low (8) to stay well under any cloud-provider per-call concurrency\n * ceiling while still amortising LIST round-trip latency on multi-value\n * `$in` queries. The planner's `IN_FANOUT_THRESHOLD` (50) caps the total\n * fan-out independently — see `packages/server/src/query-planner.ts`.\n */\nconst IN_FANOUT_PARALLELISM = 8;\n\n/**\n * Execute an {@link IndexWalkPlan} against the bucket. Returns the\n * post-filtered, fully-resolved row set. The full original\n * `state.wire` is re-applied via `matchesWire(...)` after fetching\n * rows — this defends against stale index entries AND consumes the\n * planner's residue (range clauses, unrelated equality on\n * non-indexed fields) in one place.\n *\n * Storage shape (equality-only walks):\n * - Single-field walk (`equalityKeys.length === 1`): list\n * `<collectionPrefix>/index/<name>/<v0-b32>/`; each yielded key has\n * tail `<docId>.json` (single segment).\n * - Composite full walk (`equalityKeys.length === def.on.length`):\n * list `<collectionPrefix>/index/<name>/<v0-b32>/<v1-b32>/.../<vN-b32>/`;\n * each yielded key has tail `<docId>.json` (single segment).\n * - Composite partial-prefix walk (`equalityKeys.length <\n * def.on.length`): list `<collectionPrefix>/index/<name>/<v0-b32>/\n * .../<vM-b32>/`; each yielded key has tail\n * `<v{M+1}-b32>/.../<vN-b32>/<docId>.json` — MULTI-segment.\n * Split on `/` and take the last segment.\n *\n * Storage shape (T3, range / `$in` walks):\n * - Range walk (`plan.rangeOn !== undefined`): list\n * `<collectionPrefix>/index/<name>/<eq-segs>/` and break on the\n * first decoded value-segment past the upper bound. Lower\n * bound is enforced via `startAfter` (exclusive lower) or an\n * in-loop skip (inclusive lower) — see\n * {@link RANGE_EXCLUSIVE_LOWER_SENTINEL}.\n * - `$in` walk (`plan.inOn !== undefined`): one LIST per value,\n * with the equality prefix prepended to each, dispatched in\n * batches of {@link IN_FANOUT_PARALLELISM} `Promise.all`-style.\n * Doc-ids accumulate into a single Set (union semantics).\n *\n * Stale-row defence:\n * - An index entry pointing at a docId whose underlying doc has\n * since been updated to a different value (rebuild hasn't run)\n * is dropped by the in-memory `matchesWire(...)` re-check.\n * - An index entry pointing at a docId whose underlying doc has\n * been deleted (tombstone in the log) is dropped during the\n * fold (the `D` op removes it from the materialised set).\n *\n * @internal\n */\nconst runIndexWalkPlan = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n head: CurrentJson,\n state: QueryState<T>,\n plan: IndexWalkPlan,\n): Promise<T[]> => {\n const encodedSegments = plan.equalityKeys.map((v) => encodeIndexValue(v));\n const eqPrefix =\n encodedSegments.length === 0\n ? `${ctx.collectionPrefix}/index/${plan.indexName}/`\n : `${ctx.collectionPrefix}/index/${plan.indexName}/${encodedSegments.join(\"/\")}/`;\n\n // 1. List index entries; extract docId from the LAST segment of\n // each key's tail. Multi-segment tails appear under composite\n // partial-prefix walks; single-segment tails appear under\n // single-field walks and composite full walks.\n const docIdSet = new Set<string>();\n\n if (plan.rangeOn !== undefined) {\n // Range-LIST under the equality prefix. The value-segment sits\n // immediately after `eqPrefix`; we lex-compare it against the\n // encoded bounds. Lex comparison is sound because\n // `encodeIndexValue` is value-order-preserving for every\n // supported type — numbers via the sortable IEEE 754 payload,\n // strings via UTF-8 byte order, all framed under the type-tag\n // prefix that keeps types disjoint.\n const r = plan.rangeOn;\n const loEncoded = r.lo === undefined ? undefined : encodeIndexValue(r.lo);\n const hiEncoded = r.hi === undefined ? undefined : encodeIndexValue(r.hi);\n // Exclusive lower → position the cursor past all entries\n // whose value-segment equals `ENCODE(r.lo)` via the sentinel.\n // Inclusive lower → no startAfter; in-loop skip filters values\n // strictly less than `ENCODE(r.lo)` (no-op for the bucket\n // matching `ENCODE(r.lo)` itself).\n const startAfter =\n r.lo !== undefined && !r.loInclusive\n ? `${eqPrefix}${loEncoded}/${RANGE_EXCLUSIVE_LOWER_SENTINEL}`\n : undefined;\n const listOpts = startAfter === undefined ? {} : { startAfter };\n for await (const entry of ctx.storage.list(eqPrefix, listOpts)) {\n const tail = entry.key.slice(eqPrefix.length);\n const firstSlash = tail.indexOf(\"/\");\n if (firstSlash < 0) {\n continue;\n } // defensive: malformed key\n const valueSeg = tail.slice(0, firstSlash);\n // Inclusive-lower in-loop skip (couldn't push to startAfter).\n if (loEncoded !== undefined && valueSeg < loEncoded) {\n continue;\n }\n // Upper-bound break — lex-ascending enumeration, so once we\n // pass the upper bound we're done.\n if (hiEncoded !== undefined) {\n if (r.hiInclusive ? valueSeg > hiEncoded : valueSeg >= hiEncoded) {\n break;\n }\n }\n // Decode the doc-id from the LAST `/`-separated segment of\n // the tail. Single-field walk → tail is `<valueSeg>/<docId>.json`\n // and the LAST segment is `<docId>.json`. Composite walk with\n // tail extension → tail is `<valueSeg>/...moreSegs/<docId>.json`\n // and the LAST segment is still `<docId>.json`.\n const lastSlash = tail.lastIndexOf(\"/\");\n const last =\n lastSlash === firstSlash ? tail.slice(firstSlash + 1) : tail.slice(lastSlash + 1);\n if (!last.endsWith(\".json\")) {\n continue;\n }\n const docId = last.slice(0, -\".json\".length);\n if (docId.length === 0) {\n continue;\n }\n docIdSet.add(docId);\n }\n } else if (plan.inOn !== undefined) {\n // `$in` multi-walk: dispatch up to IN_FANOUT_PARALLELISM `list()` calls\n // in parallel per batch. Union of doc-ids across all values; per-value\n // walks are independent so batching is sound. The planner has already\n // vetted the total fan-out (≤ IN_FANOUT_THRESHOLD); the encoder is\n // value-order-preserving across every supported type, so numeric\n // members route the same as strings.\n //\n // Cancellation note: `Promise.all` rejects on the first rejection but\n // does NOT cancel the other in-flight `list()` calls — the `Storage`\n // contract doesn't promise mid-stream cancellation. Storage errors\n // are rare; tightening this is out of scope.\n const values = plan.inOn.values;\n const walkOne = async (value: DocumentValue): Promise<string[]> => {\n const valPrefix = `${eqPrefix}${encodeIndexValue(value)}/`;\n const ids: string[] = [];\n for await (const entry of ctx.storage.list(valPrefix)) {\n const tail = entry.key.slice(valPrefix.length);\n if (!tail.endsWith(\".json\")) {\n continue;\n }\n const lastSlash = tail.lastIndexOf(\"/\");\n const docId =\n lastSlash === -1\n ? tail.slice(0, -\".json\".length)\n : tail.slice(lastSlash + 1, -\".json\".length);\n if (docId.length === 0) {\n continue;\n }\n ids.push(docId);\n }\n return ids;\n };\n for (let i = 0; i < values.length; i += IN_FANOUT_PARALLELISM) {\n const batch = values.slice(i, i + IN_FANOUT_PARALLELISM);\n const results = await Promise.all(batch.map(walkOne));\n for (const ids of results) {\n for (const id of ids) {\n docIdSet.add(id);\n }\n }\n }\n } else {\n // Equality-only walk (T2 path).\n for await (const entry of ctx.storage.list(eqPrefix)) {\n const tail = entry.key.slice(eqPrefix.length);\n if (!tail.endsWith(\".json\")) {\n continue;\n }\n const lastSlash = tail.lastIndexOf(\"/\");\n const docId =\n lastSlash === -1\n ? tail.slice(0, -\".json\".length)\n : tail.slice(lastSlash + 1, -\".json\".length);\n if (docId.length === 0) {\n continue;\n }\n docIdSet.add(docId);\n }\n }\n const docIds = Array.from(docIdSet);\n if (docIds.length === 0) {\n return [];\n }\n\n // 2. Resolve each docId by folding `(snapshot, log)` scoped to the\n // matched set. Same fold the table-scan path uses, scoped to\n // one Set<docId>.\n const matched = new Set(docIds);\n const baseDocs: Map<string, DocumentData> =\n head.snapshot === null\n ? new Map()\n : await loadSnapshotAsMap(ctx.storage, head.snapshot, ctx.collectionName);\n const docs = new Map<string, T>();\n for (const id of matched) {\n const seeded = baseDocs.get(id);\n if (seeded !== undefined) {\n docs.set(id, seeded as T);\n }\n }\n const logSeqStart = logSeqStartOf(head);\n const nextSeq = head.next_seq;\n const entries = await walkLogRange(ctx.storage, ctx.collectionPrefix, logSeqStart, nextSeq);\n foldLogEntriesOnto(docs, entries, { collection: ctx.collectionName, docIdFilter: matched });\n\n // 3. Apply the FULL original wire as the stale-row defence, then\n // the planner's residue postFilter on top. `matchesWire` is\n // open-world, so applying the full original wire (which the\n // planner partly consumed) is the simpler invariant: if the\n // doc still passes the original wire, it stays. Range / `in`\n // clauses that landed in `plan.postFilter` are part of\n // `state.wire` — they pass through here automatically.\n const rows: T[] = [];\n const wire = state.wire;\n for (const doc of docs.values()) {\n if (wire === undefined || matchesWire(wire, doc)) {\n rows.push(doc);\n }\n }\n return rows;\n};\n\n/**\n * Stable multi-key sort built from an `OrderSpec`. Keys are taken in\n * the spec's insertion order, which matches the caller's source-order\n * expectation. `Array.prototype.sort` is stable on Node 24+ and Workerd.\n *\n * Top-level fields only (locked at `OrderSpec<T>`).\n * Values are `DocumentValue` — string / number / boolean / object —\n * but only the primitive types are sensibly orderable; comparing two\n * objects falls through to \"considered equal,\" which preserves the\n * stable-sort order of the input.\n */\nconst sortByOrderSpec = <T extends DocumentData>(rows: T[], spec: OrderSpec<T>): T[] => {\n const entries = Object.entries(spec) as Array<[keyof T, \"asc\" | \"desc\"]>;\n return rows.toSorted((a, b) => {\n for (const [field, dir] of entries) {\n const av: T[keyof T] | undefined = a[field];\n const bv: T[keyof T] | undefined = b[field];\n if (av === bv) {\n continue;\n }\n // `undefined` (missing field) sorts low under asc / high under\n // desc — same shape SQL's `NULLS FIRST` gives on asc.\n if (av === undefined) {\n return dir === \"desc\" ? 1 : -1;\n }\n if (bv === undefined) {\n return dir === \"desc\" ? -1 : 1;\n }\n // string / number / boolean compare uniformly under `<`. Booleans\n // compare false < true (JS default). Object values fall through\n // as \"considered equal\" — see JSDoc above.\n if (typeof av === \"object\" || typeof bv === \"object\") {\n continue;\n }\n const cmp = av < bv ? -1 : 1;\n return dir === \"desc\" ? -cmp : cmp;\n }\n return 0;\n });\n};\n"],"mappings":";;;;;;AA8BA,MAAM,iBAAiB,UAKrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;;;;;;;;;AAYrE,SAAgB,MACd,QACA,OACe;CACf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./config-Bsg8wgwo.js";
1
+ import { n as loadCollectionIndexes } from "./config-DVfDGyw1.js";
2
+ import { i as rebuildIndex } from "./maintenance-BvOv6BMM.js";
3
+ import { n as parseBucketUri, t as defineBaerlySubcommand } from "./subcommand-DZcHcsYp.js";
3
4
  import { o as BaerlyError, r as emitSuccess } from "./baerly.js";
4
- import { t as rebuildIndex } from "./rebuild-index-C5gTXryd.js";
5
- import { t as defineBaerlySubcommand } from "./subcommand-BWs6K7zb.js";
6
5
  //#region src/admin/rebuild-index.ts
7
6
  /** citty arg shape. Kebab-case so --help and parsed-object keys line up. */
8
7
  const REBUILD_INDEX_ARGS = {
@@ -101,4 +100,4 @@ bundle.run;
101
100
  //#endregion
102
101
  export { rebuildIndexCmd };
103
102
 
104
- //# sourceMappingURL=rebuild-index-DwXM0WfA.js.map
103
+ //# sourceMappingURL=rebuild-index-DC_nR6wP.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"rebuild-index-DwXM0WfA.js","names":[],"sources":["../packages/cli/src/admin/rebuild-index.ts"],"sourcesContent":["/**\n * `baerly admin rebuild-index` — idempotent reconciliation for one\n * secondary index. Walks the live `(snapshot, log)` of the named\n * collection, computes the expected index-key set under the named\n * index's definition, then PUTs missing keys and DELETEs orphans.\n *\n * Cost shape: `1 GET (current.json) + 1 GET (snapshot, if any) + N\n * GETs (live tail) + 1 LIST (the index prefix) + K PUTs + L DELETEs`.\n *\n * Exit codes (standard CLI shape):\n * - `0` — success (envelope on stdout in --json mode).\n * - `1` — user error (InvalidConfig: bad bucket URI, missing\n * args, unparseable config).\n * - `2` — storage error (NetworkError, AccessDenied, anything\n * non-BaerlyError).\n * - `3` — protocol invariant (Conflict, Internal, InvalidResponse).\n *\n * Idempotent — re-running on a healthy index is `{ removed: 0,\n * added: 0 }`; re-running after a crashed mid-commit reconciles\n * toward the live current.json view.\n *\n * Args:\n * --bucket Bucket URI (s3://..., file:///<abs>, memory://...).\n * --app Application name segment (defaults to baerly.config.ts).\n * --tenant Tenant name segment (defaults to baerly.config.ts).\n * --collection Collection name.\n * --index Index name (e.g. \"by_status\").\n * --on Field the index projects on (string today; matches\n * the IndexDefinition shape declared in baerly.config.ts).\n * --config Path to a baerly.config.{js,mjs,json}. Loaded with\n * dynamic import; the matching collection.indexes[]\n * definition is used. Mutually-exclusive with --on\n * (config takes precedence). `.ts` configs are not\n * supported today — point at the compiled output.\n *\n * The reconciliation logic itself lives in `@baerly/server`'s\n * `rebuildIndex`; this command is a thin URI + arg-parsing wrapper.\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, type IndexDefinition } from \"@baerly/protocol\";\nimport { rebuildIndex } from \"@baerly/server/maintenance\";\nimport { loadCollectionIndexes } from \"../config.ts\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport { defineBaerlySubcommand } from \"../subcommand.ts\";\n\n/** citty arg shape. Kebab-case so --help and parsed-object keys line up. */\nconst REBUILD_INDEX_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Collection name\",\n valueHint: \"name\",\n },\n index: {\n type: \"string\",\n required: true,\n description: \"Index name (e.g. by_status)\",\n valueHint: \"name\",\n },\n on: {\n type: \"string\",\n required: false,\n description: \"Field the index projects on. Required unless --config supplies it.\",\n valueHint: \"field\",\n },\n config: {\n type: \"string\",\n required: false,\n description: \"Path to baerly.config.{js,mjs,json} — used to resolve the index's `on` field.\",\n valueHint: \"path\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n verbose: {\n type: \"boolean\",\n description: \"Emit a one-line summary to stdout in addition to the JSON envelope.\",\n },\n} as const satisfies ArgsDef;\n\n/** Resolve the `on` field of a single named index from the config file. */\nconst onFieldFromConfig = async (\n configPath: string,\n collection: string,\n indexName: string,\n): Promise<string | readonly string[]> => {\n const indexes = await loadCollectionIndexes(configPath, collection, \"baerly admin rebuild-index\");\n const def = indexes.find((d) => d.name === indexName);\n if (def === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin rebuild-index: config has no index ${JSON.stringify(indexName)} on collection ${JSON.stringify(collection)}`,\n );\n }\n return def.on;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.rebuild-index\",\n meta: {\n description: \"Idempotent reconciliation of one secondary index.\",\n },\n args: REBUILD_INDEX_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const on =\n args.config !== undefined && args.config.length > 0\n ? await onFieldFromConfig(args.config, args.collection, args.index)\n : args.on;\n if (on === undefined || on.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerly admin rebuild-index: --on=<field> (or --config=<path>) is required\",\n );\n }\n const def: IndexDefinition = { name: args.index, on };\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const result = await rebuildIndex(bucket.storage, currentJsonKey, def);\n emitSuccess({\n command: \"admin.rebuild-index\",\n status: \"ok\",\n added: result.added,\n removed: result.removed,\n kept: result.kept,\n });\n if (args.verbose === true) {\n process.stdout.write(\n `rebuild-index: added=${result.added} removed=${result.removed} kept=${result.kept}\\n`,\n );\n }\n return 0;\n },\n});\n\n/**\n * citty `defineCommand` block for `baerly admin rebuild-index`.\n * Mounted on the `admin` subcommand tree in `baerly.ts`.\n */\nexport const rebuildIndexCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n *\n * @param argv Args AFTER the `admin rebuild-index` subcommand.\n */\nexport const runRebuildIndex = bundle.run;\n"],"mappings":";;;;;;;AAgDA,MAAM,qBAAqB;CACzB,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,KAAK;EACH,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,YAAY;EACV,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,OAAO;EACL,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,IAAI;EACF,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,SAAS;EACP,MAAM;EACN,aAAa;CACf;AACF;;AAGA,MAAM,oBAAoB,OACxB,YACA,YACA,cACwC;CAExC,MAAM,OAAM,MADU,sBAAsB,YAAY,YAAY,4BAA4B,GAC5E,MAAM,MAAM,EAAE,SAAS,SAAS;CACpD,IAAI,QAAQ,KAAA,GACV,MAAM,IAAI,YACR,iBACA,mDAAmD,KAAK,UAAU,SAAS,EAAE,iBAAiB,KAAK,UAAU,UAAU,GACzH;CAEF,OAAO,IAAI;AACb;AAEA,MAAM,SAAS,uBAAuB;CACpC,MAAM;CACN,MAAM,EACJ,aAAa,oDACf;CACA,MAAM;CACN,SAAS,OAAO,MAAM,QAAQ;EAC5B,MAAM,SAAS,MAAM,eAAe,KAAK,MAAM;EAC/C,MAAM,KACJ,KAAK,WAAW,KAAA,KAAa,KAAK,OAAO,SAAS,IAC9C,MAAM,kBAAkB,KAAK,QAAQ,KAAK,YAAY,KAAK,KAAK,IAChE,KAAK;EACX,IAAI,OAAO,KAAA,KAAa,GAAG,WAAW,GACpC,MAAM,IAAI,YACR,iBACA,2EACF;EAEF,MAAM,MAAuB;GAAE,MAAM,KAAK;GAAO;EAAG;EACpD,MAAM,EAAE,KAAK,WAAW,MAAM,IAAI,iBAAiB;GAAE,KAAK,KAAK;GAAK,QAAQ,KAAK;EAAO,CAAC;EACzF,MAAM,iBAAiB,GAAG,OAAO,UAAU,MAAM,IAAI,UAAU,OAAO,aAAa,KAAK,WAAW;EACnG,MAAM,SAAS,MAAM,aAAa,OAAO,SAAS,gBAAgB,GAAG;EACrE,YAAY;GACV,SAAS;GACT,QAAQ;GACR,OAAO,OAAO;GACd,SAAS,OAAO;GAChB,MAAM,OAAO;EACf,CAAC;EACD,IAAI,KAAK,YAAY,MACnB,QAAQ,OAAO,MACb,wBAAwB,OAAO,MAAM,WAAW,OAAO,QAAQ,QAAQ,OAAO,KAAK,GACrF;EAEF,OAAO;CACT;AACF,CAAC;;;;;AAMD,MAAa,kBAAkB,OAAO;AASP,OAAO"}
1
+ {"version":3,"file":"rebuild-index-DC_nR6wP.js","names":[],"sources":["../packages/cli/src/admin/rebuild-index.ts"],"sourcesContent":["/**\n * `baerly admin rebuild-index` — idempotent reconciliation for one\n * secondary index. Walks the live `(snapshot, log)` of the named\n * collection, computes the expected index-key set under the named\n * index's definition, then PUTs missing keys and DELETEs orphans.\n *\n * Cost shape: `1 GET (current.json) + 1 GET (snapshot, if any) + N\n * GETs (live tail) + 1 LIST (the index prefix) + K PUTs + L DELETEs`.\n *\n * Exit codes (standard CLI shape):\n * - `0` — success (envelope on stdout in --json mode).\n * - `1` — user error (InvalidConfig: bad bucket URI, missing\n * args, unparseable config).\n * - `2` — storage error (NetworkError, AccessDenied, anything\n * non-BaerlyError).\n * - `3` — protocol invariant (Conflict, Internal, InvalidResponse).\n *\n * Idempotent — re-running on a healthy index is `{ removed: 0,\n * added: 0 }`; re-running after a crashed mid-commit reconciles\n * toward the live current.json view.\n *\n * Args:\n * --bucket Bucket URI (s3://..., file:///<abs>, memory://...).\n * --app Application name segment (defaults to baerly.config.ts).\n * --tenant Tenant name segment (defaults to baerly.config.ts).\n * --collection Collection name.\n * --index Index name (e.g. \"by_status\").\n * --on Field the index projects on (string today; matches\n * the IndexDefinition shape declared in baerly.config.ts).\n * --config Path to a baerly.config.{js,mjs,json}. Loaded with\n * dynamic import; the matching collection.indexes[]\n * definition is used. Mutually-exclusive with --on\n * (config takes precedence). `.ts` configs are not\n * supported today — point at the compiled output.\n *\n * The reconciliation logic itself lives in `@baerly/server`'s\n * `rebuildIndex`; this command is a thin URI + arg-parsing wrapper.\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, type IndexDefinition } from \"@baerly/protocol\";\nimport { rebuildIndex } from \"@baerly/server/maintenance\";\nimport { loadCollectionIndexes } from \"../config.ts\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport { defineBaerlySubcommand } from \"../subcommand.ts\";\n\n/** citty arg shape. Kebab-case so --help and parsed-object keys line up. */\nconst REBUILD_INDEX_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Collection name\",\n valueHint: \"name\",\n },\n index: {\n type: \"string\",\n required: true,\n description: \"Index name (e.g. by_status)\",\n valueHint: \"name\",\n },\n on: {\n type: \"string\",\n required: false,\n description: \"Field the index projects on. Required unless --config supplies it.\",\n valueHint: \"field\",\n },\n config: {\n type: \"string\",\n required: false,\n description: \"Path to baerly.config.{js,mjs,json} — used to resolve the index's `on` field.\",\n valueHint: \"path\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n verbose: {\n type: \"boolean\",\n description: \"Emit a one-line summary to stdout in addition to the JSON envelope.\",\n },\n} as const satisfies ArgsDef;\n\n/** Resolve the `on` field of a single named index from the config file. */\nconst onFieldFromConfig = async (\n configPath: string,\n collection: string,\n indexName: string,\n): Promise<string | readonly string[]> => {\n const indexes = await loadCollectionIndexes(configPath, collection, \"baerly admin rebuild-index\");\n const def = indexes.find((d) => d.name === indexName);\n if (def === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin rebuild-index: config has no index ${JSON.stringify(indexName)} on collection ${JSON.stringify(collection)}`,\n );\n }\n return def.on;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.rebuild-index\",\n meta: {\n description: \"Idempotent reconciliation of one secondary index.\",\n },\n args: REBUILD_INDEX_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const on =\n args.config !== undefined && args.config.length > 0\n ? await onFieldFromConfig(args.config, args.collection, args.index)\n : args.on;\n if (on === undefined || on.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerly admin rebuild-index: --on=<field> (or --config=<path>) is required\",\n );\n }\n const def: IndexDefinition = { name: args.index, on };\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const result = await rebuildIndex(bucket.storage, currentJsonKey, def);\n emitSuccess({\n command: \"admin.rebuild-index\",\n status: \"ok\",\n added: result.added,\n removed: result.removed,\n kept: result.kept,\n });\n if (args.verbose === true) {\n process.stdout.write(\n `rebuild-index: added=${result.added} removed=${result.removed} kept=${result.kept}\\n`,\n );\n }\n return 0;\n },\n});\n\n/**\n * citty `defineCommand` block for `baerly admin rebuild-index`.\n * Mounted on the `admin` subcommand tree in `baerly.ts`.\n */\nexport const rebuildIndexCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n *\n * @param argv Args AFTER the `admin rebuild-index` subcommand.\n */\nexport const runRebuildIndex = bundle.run;\n"],"mappings":";;;;;;AAgDA,MAAM,qBAAqB;CACzB,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,KAAK;EACH,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,YAAY;EACV,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,OAAO;EACL,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,IAAI;EACF,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,SAAS;EACP,MAAM;EACN,aAAa;CACf;AACF;;AAGA,MAAM,oBAAoB,OACxB,YACA,YACA,cACwC;CAExC,MAAM,OAAM,MADU,sBAAsB,YAAY,YAAY,4BAA4B,GAC5E,MAAM,MAAM,EAAE,SAAS,SAAS;CACpD,IAAI,QAAQ,KAAA,GACV,MAAM,IAAI,YACR,iBACA,mDAAmD,KAAK,UAAU,SAAS,EAAE,iBAAiB,KAAK,UAAU,UAAU,GACzH;CAEF,OAAO,IAAI;AACb;AAEA,MAAM,SAAS,uBAAuB;CACpC,MAAM;CACN,MAAM,EACJ,aAAa,oDACf;CACA,MAAM;CACN,SAAS,OAAO,MAAM,QAAQ;EAC5B,MAAM,SAAS,MAAM,eAAe,KAAK,MAAM;EAC/C,MAAM,KACJ,KAAK,WAAW,KAAA,KAAa,KAAK,OAAO,SAAS,IAC9C,MAAM,kBAAkB,KAAK,QAAQ,KAAK,YAAY,KAAK,KAAK,IAChE,KAAK;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