@gusto/baerly-storage 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.md +93 -52
  4. package/dist/API.md +151 -109
  5. package/dist/CHANGELOG.md +144 -0
  6. package/dist/THIRD-PARTY-LICENSES.txt +312 -0
  7. package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-BIzyAKzy.d.ts} +14 -2
  8. package/dist/app-config.d.ts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.js +288 -288
  11. package/dist/auth.js.map +1 -1
  12. package/dist/baerly.js +10 -10
  13. package/dist/baerly.js.map +1 -1
  14. package/dist/bytes-BXdamO3L.js.map +1 -1
  15. package/dist/{client-DYZfoZb9.d.ts → client-BJXF3XJA.d.ts} +10 -10
  16. package/dist/client-react.d.ts +3 -3
  17. package/dist/client-react.js.map +1 -1
  18. package/dist/client.d.ts +3 -3
  19. package/dist/client.js.map +1 -1
  20. package/dist/{cloudflare-CINJPKCW.js → cloudflare-Cn2ibODt.js} +178 -2
  21. package/dist/cloudflare-Cn2ibODt.js.map +1 -0
  22. package/dist/cloudflare.d.ts +4 -4
  23. package/dist/cloudflare.js +10 -11
  24. package/dist/cloudflare.js.map +1 -1
  25. package/dist/{subcommand-DZcHcsYp.js → config-CGyBopy3.js} +643 -439
  26. package/dist/config-CGyBopy3.js.map +1 -0
  27. package/dist/context-DRZ3tZ5l.js.map +1 -1
  28. package/dist/{cost-CQt1YRkA.js → cost-BZ_MDBmn.js} +6 -4
  29. package/dist/cost-BZ_MDBmn.js.map +1 -0
  30. package/dist/{current-json-C-EyJqs0.js → current-json-DsN7FNY1.js} +47 -13
  31. package/dist/current-json-DsN7FNY1.js.map +1 -0
  32. package/dist/{db-BM3y2JQw.d.ts → db-CCT6tDfY.d.ts} +26 -108
  33. package/dist/{deploy-CrAbfgCq.js → deploy-BKKyGlSJ.js} +11 -4
  34. package/dist/deploy-BKKyGlSJ.js.map +1 -0
  35. package/dist/dev-vite.d.ts +5 -5
  36. package/dist/dev-vite.js +5 -5
  37. package/dist/dev-vite.js.map +1 -1
  38. package/dist/dev.d.ts +1 -1
  39. package/dist/dev.js +1 -1
  40. package/dist/{doctor-Db-hzPmE.js → doctor-BVU4GNXN.js} +13 -132
  41. package/dist/doctor-BVU4GNXN.js.map +1 -0
  42. package/dist/{dump-BYA55NLP.js → dump-DPEAKub6.js} +5 -3
  43. package/dist/dump-DPEAKub6.js.map +1 -0
  44. package/dist/errors-DOdL95kK.js.map +1 -1
  45. package/dist/{export-Bhbz90-z.js → export-BcuCLFFe.js} +6 -4
  46. package/dist/{export-Bhbz90-z.js.map → export-BcuCLFFe.js.map} +1 -1
  47. package/dist/{fsck-CPPZWt9p.js → fsck-RXgLOaJG.js} +23 -11
  48. package/dist/fsck-RXgLOaJG.js.map +1 -0
  49. package/dist/{http-Cw8p6y5b.js → http-Bd4byR4n.js} +45 -61
  50. package/dist/http-Bd4byR4n.js.map +1 -0
  51. package/dist/http.d.ts +15 -15
  52. package/dist/http.js +1 -1
  53. package/dist/{index-cUY-36AN.d.ts → index-BDceQQi-.d.ts} +20 -4
  54. package/dist/{index-C3JAH1Yo.d.ts → index-Cmsxx-ZN.d.ts} +9 -9
  55. package/dist/{index-DSvwEUeF.d.ts → index-DW7GT6M2.d.ts} +50 -42
  56. package/dist/{index-DwDTWPSU.d.ts → index-DnBGSeuU.d.ts} +10 -7
  57. package/dist/index.d.ts +6 -6
  58. package/dist/index.js +4 -4
  59. package/dist/{indexes-DAu2AkTW.d.ts → indexes-Cx7uMXm0.d.ts} +2 -2
  60. package/dist/{inspect-Bdbzvi-_.js → inspect-DhI49PSi.js} +16 -8
  61. package/dist/inspect-DhI49PSi.js.map +1 -0
  62. package/dist/{snapshot-SS8USDUF.js → log-tail-DXeDkWEp.js} +154 -83
  63. package/dist/log-tail-DXeDkWEp.js.map +1 -0
  64. package/dist/{maintenance-BRrThz8V.d.ts → maintenance-BkhUr72A.d.ts} +91 -26
  65. package/dist/{maintenance-ClzBC1Vv.js → maintenance-CWBQpZ2y.js} +368 -161
  66. package/dist/maintenance-CWBQpZ2y.js.map +1 -0
  67. package/dist/{maintenance-BvOv6BMM.js → maintenance-C_KSkVjd.js} +204 -82
  68. package/dist/maintenance-C_KSkVjd.js.map +1 -0
  69. package/dist/maintenance.d.ts +3 -2
  70. package/dist/maintenance.js +3 -2
  71. package/dist/node.d.ts +13 -8
  72. package/dist/node.js +1 -1
  73. package/dist/normalize-XWY25_sG.js.map +1 -1
  74. package/dist/{observability-CpOiEN0k.js → observability-BYd-RzEx.js} +63 -55
  75. package/dist/observability-BYd-RzEx.js.map +1 -0
  76. package/dist/observability.d.ts +3 -3
  77. package/dist/observability.js +1 -1
  78. package/dist/{plan-DOTl21vq.js → plan-DIu_B6fy.js} +7 -4
  79. package/dist/plan-DIu_B6fy.js.map +1 -0
  80. package/dist/{query-BmiQy328.js → query-sQNO5vU_.js} +1071 -1099
  81. package/dist/query-sQNO5vU_.js.map +1 -0
  82. package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-DP4CqSSs.js} +5 -4
  83. package/dist/rebuild-index-DP4CqSSs.js.map +1 -0
  84. package/dist/{restore-C6IcmLeA.js → restore-DpQYef6r.js} +362 -328
  85. package/dist/restore-DpQYef6r.js.map +1 -0
  86. package/dist/shared-secret-BJdSwpgw.js.map +1 -1
  87. package/dist/{src-QQ7jDeL2.js → src-CWpkSbvJ.js} +40 -20
  88. package/dist/src-CWpkSbvJ.js.map +1 -0
  89. package/dist/{src-DU1sCMlr.js → src-D24wDpzR.js} +269 -258
  90. package/dist/src-D24wDpzR.js.map +1 -0
  91. package/dist/{src-zhEAmmF7.js → src-Db4-qVtM.js} +36 -96
  92. package/dist/src-Db4-qVtM.js.map +1 -0
  93. package/dist/subcommand-CP9NY2J4.js +159 -0
  94. package/dist/subcommand-CP9NY2J4.js.map +1 -0
  95. package/dist/{usage-CLjirdD-.js → usage-CTfDq9HR.js} +3 -3
  96. package/dist/{usage-CLjirdD-.js.map → usage-CTfDq9HR.js.map} +1 -1
  97. package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
  98. package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
  99. package/package.json +40 -29
  100. package/dist/cloudflare-CINJPKCW.js.map +0 -1
  101. package/dist/config-DVfDGyw1.js +0 -278
  102. package/dist/config-DVfDGyw1.js.map +0 -1
  103. package/dist/cost-CQt1YRkA.js.map +0 -1
  104. package/dist/current-json-C-EyJqs0.js.map +0 -1
  105. package/dist/deploy-CrAbfgCq.js.map +0 -1
  106. package/dist/doctor-Db-hzPmE.js.map +0 -1
  107. package/dist/dump-BYA55NLP.js.map +0 -1
  108. package/dist/fsck-CPPZWt9p.js.map +0 -1
  109. package/dist/http-Cw8p6y5b.js.map +0 -1
  110. package/dist/inspect-Bdbzvi-_.js.map +0 -1
  111. package/dist/maintenance-BvOv6BMM.js.map +0 -1
  112. package/dist/maintenance-ClzBC1Vv.js.map +0 -1
  113. package/dist/observability-CpOiEN0k.js.map +0 -1
  114. package/dist/plan-DOTl21vq.js.map +0 -1
  115. package/dist/query-BmiQy328.js.map +0 -1
  116. package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
  117. package/dist/restore-C6IcmLeA.js.map +0 -1
  118. package/dist/snapshot-SS8USDUF.js.map +0 -1
  119. package/dist/src-DU1sCMlr.js.map +0 -1
  120. package/dist/src-QQ7jDeL2.js.map +0 -1
  121. package/dist/src-zhEAmmF7.js.map +0 -1
  122. package/dist/subcommand-DZcHcsYp.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-sQNO5vU_.js","names":["utf8","#storage","#currentJsonKey","#maxRetries","#initialBackoffMs","#random","#indexes","#verifyLogIntegrityOnCommit","#singleAttemptCommit","#backoff","#emitWriteMetrics","#provisionCurrentJson","#walkLog","#observe429","#cleanupStaleIndexKeysBestEffort","#readPreImage"],"sources":["../packages/protocol/src/json.ts","../packages/protocol/src/query/merge.ts","../packages/protocol/src/types.ts","../packages/protocol/src/time.ts","../packages/server/src/path-segment.ts","../packages/server/src/doc-id.ts","../packages/server/src/query-planner-implies.ts","../packages/server/src/query-planner.ts","../packages/server/src/schema.ts","../packages/server/src/key-limit.ts","../packages/server/src/log-conflict-adoption.ts","../packages/server/src/writer.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","import { COUNT_BIT_WIDTH } from \"./constants.ts\";\n\ndeclare 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 per-collection 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 local optimistic state.\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 * Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to\n * produce an 11-char descending base-32 string with a domain of\n * 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1).\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, COUNT_BIT_WIDTH);\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` §\"LSNs, wall clocks, and downstream\n * consumers\".\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 \"@baerly/protocol\";\nimport { assertNameNotReserved } from \"./names.ts\";\n\n/**\n * Per-segment byte ceiling. S3 and R2 cap a full object key at 1024\n * UTF-8 bytes; a key is several segments, so this 256 leaves real prefix\n * headroom. The assembled multi-segment key sum is bounded separately on\n * the write path, not here. This is an intentional server-local *policy*\n * value (not the protocol-level S3/R2 fact `MAX_KEY_BYTES = 1024` in\n * `@baerly/protocol`'s `constants.ts`); it lives here, co-located with the\n * one rule that uses it, to keep `protocol/constants.ts` out of the\n * validator's bundle closure.\n */\nexport const MAX_SEGMENT_BYTES = 256;\nconst utf8 = new TextEncoder();\n// C0 (U+0000-U+001F) + DEL/C1 (U+007F-U+009F).\n// eslint-disable-next-line no-control-regex -- intentional control-char class\nconst CONTROL_CHARS = /[\\u0000-\\u001f\\u007f-\\u009f]/;\n\n/**\n * The single validation rule for every caller-controlled key segment\n * (`_id`, `collection`, `app`, `tenant`) before it becomes a written\n * key segment or `LocalFsStorage` path. Rejects empty / `\"/\"` /\n * `\".\"`|`\"..\"` / C0-C1 control / leading `\"_\"` (ADR-007) / `> MAX_SEGMENT_BYTES`,\n * all as `BaerlyError{code:\"InvalidConfig\"}`.\n *\n * @param role human label for the segment (\"_id\" | \"collection\" | \"app\" | \"tenant\").\n * @param verb optional calling-context label for the message.\n */\nexport const assertPathSegment = (value: string, role: string, verb = \"\"): void => {\n const where = verb === \"\" ? role : `${verb}: ${role}`;\n if (value.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", `${where} must be a non-empty string`);\n }\n if (value.includes(\"/\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} may not contain \"/\": ${JSON.stringify(value)}`,\n );\n }\n if (value === \".\" || value === \"..\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} may not be \".\" or \"..\": ${JSON.stringify(value)}`,\n );\n }\n if (CONTROL_CHARS.test(value)) {\n throw new BaerlyError(\"InvalidConfig\", `${where} may not contain control characters`);\n }\n if (utf8.encode(value).length > MAX_SEGMENT_BYTES) {\n throw new BaerlyError(\"InvalidConfig\", `${where} is too long (> ${MAX_SEGMENT_BYTES} bytes)`);\n }\n // Leading `_` is the ADR-007 reserved namespace.\n assertNameNotReserved(value, where);\n};\n","import { assertPathSegment } from \"./path-segment.ts\";\n\n/**\n * Guard a caller-supplied `_id` before it becomes a written key segment\n * (index keys, log `doc_id`) or filesystem path (`LocalFsStorage`). The\n * `_id` analogue of `assertKeySegment` (`db.ts`). Routes through the\n * single shared {@link assertPathSegment} rule (empty / `\"/\"` /\n * `\".\"`|`\"..\"` / C0-C1 control chars / leading `\"_\"` (ADR-007) / overlong,\n * all as `BaerlyError{code:\"InvalidConfig\"}`).\n */\nexport const assertDocId = (id: string): void => {\n assertPathSegment(id, \"_id\");\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","import { BaerlyError, MAX_KEY_BYTES } from \"@baerly/protocol\";\n\nconst utf8 = new TextEncoder();\n\n/**\n * Reject an assembled object key over the S3/R2 full-key ceiling\n * ({@link MAX_KEY_BYTES}) as `InvalidConfig`. Per-segment caps don't\n * bound the sum, and index values skip `assertPathSegment` entirely, so\n * this post-encoding check at the writer's PUT sites is their only\n * overflow guard. @see docs/spec/storage-compatibility.md\n */\nexport const assertKeyWithinLimit = (key: string): void => {\n const bytes = utf8.encode(key).length;\n if (bytes > MAX_KEY_BYTES) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `object key exceeds ${MAX_KEY_BYTES} bytes (got ${bytes}): ${JSON.stringify(key.slice(0, 80))}…`,\n );\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` creates each log entry\n * with `If-None-Match: \"*\"` — and that create IS the commit. A 412 on\n * `/log/<seq>.json` can mean either\n *\n * (a) a peer genuinely won that seq (a foreign entry is committed\n * there); or\n * (b) our OWN previous attempt landed the committing log create but\n * its ack was lost — we never observed the `200` — 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 four 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. **Matching write intent.** The occupant's writer-minted log\n * fields match the entry this writer just attempted to create.\n * Same session + same seq alone is not sufficient: a collision,\n * test seam, or out-of-model bucket writer must not be able to\n * make this writer adopt a different logical mutation.\n * 4. **Single-input commit.** `self.batchSize === 1`. Every\n * commit is single-input now, so this always holds; the guard\n * is retained as a defensive invariant (its removal is the\n * deferred follow-up tracked as D1.5). It is sound only for a single-input\n * commit because per-input adoption decisions would not\n * compose with the single-key single-write commit (the one\n * `log/<seq>` create is the all-or-nothing commit point).\n *\n * When any of (1)/(2)/(3)/(4) fails, the caller MUST refuse adoption\n * and treat the occupant as a conflicting committed entry.\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)+(4) 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 ∧ matching intent ∧ 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 §\"Contention and retries\"\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 * Input count of the parent commit attempt. Always `1` now —\n * `Writer.commit` is the only commit path and is single-input.\n * Adoption is only safe when this is exactly `1`; the field is\n * retained as a defensive invariant (removing it is the deferred\n * follow-up tracked as D1.5).\n */\n readonly batchSize: number;\n}\n\n/**\n * Discriminated outcome of {@link tryAdoptOwnSessionLogEntry}.\n * `adopt: true` carries the existing entry (which by the invariant\n * matches `self` on writer-minted intent fields); the caller\n * substitutes it for `self` so the returned `CommitResult` matches\n * what's actually stored. `adopt: false` carries a machine-readable\n * `reason` so callers and tests can discriminate which clause of the\n * invariant failed.\n */\nexport type AdoptionDecision =\n | { readonly adopt: true; readonly entry: LogEntry }\n | {\n readonly adopt: false;\n readonly reason: \"foreign-session\" | \"wrong-seq\" | \"intent-mismatch\" | \"batch\";\n };\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 * ## Correctness precondition\n *\n * A fresh `session` id is minted per `commit()` call, seq-stable\n * across that call's retries. Adoption compares the writer-minted\n * intent/body fields as well as session and seq: a dropped-ack retry\n * reuses the same attempted entry and adopts, while a same-session /\n * same-seq occupant carrying a different logical mutation is treated as\n * a conflict and skipped by the caller's forward-probe loop.\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 (4) — single-input commit. Always holds now (every commit\n // is single-input); evaluated first as a defensive guard before any\n // 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 // Clause (3) — matching write intent: full-entry equality, including\n // `commit_ts`. A legitimate lost-ack self-retry passes this ONLY under\n // two premises:\n // P1 (single mint): `commit_ts`/`lsn`/`session` are minted once per\n // `#singleAttemptCommit` (one `Date.now()`) and the inner\n // transient-retry loop re-PUTs the IDENTICAL `entry`, so a real\n // read-back is byte-identical to `self`, `commit_ts` included.\n // P2 (order-stable round-trip): stored bytes are\n // `encodeJsonBytes` (`JSON.stringify`) and read back via\n // `JSON.parse`; `JSON.stringify(JSON.parse(...))` preserves key\n // order, so the two stringifications match.\n // If either breaks (re-mint on retry, or a canonical/sorting encoder /\n // normalizing read-back), a legit self-retry would falsely mismatch\n // here and DUPLICATE-write. P2 is pinned by `bytes.test.ts`.\n if (JSON.stringify(ctx.existing) !== JSON.stringify(ctx.self)) {\n return { adopt: false, reason: \"intent-mismatch\" };\n }\n return { adopt: true, entry: ctx.existing };\n};\n","/**\n * `Writer` — stateless multi-instance write engine (single-write commit).\n *\n * Each {@link Writer.commit} reads `current.json` FRESH (for\n * `log_seq_start` / `tail_hint` as a probe FLOOR — a lower bound, NOT a\n * CAS precondition), PUTs the content body, then **creates `log/<seq>`\n * via `If-None-Match: \"*\"`. That create IS the commit / linearization\n * point.** The writer writes NOTHING to `current.json` on the commit\n * path; `tail_hint` advances outside ordinary commits via compaction\n * folds, write-tick refreshes, and explicit operator/import paths. The\n * commit model and its invariants are recorded in ADR-008\n * (`docs/adr/008-single-write-commit.md`). The\n * optional integrity walk is gated by\n * {@link WriterOptions.verifyLogIntegrityOnCommit} (default off).\n *\n * No per-write cache: every commit re-reads + re-probes, so N stateless\n * instances contend at one place — the `If-None-Match` create of\n * `log/<seq>`. The loser gets a 412 and re-probes forward to the next\n * empty slot. A 412 from the writer's OWN session at the same seq is its\n * own lost-ack / crashed-but-durable commit → adopted (not retried), so\n * the write lands at EXACTLY `seq`, never duplicated.\n *\n * **Crash safety.** Order is content + additive index `newKeys` →\n * `log/<seq>` create → stale index-key DELETEs. A crash before the\n * create leaves an unreferenced content body + orphan additive index\n * keys (no log entry references them), not an orphan log entry with\n * missing content — the compactor sweeps the content, and a stray\n * additive key only ever yields a false-POSITIVE candidate that\n * `matchesWire` (read path) drops. Emitting `newKeys` before the commit\n * means a committed row is ALWAYS index-findable; the stale-key DELETE\n * stays after the commit so a crash can never de-index a committed\n * doc. See `index-emit-order.test.ts` and ADR-008 Q4.\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 logObjectKey,\n logSeqStartOf,\n BaerlyError,\n noopMetricsRecorder,\n type Storage,\n LOG_FORWARD_PROBE_CAP,\n MAINTENANCE_PROFILE_CF_FREE,\n MAINTENANCE_TAIL_HINT_REFRESH_WRITES,\n S3_REQUEST_MAX_RETRIES,\n SESSION_ID_LENGTH,\n countKey,\n readCurrentJson,\n timestamp,\n uuid,\n versionFromContent,\n} from \"@baerly/protocol\";\nimport { assertDocId } from \"./doc-id.ts\";\nimport { allIndexKeysFor, type IndexDefinition, validateIndexDefinition } from \"./indexes.ts\";\nimport { assertKeyWithinLimit } from \"./key-limit.ts\";\nimport { readLogEntry, walkLogRange } from \"./log-walk.ts\";\nimport { findLogTail } from \"./log-tail.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 retryable `Conflict` attempts before throwing `Conflict`.\n * Foreign log-create 412s are resolved inside a single attempt by\n * occupant read-back plus bounded forward re-probe; this budget is\n * retained for future retryable conflicts and 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) — the additive\n * `newKeys` go down BEFORE the committing `log/<seq>` create, so a\n * committed row is always index-findable. On U/D, the writer reads\n * the pre-image content body from the log (one back-walk per\n * indexed collection, NOT per index) to compute the stale-key set;\n * stale keys are DELETE'd AFTER the commit, computed from the\n * resolved committing seq's pre-image.\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, tail_hint)` 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 /**\n * ETag of `current.json` as read at the start of the commit. The\n * commit path no longer writes `current.json` (the `log/<seq>`\n * create IS the commit), so this is the manifest's pre-commit ETag,\n * not a post-write one.\n */\n readonly currentEtag: string;\n\n /** How many commit attempts it took (1 = first try won). */\n readonly attempts: number;\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. A retryable log-create 412 that resolved to a foreign-session\n * occupant beyond the forward-probe budget throws\n * `BaerlyError{code:\"Conflict\"}`; the caller catches via\n * {@link isPreconditionFailed} and decides whether to retry. Non-retryable\n * failures (protocol-invariant violations, network errors) propagate.\n */\ninterface SingleAttemptSuccess {\n readonly entries: readonly LogEntry[];\n readonly currentEtag: string;\n readonly classAOps: 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 (as a\n * probe FLOOR, not a CAS precondition), PUTs the content body and any\n * additive index `newKeys`, then creates `log/<seq>` via\n * `If-None-Match: \"*\"` — that create IS the commit (single-write\n * commit; no `current.json` CAS follows it). Stale index keys are\n * DELETE'd after the commit.\n *\n * The hot-path cost under no contention on an unindexed collection is\n * 1 GET + 2 PUTs (content + the committing `log/<seq>` create); each\n * declared index that projects a key on this write adds one PUT\n * (new key, before the commit) and, on U/D, up to one DELETE (stale\n * key, after the commit). An in-flight peer write costs one extra GET\n * + the backoff sleep 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. The `log/<seq>` create also uses\n * `If-None-Match: \"*\"`, so two writers racing the same tail cause\n * exactly one create to win; the loser reads back the occupant,\n * adopts its own lost-ack write or re-probes forward to the next\n * empty slot.\n *\n * @throws BaerlyError code=\"Conflict\" when a retryable conflict\n * escapes the single-attempt helper and exhausts the retry budget\n * (presently unreachable on the log-create 412 path).\n * @throws BaerlyError code=\"Internal\" when a log entry expected in\n * `[0, tail_hint)` 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 // Validate the doc id BEFORE any I/O so every commit caller — the\n // public write path AND a direct caller like `baerly admin restore`\n // — is covered (defense in depth, mirroring the db-layer guard).\n // Rejects empty / `\"/\"` / `\".\"`|`\"..\"` / control / leading `\"_\"` /\n // overlong `docId` as `BaerlyError{code:\"InvalidConfig\"}`, so a\n // traversal-shaped `_id` can never become a written key segment.\n assertDocId(input.docId);\n const session = uuid().slice(0, SESSION_ID_LENGTH);\n const logPrefix = this.#currentJsonKey.slice(0, this.#currentJsonKey.lastIndexOf(\"/\"));\n\n // NOTE: with the post-commit fence-verify removed, no `Conflict`\n // currently escapes `#singleAttemptCommit` — a log-create 412 is\n // always resolved internally (own-session adoption or a bounded\n // forward-probe to the next empty slot; only an exhausted probe cap\n // throws, as `Internal`, not `Conflict`). So the retry-catch arm and\n // the budget-exhausted `Conflict` throw below are presently\n // unreachable. They are retained deliberately: they cost nothing on\n // the happy path and re-arm automatically if a future change ever\n // re-introduces a retryable `Conflict` out of the helper.\n for (let attempt = 1; attempt <= this.#maxRetries; attempt++) {\n let success: SingleAttemptSuccess;\n try {\n success = await this.#singleAttemptCommit([input], session, logPrefix, \"Writer\");\n } catch (error) {\n // Only a retryable `Conflict` (see NOTE above — currently none)\n // backs off and retries. Anything else propagates.\n if (!isPreconditionFailed(error)) {\n throw error;\n }\n await this.#backoff(attempt);\n continue;\n }\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 * One full commit attempt — the body of {@link commit}. Reads\n * `current.json`, PUTs content + additive index `newKeys` in parallel,\n * then forward-probes the tail and creates `log/<seq>` once via\n * `If-None-Match: \"*\"` — the numbered log create IS the commit\n * (single-write commit; no `current.json` CAS follows it). Stale index\n * keys are DELETE'd after the commit. Returns the success payload.\n *\n * Called only as `#singleAttemptCommit([input], …)`: the array shape\n * is retained dead-generality (D1.5), but every call commits exactly\n * one entry.\n *\n * A log-create 412 is disambiguated by session read-back: own session\n * / own seq ⇒ our crashed-or-lost-ack commit is already durable ⇒\n * adopt; foreign session ⇒ re-probe forward and retry at the next\n * empty slot. Thrown `BaerlyError`s (Internal, InvalidResponse,\n * NetworkError) propagate.\n *\n * Crash safety invariant: content + additive index `newKeys` PUTs are\n * awaited before the log create. A crash before the create leaves\n * orphan content + additive index keys (no log entry references them)\n * — the compactor sweeps the content, and a stray additive key only\n * yields a false-positive candidate that `matchesWire` drops. A crash\n * AFTER the create is a durable, committed write at `seq` whose index\n * `newKeys` are already present (so it's index-findable); the only\n * residual is a possibly-undeleted stale OLD-value key, dropped by\n * `matchesWire` and cleaned by a later write / `rebuild-index`. The\n * inverse — committed log entry with missing content, or a de-indexed\n * committed doc — is never produced.\n */\n async #singleAttemptCommit(\n inputs: readonly CommitInput[],\n session: string,\n logPrefix: string,\n errorPrefix: string,\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\n // ── Step 2. Optional integrity walk (`verifyLogIntegrityOnCommit`,\n // default off). Surfaces missing / malformed entries inside\n // `[log_seq_start, tail_hint)` 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.tail_hint);\n }\n\n // ── Step 3. Find the true tail (Class B forward-probe), then mint. ─\n // `tail_hint` is a non-authoritative lower bound (the writer no\n // longer advances it — only the compactor stamps it durably). The\n // forward-probe discovers the first empty seq >= the floor: the slot\n // this commit will create. Floor at `max(log_seq_start, tail_hint)`\n // so a compactor that advanced `log_seq_start` past a stale\n // `tail_hint` doesn't make us re-walk folded-but-unswept entries.\n // Bind to a local (oxlint `no-await-expression-member`).\n const probeFloor = Math.max(logSeqStartOf(current), current.tail_hint);\n // `findLogTail`'s density precondition holds: the floor sits in the\n // dense prefix because tail_hint advancers probe or derive known tails\n // from committed entries, while ordinary writer commits never stamp\n // `tail_hint`, so nothing advances the floor past a hole.\n const preCommitTail = await findLogTail(this.#storage, logPrefix, probeFloor);\n let seq = preCommitTail;\n\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). The LSN's\n // `countKey(seq)` suffix MUST track the probed seq — it's compared on\n // adoption, so a stale suffix would misfire the disambiguation.\n const commitNowMs = Date.now();\n const commitTs = new Date(commitNowMs).toISOString();\n const lsnTimestamp = timestamp(commitNowMs);\n const input0 = inputs[0]!;\n const mintEntry = (atSeq: number): LogEntry => ({\n lsn: `${lsnTimestamp}_${session}_${countKey(atSeq)}`,\n commit_ts: commitTs,\n op: input0.op,\n collection: input0.collection,\n doc_id: input0.docId,\n session,\n seq: atSeq,\n ...(input0.op !== \"D\" && input0.body !== undefined ? { after: input0.body } : {}),\n ...(input0.origin !== undefined ? { origin: input0.origin } : {}),\n });\n let entry = mintEntry(seq);\n\n // ── Step 4. PUT content bodies + additive index `newKeys` (BEFORE\n // the commit). ──────────────────────────────────────────────────\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. Content is content-\n // addressed, so writing it before the commit is crash-safe: a\n // crash here leaves an unreferenced body the compactor sweeps,\n // never an orphan log entry with missing content.\n //\n // Additive index `newKeys` (the markers for the doc's NEW value)\n // ALSO go down here, before the committing create. `newKeys`\n // depend only on `body` + `docId` (NOT on `seq`), so they're\n // stable across the forward re-probe — emit them once. Emitting\n // BEFORE the commit guarantees a committed row is ALWAYS index-\n // findable (no false-negative). A crash after a `newKey` PUT but\n // before the commit leaves an orphan additive key for an\n // UNcommitted write — benign: the index read includes the\n // candidate docId, the fold finds no committed (or the prior)\n // value, and `matchesWire` (query.ts) drops the false-positive.\n // The stale-key DELETEs (de-indexing the OLD value) stay AFTER the\n // commit (Step 5b), so a crash can never de-index a committed doc.\n // See ADR-008 Q4 + `index-emit-order.test.ts`.\n let contentPutCount = 0;\n let newKeysClassA = 0;\n const parallelPuts: Array<Promise<unknown>> = [];\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 assertKeyWithinLimit(contentKey);\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 // Additive index keys for the NEW value — emitted before the\n // commit on I/U (a D has no new value). `op:\"D\"` and a missing\n // body project to no keys. Empty `#indexes` short-circuits.\n if (this.#indexes.length > 0 && input.op !== \"D\") {\n const newKeys = allIndexKeysFor(logPrefix, this.#indexes, input.body, input.docId);\n for (const k of newKeys) {\n assertKeyWithinLimit(k);\n newKeysClassA++;\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 }\n }\n await Promise.all(parallelPuts);\n\n // ── Step 5. Create the commit: PUT log/<seq> via If-None-Match. ─\n // The numbered log create IS the commit (single-write commit). No\n // `current.json` CAS follows it — the create is the linearization\n // point (exactly-one-winner, CI-gated across all backends).\n //\n // 200 ⇒ committed at `seq`. 412 ⇒ disambiguate by session read-back:\n // - own session / own seq ⇒ our crashed-or-lost-ack commit is\n // already durable at `seq` ⇒ adopt the resolved `seq` and fall\n // through to the SAME index emit (Step 5b). The adopted commit\n // is EXACTLY the attempt that may have died after creating\n // `log/<seq>` but before emitting its index, so re-running the\n // (idempotent) emit completes it.\n // - foreign session / wrong seq ⇒ re-probe forward and retry at the\n // new first-empty slot (bounded by LOG_FORWARD_PROBE_CAP).\n // A transient NetworkError (e.g. a dropped ack on a create that may\n // already have landed) retries the SAME `seq`: the retry either\n // re-creates (write never landed) or hits the durable write → 412 →\n // own-session adoption. Either way the write lands at EXACTLY `seq`,\n // never duplicated.\n let committedEntry: LogEntry = entry;\n let probes = 0;\n let transientRetries = 0;\n for (;;) {\n const logEntryKey = logObjectKey(logPrefix, seq);\n assertKeyWithinLimit(logEntryKey);\n let conflicted = false;\n try {\n await this.#storage.put(logEntryKey, encodeJsonBytes(entry), {\n ifNoneMatch: \"*\",\n contentType: APPLICATION_JSON,\n });\n } catch (error) {\n this.#observe429(error, entry.collection);\n if (isPreconditionFailed(error)) {\n ctxMetrics().counter(\"db.r2.put.412_total\", 1, {\n collection: entry.collection,\n step: \"log-put\",\n });\n conflicted = true;\n } else if (isTransientWrite(error) && transientRetries < this.#maxRetries) {\n // Possible lost-ack — retry the SAME seq (idempotent: adoption\n // closes the double-commit window). Bounded backoff (full jitter,\n // same as the outer loop) so a backend in transient distress\n // isn't hammered; a persistent NetworkError still surfaces.\n transientRetries++;\n await this.#backoff(transientRetries);\n continue;\n } else {\n throw error;\n }\n }\n if (!conflicted) {\n committedEntry = entry;\n break;\n }\n // 412 — read back the occupant and decide.\n const existing = await readLogEntry(this.#storage, logEntryKey);\n const decision = tryAdoptOwnSessionLogEntry({\n self: entry,\n existing,\n batchSize: inputs.length,\n });\n if (decision.adopt) {\n // Own crashed/lost-ack commit already durable at `seq`. Adopt it\n // (byte-identical to the attempted `entry`, INCLUDING `commit_ts`\n // — adoption compares the full entry) — the logical write lands at\n // EXACTLY `seq`, never duplicated. Fall through to Step 5b: the\n // adopted attempt may have died after the create but before the\n // index emit, so the (idempotent) emit must still run.\n committedEntry = decision.entry;\n break;\n }\n // Foreign session (or wrong seq) — re-probe forward from seq+1 and\n // retry at the new first-empty slot, re-minting seq + LSN.\n if (++probes > LOG_FORWARD_PROBE_CAP) {\n throw new BaerlyError(\n \"Internal\",\n `${errorPrefix}: log-tail forward-probe exceeded ${LOG_FORWARD_PROBE_CAP} on ${this.#currentJsonKey}`,\n );\n }\n seq = await findLogTail(this.#storage, logPrefix, seq + 1);\n entry = mintEntry(seq);\n }\n const committedEntries: readonly LogEntry[] = [committedEntry];\n\n // ── Step 5b. DELETE stale secondary-index keys (AFTER the commit). ─\n // The additive `newKeys` already went down in Step 4 (before the\n // commit), so a committed row is always index-findable. This block\n // handles only the OTHER half: deleting the OLD value's now-obsolete\n // markers. Keeping the stale-key DELETE AFTER the commit is the\n // load-bearing polarity (ADR-008 Q4): a crash here leaves the OLD\n // value's marker lingering — benign, the index read includes the\n // candidate, the fold sees the doc's NEW committed value, and\n // `matchesWire` (query.ts) drops the false-positive; the lingering\n // key is cleaned by a later same-doc write or operator\n // `rebuild-index`. The inverse — de-indexing a committed doc with no\n // log entry to drive repair — can NEVER happen, since the DELETE is\n // strictly after the commit.\n //\n // BOTH the fresh-win and the own-session-adoption break above reach\n // here with the resolved committing `seq`. Adoption correctness: an\n // adopted lost-ack commit is EXACTLY the attempt that may have died\n // after the create but before this DELETE, so it MUST run it too (do\n // not skip it). Idempotent under re-run: `Storage.delete` is\n // contractually idempotent, and the Step-4 `newKeys` PUT is\n // `ifNoneMatch: \"*\"` (412 swallowed).\n //\n // Empty `#indexes` short-circuits the whole block (including the\n // pre-image GET), preserving zero behaviour change for collections\n // without declared indexes. An `op:\"I\"` has no pre-image and no\n // stale keys, so it never reads.\n //\n // The pre-image is read at the RESOLVED committing `seq` (Step 5\n // may have advanced `seq` past a foreign winner): `#readPreImage`\n // back-walks from `seq - 1`, so it skips the just-committed entry\n // and finds the prior same-doc image. For a same-`docId` input\n // earlier in this batch the in-batch image takes precedence.\n //\n // Filter-aware projection (T4): `allIndexKeysFor` short-circuits on\n // `def.predicate` miss. The diff `oldKeys \\ newKeys` covers all four\n // U-quadrants (match→match deletes only the changed keys; match→miss\n // DELETEs all; miss→match deletes nothing; miss→miss no-ops), each\n // pinned by a named test in `writer.test.ts` (\"Writer — filtered\n // index\").\n const staleKeysClassA = await this.#cleanupStaleIndexKeysBestEffort({\n inputs,\n logPrefix,\n seq,\n });\n // The per-logical-write index-op histogram counts BOTH halves: the\n // `newKeys` PUTs (Step 4) and the `staleKeys` DELETEs (Step 5b).\n const indexClassA = newKeysClassA + staleKeysClassA;\n if (this.#indexes.length > 0 && indexClassA > 0) {\n ctxMetrics().histogram(\"db.write.index_ops_per_logical_write\", indexClassA, {\n collection: input0.collection,\n });\n }\n\n // ── Step 6. (removed). No current.json write on the commit path. ─\n // The numbered log create above IS the commit. `tail_hint` is\n // refreshed durably only by the compactor; the writer never advances\n // it. The maintenance trigger below reads a DERIVED tail-byte\n // estimate (`estimateTailBytes`), so there is no stored byte counter.\n\n // ── Step 6b. Write-tick maintenance dispatch. ───────────────────\n // Single funnel site: write-tick maintenance dispatch. Reached by\n // `commit()` exactly once per logical commit, after the committing\n // log create has landed.\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 //\n // `prevSeq` is the pre-commit tail (`preCommitTail`); the slot we won\n // is `seq` (== prevSeq unless a forward re-probe moved it past a\n // foreign winner), so the boundary check spans `(prevSeq,\n // observedTail]`. `observedTail = seq+1` is a fresh in-memory lower\n // bound on the true tail: winning `log/<seq>` means `[tail_hint, seq)`\n // were observed occupied, so `seq+1 ≤ true tail`. We pass `current`\n // (the Step-1 read) for the snapshot fields — there is no `next`.\n const prevSeq = preCommitTail;\n const observedTail = seq + 1;\n const maint = getCurrentContext()?.maintenance;\n // Same absent-context default as runBoundedMaintenance's\n // `options?.profile ?? MAINTENANCE_PROFILE_CF_FREE` — keep the two in\n // step (this gate reads only gcInterval; the runner resolves the whole\n // profile) so the pre-fire cadence can't diverge from the fold's.\n const gcInterval =\n maint?.options?.profile?.gcInterval ?? MAINTENANCE_PROFILE_CF_FREE.gcInterval;\n const maintenanceDue =\n maint?.disabled === true\n ? observedTail - current.tail_hint >= MAINTENANCE_TAIL_HINT_REFRESH_WRITES\n : shouldFireMaintenance(current, prevSeq, gcInterval, observedTail);\n if (maintenanceDue) {\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 // Thread the in-memory observed tail so the runner's Gate-1\n // ratio + GC cadence key off the true tail without an\n // O(gap) re-probe (the stored `tail_hint` is only a lower\n // bound under single-write commit).\n observedTail,\n // `disabled` disables fold/GC phases inside the runner but\n // still permits the bounded tail_hint refresh that prevents a\n // maintenance-off collection from drifting past the probe cap.\n ...(maint?.disabled === true && { disabled: true }),\n ...(maint?.maxFoldBytes !== undefined && { maxFoldBytes: maint.maxFoldBytes }),\n },\n maint?.options,\n ).then(\n () => {},\n () => {},\n ),\n );\n }\n\n // Base class-A op count for this attempt: content PUTs (skipping\n // `op:\"D\"`) + the single log create + index PUTs + index DELETEs.\n // No current.json CAS anymore. Forward-probe GETs are Class B and\n // excluded. The caller of `commit()` adds `(attempt - 1)` for retry\n // cost.\n const classAOps = contentPutCount + 1 + indexClassA;\n return {\n entries: committedEntries,\n // No current.json write on the commit path — return the manifest\n // etag read in Step 1 (still a valid etag of the current manifest).\n currentEtag: baseEtag,\n classAOps,\n };\n }\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`, `tail_hint: 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 tail_hint: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" },\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 #cleanupStaleIndexKeysBestEffort(args: {\n inputs: readonly CommitInput[];\n logPrefix: string;\n seq: number;\n }): Promise<number> {\n if (this.#indexes.length === 0) {\n return 0;\n }\n\n let staleKeysClassA = 0;\n const indexDeletes: Array<Promise<unknown>> = [];\n // Per-docId in-batch image map: a later input on the same docId\n // reads the in-batch pre-image, not the on-disk one.\n const inBatchImage = new Map<string, DocumentData | undefined>();\n for (const input of args.inputs) {\n let staleKeys: readonly string[] = [];\n try {\n if (input.op === \"U\") {\n const preImage = inBatchImage.has(input.docId)\n ? inBatchImage.get(input.docId)\n : await this.#readPreImage(args.logPrefix, input.collection, input.docId, args.seq);\n const oldKeys = allIndexKeysFor(args.logPrefix, this.#indexes, preImage, input.docId);\n const newSet = new Set(\n allIndexKeysFor(args.logPrefix, this.#indexes, input.body, input.docId),\n );\n staleKeys = oldKeys.filter((k) => !newSet.has(k));\n } else if (input.op === \"D\") {\n const preImage = inBatchImage.has(input.docId)\n ? inBatchImage.get(input.docId)\n : await this.#readPreImage(args.logPrefix, input.collection, input.docId, args.seq);\n staleKeys = allIndexKeysFor(args.logPrefix, this.#indexes, preImage, input.docId);\n }\n } catch {\n ctxMetrics().counter(\"db.write.index_cleanup_errors_total\", 1, {\n collection: input.collection,\n step: \"pre-image-read\",\n });\n inBatchImage.set(input.docId, input.op === \"D\" ? undefined : input.body);\n continue;\n }\n\n // (op:\"I\" has no pre-image → no stale keys.)\n for (const k of staleKeys) {\n indexDeletes.push(\n this.#storage.delete(k).catch(() => {\n ctxMetrics().counter(\"db.write.index_cleanup_errors_total\", 1, {\n collection: input.collection,\n step: \"delete\",\n });\n }),\n );\n }\n staleKeysClassA += staleKeys.length;\n inBatchImage.set(input.docId, input.op === \"D\" ? undefined : input.body);\n }\n await Promise.all(indexDeletes);\n return staleKeysClassA;\n }\n\n /**\n * Read the pre-image content body for a doc by walking the live log\n * backwards from `currentNextSeq` looking for the most-recent I/U\n * entry on this `(collection, docId)`. Returns `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 the\n * doc has been folded into the snapshot but is no longer\n * referenced).\n *\n * Used ONLY by the index-emission path's stale-key half (Step 5b, on\n * `U` / `D`) to compute which OLD-value keys to DELETE. Bounded by\n * `log_seq_start`: entries below have been folded into the snapshot\n * and may already be swept off the bucket — a snapshot fold is the\n * rebuild command's job (see `./rebuild-index.ts`), not the writer's.\n *\n * **Cost note:** linear walk, O(snapshot lag). For helpdesk-shape\n * collections (100s of docs, <10k log entries) this is fine — the\n * compactor folds the live tail every ~100 entries\n * (`packages/server/src/compactor.ts`). A follow-up ticket caches\n * per-doc index head in `current.json` for O(1) lookup.\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 = logObjectKey(logPrefix, s);\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 for `commit`. `classAOps` is the per-attempt base plus\n * a charge for prior failed attempts (the retry-budget cost model),\n * computed by the caller.\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 * 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 a log-create PUT failed transiently (a `NetworkError`) —\n * the write may or may not have landed (a dropped ack). Safe to retry\n * the SAME seq: own-session adoption closes the double-commit window if\n * it did land. NOT a 412 (that's handled by adoption directly).\n */\nconst isTransientWrite = (err: unknown): boolean =>\n err instanceof BaerlyError && err.code === \"NetworkError\";\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","/* 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`). Each mutation\n * verb compiles to exactly one `Writer.commit()` call.\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, loads the snapshot it names,\n * and walks `[log_seq_start, tail_hint)` directly — no cache, no\n * `list()` round-trip for the log. Per the multi-instance rules, every\n * 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 decides whether to re-run.\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 { assertDocId } from \"./doc-id.ts\";\nimport { encodeIndexValue, type IndexDefinition } from \"./indexes.ts\";\nimport { foldLogEntriesOnto, walkLogRange } from \"./log-walk.ts\";\nimport { probeTailFrom } from \"./log-tail.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 * Optional StandardSchemaV1-shaped validator for this collection.\n * When set, `runInsert`, `runUpdate`, and `runReplaceById` validate the\n * post-image before committing — 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\n * `\"<snapshot>@<tail>\"`. `tail` is the DISCOVERED tail (defaults to\n * `json.tail_hint` when no probe has run). `null` snapshots stringify\n * as {@link MANIFEST_POINTER_EMPTY_SNAPSHOT}.\n *\n * @internal — exported for `query.test.ts`.\n */\nexport const serializeManifestPointer = (json: CurrentJson, tail = json.tail_hint): string =>\n `${json.snapshot ?? MANIFEST_POINTER_EMPTY_SNAPSHOT}@${tail}`;\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 // Guard the resolved id at the write origin — the only place a\n // user-controlled `_id` enters as a WRITTEN key segment. Minted\n // UUIDv7 always passes, so guarding unconditionally also documents\n // the invariant. The `_id` analogue of `assertKeySegment` (`db.ts`).\n assertDocId(_id);\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.\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 // The collision check defends against a doc ALREADY committed to\n // 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 // 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: each affected row commits independently — the document is the\n * atomic unit; there is no multi-row batch.\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 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 loop 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 await writerFor(ctx).commit({\n op: \"U\",\n collection: ctx.collectionName,\n docId: String(doc[\"_id\"]),\n body: merged,\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. 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 // Guard the caller-supplied id before it becomes a written key\n // segment (index keys, log `doc_id`). Same boundary as `runInsert`.\n assertDocId(id);\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`. An invalid replace throws before the commit fires.\n if (ctx.schema !== undefined) {\n await validateOrThrow(ctx.schema, body, {\n collection: ctx.collectionName,\n verb: \"replace\",\n });\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`. The document is the atomic unit; there is no\n * multi-row batch.\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 let deleted = 0;\n for (const doc of rows) {\n await writerFor(ctx).commit({\n op: \"D\",\n collection: ctx.collectionName,\n docId: String(doc[\"_id\"]),\n });\n deleted++;\n }\n return { deleted };\n};\n\n/**\n * Load `current.json` fresh, walk `[log_seq_start, tail_hint)` 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 `[log_seq_start, tail_hint)` → `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 // 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. A\n // not-found head still emits a well-defined cursor so the wire shape\n // never carries `\"\"`.\n if (head === null) {\n return { rows: [], manifestPointer: `${MANIFEST_POINTER_EMPTY_SNAPSHOT}@0`, 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 const walk = await runIndexWalkPlan<T>(ctx, head.json, state, plan);\n let rows = walk.rows;\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: serializeManifestPointer(head.json, walk.tail), 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 hint = head.json.tail_hint;\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. Strict walk [log_seq_start, tail_hint) + tolerant ──────\n // forward-probe [max(log_seq_start, tail_hint), tail). Strict range is\n // dense (a hole is corruption → `walkLogRange` THROWS); the probe\n // stops at the first 404 and its entries fold through the SAME path as\n // the strict walk. The probe floor is `max(log_seq_start, tail_hint)`:\n // under single-write commit `tail_hint` is only a lower bound, so a\n // compactor that advanced `log_seq_start` past a stale `tail_hint`\n // must NOT have its folded entries re-read by the probe.\n const probeFrom = Math.max(logSeqStart, hint);\n const entries = await walkLogRange(ctx.storage, ctx.collectionPrefix, logSeqStart, hint);\n const probe = await probeTailFrom(ctx.storage, ctx.collectionPrefix, probeFrom);\n const tail = probe.tail;\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 foldLogEntriesOnto(docs, probe.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: serializeManifestPointer(head.json, tail), 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<{ rows: T[]; tail: number }> => {\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 // Discover the true tail once (probe runs even with no matches so\n // the manifest pointer still reflects it). Strict range stays\n // `[log_seq_start, tail_hint)`; the probe folds `[max(log_seq_start,\n // tail_hint), tail)` — see the floor rationale in `runRead`.\n const logSeqStart = logSeqStartOf(head);\n const hint = head.tail_hint;\n const probe = await probeTailFrom(ctx.storage, ctx.collectionPrefix, Math.max(logSeqStart, hint));\n const tail = probe.tail;\n\n const docIds = Array.from(docIdSet);\n if (docIds.length === 0) {\n return { rows: [], tail };\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 entries = await walkLogRange(ctx.storage, ctx.collectionPrefix, logSeqStart, hint);\n foldLogEntriesOnto(docs, entries, { collection: ctx.collectionName, docIdFilter: matched });\n foldLogEntriesOnto(docs, probe.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, tail };\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,IAAI,UAAU,KAAA,GACZ,OAAO;CAET,IAAI,UAAU,MACZ;CAIF,IAAI,CAAC,cAAc,KAAsB,GACvC,OAAO;CAGT,IAAI,CAAC,cAAc,MAAM,GACvB,OAAO;CAGT,MAAM,WAAW,EAAE,GAAI,OAAwB;CAC/C,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GAAsC;EAKvE,IAAI,qBAAqB,IAAI,GAAG,GAC9B;EAEF,IAAI,MAAM,SAAS,MACjB,OAAO,SAAS;OAEhB,SAAS,OAAO,MAAM,OAAO,MAAuB,MAAM,IAAqB;CAKnF;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACtCA,MAAa,uBAAuB,GAAkB,MAAoC;CACxF,MAAM,SAAwB,EAAE,SAAS,CAAC,GAAG,EAAE,SAAS,GAAG,EAAE,OAAO,EAAE;CACtE,sBAAsB,MAAM;CAC5B,OAAO;AACT;;;;;;;ACZA,MAAa,aAAmB,OAAO,WAAW;;;;;;;;;;;;;;;;AAiBlD,MAAa,eAAqB;C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B,EAAE;GACrC,MAAM,KAA6B,EAAE;GACrC,IAAI,OAAO,IACT;GAIF,IAAI,OAAO,KAAA,GACT,OAAO,QAAQ,SAAS,IAAI;GAE9B,IAAI,OAAO,KAAA,GACT,OAAO,QAAQ,SAAS,KAAK;GAK/B,IAAI,OAAO,OAAO,YAAY,OAAO,OAAO,UAC1C;GAEF,MAAM,MAAM,KAAK,KAAK,KAAK;GAC3B,OAAO,QAAQ,SAAS,CAAC,MAAM;EACjC;EACA,OAAO;CACT,CAAC;AACH"}
@@ -1,7 +1,7 @@
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";
1
+ import { n as loadCollectionIndexes, r as parseBucketUri } from "./config-CGyBopy3.js";
2
+ import { i as rebuildIndex } from "./maintenance-C_KSkVjd.js";
4
3
  import { o as BaerlyError, r as emitSuccess } from "./baerly.js";
4
+ import { n as defineBaerlySubcommand, t as assertCollectionArg } from "./subcommand-CP9NY2J4.js";
5
5
  //#region src/admin/rebuild-index.ts
6
6
  /** citty arg shape. Kebab-case so --help and parsed-object keys line up. */
7
7
  const REBUILD_INDEX_ARGS = {
@@ -68,6 +68,7 @@ const bundle = defineBaerlySubcommand({
68
68
  args: REBUILD_INDEX_ARGS,
69
69
  handler: async (args, ctx) => {
70
70
  const bucket = await parseBucketUri(args.bucket);
71
+ assertCollectionArg(args.collection, "baerly admin rebuild-index");
71
72
  const on = args.config !== void 0 && args.config.length > 0 ? await onFieldFromConfig(args.config, args.collection, args.index) : args.on;
72
73
  if (on === void 0 || on.length === 0) throw new BaerlyError("InvalidConfig", "baerly admin rebuild-index: --on=<field> (or --config=<path>) is required");
73
74
  const def = {
@@ -100,4 +101,4 @@ bundle.run;
100
101
  //#endregion
101
102
  export { rebuildIndexCmd };
102
103
 
103
- //# sourceMappingURL=rebuild-index-DC_nR6wP.js.map
104
+ //# sourceMappingURL=rebuild-index-DP4CqSSs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rebuild-index-DP4CqSSs.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 { assertCollectionArg, 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 assertCollectionArg(args.collection, \"baerly admin rebuild-index\");\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;E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