@gusto/baerly-storage 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -124
- package/dist/API.md +161 -512
- package/dist/CHANGELOG.md +1137 -378
- package/dist/RECIPES.md +398 -80
- package/dist/THIRD-PARTY-LICENSES.txt +5 -26
- package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
- package/dist/app-config.d.ts +31 -1
- package/dist/app-config.js +1 -2
- package/dist/app-config.js.map +1 -1
- package/dist/auth.d.ts +33 -28
- package/dist/auth.js +549 -985
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +130 -138
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +97 -22
- package/dist/capacity-warning-header-BlVopyiI.js +16 -0
- package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
- package/dist/{client-ypCm3zjt.d.ts → client-CHQTXpef.d.ts} +121 -36
- package/dist/client-react.d.ts +67 -20
- package/dist/client-react.js +240 -54
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +5 -4
- package/dist/client.js +51 -16
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-wrVYf4bb.js → cloudflare-CKHYXccw.js} +61 -82
- package/dist/cloudflare-CKHYXccw.js.map +1 -0
- package/dist/cloudflare.d.ts +106 -71
- package/dist/cloudflare.js +334 -271
- package/dist/cloudflare.js.map +1 -1
- package/dist/code-resolution-CL_7L0wS.js +22 -0
- package/dist/code-resolution-CL_7L0wS.js.map +1 -0
- package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
- package/dist/config-DEzInG6M.js +4035 -0
- package/dist/config-DEzInG6M.js.map +1 -0
- package/dist/constants-D3GSH3tc.js +469 -0
- package/dist/constants-D3GSH3tc.js.map +1 -0
- package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
- package/dist/context-rlpSnHFA.js.map +1 -0
- package/dist/cost-B52llVDx.js +330 -0
- package/dist/cost-B52llVDx.js.map +1 -0
- package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
- package/dist/current-json-CC6lE4Aj.js.map +1 -0
- package/dist/db-plFUNTSF.d.ts +130 -0
- package/dist/db-read-seams-BSs0m1z1.js +3261 -0
- package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
- package/dist/{deploy-Di_Q01qx.js → deploy-Obj4nE-Z.js} +10 -14
- package/dist/deploy-Obj4nE-Z.js.map +1 -0
- package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
- package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
- package/dist/dev-landing-CD-si4dW.js +50 -0
- package/dist/dev-landing-CD-si4dW.js.map +1 -0
- package/dist/dev-vite.d.ts +9 -14
- package/dist/dev-vite.js +11 -10
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +3 -2
- package/dist/dev.js +2 -1
- package/dist/doctor-BA0i-YAN.js +270 -0
- package/dist/doctor-BA0i-YAN.js.map +1 -0
- package/dist/dump-D1vX8ozg.js +133 -0
- package/dist/dump-D1vX8ozg.js.map +1 -0
- package/dist/errors-7Rk1HGCE.js +160 -0
- package/dist/errors-7Rk1HGCE.js.map +1 -0
- package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
- package/dist/export-BVL2EvYE.js.map +1 -0
- package/dist/fsck-BWkPgov4.js +145 -0
- package/dist/fsck-BWkPgov4.js.map +1 -0
- package/dist/{gcs-admin-Bx6xSNJj.d.ts → gcs-admin-Dso1HWQj.d.ts} +18 -14
- package/dist/gcs.d.ts +19 -7
- package/dist/gcs.js +1 -2
- package/dist/{goog4-signer-Z7KnJ1su.js → goog4-signer-CeLIABoE.js} +102 -92
- package/dist/goog4-signer-CeLIABoE.js.map +1 -0
- package/dist/{http-7zT29K3P.js → http-Z5rZyYMX.js} +898 -271
- package/dist/http-Z5rZyYMX.js.map +1 -0
- package/dist/http-transport-DNUM8kU-.js +1299 -0
- package/dist/http-transport-DNUM8kU-.js.map +1 -0
- package/dist/http.d.ts +366 -294
- package/dist/http.js +2 -2
- package/dist/index-JJrIu1pO.d.ts +135 -0
- package/dist/index-LEgHN0qJ.d.ts +50 -0
- package/dist/{index-DP3ClvcA.d.ts → index-RiEYj8t0.d.ts} +291 -78
- package/dist/index.d.ts +27 -6
- package/dist/index.js +3 -5
- package/dist/inspect-BTsVYZKd.js +196 -0
- package/dist/inspect-BTsVYZKd.js.map +1 -0
- package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
- package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
- package/dist/ledger-Dj_bGgo0.js +192 -0
- package/dist/ledger-Dj_bGgo0.js.map +1 -0
- package/dist/legacy-names-DgZBtgOh.js +47 -0
- package/dist/legacy-names-DgZBtgOh.js.map +1 -0
- package/dist/log-C9W15Dfo.d.ts +94 -0
- package/dist/log-tail-DWJbneBF.js +142 -0
- package/dist/log-tail-DWJbneBF.js.map +1 -0
- package/dist/log-walk-C-vA-WGJ.js +111 -0
- package/dist/log-walk-C-vA-WGJ.js.map +1 -0
- package/dist/maintenance-Dd-Yakqj.js +1709 -0
- package/dist/maintenance-Dd-Yakqj.js.map +1 -0
- package/dist/maintenance-DevB6z4e.js +2237 -0
- package/dist/maintenance-DevB6z4e.js.map +1 -0
- package/dist/maintenance.d.ts +100 -3
- package/dist/maintenance.js +1 -3
- package/dist/node.d.ts +119 -92
- package/dist/node.js +3 -3
- package/dist/{observability-Ch-VQJyE.js → observability-C-ISCCLE.js} +1247 -326
- package/dist/observability-C-ISCCLE.js.map +1 -0
- package/dist/observability.d.ts +27 -3
- package/dist/observability.js +3 -3
- package/dist/path-segment-DBXG26PW.js +363 -0
- package/dist/path-segment-DBXG26PW.js.map +1 -0
- package/dist/{plan-C4qgiXSg.js → plan-BvQbaNMe.js} +19 -11
- package/dist/plan-BvQbaNMe.js.map +1 -0
- package/dist/request-CRWiTrza.js +272 -0
- package/dist/request-CRWiTrza.js.map +1 -0
- package/dist/restore-U6Im8V1V.js +1467 -0
- package/dist/restore-U6Im8V1V.js.map +1 -0
- package/dist/retry-OBtLB2GC.js +126 -0
- package/dist/retry-OBtLB2GC.js.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
- package/dist/{runtime-spec--LykAdl1.js → runtime-spec-B5mg3pHF.js} +189 -28
- package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
- package/dist/{s3-http-DD5gDc7t.d.ts → s3-http-DBC_wiCL.d.ts} +14 -8
- package/dist/s3.d.ts +20 -7
- package/dist/s3.js +4 -5
- package/dist/s3.js.map +1 -1
- package/dist/{sha256-CqcKTjw9.js → sha256-4FfGQNPw.js} +9 -9
- package/dist/sha256-4FfGQNPw.js.map +1 -0
- package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
- package/dist/shared-secret-Vkur-8r0.js.map +1 -0
- package/dist/{aws4fetch.esm-CXE5ZbAa.js → sigv4-sign-5IUflUD_.js} +143 -96
- package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
- package/dist/snapshot-CknzkDM0.js +148 -0
- package/dist/snapshot-CknzkDM0.js.map +1 -0
- package/dist/{src-BMFfDUI2.js → src-Actga-bO.js} +949 -363
- package/dist/src-Actga-bO.js.map +1 -0
- package/dist/src-D0MQfvOp.js +812 -0
- package/dist/src-D0MQfvOp.js.map +1 -0
- package/dist/src-Dr9uo3dc.js +501 -0
- package/dist/src-Dr9uo3dc.js.map +1 -0
- package/dist/{subcommand-BV68pqwJ.js → subcommand-BLoF66dG.js} +89 -16
- package/dist/subcommand-BLoF66dG.js.map +1 -0
- package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
- package/dist/time-DRxTP9iv.js.map +1 -0
- package/dist/types-suVbsEWS.d.ts +116 -0
- package/dist/{usage-BMZR8o6U.js → usage-CPzVhrQr.js} +40 -45
- package/dist/usage-CPzVhrQr.js.map +1 -0
- package/dist/uuid-BuT_c404.js +333 -0
- package/dist/uuid-BuT_c404.js.map +1 -0
- package/dist/verifier-Bmlmndzo.d.ts +95 -0
- package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
- package/dist/wire-DndvKU-K.js.map +1 -0
- package/package.json +90 -69
- package/dist/aws4fetch.esm-CXE5ZbAa.js.map +0 -1
- package/dist/bytes-BXdamO3L.js +0 -11
- package/dist/bytes-BXdamO3L.js.map +0 -1
- package/dist/cloudflare-wrVYf4bb.js.map +0 -1
- package/dist/config-B6nTy8e2.js +0 -3095
- package/dist/config-B6nTy8e2.js.map +0 -1
- package/dist/constants-CfeMWQWk.js +0 -222
- package/dist/constants-CfeMWQWk.js.map +0 -1
- package/dist/context-DRZ3tZ5l.js.map +0 -1
- package/dist/cost-_SE_SVgZ.js +0 -203
- package/dist/cost-_SE_SVgZ.js.map +0 -1
- package/dist/current-json-C6nhPOm1.js.map +0 -1
- package/dist/db-DjjthkTi.d.ts +0 -254
- package/dist/deploy-Di_Q01qx.js.map +0 -1
- package/dist/doctor-RWVRpvat.js +0 -102
- package/dist/doctor-RWVRpvat.js.map +0 -1
- package/dist/dump-m2vEYDNY.js +0 -94
- package/dist/dump-m2vEYDNY.js.map +0 -1
- package/dist/errors-Dfa3p78c.js +0 -78
- package/dist/errors-Dfa3p78c.js.map +0 -1
- package/dist/export-DenKwEQu.js +0 -401
- package/dist/export-DenKwEQu.js.map +0 -1
- package/dist/fsck-2Vq-7-e2.js +0 -279
- package/dist/fsck-2Vq-7-e2.js.map +0 -1
- package/dist/goog4-signer-Z7KnJ1su.js.map +0 -1
- package/dist/http-7zT29K3P.js.map +0 -1
- package/dist/http-transport-BTgVCY5r.js +0 -1250
- package/dist/http-transport-BTgVCY5r.js.map +0 -1
- package/dist/index-BHz92Acj.d.ts +0 -162
- package/dist/index-CEZKQsKt.d.ts +0 -1113
- package/dist/index-uE-w2dgj.d.ts +0 -115
- package/dist/indexes-Dn9hbGQG.d.ts +0 -22
- package/dist/inspect-BpYbH1DM.js +0 -133
- package/dist/inspect-BpYbH1DM.js.map +0 -1
- package/dist/log-tail-QWU4wlu-.js +0 -514
- package/dist/log-tail-QWU4wlu-.js.map +0 -1
- package/dist/maintenance-BGHGt2Yg.d.ts +0 -537
- package/dist/maintenance-DULFcpd1.js +0 -2144
- package/dist/maintenance-DULFcpd1.js.map +0 -1
- package/dist/maintenance-fEi-UZ2o.js +0 -1412
- package/dist/maintenance-fEi-UZ2o.js.map +0 -1
- package/dist/normalize-rjnZLwS4.js +0 -133
- package/dist/normalize-rjnZLwS4.js.map +0 -1
- package/dist/observability-Ch-VQJyE.js.map +0 -1
- package/dist/plan-C4qgiXSg.js.map +0 -1
- package/dist/query-C43r-6ib.js +0 -1773
- package/dist/query-C43r-6ib.js.map +0 -1
- package/dist/rebuild-index-BH1dc1p6.js +0 -81
- package/dist/rebuild-index-BH1dc1p6.js.map +0 -1
- package/dist/request-u0M51mhJ.js +0 -72
- package/dist/request-u0M51mhJ.js.map +0 -1
- package/dist/restore-D0VYWzfP.js +0 -778
- package/dist/restore-D0VYWzfP.js.map +0 -1
- package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
- package/dist/runtime-spec--LykAdl1.js.map +0 -1
- package/dist/sha256-CqcKTjw9.js.map +0 -1
- package/dist/shared-secret-DgEicd3x.js.map +0 -1
- package/dist/src-BMFfDUI2.js.map +0 -1
- package/dist/src-DYZ4H1aF.js +0 -392
- package/dist/src-DYZ4H1aF.js.map +0 -1
- package/dist/src-DvbTEya2.js +0 -536
- package/dist/src-DvbTEya2.js.map +0 -1
- package/dist/subcommand-BV68pqwJ.js.map +0 -1
- package/dist/time-DUqvFMHq.js.map +0 -1
- package/dist/usage-BMZR8o6U.js.map +0 -1
- package/dist/validate-DtljsCh1.js.map +0 -1
- package/dist/wire-izfGZDvr.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"db-read-seams-BSs0m1z1.js","names":[],"sources":["../packages/protocol/src/document-size.ts","../packages/protocol/src/json.ts","../packages/protocol/src/query/matches.ts","../packages/protocol/src/query/_internals.ts","../packages/protocol/src/query/satisfiable.ts","../packages/protocol/src/query/merge.ts","../packages/protocol/src/query/validate.ts","../packages/server/src/doc-id.ts","../packages/server/src/capacity.ts","../packages/server/src/query-eval.ts","../packages/server/src/read-admission.ts","../packages/server/src/schema.ts","../packages/server/src/key-limit.ts","../packages/server/src/log-conflict-adoption.ts","../packages/server/src/post-image-identity.ts","../packages/server/src/writer.ts","../packages/server/src/query.ts","../packages/server/src/db-read-seams.ts"],"sourcesContent":["import { MAX_DOCUMENT_BYTES } from \"./constants.ts\";\nimport { BaerlyError } from \"./errors.ts\";\n\nconst utf8Encoder = new TextEncoder();\n\n// Kept apart from `document-input.ts`: the HTTP client bundles that module\n// for its pre-send value check, and the size cap is the server's to enforce.\nconst DOCUMENT_SIZE_RESOLUTION = `Keep each document at or under ${MAX_DOCUMENT_BYTES} bytes (1 MiB) of JSON: move large or growing data (attachments, long histories, arrays that keep growing) into rows of their own, or store blobs outside the database and keep a reference.`;\n\n/**\n * UTF-8 byte length of `json` when it is over `limit`, else `undefined`.\n * Skips the encode when the string is short enough to decide it: a UTF-16\n * code unit encodes to at most 3 bytes.\n */\nconst jsonByteLengthAbove = (json: string, limit: number): number | undefined => {\n if (json.length * 3 <= limit) {\n return undefined;\n }\n const bytes = utf8Encoder.encode(json).byteLength;\n return bytes > limit ? bytes : undefined;\n};\n\n/**\n * Refuse a post-image larger than {@link MAX_DOCUMENT_BYTES} once encoded\n * as stored (`encodeJsonBytes`, which sorts nothing, so key order does not\n * change the size). Call it on the whole document a write would commit,\n * not on an update patch: a small patch can still grow a row past the cap.\n * A row already stored larger is not checked here; only a write producing\n * an over-cap post-image is refused.\n *\n * I/O-free. The value must already be in the JSON document domain (see\n * `assertDocumentValues`); a value `JSON.stringify` cannot encode\n * throws its own error.\n *\n * @param verb the calling verb, used as the message prefix.\n * @throws BaerlyError code=\"InvalidConfig\" — the encoded post-image is over\n * the cap. The message states its size and the limit.\n */\nexport const assertDocumentSize = (value: unknown, verb: string): void => {\n const bytes = jsonByteLengthAbove(JSON.stringify(value), MAX_DOCUMENT_BYTES);\n if (bytes !== undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${verb}: the document encodes to ${bytes} bytes of JSON, over the ${MAX_DOCUMENT_BYTES}-byte (1 MiB) document limit`,\n { resolution: DOCUMENT_SIZE_RESOLUTION },\n );\n }\n};\n","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-storage'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-storage 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\n/**\n * The patch an `update` takes for a row of type `T`: a JSON Merge Patch\n * (RFC 7396), typed against the row.\n *\n * - Every key is optional; a key left out is left unchanged.\n * - An optional key also accepts `null`, which deletes the field.\n * A required key does not: remove it with `replace` instead.\n * - A required object member with a single object type accepts a nested\n * `MergePatch`, merged field by field. Union-valued members require a\n * whole value because the current value may belong to another variant.\n * - An optional plain-object member takes its whole value or `null`,\n * never a nested patch: to change part of an optional object, pass\n * the whole object or use `replace`.\n * - Arrays and scalars replace the stored value whole; array elements\n * are never merged.\n *\n * Supplying a whole object still merges its fields; use `replace` to\n * discard existing fields. Values must be plain JSON at runtime; this\n * structural type cannot distinguish data-only classes from interfaces.\n *\n * On an unbound collection (`T` is `DocumentData`) every key is\n * optional, so any field accepts a value, a nested patch or `null`.\n *\n * @example\n * ```ts\n * type Ticket = {\n * title: string;\n * note?: string;\n * meta: { owner: string; reviewer?: string };\n * extra?: { flag?: boolean };\n * };\n *\n * const patch: MergePatch<Ticket> = {\n * note: null, // deletes `note`\n * meta: { reviewer: null }, // merges into the required `meta`\n * extra: { flag: true }, // supplies the whole optional object\n * };\n * // @ts-expect-error — `title` is required; use `replace` to remove it\n * const bad: MergePatch<Ticket> = { title: null };\n * ```\n */\nexport type MergePatch<T> = {\n [K in keyof T]?: string extends K\n ? MergePatchObjectValue<T[K]> | null\n : {} extends Pick<T, K>\n ? T[K] | null\n : MergePatchValue<T[K]>;\n};\n\n/**\n * Only a single object type guarantees that required nested fields\n * already exist. A union may switch variants, so it takes a whole value.\n */\ntype MergePatchValue<V> = true extends IsUnion<V> ? V : MergePatchObjectValue<V>;\n\ntype IsUnion<T, Whole = T> = T extends Whole ? ([Whole] extends [T] ? false : true) : never;\n\n/** Index-signature values stay permissive, including nested patches. */\ntype MergePatchObjectValue<V> = V extends readonly unknown[]\n ? V\n : V extends object\n ? MergePatch<V>\n : V;\n\nexport type JSONObject = { [x: string]: JSONValue };\nexport type JSONValue = string | number | boolean | null | JSONObject | Array<JSONValue>;\n\n/**\n * Structural equality of two JSON values.\n *\n * Both inputs must already be JSON-normalized, i.e. the result of a\n * `JSON.parse` — typically `JSON.parse(JSON.stringify(body))` compared\n * against a stored row decoded from JSON. The round-trip drops\n * `undefined` properties (as the write path's encoder does) and turns\n * `-0` into `0`; that normalization is the caller's responsibility.\n * Raw inputs holding `undefined` or `-0` are outside the contract.\n *\n * Uses an explicit work stack so comparison does not consume the\n * JavaScript call stack with each nesting level. No depth cap is enforced.\n *\n * - Object key order is ignored; the key sets must match exactly.\n * - Arrays compare element-wise in order, and an array is never equal\n * to an object (`[1]` vs `{\"0\":1}` is `false`).\n * - Primitives compare with `===`.\n *\n * Deliberately not `deepEqualDocumentValue`, which cannot tell an array\n * from an index-keyed object.\n */\nexport function jsonValueEqual(a: JSONValue, b: JSONValue): boolean {\n const pending: Array<[JSONValue, JSONValue]> = [[a, b]];\n while (pending.length > 0) {\n const [left, right] = pending.pop()!;\n if (left === right) {\n continue;\n }\n if (typeof left !== \"object\" || typeof right !== \"object\" || left === null || right === null) {\n return false;\n }\n if (Array.isArray(left)) {\n if (!Array.isArray(right) || left.length !== right.length) {\n return false;\n }\n // Indexed loop, not `every`: `every` skips holes, which would make a\n // sparse array compare asymmetrically.\n for (let i = 0; i < left.length; i++) {\n pending.push([left[i]!, right[i]!]);\n }\n continue;\n }\n if (Array.isArray(right)) {\n return false;\n }\n const keys = Object.keys(left);\n if (keys.length !== Object.keys(right).length) {\n return false;\n }\n for (const key of keys) {\n if (!Object.prototype.hasOwnProperty.call(right, key)) {\n return false;\n }\n pending.push([left[key]!, right[key]!]);\n }\n }\n return true;\n}\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 * Apply a JSON Merge Patch to a document, exactly as RFC 7396 §2 defines\n * it. This is what `update` commits: `applyMergePatch(row, patch)`.\n *\n * An object patch merges key by key into the target, or into `{}` when\n * the target is absent or not an object. A `null` member deletes that\n * key, at every depth, so a patch never stores a `null` member: under an\n * absent field, `{ meta: { a: 1, b: null } }` stores `meta: { a: 1 }`.\n * A scalar or array patch replaces the target whole; arrays are opaque\n * values, so a `null` inside one is kept. An `undefined` member is\n * absent, as in the patch's JSON form.\n *\n * Two values outside RFC 7396's JSON domain: an `undefined` patch is the\n * identity (returns `target`), and a `null` patch at the root returns\n * `undefined`, since a document cannot be `null`.\n *\n * `__proto__`, `constructor` and `prototype` members are skipped\n * (`FORBIDDEN_MERGE_KEYS`). Recursion follows the patch, whose depth\n * `assertDocumentValues` caps at `MAX_DOCUMENT_DEPTH` before `update`\n * applies it.\n */\nexport function applyMergePatch<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 if (!isPlainObject(patch as DocumentValue)) {\n return patch as T;\n }\n // An absent or non-object target merges as `{}` (RFC 7396 §2).\n const combined: DocumentData = isPlainObject(target) ? { ...target } : {};\n const members = patch as Record<string, DocumentValue | null | undefined>;\n for (const key of Object.keys(members)) {\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 const value = members[key];\n if (value === undefined) {\n continue;\n }\n if (value === null) {\n delete combined[key];\n } else {\n combined[key] = applyMergePatch(combined[key], value)!;\n }\n }\n return combined as T;\n}\n\n/**\n * Coalesce two merge patches into one: the summary patch for `earlier`\n * followed by `later`. Folding from `undefined`,\n * `fold(coalesceMergePatches, undefined, patches)` summarizes a window.\n *\n * Unlike {@link applyMergePatch}, an object patch over an absent or\n * non-object accumulator is taken as written, nulls included, so\n * `coalesceMergePatches(undefined, { x: null })` keeps the delete as\n * `{ x: null }`. The summary is exact only inside the type-stable window\n * `docs/spec/json-merge-patch.md` (\"Log can be coalesced\") describes: a\n * `later` delete of a key `earlier` set removes it from the summary, and\n * a delete followed by an object re-add cannot be expressed. No runtime\n * path coalesces patches today; `update` commits full post-images.\n */\nexport function coalesceMergePatches<T extends DocumentValue>(\n earlier: T | undefined,\n later: Partial<T> | null | undefined,\n): T | undefined {\n if (later === undefined) {\n return earlier;\n }\n if (later === null) {\n return undefined;\n }\n\n // Later patch is primitive or an array → replace wholesale.\n if (!isPlainObject(later as DocumentValue)) {\n return later as T;\n }\n // Later patch is a plain object but the accumulator isn't → take it\n // as written, so its deletes survive.\n if (!isPlainObject(earlier)) {\n return later as T;\n }\n\n const combined = { ...(earlier as DocumentData) } as T;\n for (const key of Object.keys(later) as Array<Extract<keyof T, string>>) {\n if (FORBIDDEN_MERGE_KEYS.has(key)) {\n continue;\n }\n if (later[key] === null) {\n delete combined[key];\n } else {\n combined[key] = coalesceMergePatches(\n earlier[key] as DocumentValue,\n later[key] as DocumentValue,\n ) as T[Extract<keyof T, string>];\n }\n }\n return combined as T;\n}\n","/**\n * Wire predicate evaluator. Walks a validated {@link PredicateWire}\n * against a `JSONObject` document and returns `true` iff every\n * clause holds. Multiple clauses across all fields AND together.\n *\n * Pre-condition: `wire` must have been returned by\n * {@link validateWire} (see `./validate.ts`). Passing an\n * un-validated wire is a caller bug; behaviour is undefined.\n *\n * Companion modules: `./validate.ts` (construction-time check),\n * `./merge.ts` (AND-merge), `./wire.ts` (types).\n */\n\nimport type { DocumentValue, JSONObject, JSONValue } from \"../json.ts\";\n\nimport type { PredicateClause, PredicateWire } from \"./wire.ts\";\n\n/**\n * Evaluate a validated wire-form predicate against a `JSONObject`\n * document. Returns `true` iff every clause holds.\n *\n * @example\n * ```ts\n * matchesWire(\n * { clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] },\n * { status: \"open\", priority: \"p1\" },\n * ); // true\n *\n * matchesWire(\n * { clauses: [{ op: \"in\", field: \"priority\", value: [\"p1\", \"p2\"] }] },\n * { priority: \"p3\" },\n * ); // false\n *\n * matchesWire(\n * {\n * clauses: [\n * { op: \"gte\", field: \"count\", value: 1 },\n * { op: \"lt\", field: \"count\", value: 10 },\n * ],\n * },\n * { count: 5 },\n * ); // true\n * ```\n */\nexport const matchesWire = (wire: PredicateWire, doc: JSONObject): boolean => {\n for (const clause of wire.clauses) {\n const actual = lookupPath(doc, clause.field);\n if (!matchesClause(clause, actual)) {\n return false;\n }\n }\n return true;\n};\n\nconst lookupPath = (doc: JSONObject, field: string): JSONValue | undefined =>\n // Fast path: no dot → top-level lookup. Avoids allocating a split\n // array for the common case.\n // Stryker disable next-line StringLiteral,ConditionalExpression: fast-path equivalence — for any valid field, the slow split-and-traverse path produces the same result; the fast path is a performance optimisation only\n field.includes(\".\") ? walkPath(doc, field.split(\".\")) : doc[field];\n\n/** Follow a split dotted path from `doc`; `undefined` when it cannot be consumed. */\nconst walkPath = (doc: JSONObject, segments: readonly string[]): JSONValue | undefined => {\n let cursor: JSONValue | undefined = doc;\n for (const segment of segments) {\n if (\n // Stryker disable next-line ConditionalExpression: redundant guard — cursor===undefined is always caught by the typeof check on the next line (typeof undefined!==\"object\" is true); removing this check is observationally equivalent\n cursor === undefined ||\n cursor === null ||\n // Stryker disable next-line ConditionalExpression: redundant guard — for non-object primitives, (primitive as JSONObject)[segment] returns undefined; the next iteration's cursor===undefined check catches it; removing this check produces the same return value\n typeof cursor !== \"object\" ||\n Array.isArray(cursor)\n ) {\n // Traversal hit a primitive, null, missing key, or array\n // before consuming the path. Predicate cannot match.\n return undefined;\n }\n cursor = (cursor as JSONObject)[segment];\n }\n return cursor;\n};\n\n/**\n * Compile a validated wire-form predicate into a per-document test that\n * agrees with {@link matchesWire} on every document. Each dotted clause\n * path is split once here rather than once per document, so a filter\n * over n rows pays one split per clause instead of n. Clause order,\n * path walk and clause matchers are {@link matchesWire}'s.\n *\n * Same pre-condition as {@link matchesWire}: `wire` has passed\n * {@link validateWire}.\n *\n * @example\n * ```ts\n * const open = compileWire({ clauses: [{ op: \"eq\", field: \"meta.state\", value: \"open\" }] });\n * docs.filter(open);\n * ```\n */\nexport const compileWire = (wire: PredicateWire): ((doc: JSONObject) => boolean) => {\n const compiled = wire.clauses.map((clause) => ({\n clause,\n field: clause.field,\n segments: clause.field.includes(\".\") ? clause.field.split(\".\") : undefined,\n }));\n return (doc) => {\n for (const { clause, field, segments } of compiled) {\n if (!matchesClause(clause, segments === undefined ? doc[field] : walkPath(doc, segments))) {\n return false;\n }\n }\n return true;\n };\n};\n\nconst matchesClause = (clause: PredicateClause, actual: JSONValue | undefined): boolean => {\n switch (clause.op) {\n case \"eq\": {\n return matchesEq(clause.value as DocumentValue, actual);\n }\n case \"in\": {\n return matchesIn(clause.value as ReadonlyArray<DocumentValue>, actual);\n }\n case \"gt\": {\n return compareGT(actual, clause.value as DocumentValue, false);\n }\n case \"gte\": {\n return compareGT(actual, clause.value as DocumentValue, true);\n }\n case \"lt\": {\n return compareLT(actual, clause.value as DocumentValue, false);\n }\n case \"lte\": {\n return compareLT(actual, clause.value as DocumentValue, true);\n }\n }\n};\n\nconst matchesEq = (expected: DocumentValue, actual: JSONValue | undefined): boolean => {\n if (typeof expected === \"object\") {\n // Nested object equality is a sub-predicate match — open-world:\n // doc may carry extra keys. The object-form normaliser flattens\n // nested sub-predicates to dotted-path clauses on the way in, so\n // the only callers reaching this branch are callback-form\n // `q.eq(\"nested\", { ... })`.\n if (\n // Stryker disable next-line ConditionalExpression: redundant guard — actual===undefined is caught by the typeof check below (typeof undefined!==\"object\" is true); removing this check produces the same false result\n actual === undefined ||\n actual === null ||\n typeof actual !== \"object\" ||\n Array.isArray(actual)\n ) {\n return false;\n }\n for (const subKey of Object.keys(expected)) {\n const subExpected = (expected as Record<string, DocumentValue>)[subKey];\n if (subExpected === undefined) {\n continue;\n }\n const subActual = (actual as JSONObject)[subKey];\n if (!matchesEq(subExpected, subActual)) {\n return false;\n }\n }\n return true;\n }\n return expected === actual;\n};\n\nconst matchesIn = (\n members: ReadonlyArray<DocumentValue>,\n actual: JSONValue | undefined,\n): boolean => {\n for (const m of members) {\n // Stryker disable next-line ConditionalExpression: equivalence — for non-null primitives, matchesEq(m, actual) reduces to `m === actual` (the typeof check fails); routing all members through matchesEq (→true) gives the same result as the two-branch structure\n if (typeof m === \"object\") {\n if (matchesEq(m, actual)) {\n return true;\n }\n } else if (m === actual) {\n return true;\n }\n }\n return false;\n};\n\nconst compareGT = (\n actual: JSONValue | undefined,\n bound: DocumentValue,\n inclusive: boolean,\n): boolean => {\n if (typeof bound === \"string\") {\n return typeof actual === \"string\" && (inclusive ? actual >= bound : actual > bound);\n }\n if (typeof bound === \"number\") {\n return typeof actual === \"number\" && (inclusive ? actual >= bound : actual > bound);\n }\n // Validator forbids boolean / null / object range bounds; defensive miss.\n return false;\n};\n\nconst compareLT = (\n actual: JSONValue | undefined,\n bound: DocumentValue,\n inclusive: boolean,\n): boolean => {\n if (typeof bound === \"string\") {\n return typeof actual === \"string\" && (inclusive ? actual <= bound : actual < bound);\n }\n if (typeof bound === \"number\") {\n return typeof actual === \"number\" && (inclusive ? actual <= bound : actual < bound);\n }\n return false;\n};\n","/**\n * Shared comparator helpers for the predicate algebra. `./satisfiable.ts`\n * is the only module that consumes them; none is re-exported from\n * `./index.ts`.\n */\n\nimport type { DocumentValue } from \"../json.ts\";\n\n/** @internal Same primitive type for comparison purposes. */\nexport const sameComparableType = (a: DocumentValue, b: DocumentValue): boolean =>\n (typeof a === \"string\" && typeof b === \"string\") ||\n (typeof a === \"number\" && typeof b === \"number\");\n\n/**\n * @internal Returns negative / zero / positive for a<b / a==b / a>b.\n */\nexport const compareScalar = (a: DocumentValue, b: DocumentValue): number => {\n if (typeof a === \"number\" && typeof b === \"number\") {\n return a - b;\n }\n if (typeof a === \"string\" && typeof b === \"string\") {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n }\n return 0;\n};\n\n/** @internal Render a predicate path for use in error messages. */\nexport const formatPath = (path: ReadonlyArray<string>): string =>\n path.length === 0 ? \"<root>\" : path.map((p) => JSON.stringify(p)).join(\".\");\n\n/**\n * Recursive structural equality for `DocumentValue` values. Exported so\n * `./satisfiable.ts` and other callers reuse the same comparison rule\n * the validator + merger already trust. Two\n * values `a` and `b` are equal iff:\n *\n * - they are reference-equal (covers primitives and object identity);\n * - or they are both non-`null` objects with the same key set, and\n * every value pair is recursively equal.\n *\n * Arrays are out-of-band for `DocumentValue`; this function rejects\n * them implicitly via the same key-set walk (an array reads as an\n * object with numeric-string keys plus a `length` exposure that\n * `Object.keys` happens to skip — defensive callers should still gate\n * with `Array.isArray` first).\n */\nexport const deepEqualDocumentValue = (a: DocumentValue, b: DocumentValue): boolean => {\n if (a === b) {\n return true;\n } // primitives + object identity\n if (typeof a !== \"object\" || typeof b !== \"object\") {\n return false;\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n for (const key of aKeys) {\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — a key in aKeys but absent from b makes b[key] undefined, which the `aSub === undefined || bSub === undefined` guard below catches identically; no input observes the difference.\n if (!(key in b)) {\n return false;\n }\n const aSub = (a as Record<string, DocumentValue>)[key];\n const bSub = (b as Record<string, DocumentValue>)[key];\n // Stryker disable next-line LogicalOperator,ConditionalExpression: equivalent — this guard is a redundant fast-path. Whichever way it is mutated (operator `||`→`&&`, or either `=== undefined` operand forced to false), a slot that is undefined still flows into deepEqualDocumentValue below, whose typeof check returns false for `(undefined, defined)`; the only case that reaches `true` is both-undefined, which the surviving sibling operand still catches. No input over 500k randomized DocumentValues observes a difference.\n if (aSub === undefined || bSub === undefined) {\n return false;\n }\n if (!deepEqualDocumentValue(aSub, bSub)) {\n return false;\n }\n }\n return true;\n};\n","/**\n * Per-field satisfiability check for a {@link PredicateWire}. Groups\n * clauses by field, then runs the same logic the pre-redesign\n * `assertOpObjectSatisfiable` ran on a single op-object — but\n * generalised across N clauses on the same field (the wire merger\n * concatenates lists without coalescing).\n *\n * Triggers:\n * - Two `eq` clauses on the same field with different values →\n * `InvalidConfig` (the same conflict that pre-redesign\n * `mergePredicates` threw on shared primitive keys).\n * - Range bounds with `lo > hi` (or `lo == hi` with strict on\n * either side) → `UnsatisfiablePredicate`.\n * - `eq` value outside the residual range interval or absent from\n * every `in` set on the same field → `UnsatisfiablePredicate`.\n * - `in` sets that intersect to empty across multiple clauses →\n * `UnsatisfiablePredicate`.\n *\n * Used by both `./validate.ts` (wire-arrival check) and\n * `./merge.ts` (post-merge re-check, kept in lockstep).\n */\n\nimport { BaerlyError } from \"../errors.ts\";\nimport type { DocumentValue } from \"../json.ts\";\n\nimport {\n compareScalar,\n deepEqualDocumentValue,\n formatPath,\n sameComparableType,\n} from \"./_internals.ts\";\nimport type { PredicateClause, PredicateWire } from \"./wire.ts\";\n\ninterface FieldGroup {\n readonly eqs: DocumentValue[];\n readonly ins: ReadonlyArray<DocumentValue>[];\n lo?: { value: DocumentValue; inclusive: boolean };\n hi?: { value: DocumentValue; inclusive: boolean };\n}\n\nconst groupByField = (wire: PredicateWire): Map<string, FieldGroup> => {\n const out = new Map<string, FieldGroup>();\n for (const clause of wire.clauses) {\n let group = out.get(clause.field);\n if (group === undefined) {\n group = { eqs: [], ins: [] };\n out.set(clause.field, group);\n }\n applyClause(group, clause.field, clause);\n }\n return out;\n};\n\nconst applyClause = (group: FieldGroup, field: string, clause: PredicateClause): void => {\n switch (clause.op) {\n case \"eq\": {\n group.eqs.push(clause.value as DocumentValue);\n return;\n }\n case \"in\": {\n group.ins.push(clause.value as ReadonlyArray<DocumentValue>);\n return;\n }\n case \"gt\": {\n tightenLower(group, field, clause.value as DocumentValue, false);\n return;\n }\n case \"gte\": {\n tightenLower(group, field, clause.value as DocumentValue, true);\n return;\n }\n case \"lt\": {\n tightenUpper(group, field, clause.value as DocumentValue, false);\n return;\n }\n case \"lte\": {\n tightenUpper(group, field, clause.value as DocumentValue, true);\n return;\n }\n }\n};\n\nconst tightenLower = (\n group: FieldGroup,\n field: string,\n value: DocumentValue,\n inclusive: boolean,\n): void => {\n if (group.lo === undefined) {\n group.lo = { value, inclusive };\n return;\n }\n if (!sameComparableType(group.lo.value, value)) {\n // Type-incompatible bounds on the same field — the user wrote\n // (say) `q.gt(\"x\", 1).gt(\"x\", \"a\")`. Range matching is type-\n // strict at evaluation time so this is always-miss; surface\n // eagerly as `UnsatisfiablePredicate`.\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has type-incompatible lower bounds (${JSON.stringify(group.lo.value)} vs ${JSON.stringify(value)}).`,\n );\n }\n const c = compareScalar(group.lo.value, value);\n // Stryker disable next-line ConditionalExpression: two sub-expression-to-true mutants are\n // equivalent. (1) `inclusive === false → true`: fires when c=0, existing=inclusive,\n // new=inclusive — tighten updates lo to {value, inclusive=true}, identical to the existing\n // {same value, inclusive=true}; no observable change. (2) `group.lo.inclusive === true → true`:\n // fires when c=0, new=exclusive, existing=exclusive — tighten updates lo to {value, false},\n // identical to existing {same value, false}; no observable change.\n if (c < 0 || (c === 0 && inclusive === false && group.lo.inclusive === true)) {\n group.lo = { value, inclusive };\n }\n};\n\nconst tightenUpper = (\n group: FieldGroup,\n field: string,\n value: DocumentValue,\n inclusive: boolean,\n): void => {\n if (group.hi === undefined) {\n group.hi = { value, inclusive };\n return;\n }\n if (!sameComparableType(group.hi.value, value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has type-incompatible upper bounds (${JSON.stringify(group.hi.value)} vs ${JSON.stringify(value)}).`,\n );\n }\n const c = compareScalar(group.hi.value, value);\n // Stryker disable next-line ConditionalExpression: two sub-expression-to-true mutants are\n // equivalent. (1) `inclusive === false → true`: fires when c=0, existing=inclusive,\n // new=inclusive — tighten updates hi to {value, inclusive=true}, same as existing; no change.\n // (2) `group.hi.inclusive === true → true`: fires when c=0, new=exclusive, existing=exclusive —\n // tighten updates hi to {value, false}, same as existing; no observable change.\n if (c > 0 || (c === 0 && inclusive === false && group.hi.inclusive === true)) {\n group.hi = { value, inclusive };\n }\n};\n\nconst intersectInSets = (\n sets: ReadonlyArray<ReadonlyArray<DocumentValue>>,\n): ReadonlyArray<DocumentValue> => {\n // Stryker disable ConditionalExpression,BlockStatement,ArrayDeclaration: dead-code guard\n // — callers only invoke intersectInSets when group.ins.length > 1 (i.e., sets.length >= 2),\n // so sets.length === 0 is unreachable in production. Any mutation here is an equivalent mutant.\n if (sets.length === 0) {\n return [];\n }\n // Stryker restore ConditionalExpression,BlockStatement,ArrayDeclaration\n let acc: ReadonlyArray<DocumentValue> = sets[0]!;\n for (let i = 1; i < sets.length; i++) {\n const next: DocumentValue[] = [];\n for (const a of acc) {\n for (const b of sets[i]!) {\n if (deepEqualDocumentValue(a, b)) {\n next.push(a);\n break;\n }\n }\n }\n acc = next;\n }\n return acc;\n};\n\n/**\n * Check that every per-field clause group on `wire` is jointly\n * satisfiable. Throws `BaerlyError{code:\"UnsatisfiablePredicate\"}`\n * (or `\"InvalidConfig\"` for conflicting `eq` clauses) on the\n * first contradiction. Returns `void` on success.\n */\nexport const assertWireSatisfiable = (wire: PredicateWire): void => {\n const groups = groupByField(wire);\n for (const [field, group] of groups) {\n // Multiple `eq` clauses on the same field must agree.\n // Stryker disable next-line EqualityOperator,ConditionalExpression: equivalent — the inner\n // loop starts at i=1, so with 0 or 1 eqs the loop body never executes regardless of whether\n // we enter the outer if. `>= 1` enters with 1 eq (0 loop iterations); `true` enters with 0\n // eqs (0 loop iterations). Both are observationally identical to `> 1`.\n if (group.eqs.length > 1) {\n for (let i = 1; i < group.eqs.length; i++) {\n if (!deepEqualDocumentValue(group.eqs[0]!, group.eqs[i]!)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Conflicting equality clauses on field ${formatPath([field])} (${JSON.stringify(group.eqs[0]!)} vs ${JSON.stringify(group.eqs[i]!)}). Predicate chains must agree on shared equality.`,\n );\n }\n }\n }\n const eq = group.eqs[0];\n // Range interval must be non-empty.\n if (\n group.lo !== undefined &&\n group.hi !== undefined &&\n sameComparableType(group.lo.value, group.hi.value)\n ) {\n const c = compareScalar(group.lo.value, group.hi.value);\n if (c > 0 || (c === 0 && (!group.lo.inclusive || !group.hi.inclusive))) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has empty interval (lo=${JSON.stringify(group.lo.value)} ${group.lo.inclusive ? \"gte\" : \"gt\"}, hi=${JSON.stringify(group.hi.value)} ${group.hi.inclusive ? \"lte\" : \"lt\"}).`,\n );\n }\n }\n // `eq` outside the residual interval / membership set.\n if (eq !== undefined) {\n if (group.lo !== undefined) {\n if (!sameComparableType(eq, group.lo.value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} (${typeof eq}) is type-incompatible with lower bound ${JSON.stringify(group.lo.value)} (${typeof group.lo.value}); range ops require matching primitive types.`,\n );\n }\n const c = compareScalar(eq, group.lo.value);\n if (c < 0 || (c === 0 && !group.lo.inclusive)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} excluded by lower bound ${JSON.stringify(group.lo.value)} (${group.lo.inclusive ? \"gte\" : \"gt\"}).`,\n );\n }\n }\n if (group.hi !== undefined) {\n if (!sameComparableType(eq, group.hi.value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} (${typeof eq}) is type-incompatible with upper bound ${JSON.stringify(group.hi.value)} (${typeof group.hi.value}); range ops require matching primitive types.`,\n );\n }\n const c = compareScalar(eq, group.hi.value);\n if (c > 0 || (c === 0 && !group.hi.inclusive)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} excluded by upper bound ${JSON.stringify(group.hi.value)} (${group.hi.inclusive ? \"lte\" : \"lt\"}).`,\n );\n }\n }\n // Stryker disable next-line EqualityOperator,ConditionalExpression: equivalent — the for-of\n // loop over group.ins is a no-op when group.ins is empty, so `>= 0` (always true) and\n // `true` (always enter) produce identical behavior: zero iterations when ins is empty,\n // same iterations as `> 0` when ins is non-empty.\n if (group.ins.length > 0) {\n for (const set of group.ins) {\n let found = false;\n for (const m of set) {\n if (deepEqualDocumentValue(eq, m)) {\n found = true;\n break;\n }\n }\n if (!found) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} not present in in() set.`,\n );\n }\n }\n }\n }\n // Multiple `in` sets must intersect non-empty.\n // Stryker disable next-line EqualityOperator: equivalent — intersectInSets([single_set])\n // returns that set unchanged; since validateWire rejects empty in-arrays, the single set\n // is always non-empty, so isect.length === 0 is false and no throw occurs. `>= 1` (entering\n // with 1 in-set) behaves identically to `> 1` (skipping for 1 in-set).\n if (group.ins.length > 1) {\n const isect = intersectInSets(group.ins);\n if (isect.length === 0) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has empty in() intersection across multiple clauses.`,\n );\n }\n }\n }\n};\n","/**\n * AND-merge two validated wire predicates. Powers chained\n * `Query<T>.where(...).where(...)`.\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","/**\n * Wire predicate validator. Walks a {@link PredicateWire} and throws\n * on a structurally bad clause (`BaerlyError{code:\"InvalidConfig\"}`)\n * or a per-field clause group that contradicts itself\n * (`BaerlyError{code:\"UnsatisfiablePredicate\"}`).\n *\n * The object-form normaliser at `./normalize.ts` enforces shape on\n * the way in (rejecting `$`-keys / non-scalars / null / undefined);\n * the callback builder at `./builder.ts` enforces shape via the\n * type system. This validator is the wire-arrival check: it runs\n * over already-normalised clauses, defending against raw-`fetch`\n * callers who bypass the typed seam and submit arbitrary JSON.\n *\n * Companion modules: `./matches.ts` (evaluator), `./merge.ts`\n * (AND-merge). Shared helpers live in `./_internals.ts`.\n */\n\nimport { BaerlyError } from \"../errors.ts\";\n\nimport { assertWireSatisfiable } from \"./satisfiable.ts\";\nimport type { PredicateClause, PredicateOpName, PredicateWire } from \"./wire.ts\";\n\nconst OP_NAMES: ReadonlyArray<PredicateOpName> = [\"eq\", \"gt\", \"gte\", \"lt\", \"lte\", \"in\"];\nconst RANGE_OPS: ReadonlyArray<PredicateOpName> = [\"gt\", \"gte\", \"lt\", \"lte\"];\n\n/**\n * Validate a normalised predicate wire. Throws\n * `BaerlyError{code:\"InvalidConfig\"}` on a structurally bad clause,\n * or `BaerlyError{code:\"UnsatisfiablePredicate\"}` when a clause\n * group on one field contradicts itself.\n *\n * Returns the wire unchanged on success — callers can thread the\n * validated wire forward.\n *\n * @example\n * ```ts\n * validateWire({ clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] }); // ok\n * validateWire({ clauses: [{ op: \"in\", field: \"priority\", value: [] }] }); // throws UnsatisfiablePredicate\n * validateWire({ clauses: [{ op: \"eq\", field: \"_id\", value: \"x\" }] }); // throws InvalidConfig (top-level _id)\n * ```\n */\nexport const validateWire = (wire: PredicateWire): PredicateWire => {\n if (\n wire === null ||\n typeof wire !== \"object\" ||\n !Array.isArray((wire as { clauses?: unknown }).clauses)\n ) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate wire must be an object with a \"clauses\" array.`,\n );\n }\n for (let i = 0; i < wire.clauses.length; i++) {\n validateClause(wire.clauses[i]!, i);\n }\n assertWireSatisfiable(wire);\n return wire;\n};\n\nconst validateClause = (clause: PredicateClause, index: number): void => {\n if (clause === null || typeof clause !== \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} must be an object — got ${JSON.stringify(clause)}.`,\n );\n }\n const { op, field, value } = clause;\n // Stryker disable next-line ConditionalExpression: `typeof op !== \"string\"` is redundant —\n // OP_NAMES contains only string literals; Array.prototype.includes uses SameValueZero\n // (effectively ===), so any non-string op is already rejected by the `!includes` half.\n // The early string-type check is a readability guard, not an observable branch.\n if (typeof op !== \"string\" || !(OP_NAMES as ReadonlyArray<string>).includes(op)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} has unsupported op ${JSON.stringify(op)} — supported: ${OP_NAMES.join(\" / \")}.`,\n );\n }\n if (typeof field !== \"string\" || field.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} has empty / non-string field.`,\n );\n }\n // Reject `_id` AND any nested `_id.<path>` — `Path<T>` excludes both\n // (`\"_id\" | \\`_id.${string}\\``), so a raw-wire caller (the threat this\n // validator names) must not slip a dotted `_id.x` past a check that\n // only matched the exact root field.\n if (field === \"_id\" || field.startsWith(\"_id.\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n 'Predicates may not key on \"_id\"; use .get(id) / .update(id, patch) / .replace(id, doc) / .delete(id) instead.',\n );\n }\n if (op === \"in\") {\n if (!Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} (op=\"in\", field=${JSON.stringify(field)}) must carry an array value.`,\n );\n }\n if (value.length === 0) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate clause at index ${index} (op=\"in\", field=${JSON.stringify(field)}) has empty value array — no document can match.`,\n );\n }\n for (let i = 0; i < value.length; i++) {\n validateMemberValue(value[i], field, index, i);\n }\n return;\n }\n if (Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} (op=${JSON.stringify(op)}, field=${JSON.stringify(field)}) must carry a primitive value, got an array — only op=\"in\" accepts arrays.`,\n );\n }\n if ((RANGE_OPS as ReadonlyArray<string>).includes(op)) {\n validateRangeBound(value, field, index);\n return;\n }\n validateScalar(value, field, index);\n};\n\nconst validateMemberValue = (\n value: unknown,\n field: string,\n clauseIndex: number,\n memberIndex: number,\n): void => {\n // Stryker disable next-line ConditionalExpression: `|| value === undefined` is redundant —\n // undefined falls through to `typeof value` = \"undefined\", which is caught by the\n // `t !== \"string\" && t !== \"number\" && t !== \"boolean\"` check below with the same\n // InvalidConfig code. The early check gives a more descriptive \"undefined\" message\n // but no input can distinguish the two code paths via the public error code alone.\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is ${value === null ? \"null\" : \"undefined\"} — members must be string / number / boolean / nested object.`,\n );\n }\n if (Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is an array — members must be string / number / boolean / nested object.`,\n );\n }\n const t = typeof value;\n if (t === \"object\") {\n return;\n }\n if (t !== \"string\" && t !== \"number\" && t !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n\nconst validateScalar = (value: unknown, field: string, clauseIndex: number): void => {\n // Stryker disable next-line ConditionalExpression: `|| value === undefined` is redundant —\n // undefined falls through to `typeof value` = \"undefined\", caught by the\n // `t !== \"string\" && t !== \"number\" && t !== \"boolean\"` check with the same code.\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value is ${value === null ? \"null\" : \"undefined\"} — terminal values must be string / number / boolean / nested object.`,\n );\n }\n const t = typeof value;\n if (t === \"object\") {\n // Equality clauses against nested objects survive only via callback\n // form (the normaliser flattens object-form sub-predicates to\n // dotted-path eq clauses). Keep the structural recursion light —\n // values are sealed from the typed seam.\n return;\n }\n if (t !== \"string\" && t !== \"number\" && t !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n\nconst validateRangeBound = (value: unknown, field: string, clauseIndex: number): void => {\n // Stryker disable next-line ConditionalExpression: `|| value === undefined` is redundant —\n // undefined falls through to `typeof value` = \"undefined\", caught by `t !== \"string\" && t !== \"number\"`\n // with the same InvalidConfig code.\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is ${value === null ? \"null\" : \"undefined\"} — range bounds must be string or finite number.`,\n );\n }\n const t = typeof value;\n if (t === \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is a boolean — range bounds must be string or finite number (booleans are not ordered).`,\n );\n }\n if (t === \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is a nested object — range bounds must be string or finite number.`,\n );\n }\n if (t !== \"string\" && t !== \"number\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) has unsupported type ${JSON.stringify(t)} — must be string or finite number.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n","import { BaerlyError, CODE_RESOLUTIONS, type DocumentData, jsonValueEqual } from \"@baerly/protocol\";\nimport { markCallerFacing } from \"./caller-facing-error.ts\";\nimport { getCurrentContext } from \"./observability/context.ts\";\nimport { assertNfcSegment, assertPathSegment, assertWellFormedSegment } from \"./path-segment.ts\";\n\n/**\n * Resolution for a non-NFC `_id`. A row stored under one by an earlier\n * release stays readable and deletable, so it is migrated by copy.\n */\nconst DOC_ID_NFC_RESOLUTION =\n 'Pass id.normalize(\"NFC\") for a new _id. To migrate a stored non-NFC row, insert a copy under a fresh NFC id that is not canonically equivalent to the original (for example, omit _id for a UUID), then delete the original.';\n\n/**\n * Resolution for an `_id` with an unpaired surrogate. A row stored under\n * one by an earlier release stays readable and deletable in-process, so it\n * is migrated by copy.\n */\nconst DOC_ID_WELL_FORMED_RESOLUTION =\n \"Pass an _id with no unpaired UTF-16 surrogate (id.isWellFormed() is true), or omit _id for a UUID. To migrate a stored row with such an _id, read it by _id, remove _id from the copy so insert generates a fresh UUID, then delete the original.\";\n\n/**\n * Resolution for a point read whose id no row can be stored under.\n */\nconst READ_ID_RESOLUTION =\n 'Pass the _id string of a stored row. A valid _id is non-empty, at most 256 UTF-8 bytes, has no \"/\" or control characters, does not start with \"_\", and is not \".\" or \"..\".';\n\n/**\n * Guard an `_id` a write is about to store a row under: an insert, a\n * replace, an update, or any `I` / `U` commit. The `_id` analogue of\n * `assertKeySegment` (`db.ts`).\n *\n * Applies {@link assertStoredDocId}, then requires the id to be\n * well-formed UTF-16 (no unpaired surrogate, which no URL or S3 key can\n * carry) and in Unicode Normalization Form C (`id === id.normalize(\"NFC\")`),\n * so each canonical-equivalence class (NFC `é` and NFD `e` + U+0301) has one\n * spelling and one byte form. R2 stores canonically-equivalent keys as one\n * object, so any object a future format keys by `_id` (an index-aware\n * snapshot, say) would otherwise merge two rows whose ids differ only by\n * normalization; the rule keeps that door open, and loosening it later is\n * not a breaking change. Case and compatibility variants (`A` / `a`, `fi` / `fi`)\n * are distinct NFC strings and stay distinct ids.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — the id breaks the key-segment\n * rule, holds an unpaired surrogate, or is not NFC.\n */\nexport const assertDocId = (id: string): void => {\n assertStoredDocId(id);\n assertWellFormedSegment(id, \"_id\", \"\", DOC_ID_WELL_FORMED_RESOLUTION);\n assertNfcSegment(id, \"_id\", \"\", DOC_ID_NFC_RESOLUTION);\n};\n\n/**\n * Guard an `_id` that names an existing row: the `doc_id` of a delete.\n * Only the key-segment rule applies (the single shared\n * {@link assertPathSegment}: empty / `\"/\"` / `\".\"`|`\"..\"` / C0-C1 control\n * chars / leading `\"_\"` (ADR-003) / overlong, all as\n * `BaerlyError{code:\"InvalidConfig\"}`), so a row stored under a non-NFC\n * id, or an id with an unpaired surrogate, before {@link assertDocId}\n * refused them can still be deleted.\n */\nexport const assertStoredDocId = (id: string): void => {\n assertPathSegment(id, \"_id\");\n};\n\n/**\n * Guard the `id` of a point read (`Collection.get`, `GET\n * /v1/c/:collection/:id`) before any I/O. Applies the stored-id rule\n * ({@link assertStoredDocId}), not the NFC or well-formed write rules, so\n * a row an earlier release stored under such an id stays readable. The error is marked\n * caller-facing so HTTP returns its message with the 400.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `id` is not a string or breaks\n * the key-segment rule.\n */\nexport const assertReadDocId = (id: string): void => {\n let message: string | undefined;\n if (typeof id !== \"string\") {\n message = `get: _id must be a string, got ${typeof id}`;\n } else {\n try {\n assertPathSegment(id, \"_id\", \"get\");\n } catch (error) {\n if (!(error instanceof BaerlyError)) {\n throw error;\n }\n message = error.message;\n }\n }\n if (message !== undefined) {\n throw markCallerFacing(\n new BaerlyError(\"InvalidConfig\", message, { resolution: READ_ID_RESOLUTION }),\n );\n }\n};\n\n/**\n * The `AlreadyExists` an insert throws when a live row holds `docId`.\n * Shared by `runInsert`'s check read (`./query.ts`) and the writer's\n * insert guard (`./writer.ts`), so a caller sees one error whichever\n * side caught the collision. Not retriable; `err._id` is `docId`.\n */\nexport const insertAlreadyExists = (collection: string, docId: string): BaerlyError =>\n new BaerlyError(\n \"AlreadyExists\",\n `insert: _id ${JSON.stringify(docId)} already exists in collection ${JSON.stringify(collection)}`,\n { resolution: CODE_RESOLUTIONS.AlreadyExists, _id: docId },\n );\n\n/**\n * `true` when the stored live row `stored` is the row an insert of `body`\n * would have written: structurally equal after the JSON round-trip the\n * write path's encoder applies (key order ignored, `undefined` properties\n * dropped). `body` is the insert's post-image `{ ...doc, _id }`; the\n * stored row carries no other server-stamped field (log metadata lives on\n * the `LogEntry`, not in `after`).\n *\n * Shared by `runInsert`'s check read and the writer's insert guard, so an\n * SDK-minted insert replays on the same rule whichever side found the row.\n */\nexport const insertReplaysRow = (body: DocumentData, stored: DocumentData | undefined): boolean =>\n stored !== undefined && jsonValueEqual(JSON.parse(JSON.stringify(body)), stored);\n\n/**\n * Count an SDK-minted insert answered as a replay of its stored row on\n * `db.write.insert_replayed_total` (labelled by `collection`). A replay\n * commits nothing and records no write metric, so without this counter it\n * is invisible on the canonical line. Shared by `runInsert`'s check read\n * and the writer's insert guard, the two places a replay is decided.\n */\nexport const recordInsertReplay = (collection: string): void => {\n getCurrentContext()?.recorder.counter(\"db.write.insert_replayed_total\", 1, { collection });\n};\n","/**\n * Growth refusal at the host's fold ceiling (main-10, rulings G3–G5, G7).\n *\n * The in-band fold can only rebuild a snapshot within the serving host's\n * ceilings: `E` rows (`maxFoldRows`) and `C` bytes (`maxFoldBytes`, or\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`). `compact()` folds the longest\n * prefix of the tail that keeps the snapshot within `E` rows, so it stops\n * at the first entry that would add a row to an `E`-row snapshot, and of\n * that, the longest prefix of its pass that rebuilds within `C` bytes. Past\n * a point no pass can fold, nothing folds, and every read pays one GET per\n * pending tail entry.\n * The write verbs call {@link capacityDecision} after their pre-commit read\n * and before any commit, so a refused write commits nothing, and again\n * inside each commit, before its `log/<seq>` create, whenever another\n * write landed since that read, so concurrent growth writes that each\n * passed cannot together pass the ceiling (G5-race).\n *\n * The decision is a pure function of the state that read already loaded\n * (`current.json`, the snapshot rows, the pending tail) plus the planned\n * writes. Nothing is persisted, so the refusal clears as soon as that\n * state changes.\n *\n * An admitted write that leaves the collection within\n * `CAPACITY_WARN_FRACTION` of that point carries a warning (G7), computed\n * from the same state, so it too needs no persisted flag.\n *\n * Near the ceiling the verbs also drive the fold (G6): an accepted write\n * that leaves the collection at its growth-refusal point forces its\n * write tick, and a refused growth write whose room the pending tail\n * would free dispatches one forced fold and refuses with\n * `MaintenancePending` instead of `CapacityExceeded`.\n */\n\nimport {\n BaerlyError,\n CAPACITY_BYTES_MARGIN,\n CAPACITY_WARN_FRACTION,\n CODE_RESOLUTIONS,\n MAINTENANCE_PENDING_RETRY_AFTER_SECONDS,\n MAINTENANCE_PROFILE_CF_FREE,\n type CurrentJson,\n type DocumentData,\n type LogEntry,\n} from \"@baerly/protocol\";\nimport {\n type FoldCeilings,\n isFoldViable,\n type MaintenanceProfile,\n resolveFoldCeilings,\n} from \"./maintenance.ts\";\nimport { getCurrentContext } from \"./observability/context.ts\";\nimport { isOwnCollection } from \"./collection-alias.ts\";\nimport { projectSnapshot, rowBytes, type SnapshotProjection } from \"./snapshot-projection.ts\";\n\n/** One mutation a verb is about to commit, in commit order. */\nexport interface PlannedWrite {\n readonly op: \"I\" | \"U\" | \"D\";\n readonly docId: string;\n /** Post-image for `I` / `U`. */\n readonly after?: DocumentData;\n /** For `U`: the row's current body, as the verb's read returned it. */\n readonly before?: DocumentData;\n}\n\n/** A host's fold ceilings plus the entries one fold pass applies. */\nexport type HostFoldLimits = FoldCeilings & Pick<MaintenanceProfile, \"maxFoldEntriesPerPass\">;\n\n/**\n * The fold ceilings and pass size of the host serving this request,\n * resolved as the write-tick runner resolves them\n * ({@link resolveFoldCeilings}, absent profile ⇒ cf-free) so refusal and\n * folding always agree.\n */\nexport const currentFoldCeilings = (): HostFoldLimits => {\n const maint = getCurrentContext()?.maintenance;\n const profile = maint?.options?.profile;\n return {\n ...resolveFoldCeilings(profile, maint?.maxFoldBytes),\n // The runner's own default when no profile is threaded.\n maxFoldEntriesPerPass: (profile ?? MAINTENANCE_PROFILE_CF_FREE).maxFoldEntriesPerPass,\n };\n};\n\n/**\n * The refusal message names the state and the app-side remedy only. The\n * host-side route (a larger maintenance profile) is an operator decision:\n * it reaches operators through the `fold_deferred` log line and\n * `graduation.md`, never the app-authoring surface, so an agent reading\n * this error is not invited to retune a host setting.\n */\nconst refuse = (message: string): BaerlyError =>\n new BaerlyError(\"CapacityExceeded\", message, {\n resolution: CODE_RESOLUTIONS.CapacityExceeded,\n });\n\n/**\n * Growth (G3): an insert, or an update whose post-image encodes larger\n * than the row's current body. An update with no known `before` counts as\n * growth, which fails closed.\n */\nconst isGrowth = (write: PlannedWrite): boolean => {\n if (write.op === \"I\") {\n return true;\n }\n if (write.op === \"D\" || write.after === undefined) {\n return false;\n }\n return (\n write.before === undefined ||\n rowBytes(write.docId, write.after) > rowBytes(write.docId, write.before)\n );\n};\n\n/**\n * Backpressure for a refused growth write whose room the pending tail\n * frees once it folds (G6). Like `CapacityExceeded`, it names the state\n * and the app-side remedy only.\n */\nexport const maintenancePending = (collection: string): BaerlyError =>\n new BaerlyError(\n \"MaintenancePending\",\n `collection ${JSON.stringify(collection)} is waiting on maintenance: this write would grow ` +\n `it past what this host can fold until the pending changes fold, so it was refused and ` +\n `not committed (rows a batch committed before it are kept). Retry after ${MAINTENANCE_PENDING_RETRY_AFTER_SECONDS}s.`,\n {\n resolution: CODE_RESOLUTIONS.MaintenancePending,\n retryAfter: MAINTENANCE_PENDING_RETRY_AFTER_SECONDS,\n },\n );\n\n/**\n * An admitted write is approaching the growth-refusal point (G7). `used`\n * and `limit` are in the named dimension: rows against `E`, or projected\n * bytes against `C - CAPACITY_BYTES_MARGIN`.\n */\nexport interface CapacityWarning {\n readonly dimension: \"rows\" | \"bytes\";\n readonly used: number;\n readonly limit: number;\n /** The human text: the state and the app-side remedy, no host settings. */\n readonly text: string;\n}\n\n/** Canonical-line field carrying {@link CapacityWarning.text}. */\nexport const CAPACITY_WARNING_FIELD = \"capacity_warning\";\n\n/**\n * The warning for a projection peaking at `peakRows` / `peakBytes`, or\n * `undefined` while both dimensions sit under `CAPACITY_WARN_FRACTION` of\n * their limits. The more-used dimension is reported. The text names the\n * state and the app-side remedy only, like the refusal it precedes.\n */\nconst warningFor = (\n peakRows: number,\n peakBytes: number,\n maxRows: number,\n byteLimit: number,\n): CapacityWarning | undefined => {\n const rowFraction = peakRows / maxRows;\n const byteFraction = peakBytes / byteLimit;\n const rows = rowFraction >= byteFraction;\n const fraction = rows ? rowFraction : byteFraction;\n // `!(x >= y)` rather than `x < y`: a NaN ceiling must not read as \"room\".\n if (!(fraction >= CAPACITY_WARN_FRACTION) || !Number.isFinite(fraction)) {\n return undefined;\n }\n const used = rows ? peakRows : peakBytes;\n const limit = rows ? maxRows : byteLimit;\n const percent = Math.floor(fraction * 100);\n return {\n dimension: rows ? \"rows\" : \"bytes\",\n used,\n limit,\n text:\n `this collection is at ${percent}% of what this host can hold (${used} of ${limit} ` +\n `${rows ? \"rows\" : \"bytes\"}); inserts and growing updates will be refused at the limit. ` +\n `Delete rows or shrink documents to make room, or export with baerly admin dump.`,\n };\n};\n\n/**\n * Stamp `warning` on the request's canonical line (and so the log record)\n * under {@link CAPACITY_WARNING_FIELD}. The HTTP router copies the same\n * text onto the write response. A no-op without a request context, as for\n * any field setter.\n */\nexport const noteCapacityWarning = (warning: CapacityWarning): void => {\n getCurrentContext()?.fields.set(CAPACITY_WARNING_FIELD, warning.text);\n};\n\n/** What {@link capacityDecision} decided for one batch of planned writes. */\nexport type CapacityDecision =\n | {\n readonly refusal: undefined;\n /**\n * Set when the admitted writes leave the collection within\n * `CAPACITY_WARN_FRACTION` of its refusal point (G7).\n */\n readonly warning?: CapacityWarning;\n /**\n * The verb forces its write tick (G6): the collection sits at its\n * growth-refusal point once these writes commit, and folding the\n * pending tail frees room or the tail holds a full fold pass.\n */\n readonly pressure: boolean;\n }\n | {\n /** The `CapacityExceeded` refusal to throw. */\n readonly refusal: BaerlyError;\n /**\n * A growth refusal (never the no-progress state) that the pending\n * tail would lift once it folds, where the next fold pass can land.\n * The verb may dispatch that fold and refuse with\n * {@link maintenancePending} instead.\n */\n readonly foldFreesRoom: boolean;\n };\n\n/**\n * Decide whether `writes` must be refused on the host with `ceilings`.\n *\n * - **No progress** (G5): the stored snapshot is over `E` rows or `C`\n * bytes, or the pending tail holds an entry the fold stops at (one that\n * adds a row while the projected snapshot holds `E` rows), or\n * `maxFoldEntriesPerPass` consecutive pending seqs whose folded snapshot\n * each rebuilds past `C`, a run no fold pass can cross. Every write is\n * refused, since anything appended behind that point never folds on this\n * host. A write that would itself complete such a run is refused too.\n * - **Growth** (an insert or a byte-growing update, G3): refused when the\n * projected snapshot, at its peak over every prefix of the pending tail\n * followed by the planned writes up to this one, would reach `E` rows or\n * exceed `C - CAPACITY_BYTES_MARGIN` bytes (G4). The peak counts because\n * a fold can land at any prefix. `foldFreesRoom` (G6) is set when the\n * same writes would be admitted onto the snapshot the whole pending tail\n * folds to, and the whole tail folds within `C`, so folds alone admit\n * the writes.\n * - Anything else (deletes, same-size and shrinking updates) commits, at\n * `E` rows included: the fold drains them in place. `pressure` reports\n * whether the commit forces its write tick (see `forcesTick` inside).\n *\n * A batch is decided whole, before its first row commits. The verbs\n * re-run the decision at each commit over the entries that landed since\n * (G5-race, `admitWrites` in `./query.ts`), for the writes not yet\n * committed.\n *\n * @param head `current.json` as the pre-commit read saw it.\n * @param base The snapshot rows that read loaded (`docId → body`).\n * @param tail Every log entry that read folded on top of `base`, in order.\n */\nexport const capacityDecision = (args: {\n readonly collection: string;\n readonly head: Pick<CurrentJson, \"snapshot_rows\" | \"snapshot_bytes\" | \"log_seq_start\">;\n readonly base: ReadonlyMap<string, DocumentData>;\n readonly tail: readonly LogEntry[];\n readonly writes: readonly PlannedWrite[];\n readonly ceilings: HostFoldLimits;\n}): CapacityDecision => {\n const { collection, head, base, tail, writes, ceilings } = args;\n if (writes.length === 0) {\n return { refusal: undefined, pressure: false };\n }\n const { maxFoldRows: maxRows, maxFoldBytes: maxBytes } = ceilings;\n const byteLimit = maxBytes - CAPACITY_BYTES_MARGIN;\n const noProgress = (why: string): CapacityDecision => ({\n refusal: refuse(\n `collection ${JSON.stringify(collection)} has outgrown this host (${why}): no fold can ` +\n `make progress here, so every write is refused and reads keep working. The collection ` +\n `needs a larger host or graduation; export it with baerly admin dump.`,\n ),\n foldFreesRoom: false,\n });\n // The runner's own pre-fold gate; it fails closed on a NaN ceiling.\n if (!isFoldViable(head.snapshot_bytes, head.snapshot_rows, ceilings)) {\n return noProgress(\n `${head.snapshot_rows} rows of ${maxRows}, ${head.snapshot_bytes} bytes of ${maxBytes}`,\n );\n }\n\n // Skip what the fold skips (`foldLogEntriesOnto`): another collection's entries.\n const own = tail.filter((entry) => isOwnCollection(entry.collection, collection));\n const projection = projectSnapshot(head, base, collection);\n // `compact()` folds at most `maxFoldEntriesPerPass` seqs from\n // `log_seq_start` (other collections' entries count toward it) and\n // publishes the longest prefix of that pass whose rebuilt snapshot fits\n // `C`. Whether a prefix fits depends only on the log up to its end, not\n // on where passes fall: a seq \"over\" `C` (the snapshot folded through it\n // rebuilds past `C`) is never a fold end. A run of `pass` consecutive\n // over seqs is therefore a wall: no pass from the last fitting seq before\n // it reaches past it, and the log is immutable, so it and everything\n // behind it never fold here (G5). A shorter run is crossed by the pass\n // that starts before it, and a run at the end of the tail can still be\n // ended by later entries.\n const pass = ceilings.maxFoldEntriesPerPass;\n let overRun = 0;\n for (const [i, entry] of tail.entries()) {\n if (isOwnCollection(entry.collection, collection)) {\n // Where `compact()` stops: a row-adding entry at `E` rows.\n if (projection.addsRow(entry.op, entry.doc_id, entry.after) && !(projection.rows < maxRows)) {\n return noProgress(\n `a pending insert cannot fold onto ${projection.rows} rows of ${maxRows}`,\n );\n }\n projection.apply(entry.op, entry.doc_id, entry.after);\n }\n // The snapshot folded through this seq, exactly as compact() sizes it against `C`.\n const rebuilt = projection.bytesAt(head.log_seq_start + i + 1);\n overRun = rebuilt <= maxBytes ? 0 : overRun + 1;\n if (!(overRun < pass)) {\n return noProgress(\n `${overRun} pending entries in a row each leave the snapshot past ${maxBytes} bytes`,\n );\n }\n }\n // Every forced fold of the tail lands: each pass reaches a fitting seq,\n // and the last one ends the tail.\n const tailLands = overRun === 0;\n\n /**\n * Whether an accepted batch forces its write tick (G6), given `p` with\n * the tail and the writes applied. Only at the refusal point (one more\n * inserted row, or one more byte of growth, would be refused), and then\n * only when that fold is worth its full snapshot rebuild:\n *\n * - folding the pending tail frees room for growth (the snapshot it\n * rebuilds to admits one more row and byte), or\n * - the pending tail, these writes included, holds a full pass\n * (`maxFoldEntriesPerPass`).\n *\n * Otherwise the runner's ratio trigger and entry floor apply as usual.\n * The pass floor is the cheapest cadence that keeps the tail bounded at\n * the ceiling: every pending entry costs each read one GET, and on\n * Workers Free the ratio trigger alone would let a collection held at\n * `E - 1` by same-size updates queue ~300 entries. One forced fold per\n * pass also bounds the rebuild cost to one full snapshot per\n * `maxFoldEntriesPerPass` writes, rather than one per write, and with it\n * the snapshots each rebuild orphans: on cf-free that is under one\n * orphan (20-entry pass) per hard-GC interval of 16 writes, against that\n * slice's sweep budget of 10, so GC keeps up even though a forced fold\n * is the tick's only phase.\n */\n const forcesTick = (p: SnapshotProjection): boolean => {\n const atRefusalPoint =\n !(Math.max(p.peakRows, p.rows + 1) < maxRows) || !(p.peakBytes < byteLimit);\n if (!atRefusalPoint) {\n return false;\n }\n // A forced fold that defers rebuilds the snapshot for nothing. Every\n // pass lands when the tail does: each reaches a fitting seq of the\n // tail, and an admitted growth write keeps every prefix within\n // `C - margin` (the margin covers the header's later `max_seq` digits).\n if (!tailLands) {\n return false;\n }\n const foldFreesRoom = p.rows + 1 < maxRows && p.bytes < byteLimit;\n return foldFreesRoom || tail.length + writes.length >= pass;\n };\n\n /**\n * The first write `p` refuses, applying every write onto `p` from a\n * state `overRun` seqs into a run over `C`: a growth write past the\n * growth limit, or any write that would complete a wall of `pass` seqs\n * over `C` (`stranded`), which it would itself sit behind.\n */\n const firstRefused = (\n p: SnapshotProjection,\n run: number,\n ): { write: PlannedWrite; stranded: boolean } | undefined => {\n for (const [j, write] of writes.entries()) {\n const growth = isGrowth(write);\n p.apply(write.op, write.docId, write.after);\n if (growth && (!(p.peakRows < maxRows) || !(p.peakBytes <= byteLimit))) {\n return { write, stranded: false };\n }\n run = p.bytesAt(head.log_seq_start + tail.length + j + 1) <= maxBytes ? 0 : run + 1;\n if (!(run < pass)) {\n return { write, stranded: true };\n }\n }\n return undefined;\n };\n\n const first = firstRefused(projection, overRun);\n if (first === undefined) {\n const warning = warningFor(projection.peakRows, projection.peakBytes, maxRows, byteLimit);\n return {\n refusal: undefined,\n pressure: forcesTick(projection),\n ...(warning !== undefined && { warning }),\n };\n }\n if (first.stranded) {\n return {\n refusal: refuse(\n `collection ${JSON.stringify(collection)} is waiting on changes this host cannot fold: ` +\n `the pending changes leave it past ${maxBytes} bytes, and this write would leave ` +\n `them stuck there for good, so it was refused and not committed (rows a batch ` +\n `committed before it are kept). A write that brings the collection back within ` +\n `${maxBytes} bytes still commits; otherwise it needs a larger host or graduation.`,\n ),\n foldFreesRoom: false,\n };\n }\n const refused = first.write;\n const { peakRows, peakBytes } = projection;\n const detail = !(peakRows < maxRows)\n ? `${peakRows} rows would reach the ${maxRows}-row ceiling`\n : `${peakBytes} bytes would pass the ${maxBytes}-byte ceiling`;\n const refusal = refuse(\n `collection ${JSON.stringify(collection)} is full on this host: ${detail}, so this ` +\n `${refused.op === \"I\" ? \"insert\" : \"growing update\"} was refused and not ` +\n `committed (rows a batch committed before it are kept). Deletes and same-size or shrinking updates still commit; delete or shrink ` +\n `rows to make room. If the collection must keep growing, it needs a larger host or graduation.`,\n );\n // `MaintenancePending` promises that folds alone admit these writes, so\n // every pass of the tail must land.\n if (own.length === 0 || !tailLands) {\n return { refusal, foldFreesRoom: false };\n }\n // Would the writes fit once the pending tail folds? The tail's own prefix\n // peaks no longer count after it folds, so the projection restarts at the\n // snapshot the whole tail rebuilds, byte for byte what the retry projects\n // from, so the retry admits what this promises.\n const settled = projectSnapshot(head, base, collection);\n for (const entry of own) {\n settled.apply(entry.op, entry.doc_id, entry.after);\n }\n settled.settle(head.log_seq_start + tail.length);\n return { refusal, foldFreesRoom: firstRefused(settled, 0) === undefined };\n};\n","/**\n * In-memory query evaluation over a folded row map: the predicate\n * filter, the counting pass, `order` with its bounded top-k, and the\n * `limit` cut. `runReadRows`\n * (`./query.ts`) calls these after the snapshot + log fold; they do no\n * I/O.\n */\n\nimport {\n compileWire,\n type DocumentData,\n type OrderSpec,\n type PredicateWire,\n QUERY_TOP_K_MAX,\n QUERY_TOP_K_SAMPLE,\n} from \"@baerly/protocol\";\n\n/**\n * A materialised row paired with the `doc_id` it is stored under. The\n * mutation verbs commit under `docId`, and check that the row's own `_id`\n * agrees with it (see `storedRowId` in `./query.ts`).\n */\nexport interface StoredDoc<D extends DocumentData> {\n readonly docId: string;\n readonly doc: D;\n}\n\n/**\n * The rows of `docs` that satisfy `wire`, in map order, built in one pass.\n * With no predicate, every row.\n */\nexport const filterRows = <D extends DocumentData>(\n docs: ReadonlyMap<string, D>,\n wire: PredicateWire | undefined,\n): StoredDoc<D>[] => {\n if (wire === undefined) {\n return Array.from(docs, ([docId, doc]) => ({ docId, doc }));\n }\n const matches = compileWire(wire);\n const rows: StoredDoc<D>[] = [];\n for (const [docId, doc] of docs) {\n if (matches(doc)) {\n rows.push({ docId, doc });\n }\n }\n return rows;\n};\n\n/** How many rows of `docs` satisfy `wire`, without materialising them. */\nexport const countMatches = <D extends DocumentData>(\n docs: ReadonlyMap<string, D>,\n wire: PredicateWire | undefined,\n): number => {\n if (wire === undefined) {\n return docs.size;\n }\n const matches = compileWire(wire);\n let count = 0;\n for (const doc of docs.values()) {\n if (matches(doc)) {\n count++;\n }\n }\n return count;\n};\n\n/**\n * How many of `n` rows `limit` keeps: the length `rows.slice(0, limit)`\n * would have. Both the row path (which truncates to it) and the count\n * use it, so a count honours `limit` exactly as `all()` does, including\n * a fractional or negative `limit` (`slice` truncates it, and counts a\n * negative end from the back).\n */\nexport const limitedLength = (n: number, limit: number | undefined): number => {\n if (limit === undefined || !(limit < n)) {\n return n;\n }\n // `|| 0` folds `-0` (from a limit in (-1, 0)) to `0`, as `slice` does.\n const end = Math.trunc(limit) || 0;\n return end < 0 ? Math.max(n + end, 0) : end;\n};\n\n/**\n * Compare two primitive order-key values under one direction, as\n * {@link sortByOrderSpec} does: a missing value sorts low under `asc`\n * and high under `desc`; otherwise `<`. {@link orderRows} calls it only\n * once its pre-scan has ruled out objects and `null`.\n */\nconst compareKey = (a: unknown, b: unknown, desc: boolean): number => {\n if (a === b) {\n return 0;\n }\n if (a === undefined) {\n return desc ? 1 : -1;\n }\n if (b === undefined) {\n return desc ? -1 : 1;\n }\n const cmp = (a as number) < (b as number) ? -1 : 1;\n return desc ? -cmp : cmp;\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 26+ 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 */\nexport const sortByOrderSpec = <D extends DocumentData, R extends StoredDoc<D>>(\n rows: readonly R[],\n spec: OrderSpec<D>,\n): R[] => {\n const entries = Object.entries(spec) as Array<[keyof D, \"asc\" | \"desc\"]>;\n return rows.toSorted((a, b) => {\n for (const [field, dir] of entries) {\n const av: D[keyof D] | undefined = a.doc[field];\n const bv: D[keyof D] | undefined = b.doc[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\n/**\n * `sortByOrderSpec(rows, spec)` cut by `limit` as the row path cuts it,\n * without sorting every row when `limit` is small.\n *\n * The bounded path runs when `limit` is an integer in\n * `[1, QUERY_TOP_K_MAX]` below `rows.length` (PostgreSQL's bounded\n * top-N heapsort for `ORDER BY … LIMIT` has the same shape). One O(n)\n * pass checks that each order key holds a single primitive type (plus\n * missing values), under which the comparator is a total preorder; a\n * key holding objects, `null` or mixed types falls back to the full\n * sort, whose comparator is not transitive there. The same pass\n * compares adjacent rows:\n *\n * - No row orders before its predecessor: the input is already in\n * order, so the first `limit` rows are the answer.\n * - No row orders after its predecessor: the input is in reverse order,\n * so the answer is read from the end, keeping tied rows in input\n * order.\n * - Otherwise a max-heap keeps the best `limit` rows under the\n * comparator, ties broken by input index, which is the stable sort's\n * order. The heap's result does not depend on the order rows are fed\n * in, so it reads the input from the end when more compared adjacent\n * pairs fall than rise (later rows ordering first), which keeps root\n * replacements rare on nearly reversed input.\n *\n * The output is identical to `sortByOrderSpec(rows, spec).slice(0, limit)`.\n */\nexport const orderRows = <D extends DocumentData, R extends StoredDoc<D>>(\n rows: R[],\n spec: OrderSpec<D>,\n limit: number | undefined,\n): R[] => {\n const n = rows.length;\n if (\n limit === undefined ||\n !Number.isInteger(limit) ||\n limit < 1 ||\n limit > QUERY_TOP_K_MAX ||\n limit >= n\n ) {\n return sortByOrderSpec(rows, spec);\n }\n const fields = Object.keys(spec) as Array<keyof D>;\n const desc = fields.map((field) => spec[field] === \"desc\");\n const types: Array<string | undefined> = [];\n // Key values of the previous and current row, so each row is read once.\n let prev: unknown[] = [];\n let cur: unknown[] = [];\n let ascents = 0;\n let descents = 0;\n for (let i = 0; i < n; i++) {\n const doc = rows[i]!.doc;\n for (let j = 0; j < fields.length; j++) {\n const value: unknown = doc[fields[j]!];\n if (value !== undefined) {\n const type = typeof value;\n if (type === \"object\" || (types[j] !== undefined && types[j] !== type)) {\n return sortByOrderSpec(rows, spec).slice(0, limit);\n }\n types[j] = type;\n }\n cur[j] = value;\n }\n // Compare a sample prefix, then only while the input still looks\n // monotone: the counts pick a path, the answer never depends on them.\n if (i > 0 && (i <= QUERY_TOP_K_SAMPLE || ascents === 0 || descents === 0)) {\n let cmp = 0;\n for (let j = 0; j < fields.length && cmp === 0; j++) {\n cmp = compareKey(prev[j], cur[j], desc[j]!);\n }\n if (cmp < 0) {\n ascents++;\n } else if (cmp > 0) {\n descents++;\n }\n }\n const swap = prev;\n prev = cur;\n cur = swap;\n }\n if (descents === 0) {\n return rows.slice(0, limit);\n }\n const compareKeys = (a: number, b: number): number => {\n const x = rows[a]!.doc;\n const y = rows[b]!.doc;\n let cmp = 0;\n for (let j = 0; j < fields.length && cmp === 0; j++) {\n cmp = compareKey(x[fields[j]!], y[fields[j]!], desc[j]!);\n }\n return cmp;\n };\n if (ascents === 0) {\n // Reverse order: take tie groups from the end, each in input order.\n const out: R[] = [];\n let end = n;\n while (out.length < limit) {\n let start = end - 1;\n while (start > 0 && compareKeys(start - 1, start) === 0) {\n start--;\n }\n for (let i = start; i < end && out.length < limit; i++) {\n out.push(rows[i]!);\n }\n end = start;\n }\n return out;\n }\n // The stable sort's order: ties keep input order.\n const compare = (a: number, b: number): number => compareKeys(a, b) || a - b;\n // Max-heap of row indices, full at `limit`: the root is the worst row kept.\n const heap: number[] = [];\n const siftDown = (pos: number): void => {\n for (;;) {\n const left = 2 * pos + 1;\n if (left >= limit) {\n return;\n }\n const right = left + 1;\n const worst = right < limit && compare(heap[right]!, heap[left]!) > 0 ? right : left;\n if (compare(heap[worst]!, heap[pos]!) < 0) {\n return;\n }\n [heap[pos], heap[worst]] = [heap[worst]!, heap[pos]!];\n pos = worst;\n }\n };\n const backward = descents > ascents;\n for (let x = 0; x < n; x++) {\n const i = backward ? n - 1 - x : x;\n if (heap.length < limit) {\n // Heapify once the first `limit` rows are in.\n if (heap.push(i) === limit) {\n for (let pos = (limit >> 1) - 1; pos >= 0; pos--) {\n siftDown(pos);\n }\n }\n } else if (compare(i, heap[0]!) < 0) {\n heap[0] = i;\n siftDown(0);\n }\n }\n return heap.toSorted(compare).map((i) => rows[i]!);\n};\n","/**\n * Staged read admission (main-2): a read whose work falls outside the\n * serving host's read envelope is refused whole with `CapacityExceeded`,\n * never truncated, and a read inside it is served exactly as on any other\n * host (P1). Reads stay pure: a refusal writes nothing and dispatches no\n * maintenance, so a read never carries `MaintenancePending`.\n *\n * Every read, index-covered or not, is a full fold: it takes membership\n * from the snapshot plus the log tail, never from an index LIST, so its\n * work is bounded by the full-fold bounds below (I1: materialized =\n * snapshot rows + tail entries). There is no index-specific bound.\n *\n * Two stages, both over the current layout (one snapshot plus the live\n * log tail):\n *\n * 1. **Head.** `current.json` alone refuses a read that is certain not to\n * fit: its snapshot is over the byte or row bound, or the strict log\n * range `[log_seq_start, tail_hint)` alone is over the tail or\n * materialization bound, or the storage calls the read must issue at\n * least are more than the request ledger has left. `tail_hint` is a\n * lower bound on the tail, so every head check is a lower bound and\n * never refuses a read that fits.\n * 2. **Staged.** The read charges each log body before decoding it (tail\n * entries, tail bytes, materialized rows), and checks the answer's row\n * count before returning it. Two buckets with identical heads but different tails are told apart\n * here. Storage calls are charged by the request ledger at issue\n * (`retryStorageCall`), retries included.\n *\n * Memory: the adapter `GET` has already allocated a body when its length is\n * checked; the head's `snapshot_bytes` bounds the snapshot before its GET.\n * A bounded-read `Storage` seam is not needed while each log entry is one\n * small object.\n */\n\nimport {\n BaerlyError,\n type CurrentJson,\n currentRequestLedger,\n type RequestPool,\n} from \"@baerly/protocol\";\nimport { getCurrentContext } from \"./observability/context.ts\";\n\n/**\n * A host's read envelope. Every bound is optional; an absent bound is\n * unbounded. The adapter that owns the invocation sets it on the\n * observability context (`readEnvelope`) next to the request ledger, which\n * carries the storage-call bound.\n */\nexport interface ReadEnvelope {\n /** Snapshot body bytes (`current.json` `snapshot_bytes`) a read may load. */\n readonly maxSnapshotBytes?: number;\n /** Snapshot rows (`snapshot_rows`) a read may decode. */\n readonly maxSnapshotRows?: number;\n /** Live log entries at or past `log_seq_start` a read may load. */\n readonly maxTailEntries?: number;\n /** Sum of those entries' stored body bytes. */\n readonly maxTailBytes?: number;\n /**\n * Rows decoded before predicate, sort and limit: snapshot rows plus tail\n * entries. On the current layout a sorted `limit(n)` materializes every\n * row, so this bounds it independently of the output.\n */\n readonly maxMaterializedRows?: number;\n /** Rows in the answer. A count's answer is one number, so a count is not output-bounded. */\n readonly maxOutputRows?: number;\n /**\n * The request-ledger pool the host's storage charges: `\"internal\"` for\n * the R2 binding, `\"external\"` for storage reached through `fetch`. Sizes\n * the head check against what the ledger has left. Default `\"internal\"`,\n * the pool every storage call is charged to.\n */\n readonly requestPool?: RequestPool;\n}\n\n/** The serving host's read envelope; unbounded outside a context that sets one. */\nexport const currentReadEnvelope = (): ReadEnvelope => getCurrentContext()?.readEnvelope ?? {};\n\n/**\n * Storage calls the active invocation's request ledger still allows on\n * `pool`; `Infinity` without a ledger.\n */\nexport const remainingStorageCalls = (pool: RequestPool = \"internal\"): number =>\n currentRequestLedger()?.remaining(pool) ?? Infinity;\n\n/**\n * Which admission check refused a read, carried on the refusal's\n * `cause.bound`. A request-ledger refusal at issue carries the ledger's own\n * cause (`refused: true`) instead.\n */\nexport type ReadRefusalBound =\n | \"snapshotBytes\"\n | \"snapshotRows\"\n | \"tailEntries\"\n | \"tailBytes\"\n | \"materializedRows\"\n | \"outputRows\"\n | \"headStorageCalls\"\n | \"probeStorageCalls\";\n\nconst refuseRead = (\n collection: string,\n bound: ReadRefusalBound,\n why: string,\n remedy: string,\n): BaerlyError =>\n new BaerlyError(\n \"CapacityExceeded\",\n `this read of collection ${JSON.stringify(collection)} ${why}, more than one request can ` +\n `do on this host, so it was refused and returned no rows. ${remedy}`,\n { resolution: remedy, cause: { bound } },\n );\n\n// Each refusal's remedy closes its message and is its `resolution`: the\n// code's canonical resolution is the write remedy, which is wrong for a\n// read. State plus an app-side remedy, never a host setting.\n\n/** Only for the output bound: a narrower predicate or a limit shrinks the answer, not the load. */\nconst NARROW = \"Do not retry unchanged: narrow the predicate or add a limit.\";\nconst TAIL =\n \"Retry once maintenance has absorbed the pending writes: later writes run it as they commit, \" +\n \"and so does a scheduled runScheduledMaintenance call. Until then this read is refused.\";\nconst OUTGROWN =\n \"Do not retry unchanged: delete or shrink rows, or export the collection with baerly admin dump.\";\nconst MATERIALIZED =\n \"Delete or shrink rows, or retry once maintenance has absorbed the pending writes (later writes \" +\n \"and scheduled runScheduledMaintenance calls run it). Otherwise export the collection with \" +\n \"baerly admin dump.\";\n\n/**\n * One read's admission state. Built after the read GETs `current.json`;\n * {@link admitHead} runs before any other storage call, and the other\n * methods as the read stages its work. A refusal is always\n * `CapacityExceeded`, not retriable, whose `resolution` is the remedy for\n * the bound it hit.\n */\nexport class ReadBudget {\n readonly #collection: string;\n readonly #envelope: ReadEnvelope;\n #snapshotRows = 0;\n #tailEntries = 0;\n #tailBytes = 0;\n\n constructor(collection: string, envelope: ReadEnvelope = currentReadEnvelope()) {\n this.#collection = collection;\n this.#envelope = envelope;\n }\n\n /** The pool the host's storage charges; see {@link ReadEnvelope.requestPool}. */\n get requestPool(): RequestPool {\n return this.#envelope.requestPool ?? \"internal\";\n }\n\n /**\n * Refuse from the head alone when the read cannot fit (stage 1). Every\n * read folds up front: it loads the snapshot and walks the strict log\n * range `[log_seq_start, tail_hint)`. Every figure here is a lower bound\n * on the read's work, because `tail_hint` never passes the true tail.\n *\n * @throws BaerlyError code=\"CapacityExceeded\"\n */\n admitHead(head: CurrentJson): void {\n const strict = Math.max(0, head.tail_hint - head.log_seq_start);\n if (strict > (this.#envelope.maxTailEntries ?? Infinity)) {\n throw this.#tailEntriesRefusal(strict);\n }\n this.admitSnapshot(head, strict);\n // The snapshot, the strict range, and the probe's closing empty slot.\n const calls = 1 + strict + (head.snapshot === null ? 0 : 1);\n const left = remainingStorageCalls(this.requestPool);\n if (calls > left) {\n throw refuseRead(\n this.#collection,\n \"headStorageCalls\",\n `must issue at least ${calls} storage calls, over the ${left} this request has left`,\n TAIL,\n );\n }\n }\n\n /**\n * Admit loading the snapshot `head` names, before its GET: its bytes and\n * rows, and its rows plus `pendingEntries` (the tail entries the read\n * will fold at least, beyond those already charged) toward\n * materialization.\n *\n * @throws BaerlyError code=\"CapacityExceeded\"\n */\n admitSnapshot(head: CurrentJson, pendingEntries = 0): void {\n const env = this.#envelope;\n if (head.snapshot_bytes > (env.maxSnapshotBytes ?? Infinity)) {\n throw refuseRead(\n this.#collection,\n \"snapshotBytes\",\n `must load a ${head.snapshot_bytes}-byte snapshot, over the ${env.maxSnapshotBytes} bytes it may load`,\n OUTGROWN,\n );\n }\n if (head.snapshot_rows > (env.maxSnapshotRows ?? Infinity)) {\n throw refuseRead(\n this.#collection,\n \"snapshotRows\",\n `must decode ${head.snapshot_rows} snapshot rows, over the ${env.maxSnapshotRows} it may decode`,\n OUTGROWN,\n );\n }\n this.#snapshotRows = head.snapshot_rows;\n this.#checkMaterialized(this.#tailEntries + pendingEntries);\n }\n\n /**\n * Charge one log entry's stored body before it is decoded (stage 2).\n * Bound so it can be passed as a callback.\n *\n * @throws BaerlyError code=\"CapacityExceeded\"\n */\n readonly chargeTailBody = (bytes: number): void => {\n const env = this.#envelope;\n this.#tailEntries += 1;\n this.#tailBytes += bytes;\n if (this.#tailEntries > (env.maxTailEntries ?? Infinity)) {\n throw this.#tailEntriesRefusal(this.#tailEntries);\n }\n if (this.#tailBytes > (env.maxTailBytes ?? Infinity)) {\n throw refuseRead(\n this.#collection,\n \"tailBytes\",\n `must load more than ${env.maxTailBytes} bytes of pending log entries`,\n TAIL,\n );\n }\n this.#checkMaterialized(this.#tailEntries);\n };\n\n /**\n * The refusal for a forward probe that ran out of request budget before\n * it found the tail.\n */\n readonly probeRefusal = (): BaerlyError =>\n refuseRead(\n this.#collection,\n \"probeStorageCalls\",\n `must probe more pending log entries than this request has storage calls left`,\n TAIL,\n );\n\n /**\n * Refuse an answer over the output bound whole, never a truncated one.\n *\n * @throws BaerlyError code=\"CapacityExceeded\"\n */\n admitOutput(rows: number): void {\n const max = this.#envelope.maxOutputRows ?? Infinity;\n if (rows > max) {\n throw refuseRead(\n this.#collection,\n \"outputRows\",\n `returns ${rows} rows, over the ${max} it may return`,\n NARROW,\n );\n }\n }\n\n #checkMaterialized(tailEntries: number): void {\n const rows = this.#snapshotRows + tailEntries;\n const max = this.#envelope.maxMaterializedRows ?? Infinity;\n if (rows > max) {\n throw refuseRead(\n this.#collection,\n \"materializedRows\",\n `must decode at least ${rows} rows before filtering, over the ${max} it may decode`,\n MATERIALIZED,\n );\n }\n }\n\n #tailEntriesRefusal(entries: number): BaerlyError {\n return refuseRead(\n this.#collection,\n \"tailEntries\",\n `must load at least ${entries} pending log entries, over the ${this.#envelope.maxTailEntries} it may load`,\n TAIL,\n );\n }\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 { 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 three hold:\n *\n * 1. **Same session.** `existing.session === self.session`. The\n * session id is a per-commit, in-RAM-only secret minted at\n * `Writer.commit` from `crypto.randomUUID().slice(0,\n * SESSION_ID_LENGTH)`; an adversary with bucket-write access\n * can forge any other field but cannot forge a value they\n * did not observe being PUT.\n * 2. **Matching seq.** `existing.seq === self.expectedSeq`. The\n * seq match is also implied by the key shape (the writer\n * reads `/log/<expectedSeq>.json`), but is re-asserted here\n * so the invariant is visible at the decision site.\n * 3. **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 *\n * When any of (1)/(2)/(3) fails, the caller MUST refuse adoption\n * and treat the occupant as a conflicting committed entry.\n *\n * A fourth precondition — single-input commit — is now structural,\n * not a runtime check: `#singleAttemptCommit` takes one `CommitInput`,\n * so a multi-input commit is unrepresentable. It matters because the\n * single `log/<seq>` create is the all-or-nothing commit point, so\n * per-input adoption decisions could not compose.\n *\n * ## Threat model\n *\n * The adversary may (a) write arbitrary bytes to any key in the\n * bucket, (b) replay any PUT they previously observed on the wire,\n * (c) reorder or drop network packets between the writer and the\n * bucket. The adversary may NOT (d) read the writer's local RAM\n * and therefore cannot learn the per-commit `session` id before\n * observing the writer's own `/log/<seq>.json` PUT. Under these\n * constraints, conditions (1)+(2)+(3) close every attack path in\n * the adversarial-replay property test\n * (`tests/integration/log-conflict-adversarial.test.ts`).\n *\n * **Pinned by:** `tests/integration/log-conflict-forgery.test.ts`\n * exercises the session-id-unguessability claim under a\n * `ForgeryStorage` adversary that plants arbitrary entries at the\n * writer's expected log key. Property verified by default at\n * `numRuns: 1000`; `FC_NUM_RUNS=10000` for the hardening sweep.\n *\n * ## Prior art\n *\n * SlateDB's manifest-pivot writer protocol (rfcs/0001-manifest.md,\n * scenarios 1–4) is the closest published prior art on the broader\n * commit-protocol skeleton. SlateDB's scenario 3 — \"conflicting SST\n * has same `writer_epoch` as me\" — is explicitly labelled an\n * **illegal state that should panic**. The three-clause adoption\n * decision encoded here (same session ∧ matching seq ∧ matching intent)\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 wider prior-art comparison.\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\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\";\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 (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 // slot in `#singleAttemptCommit` (one `Date.now()`), the Writer\n // sends that entry once, and the adapter's retries re-send the same\n // bytes, so a real read-back is byte-identical to `self`,\n // `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","import { BaerlyError, type DocumentData } from \"@baerly/protocol\";\nimport type { CodecCode, CodecFail } from \"./snapshot-codec.ts\";\n\nconst throwBaerlyError: CodecFail = (code, message, cause) => {\n throw new BaerlyError(code, `post-image: ${message}`, { cause });\n};\n\n/**\n * Assert that an insert/update post-image names the document it is stored\n * under: `after` is a plain object (prototype `Object.prototype` or `null`,\n * not an array) whose own enumerable data property `_id` is a string\n * `=== docId`.\n *\n * This checks identity only. It does not validate `docId` against the\n * `utf8-scalar-v1` domain, and it does not validate any other field of the\n * document. Callers that need the scalar domain call `assertSnapshotDocId`\n * first.\n *\n * `code` selects the failure polarity: `InvalidConfig` for caller input,\n * `InvalidResponse` for stored input. Failures go through `fail` when given,\n * so a codec keeps its own message prefix; otherwise this throws a\n * `BaerlyError` with `code`.\n */\nexport function assertPostImageIdentity(\n docId: string,\n after: unknown,\n code: CodecCode,\n fail: CodecFail = throwBaerlyError,\n): asserts after is DocumentData {\n if (after === null || typeof after !== \"object\" || Array.isArray(after)) {\n fail(code, \"after must be a document object\");\n }\n const prototype = Object.getPrototypeOf(after);\n if (prototype !== Object.prototype && prototype !== null) {\n fail(code, \"after must be a plain object\");\n }\n const descriptor = Object.getOwnPropertyDescriptor(after, \"_id\");\n if (descriptor === undefined || !descriptor.enumerable || !(\"value\" in descriptor)) {\n fail(code, \"after._id must be an own enumerable data property\");\n }\n if (typeof descriptor.value !== \"string\" || descriptor.value !== docId) {\n fail(code, \"after._id must equal doc_id\");\n }\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), then **creates `log/<seq>` via `If-None-Match: \"*\"`.\n * That create IS the commit / linearization 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-004\n * (`docs/adr/004-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 * **First insert wins.** An `I` carrying {@link CommitInput.insertGuard}\n * reads the log window its caller's absence check could not see and\n * refuses to commit over a live row a peer's `I` put there\n * (`AlreadyExists`), so of concurrent inserts of one `doc_id` at most one\n * commits (exactly one, absent storage failures). See {@link InsertGuard}\n * and `docs/spec/sync-protocol.md` §\"Insert: the first `I` wins\".\n *\n * **Caller re-decisions.** A {@link CommitAdmission} re-runs the caller's\n * decision over the same window; its verdict may replace a `U`'s\n * post-image, which the write verbs use to re-apply an update to the\n * newest version of its row. See {@link CommitVerdict} and\n * `docs/spec/sync-protocol.md` §\"Update and delete: decided on the newest\n * row version\".\n *\n * **Crash safety.** The `log/<seq>` create is the commit's only write.\n * `LogEntry.after` is the authoritative post-image, so a crash before the\n * create leaves nothing of the commit on the bucket, and a crash after it\n * leaves a durable commit. The writer maintains no secondary objects:\n * declared indexes change no storage call (ADR-004 Q4, superseded in 0.7).\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 assertDocumentSize,\n CODE_RESOLUTIONS,\n COMMIT_RESOLUTION_RESERVE,\n type CurrentJson,\n type CurrentJsonRead,\n type DocumentData,\n type LogEntry,\n type MetricsRecorder,\n certifiedDeleteFloor,\n createCurrentJson,\n decodeJsonBytes,\n encodeJsonBytes,\n logObjectKey,\n logSeqStartOf,\n mintGeneration,\n BaerlyError,\n isWriteConflict,\n noopMetricsRecorder,\n type Storage,\n LOG_FORWARD_PROBE_CAP,\n MAX_PARALLEL_LOG_READS,\n MAINTENANCE_PROFILE_CF_FREE,\n MAINTENANCE_TAIL_HINT_REFRESH_WRITES,\n SESSION_ID_LENGTH,\n STORAGE_RETRY_MAX_ATTEMPTS,\n countKey,\n readCurrentJson,\n timestamp,\n uuid,\n} from \"@baerly/protocol\";\nimport {\n assertDocId,\n assertStoredDocId,\n insertAlreadyExists,\n insertReplaysRow,\n recordInsertReplay,\n} from \"./doc-id.ts\";\nimport { assertKeyWithinLimit } from \"./key-limit.ts\";\nimport { walkLogRange } from \"./log-walk.ts\";\nimport { findLogTail, probeTailFrom } from \"./log-tail.ts\";\nimport { tryAdoptOwnSessionLogEntry } from \"./log-conflict-adoption.ts\";\nimport { dispatchWriteTick, shouldFireMaintenance } from \"./maintenance.ts\";\nimport type { InternalBoundedMaintenanceOptions } from \"./maintenance-options.ts\";\nimport { getCurrentContext, runWithContext } from \"./observability/context.ts\";\nimport { assertPostImageIdentity } from \"./post-image-identity.ts\";\nimport { isOwnCollection } from \"./collection-alias.ts\";\n\nconst ctxMetrics = (): MetricsRecorder => getCurrentContext()?.recorder ?? noopMetricsRecorder;\n\n/**\n * Tunables for {@link Writer}. All optional.\n *\n * There is no Writer retry knob: the `Storage` adapter retries each\n * request under the one storage retry policy, and the Writer resolves an\n * uncertain log create by occupant readback rather than resending it.\n */\nexport interface WriterOptions {\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: the walk issues `O(tail)`\n * Class-B GETs on every commit. 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 /**\n * The document primary key. Becomes {@link LogEntry.doc_id}. Must be\n * NFC for `I` / `U`; a `D` accepts any key-safe id, so a row stored\n * under a non-NFC id by an earlier release stays deletable.\n */\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 * First-insert-wins guard. Valid only with `op: \"I\"`; any other op\n * throws `InvalidConfig` before I/O. See {@link InsertGuard}.\n *\n * @internal — set by `Collection.insert` (`runInsert` in `./query.ts`).\n */\n readonly insertGuard?: InsertGuard;\n\n /**\n * Force the post-commit maintenance tick (main-10 G6): dispatch it even\n * when the ratio-OR-boundary gate is closed, and let it bypass Gate 1\n * inside the runner. Ignored under `BAERLY_MAINTENANCE_DISABLE`.\n *\n * @internal — set by the write verbs in `./query.ts` while a growth\n * write would be refused (`capacityDecision`'s `pressure`).\n */\n readonly forceMaintenance?: boolean;\n\n /**\n * Commit-time re-check of a decision the caller made at a log tail it\n * read (main-10 G5-race). See {@link CommitAdmission}.\n *\n * @internal — set by the write verbs in `./query.ts` for the capacity\n * re-check (`capacityDecision`).\n */\n readonly admission?: CommitAdmission;\n}\n\n/**\n * Backward validation of a caller's decision, like {@link InsertGuard}\n * but with the decision supplied by the caller. The caller decided to\n * commit from the collection state folded through log tail `fromSeq`.\n * The writer reads every log entry in `[fromSeq, seq)` (the same window\n * read as the insert guard, shared with it when both are set) and passes\n * it to `check` before the first create, and again with the longer\n * window after each lost create race, before the next create.\n * `check` throws to refuse; nothing is committed. It may instead return a\n * {@link CommitVerdict} whose `body` replaces a `U`'s post-image: the\n * write verbs re-apply an update to the newest version of its row this\n * way (EvalPlanQual; `docs/spec/sync-protocol.md` §\"Update and delete:\n * decided on the newest row version\").\n *\n * Precondition: `fromSeq` is a tail a read-path probe observed on this\n * collection's log, or one past a seq the caller's own commit landed at.\n * With an `insertGuard`, it must equal `absentBelowSeq`.\n *\n * @internal\n */\nexport interface CommitAdmission {\n /** The log tail the caller's decision folded through. */\n readonly fromSeq: number;\n /**\n * Re-decide over `window`, every entry in `[fromSeq, tail)` in seq\n * order, where `tail` is the slot the next create targets. Throw to\n * refuse the commit. The verdict of the last call before the winning\n * create decides what commits; `undefined` keeps the input as given.\n */\n readonly check: (\n window: readonly LogEntry[],\n tail: number,\n ) => CommitVerdict | undefined | Promise<CommitVerdict | undefined>;\n}\n\n/**\n * What a {@link CommitAdmission.check} call decided.\n *\n * @internal\n */\nexport interface CommitVerdict {\n /**\n * Force the post-commit maintenance tick, as\n * {@link CommitInput.forceMaintenance} does.\n */\n readonly forceMaintenance?: boolean;\n /**\n * The post-image to commit instead of {@link CommitInput.body}; valid\n * only on a `U`, and identity-checked like the input body.\n */\n readonly body?: DocumentData;\n}\n\n/**\n * Backward validation for an `I` commit. The caller has already checked\n * that the doc has no live row in the collection state folded through\n * log tail `absentBelowSeq`. The writer then reads every log entry in\n * `[absentBelowSeq, seq)` — the window that check could not see — and\n * refuses the commit with `AlreadyExists` when the last entry for this\n * `(collection, doc_id)` in it is an `I` or `U`. So the first `I` for a\n * `doc_id` wins, and a concurrent later insert commits nothing.\n *\n * With `replayIdentical`, a live last entry whose `after` equals the\n * insert's body is not a collision but this insert's own earlier success\n * (an SDK resending an auto-ID insert): the commit returns that entry and\n * writes nothing.\n *\n * Precondition: `absentBelowSeq` is a tail observed on this\n * collection's log by a read-path probe (the first empty slot it found).\n * A value above the true tail would make the writer create past a hole.\n *\n * @internal\n */\nexport interface InsertGuard {\n /** The log tail the caller's absence check folded through. */\n readonly absentBelowSeq: number;\n /**\n * Treat a live `I` / `U` for the doc whose `after` equals the body\n * (`insertReplaysRow`) as this insert's original success: return it\n * as the commit result, with no create and no maintenance tick. Set only for an\n * SDK-minted `_id` (`runInsert`'s `mintedId`); a caller-chosen `_id`\n * keeps strict `AlreadyExists`. Default `false`.\n */\n readonly replayIdentical?: boolean;\n}\n\n/** Return shape of {@link Writer.commit}. */\nexport interface CommitResult {\n /**\n * The committed `LogEntry`. Caller can ack on `entry.lsn`. For a\n * guarded insert that replayed ({@link InsertGuard.replayIdentical}),\n * it is instead the stored live `I` / `U` in the guarded window whose\n * `after` the body matched, written by an earlier commit, and this call\n * wrote nothing.\n */\n readonly entry: LogEntry;\n\n /**\n * ETag of `current.json` as read at the start of the commit (Step 1),\n * on a replay as on a commit. The commit path never writes\n * `current.json` (the `log/<seq>` create IS the commit), so this is the\n * manifest's pre-commit ETag, not a post-write one.\n */\n readonly currentEtag: string;\n}\n\nconst APPLICATION_JSON = \"application/json\";\n\n/**\n * Successful outcome of one full {@link Writer.#singleAttemptCommit}\n * attempt: either it committed (`replayed: false`, with the commit's\n * Class A op count), or a guarded insert replayed a stored identical row\n * (`replayed: true`) and committed nothing, so it is not a logical write.\n * Rejected creates resolve by readback or throw non-retriable\n * `AmbiguousCommit`; exceeding the foreign-occupant forward-probe budget\n * throws `Internal`. Failures before dispatching the create, and a\n * definitive rejection of the slot's only send, propagate.\n */\ntype SingleAttemptSuccess =\n | {\n readonly replayed: false;\n readonly entries: readonly LogEntry[];\n readonly currentEtag: string;\n readonly classAOps: number;\n }\n | {\n readonly replayed: true;\n readonly entries: readonly LogEntry[];\n readonly currentEtag: string;\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);\n * ```\n */\nexport class Writer {\n readonly #storage: Storage;\n readonly #currentJsonKey: string;\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 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.#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), then creates `log/<seq>` via\n * `If-None-Match: \"*\"` — that create IS the commit (single-write\n * commit; no `current.json` CAS follows it).\n *\n * The hot-path cost under no contention is 3 GETs + 1 PUT, whatever\n * indexes the collection declares: the Step 1 `current.json` read,\n * `findLogTail`'s forward probe (one 404 GET when `tail_hint` is\n * accurate, `O(log gap)` GETs when it lags a fold interval), the\n * committing `log/<seq>` create, and the post-create `current.json`\n * re-read that rejects a create landing below the certified delete\n * floor (`#assertCommitAboveDeleteFloor`). A peer that won the slot\n * costs one occupant readback GET, the forward probe's GETs, and one\n * more create at the next slot.\n *\n * Idempotency: `LogEntry.after` carries the full post-image, and the\n * `log/<seq>` create uses `If-None-Match: \"*\"`, so two writers racing\n * 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 * **Uncertain commit fate.** If the committing create wins at a\n * `seq` the collection has already certified deleted — reachable when a\n * create PUT or a lost-ack retry straddles a fold plus a retirement pass —\n * the object it wrote is beneath every reader's floor. The commit then fails\n * with `AmbiguousCommit` rather than acknowledging a mutation no fresh\n * reader can see. The writer cannot tell whether an earlier attempt of its\n * own landed and was folded before retirement removed the slot, so the\n * mutation may or may not have been applied. The same uncertainty exists\n * when a rejected create cannot be resolved by reading its slot, including\n * rejections that follow a send of unknown outcome. The Writer never\n * resends a create at the same slot (the adapter already retried it); it\n * reads the slot back once instead. A missing readback does not prove that\n * an earlier send will not land. Exact own-entry readback is adopted; an\n * unresolved fate throws `AmbiguousCommit` with `err.retriable === false`.\n * Reconcile state before deliberately retrying: a new logical call can\n * duplicate work, including minting a second auto-ID document.\n *\n * @throws BaerlyError code=\"AmbiguousCommit\" when the committing create\n * landed below `min(log_delete_floor, log_seq_start)`, or a possibly\n * durable create could not be resolved. The mutation's fate is unknown;\n * `err._id` is `input.docId`.\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 * @throws BaerlyError code=\"InvalidConfig\" when `docId` breaks the\n * key-segment rule, when an `I` / `U` `docId` is not NFC, when an\n * `I` / `U` body is not a plain object whose own `_id` is the string\n * `docId`, when an `I` / `U` post-image encodes to more than\n * `MAX_DOCUMENT_BYTES`, or when `insertGuard` is set on a non-`I` op.\n * Checked before any I/O (an admission verdict's replacement\n * post-image is size-checked when it is returned).\n * @throws BaerlyError code=\"AlreadyExists\" when `insertGuard` is set and\n * the log window `[absentBelowSeq, seq)` holds a live `I` / `U` for\n * this doc (unless `replayIdentical` is set and its `after` equals the\n * body, which returns that entry instead). Nothing was committed;\n * `err._id` is `input.docId`.\n * @throws BaerlyError code=\"WriteConflict\" when `insertGuard` or\n * `admission` is set and part of its window was folded and retired (or\n * is longer than `LOG_FORWARD_PROBE_CAP`) before the writer could read\n * it. Nothing was committed; re-read and retry.\n * @throws BaerlyError code=\"CapacityExceeded\" when the request ledger\n * cannot afford this commit's create and `COMMIT_RESOLUTION_RESERVE`,\n * checked before each create; or when the ledger refused the create\n * itself before any attempt was sent (`cause.notApplied`), or any\n * storage call before it. Nothing was committed.\n * @throws whatever `admission.check` throws (the write verbs throw\n * `CapacityExceeded` or `MaintenancePending`). Nothing was committed.\n *\n * **Window cost.** A commit with `insertGuard` or `admission` probes the\n * tail linearly from `max(windowFrom, log_seq_start)` with\n * `probeTailFrom` instead of galloping from\n * `max(log_seq_start, tail_hint)`. Uncontended, `windowFrom` is the\n * tail, so that is one 404 GET. Each entry a peer committed after the\n * caller's read costs one more GET, and if a fold moved `log_seq_start`\n * past `windowFrom`, each folded slot in between costs one GET too.\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 // An `I` / `U` mints a row identity, so it must also be NFC: one id\n // has one byte form, whatever key canonicalization a backend applies\n // to a future id-keyed object. A `D` only names an existing row, which\n // an earlier release may have stored under a non-NFC id.\n if (input.op === \"D\") {\n assertStoredDocId(input.docId);\n } else {\n assertDocId(input.docId);\n }\n // An `I` / `U` post-image must name the document it is stored under:\n // a plain object whose own `_id` is the string `docId`. Without this,\n // `log/<seq>` would record a row whose `after._id` disagrees with its\n // `doc_id`, and later reads key that row by the wrong id.\n if (input.op !== \"D\") {\n assertPostImageIdentity(input.docId, input.body, \"InvalidConfig\");\n // The committed post-image is bounded, whatever the write path: an\n // in-process call has no body cap, and a merge-patch within one can\n // still grow the row. A `D` is never checked, so a row stored larger\n // by an earlier release stays deletable.\n assertDocumentSize(input.body, \"Writer\");\n }\n if (input.insertGuard !== undefined) {\n assertInsertGuardShape(input);\n }\n if (input.admission !== undefined) {\n assertAdmissionShape(input);\n }\n const session = uuid().slice(0, SESSION_ID_LENGTH);\n const logPrefix = this.#currentJsonKey.slice(0, this.#currentJsonKey.lastIndexOf(\"/\"));\n\n // One attempt: a log-create 412 is resolved inside it (own-session\n // adoption or a bounded forward-probe), and nothing after the create\n // may re-run it — a durable create re-run at a fresh tail would\n // duplicate the logical write.\n const success = await this.#singleAttemptCommit(input, session, logPrefix, \"Writer\");\n // A replay committed nothing, so it is not a logical write and records\n // no write-amplification sample; it is counted as a replay instead.\n if (success.replayed) {\n recordInsertReplay(input.collection);\n } else {\n this.#emitWriteMetrics(input.collection, success.classAOps);\n }\n return {\n entry: success.entries[0]!,\n currentEtag: success.currentEtag,\n };\n }\n\n /**\n * One full commit attempt — the body of {@link commit}. Reads\n * `current.json`, then forward-probes the tail and creates `log/<seq>`\n * once via `If-None-Match: \"*\"` — the numbered log create IS the commit\n * (single-write commit; no `current.json` CAS follows it). Returns the\n * success payload.\n *\n * Commits exactly one {@link CommitInput} — the numbered log create is\n * the single linearization point per call.\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 create at the next\n * empty slot. Each slot gets one `Storage.put` and never a same-slot\n * resend, because the adapter already retried it. A definitive\n * `AccessDenied` / `InvalidConfig` propagates as-is. A 412 or an uncertain\n * failure resolves by one occupant readback, because adapters can hide\n * earlier sends. When the call reports every attempt refused unapplied\n * (`cause.notApplied`), the same readback runs because a throttle can hide\n * a lost race: a foreign occupant forward-probes, a slot read back as\n * empty or unreadable propagates the retriable `NetworkError`: the\n * adapter already guarantees no attempt applied or can still apply.\n * Unresolved creates throw non-retriable `AmbiguousCommit`; failures\n * before the create propagate.\n *\n * Crash safety: the create is the attempt's only write. A crash before\n * it leaves nothing; a crash after it is a durable, committed write at\n * `seq`, carrying its full post-image in `LogEntry.after`.\n */\n async #singleAttemptCommit(\n input: 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 //\n // A guarded insert (`input.insertGuard`) or an admission re-check\n // (`input.admission`) instead reads every entry in its unseen window\n // `[windowFrom, tail)`: Step 3a GETs the part a fold already moved\n // below `log_seq_start`, and Step 3b probes the rest with\n // `probeTailFrom`, which returns the entries it passes.\n const guard = input.insertGuard;\n const admission = input.admission;\n const windowFrom = guard?.absentBelowSeq ?? admission?.fromSeq;\n const logSeqStart = logSeqStartOf(current);\n let commitWindow: LogEntry[] | undefined;\n // Whether the latest `admission.check` asked to force the write tick.\n let admissionForces = false;\n // The post-image this attempt commits: the input's, or the latest\n // `admission.check` verdict's.\n let body = input.body;\n const decide = async (window: readonly LogEntry[], tail: number): Promise<void> => {\n if (admission === undefined) {\n return;\n }\n const verdict = await admission.check(window, tail);\n admissionForces = verdict?.forceMaintenance === true;\n if (verdict?.body !== undefined) {\n if (input.op !== \"U\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${errorPrefix}: an admission verdict may replace only a U post-image; got op ${JSON.stringify(input.op)}`,\n );\n }\n assertPostImageIdentity(input.docId, verdict.body, \"InvalidConfig\");\n assertDocumentSize(verdict.body, errorPrefix);\n body = verdict.body;\n }\n };\n let preCommitTail: number;\n if (windowFrom === undefined) {\n const probeFloor = Math.max(logSeqStart, 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 preCommitTail = await findLogTail(this.#storage, logPrefix, probeFloor);\n } else {\n // ── Step 3a. Folded part of the window, `[windowFrom, floor)`.\n const folded = await this.#readFoldedWindow(logPrefix, windowFrom, logSeqStart, errorPrefix);\n // ── Step 3b. Live part, probed from `max(windowFrom, floor)`.\n // That start meets `probeTailFrom`'s retention precondition (it is\n // at or above this manifest read's `log_seq_start`) and sits in the\n // dense prefix: `windowFrom` was the first empty slot a read probe\n // found with every slot from its floor up occupied (or one past a\n // slot the caller's own create won), creates only ever land at a\n // first-empty slot, and retirement stays below `log_seq_start`.\n // Starting below `tail_hint` re-reads the slots in\n // `[windowFrom, tail_hint)`; those are exactly the window entries the\n // caller's decision could not see, so none of the GETs is wasted.\n // Uncontended, `windowFrom` is the tail: one 404 GET, never more\n // than the gallop above.\n const probe = await probeTailFrom(\n this.#storage,\n logPrefix,\n Math.max(windowFrom, logSeqStart),\n );\n commitWindow = [...folded, ...probe.entries];\n // ── Step 3c. Window decisions, BEFORE the first create, so a loser\n // caught here writes nothing at all, and a replay of an identical\n // live row returns it having written nothing.\n // The insert decision runs first: a peer's live row is\n // `AlreadyExists` whatever the capacity re-check would say.\n if (guard !== undefined) {\n const replayed = decideInsertTarget(commitWindow, input);\n if (replayed !== undefined) {\n return { replayed: true, entries: [replayed], currentEtag: baseEtag };\n }\n }\n await decide(commitWindow, probe.tail);\n preCommitTail = probe.tail;\n }\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 mintEntry = (atSeq: number): LogEntry => ({\n lsn: `${lsnTimestamp}_${session}_${countKey(atSeq)}`,\n commit_ts: commitTs,\n op: input.op,\n collection: input.collection,\n doc_id: input.docId,\n session,\n seq: atSeq,\n ...(input.op !== \"D\" && body !== undefined ? { after: body } : {}),\n ...(input.origin !== undefined ? { origin: input.origin } : {}),\n });\n let entry = mintEntry(seq);\n\n // ── Step 4. 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 // The commit-resolution reserve (`COMMIT_RESOLUTION_RESERVE`): each\n // slot's attempt (the create, the readback, and on a resolved commit\n // the Step 4a floor check) runs under a request ledger hold of\n // everything it may spend, taken only if it fits; otherwise\n // `CapacityExceeded`, with nothing of the attempt sent.\n //\n // Each slot gets exactly ONE `storage.put`: the adapter already retried\n // it under the storage retry policy, so a Writer-level resend would\n // multiply that policy's attempts (retry at one layer). The outcome of\n // that one call decides the next step:\n // - success ⇒ committed at `seq`;\n // - `cause.notApplied` (every attempt provably unapplied) ⇒ one\n // occupant readback, because a throttle may hide a lost race: own\n // entry ⇒ adopt; foreign ⇒ forward-probe; an observed empty slot\n // or unreadable ⇒ the retriable `NetworkError` propagates;\n // - `AccessDenied` / `InvalidConfig` ⇒ definitive under the\n // `Storage.put` contract; propagates as-is;\n // - a 412, or any other failure (an uncertain send — e.g. a dropped\n // ack on a create that may already have landed) ⇒ one occupant\n // readback. Own entry ⇒ adopt; foreign ⇒ forward-probe (a new\n // slot, not a resend); absent or unreadable ⇒ `AmbiguousCommit`,\n // because an absent slot cannot prove an in-flight send won't land.\n // A lost ack resolves without a resend: the adapter's own next attempt\n // sees the landed object as a 412, or the readback finds it.\n let committedEntry: LogEntry;\n let probes = 0;\n const ambiguous = (cause: unknown): BaerlyError => {\n ctxMetrics().counter(\"db.write.unresolved_create_total\", 1, {\n collection: entry.collection,\n });\n return new BaerlyError(\n \"AmbiguousCommit\",\n `${errorPrefix}: the committing create at seq ${seq} on ${this.#currentJsonKey} was rejected and its fate could not be resolved; an earlier send may already have landed or may still land, so retrying may duplicate logical work`,\n { cause, resolution: CODE_RESOLUTIONS.AmbiguousCommit, _id: entry.doc_id },\n );\n };\n for (;;) {\n const outcome = await this.#withCommitHold(\n errorPrefix,\n async (): Promise<{ committed: LogEntry } | { foreign: LogEntry }> => {\n const logEntryKey = logObjectKey(logPrefix, seq);\n assertKeyWithinLimit(logEntryKey);\n // Encoded outside the try: an unencodable entry is the caller's\n // error, and no send was made that a readback would need to resolve.\n const entryBody = encodeJsonBytes(entry);\n let resolved: LogEntry | undefined;\n let createFailure: unknown;\n let notApplied = false;\n try {\n await this.#storage.put(logEntryKey, entryBody, {\n ifNoneMatch: \"*\",\n contentType: APPLICATION_JSON,\n });\n resolved = entry;\n } catch (error) {\n createFailure = error;\n this.#observe429(error, entry.collection);\n if (isWriteConflict(error)) {\n ctxMetrics().counter(\"db.r2.put.412_total\", 1, {\n collection: entry.collection,\n step: \"log-put\",\n });\n // Even a visible 412 can be our entry: the adapter may have\n // retried a landed send internally.\n } else if (isDefinitiveCreateRejection(error)) {\n // `Storage.put` contract: no attempt of this call was applied,\n // and this is the slot's only send, so nothing of ours is at\n // `seq`.\n throw error;\n } else if (isCreateNotApplied(error)) {\n // A throttle can hide a lost race (R2 can answer a same-key\n // create race with a 429, not a 412), so the readback still\n // tells a peer's slot from an empty one.\n notApplied = true;\n }\n }\n if (resolved === undefined) {\n let occupant: LogEntry;\n let decision: ReturnType<typeof tryAdoptOwnSessionLogEntry>;\n try {\n occupant = await this.#readLogOccupant(logEntryKey);\n decision = tryAdoptOwnSessionLogEntry({ self: entry, existing: occupant });\n } catch (error) {\n if (notApplied) {\n // The adapter guarantees no attempt applied or can still\n // apply. An empty, unreadable, or malformed slot cannot make\n // retry unsafe.\n throw createFailure;\n }\n throw ambiguous(\n new AggregateError(\n [createFailure, error],\n \"The create and its readback could not be resolved\",\n ),\n );\n }\n if (!decision.adopt) {\n return { foreign: occupant };\n }\n // Own crashed/lost-ack commit already durable at `seq`. Adopt it\n // (byte-identical to the attempted `entry`, INCLUDING\n // `commit_ts` — adoption compares the full entry) — the logical\n // write lands at EXACTLY `seq`, never duplicated.\n resolved = decision.entry;\n }\n // ── Step 4a. Refuse a create that re-filled a retired hole. ─────\n // Both resolved paths above land here with the resolved committing\n // `seq`: the fresh win and the own-session adoption.\n await this.#assertCommitAboveDeleteFloor(\n logPrefix,\n seq,\n input.collection,\n input.docId,\n errorPrefix,\n );\n return { committed: resolved };\n },\n );\n if (\"committed\" in outcome) {\n committedEntry = outcome.committed;\n break;\n }\n const occupant = outcome.foreign;\n // Foreign session (or wrong seq) — re-probe forward from seq+1 and\n // create at the new first-empty slot, re-minting seq + LSN. The hold\n // is released: the occupant proves nothing of this commit landed, so\n // a refusal from here to the next hold is clean.\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 if (commitWindow === undefined) {\n seq = await findLogTail(this.#storage, logPrefix, seq + 1);\n } else {\n // Windowed commit: the occupant and every entry the forward probe\n // passes join the window, and the window decisions re-run before\n // the next create. A refusal here (`AlreadyExists`, or the\n // admission's own error) is sound because a foreign occupant at\n // `seq` proves this commit's send did not land there. A replay of\n // an identical live row returns here for the same reason: nothing\n // of this commit landed.\n commitWindow.push(occupant);\n const probe = await probeTailFrom(this.#storage, logPrefix, seq + 1);\n commitWindow.push(...probe.entries);\n if (guard !== undefined) {\n const replayed = decideInsertTarget(commitWindow, input);\n if (replayed !== undefined) {\n return { replayed: true, entries: [replayed], currentEtag: baseEtag };\n }\n }\n await decide(commitWindow, probe.tail);\n seq = probe.tail;\n }\n entry = mintEntry(seq);\n }\n const committedEntries: readonly LogEntry[] = [committedEntry];\n\n // ── Step 5. 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 // A forced tick (main-10 G6) skips the ratio-OR-boundary gate: the\n // verb found the collection at its growth-refusal point.\n const forceFold =\n (input.forceMaintenance === true || admissionForces) && maint?.disabled !== true;\n // The adapter's host trigger (`InternalBoundedMaintenanceOptions`): a\n // live tail this long fires too, so the runner's Gate 1 sees it.\n const foldAtTailEntries = (maint?.options as InternalBoundedMaintenanceOptions | undefined)\n ?.foldAtTailEntries;\n const maintenanceDue =\n maint?.disabled === true\n ? observedTail - current.tail_hint >= MAINTENANCE_TAIL_HINT_REFRESH_WRITES\n : forceFold ||\n (foldAtTailEntries !== undefined &&\n observedTail - current.log_seq_start >= foldAtTailEntries) ||\n shouldFireMaintenance(current, prevSeq, gcInterval, observedTail);\n if (maintenanceDue) {\n await dispatchWriteTick({\n storage: this.#storage,\n currentJsonKey: this.#currentJsonKey,\n collection: input.collection,\n prevSeq,\n observedTail,\n ...(forceFold && { forceFold: true }),\n });\n }\n\n // Class-A op count for this commit: the committing log create alone.\n // No current.json CAS. Forward-probe and readback GETs are Class B and\n // excluded, as are creates refused at slots a foreign writer won.\n const classAOps = 1;\n return {\n replayed: false,\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 `WriteConflict`; 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`, so an\n * operator who pre-provisions and a writer who auto-creates land on\n * equivalent state. NOT byte-identical any more: `generation` is a\n * fresh nonce per provisioner. That is harmless — `If-None-Match`\n * means exactly one of them ever lands, and no reader compares a\n * generation across provisioners, only against the cursor it minted.\n *\n * @throws BaerlyError code=\"InvalidResponse\" — the post-recover\n * re-read also returned null. Defensive guard; in practice\n * unreachable because the WriteConflict 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 generation: mintGeneration(),\n };\n let createFailure: unknown;\n try {\n return await createCurrentJson(this.#storage, this.#currentJsonKey, initial);\n } catch (error) {\n // A provably unapplied create may hide a peer provisioning the same\n // key, so it recovers by re-read like a 412.\n if (!isWriteConflict(error) && !isCreateNotApplied(error)) {\n throw error;\n }\n createFailure = error;\n }\n const recovered = await readCurrentJson(this.#storage, this.#currentJsonKey);\n if (recovered === null && isCreateNotApplied(createFailure)) {\n throw createFailure;\n }\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 /**\n * Fail the commit if the create landed at a sequence the collection has\n * already certified deleted.\n *\n * **What a sub-floor `seq` proves, and what it does not.** A winning\n * `If-None-Match: \"*\"` create means the slot was empty immediately before the\n * PUT, so the object this commit just wrote sits beneath every reader's floor\n * and no reader will ever consult it. What a sub-floor `seq` does NOT prove\n * is that the *logical mutation* is invisible. Two histories reach this\n * branch: the create re-filled a hole retirement had already certified\n * deleted (invisible — the defect this check exists for), or it landed in a\n * live empty slot that a fold and then a retirement pass swept out from under\n * it (visible through the snapshot). That second history is a real\n * over-rejection, pinned as contract by a test in\n * `./log-retirement-aba.test.ts`, not an accident. It is the safe direction,\n * and \"What the caller is being told\" below is why guessing between the two\n * is worse than reporting both as ambiguous.\n *\n * **`log_delete_floor <= seq < log_seq_start` is NOT a failure.** Not because\n * that band is provably safe — it is undecidable in the very same way. A\n * winning create means the slot was empty just before the PUT, so what a fold\n * absorbed there was either an earlier attempt of ours (mutation visible) or\n * a foreign writer's entry (ours invisible), and the fold keeps no writer\n * identity to tell them apart. The band is accepted because keying the check\n * on `log_seq_start` would reject ordinary post-fold commits — a far\n * larger harm than the residual it would catch. That residual is the\n * invisible half of the undecidable band `docs/spec/sync-protocol.md`\n * invariant 5 describes; it is not reachable by the certified-floor check,\n * by construction.\n *\n * The floor is clamped to `min(log_delete_floor, log_seq_start)` for the\n * reason invariant 12 gives: the `<= log_seq_start` bound is\n * transition-scoped, so an out-of-bound stored floor is readable off disk\n * and would otherwise fail a perfectly good commit.\n *\n * **What the caller is being told.** Not \"your write failed\" —\n * `AmbiguousCommit`. An earlier attempt by this same writer may have landed\n * and been folded before retirement removed the slot, and nothing durable\n * distinguishes that history from a foreign writer's entry being folded\n * instead: the fold keeps no writer identity, tombstones are purged,\n * `current.json` holds no per-writer completion state, and `writer_fence` is\n * not a replay filter (invariant 11). So the write contract under this fault\n * is at-least-once, and re-probing-and-re-applying is emphatically not a\n * safe default: `LogEntry.after` is a full post-image, so a duplicate\n * clobbers a concurrent newer value and mints a second `lsn` for one logical\n * mutation.\n *\n * The phantom object is DELETEd best-effort, and it is the only thing\n * standing between a rejected commit and a permanently leaked object.\n * Nothing reclaims the phantom afterwards: it sits at a seq *below*\n * `log_delete_floor` — that is the precondition for reaching this branch —\n * and `computeRetirableRange` (`./log-retention.ts`) *starts* at the\n * certified floor, so retirement never revisits a slot beneath its own\n * floor. GC does not reclaim log objects at all. So a `cleanup: \"failed\"`\n * on `db.write.ambiguous_commit_total` is a genuine permanent leak, not a\n * deferral. Deleting it is safe: no reader may read below the certified\n * floor (invariant 5). A failed cleanup is recorded on the counter and never masks the\n * throw.\n *\n * **A failed manifest read skips the check rather than failing the commit —\n * except an abort, which propagates.** The check runs over an already-durable\n * create, and an unreadable manifest is no evidence of a sub-floor `seq`, so a\n * transient read failure is swallowed. An `AbortError` is rethrown instead: it\n * is the caller's own cancellation rather than a blip, and it carries none of\n * the `retriable` re-run hazard that motivates swallowing the rest. The skip\n * is recorded on `db.write.delete_floor_check_skipped_total` so a sustained\n * rate is visible to an operator rather than silent.\n *\n * Cost: one Class B GET per commit.\n * `billableClassAOps = puts + lists` excludes GET, so billing is unchanged;\n * it is one of the calls `COMMIT_RESOLUTION_RESERVE` keeps on the request\n * ledger.\n *\n * @throws BaerlyError code=\"AmbiguousCommit\"\n */\n async #assertCommitAboveDeleteFloor(\n logPrefix: string,\n seq: number,\n collection: string,\n docId: string,\n errorPrefix: string,\n ): Promise<void> {\n let read: CurrentJsonRead | null;\n try {\n read = await readCurrentJson(this.#storage, this.#currentJsonKey);\n } catch (error) {\n if (isAbortError(error)) {\n // An abort is the caller's deliberate cancellation, not a transient\n // blip, and the caller already knows it cancelled. The hazard the\n // swallow below exists for is specific to `retriable` errors; an\n // `AbortError` is not one, so rethrowing costs that reasoning nothing.\n throw error;\n }\n // A failed read is not evidence of a sub-floor commit, so skipping the\n // check preserves the pre-existing commit contract exactly and forgoes\n // only a safety net on a rare blip. Propagating instead would be worse\n // than useless: the create already committed, and `NetworkError` is\n // `retriable`, so a generic retry wrapper would re-run the whole logical\n // write at a fresh tail — duplicating the mutation and minting a second\n // `lsn`. The maintenance dispatch after it swallows its non-abort\n // failures for the same reason. Failing closed is not the answer either\n // — throwing `AmbiguousCommit` on an unreadable manifest would reject\n // durable commits far more often than the fault this check catches.\n ctxMetrics().counter(\"db.write.delete_floor_check_skipped_total\", 1, { collection });\n countPostCommitRefusal(error, collection, \"delete-floor-check\");\n return;\n }\n if (read === null) {\n // The manifest vanished between Step 1 and here. Unreachable in\n // practice (Step 1 read or provisioned it), and a missing manifest\n // certifies no deleted prefix, so there is nothing to reject against.\n return;\n }\n const deleteFloor = certifiedDeleteFloor(read.json);\n // `deleteFloor === 0` means no deleted prefix is certified — same silent\n // arm as `Db.assertAtOrAboveLogFloor`.\n if (deleteFloor <= 0 || seq >= deleteFloor) {\n return;\n }\n let cleanup: \"deleted\" | \"failed\" = \"deleted\";\n await this.#storage.delete(logObjectKey(logPrefix, seq)).catch(() => {\n cleanup = \"failed\";\n });\n ctxMetrics().counter(\"db.write.ambiguous_commit_total\", 1, { collection, cleanup });\n throw new BaerlyError(\n \"AmbiguousCommit\",\n `${errorPrefix}: the committing create at seq ${seq} on ${this.#currentJsonKey} landed below the certified delete floor ${deleteFloor}; that log object is beneath every reader's floor, and this mutation may or may not have been applied by an earlier attempt — retry is at-least-once`,\n { resolution: CODE_RESOLUTIONS.AmbiguousCommit, _id: docId },\n );\n }\n\n /**\n * Run one commit slot's attempt, `fn` (the committing create and the\n * calls that resolve it), under a hold on the active request ledger of\n * everything it may spend: the create at full retries, plus\n * {@link COMMIT_RESOLUTION_RESERVE} for the readback and the delete-floor\n * check. `fn` runs in a child observability context carrying the hold, so\n * only its own storage calls draw on it; work outside that context (a\n * `ctx.waitUntil` write tick of an earlier row, the read cache) sees the\n * ledger net of it and cannot spend it. The hold is released when `fn`\n * settles.\n *\n * Refuses, before `fn` sends anything, when the ledger's room is short\n * of the hold. No create of this commit has landed or can land then:\n * before the first slot nothing was sent, and before a later one a\n * foreign occupant holds the slot this commit's only send targeted. A host without request\n * limits (Node, or no ledger) never refuses and takes no hold.\n *\n * @throws BaerlyError code=\"CapacityExceeded\", cause `{ refused: true }`.\n */\n /**\n * The collection segment of `current.json`'s key, for messages that\n * reach HTTP callers unscrubbed (`CapacityExceeded` is `public`), which\n * must not carry the storage key.\n */\n #collectionName(): string {\n const parts = this.#currentJsonKey.split(\"/\");\n return parts[parts.length - 2] ?? \"\";\n }\n\n async #withCommitHold<T>(errorPrefix: string, fn: () => Promise<T>): Promise<T> {\n const ctx = getCurrentContext();\n const ledger = ctx?.ledger;\n const remaining = ledger?.storageRemaining() ?? Infinity;\n if (ctx === undefined || ledger === undefined || remaining === Infinity) {\n return await fn();\n }\n const needed = STORAGE_RETRY_MAX_ATTEMPTS + COMMIT_RESOLUTION_RESERVE;\n if (remaining < needed) {\n throw new BaerlyError(\n \"CapacityExceeded\",\n `${errorPrefix}: this request has ${String(remaining)} storage calls left, fewer than the ${String(needed)} a commit to collection ${JSON.stringify(this.#collectionName())} may need (the committing create, with retries, plus resolving it), so nothing was committed; the work this request needs does not fit in one request on this host`,\n // The HTTP envelope fills in the code's canonical resolution.\n { cause: { refused: true, needed, remaining } },\n );\n }\n const hold = ledger.hold(needed);\n try {\n return await runWithContext({ ...ctx, hold }, fn);\n } finally {\n hold.release();\n }\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 * Read `[fromSeq, logSeqStart)` for a windowed commit (insert guard or\n * admission) whose window starts below the floor of this commit's\n * manifest read: a fold absorbed those entries after the caller's read. Slots below the floor stay\n * readable until log retirement deletes them, so a missing slot means\n * this commit can no longer check its window: `WriteConflict`, nothing\n * committed, and the caller's next read sees the folded state. A window\n * longer than {@link LOG_FORWARD_PROBE_CAP} is refused the same way\n * rather than spending an unbounded run of GETs on the write path.\n *\n * @throws BaerlyError code=\"WriteConflict\" — a slot is missing, or the\n * range exceeds the cap.\n * @throws BaerlyError code=\"InvalidResponse\" — a slot's body is not JSON.\n */\n async #readFoldedWindow(\n logPrefix: string,\n fromSeq: number,\n logSeqStart: number,\n errorPrefix: string,\n ): Promise<LogEntry[]> {\n if (fromSeq >= logSeqStart) {\n return [];\n }\n const refuse = (detail: string): BaerlyError =>\n new BaerlyError(\n \"WriteConflict\",\n `${errorPrefix}: commit window [${fromSeq}, ${logSeqStart}) on ${this.#currentJsonKey} ${detail}; nothing was committed`,\n );\n // Backstop only. In practice the window holds just the entries a fold\n // absorbed between two reads in one request, and the host's\n // subrequest budget ends that request long before 100k GETs.\n if (logSeqStart - fromSeq > LOG_FORWARD_PROBE_CAP) {\n throw refuse(`exceeds ${LOG_FORWARD_PROBE_CAP} folded entries`);\n }\n const entries: LogEntry[] = [];\n for (let chunk = fromSeq; chunk < logSeqStart; chunk += MAX_PARALLEL_LOG_READS) {\n const end = Math.min(chunk + MAX_PARALLEL_LOG_READS, logSeqStart);\n const keys = Array.from({ length: end - chunk }, (_, i) =>\n logObjectKey(logPrefix, chunk + i),\n );\n const bodies = await Promise.all(keys.map((key) => this.#storage.get(key)));\n for (let i = 0; i < bodies.length; i++) {\n const got = bodies[i];\n if (got === null || got === undefined) {\n throw refuse(`was retired at seq ${chunk + i} before it could be checked`);\n }\n try {\n entries.push(decodeJsonBytes<LogEntry>(got.body));\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `${errorPrefix}: malformed log entry at ${keys[i]!}`,\n { cause: error },\n );\n }\n }\n }\n return entries;\n }\n\n /**\n * Read the occupant of a slot whose committing create was rejected, with\n * one `Storage.get` (the adapter retries it; the Writer does not). A failed\n * read, an empty slot, or an occupant without a writer identity throws:\n * none of them proves the slot holds a foreign entry rather than a pending\n * send of our own.\n */\n async #readLogOccupant(key: string): Promise<LogEntry> {\n const got = await this.#storage.get(key);\n if (got === null) {\n throw new BaerlyError(\"NotFound\", `Writer: ${key} is empty after its create was rejected`);\n }\n let existing: unknown;\n try {\n existing = decodeJsonBytes(got.body);\n } catch (error) {\n throw new BaerlyError(\"InvalidResponse\", `Writer: malformed log occupant at ${key}`, {\n cause: error,\n });\n }\n if (!hasWriterIdentity(existing)) {\n // Parsed JSON alone cannot establish a conflicting writer's identity.\n throw new BaerlyError(\"InvalidResponse\", `Writer: malformed log occupant at ${key}`);\n }\n return existing;\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 `isWriteConflict` (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 committing create, computed\n * by `#singleAttemptCommit`.\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// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\n/**\n * `true` when a create rejection proves the create did not land. Under the\n * `Storage.put` contract an adapter that retried internally reports such a\n * rejection as `NetworkError`, so these codes describe the only attempt.\n */\nconst isDefinitiveCreateRejection = (err: unknown): boolean =>\n err instanceof BaerlyError && (err.code === \"AccessDenied\" || err.code === \"InvalidConfig\");\n\n/**\n * `true` when a create-only put reports, per the `Storage.put` contract,\n * that no attempt of the call was applied: a `NetworkError` after every\n * attempt was throttled or refused before issue, or the request ledger's\n * `CapacityExceeded` when it refused the call before any attempt of\n * unknown outcome. `cause.notApplied` is the proof either way.\n */\nconst isCreateNotApplied = (err: unknown): boolean =>\n err instanceof BaerlyError &&\n (err.code === \"NetworkError\" || err.code === \"CapacityExceeded\") &&\n ((err as BaerlyError).cause as { notApplied?: boolean } | undefined)?.notApplied === true;\n\n/**\n * Count a post-commit step the request ledger refused on\n * `db.write.post_commit_refused_total`. The step runs after a known\n * commit and swallows its failure, so the refusal leaves the commit\n * acknowledged; `phase` names the step that went without (the delete-floor\n * check is the only one).\n */\nconst countPostCommitRefusal = (\n err: unknown,\n collection: string,\n phase: \"delete-floor-check\",\n): void => {\n if (\n err instanceof BaerlyError &&\n err.code === \"CapacityExceeded\" &&\n (err.cause as { refused?: boolean } | undefined)?.refused === true\n ) {\n ctxMetrics().counter(\"db.write.post_commit_refused_total\", 1, { collection, phase });\n }\n};\n\n/**\n * Reject an `insertGuard` on anything but an `I`, or with an\n * `absentBelowSeq` that is not a log seq. Runs before any I/O.\n */\nconst assertInsertGuardShape = (input: CommitInput): void => {\n if (input.op !== \"I\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Writer: insertGuard is valid only with op \"I\"; got op ${JSON.stringify(input.op)}`,\n );\n }\n const seq = input.insertGuard?.absentBelowSeq;\n if (typeof seq !== \"number\" || !Number.isSafeInteger(seq) || seq < 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Writer: insertGuard.absentBelowSeq must be a non-negative safe integer; got ${String(seq)}`,\n );\n }\n const replay = input.insertGuard?.replayIdentical;\n if (replay !== undefined && typeof replay !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Writer: insertGuard.replayIdentical must be a boolean; got ${typeof replay}`,\n );\n }\n};\n\n/**\n * Reject an `admission` whose `fromSeq` is not a log seq, or differs from\n * the insert guard's window start. Runs before any I/O.\n */\nconst assertAdmissionShape = (input: CommitInput): void => {\n const seq = input.admission?.fromSeq;\n if (typeof seq !== \"number\" || !Number.isSafeInteger(seq) || seq < 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Writer: admission.fromSeq must be a non-negative safe integer; got ${String(seq)}`,\n );\n }\n if (typeof input.admission?.check !== \"function\") {\n throw new BaerlyError(\"InvalidConfig\", \"Writer: admission.check must be a function\");\n }\n const guarded = input.insertGuard?.absentBelowSeq;\n if (guarded !== undefined && guarded !== seq) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Writer: admission.fromSeq ${seq} must equal insertGuard.absentBelowSeq ${guarded}`,\n );\n }\n};\n\n/**\n * Window decision for a guarded insert. `window` holds the log entries\n * in `[absentBelowSeq, seq)` in seq order, unfiltered. The LAST entry for\n * this `(collection, doc_id)` decides: a `D`, or no entry, means the row\n * is absent and the insert may commit (`undefined`). An `I` or `U` means a\n * row is live: with `replayIdentical` set and that entry's `after` equal\n * to the body, the insert is a replay of its own earlier success and the\n * entry is returned; otherwise the insert throws `AlreadyExists`.\n *\n * @throws BaerlyError code=\"AlreadyExists\"\n */\nconst decideInsertTarget = (\n window: readonly LogEntry[],\n input: CommitInput,\n): LogEntry | undefined => {\n for (let i = window.length - 1; i >= 0; i--) {\n const e = window[i]!;\n if (!isOwnCollection(e.collection, input.collection) || e.doc_id !== input.docId) {\n continue;\n }\n if (e.op === \"D\") {\n return undefined;\n }\n if (\n input.insertGuard?.replayIdentical === true &&\n input.body !== undefined &&\n insertReplaysRow(input.body, e.after)\n ) {\n return e;\n }\n throw insertAlreadyExists(input.collection, input.docId);\n }\n return undefined;\n};\n\n/** `true` when a decoded log occupant carries the identity adoption compares. */\nconst hasWriterIdentity = (value: unknown): value is LogEntry => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const { session, seq } = value as { session?: unknown; seq?: unknown };\n return (\n typeof session === \"string\" &&\n session.length > 0 &&\n typeof seq === \"number\" &&\n Number.isSafeInteger(seq) &&\n seq >= 0\n );\n};\n\n/**\n * `true` when a rejection is an `AbortError` — the caller's own cancellation\n * through an `AbortSignal`, never a transient storage failure. Matched\n * structurally on `name` rather than `instanceof DOMException` because a host\n * may surface an abort as a plain `Error` so named (as `Storage` impls and the\n * test fixtures do). `@baerly/client` carries the same predicate; it is\n * duplicated rather than shared because `server` may not import `client`\n * (`scripts/lint-package-layers.mjs`) and one predicate does not earn a new\n * module in `@baerly/protocol`.\n */\nconst isAbortError = (err: unknown): boolean =>\n typeof err === \"object\" && err !== null && \"name\" in err && err.name === \"AbortError\";\n\n/**\n * `true` when the underlying storage surfaced an R2 prefix-partition\n * rate-limit. {@link S3HttpStorage} stamps the upstream HTTP status\n * onto `BaerlyError.cause` as `{ status }`; we discriminate on that\n * structured field rather than regex-matching the message.\n */\nconst is429 = (err: unknown): boolean => {\n if (!(err instanceof BaerlyError) || err.code !== \"NetworkError\") {\n return false;\n }\n const cause = err.cause as { status?: number } | undefined;\n return cause?.status === 429;\n};\n","/**\n * 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. Contention on the\n * committing log create is resolved inside `Writer.commit()` (occupant\n * readback, then a bounded forward probe); the verbs do NOT add their\n * own retry loop. Errors from `commit()` surface unchanged — the caller\n * decides whether to re-run.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\n\nimport {\n assertDocumentSize,\n assertDocumentValues,\n assertInsertIdType,\n type CurrentJson,\n type DocumentData,\n type LogEntry,\n logSeqStartOf,\n type MergePatch,\n MANIFEST_POINTER_EMPTY_SNAPSHOT,\n compileWire,\n applyMergePatch,\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 {\n type CapacityDecision,\n type CapacityWarning,\n capacityDecision,\n currentFoldCeilings,\n maintenancePending,\n noteCapacityWarning,\n type PlannedWrite,\n} from \"./capacity.ts\";\nimport { callerFacingCheck, markCallerFacing } from \"./caller-facing-error.ts\";\nimport {\n assertDocId,\n assertReadDocId,\n insertAlreadyExists,\n insertReplaysRow,\n recordInsertReplay,\n} from \"./doc-id.ts\";\nimport { foldLogEntriesOnto, walkLogRange } from \"./log-walk.ts\";\nimport { probeReadTail } from \"./log-tail.ts\";\nimport {\n countMatches,\n filterRows,\n limitedLength,\n orderRows,\n type StoredDoc,\n} from \"./query-eval.ts\";\nimport { dispatchWriteTick } from \"./maintenance.ts\";\nimport { getCurrentContext } from \"./observability/context.ts\";\nimport { ReadBudget } from \"./read-admission.ts\";\nimport { type SchemaValidator, validateOrThrow } from \"./schema.ts\";\nimport { type CommitAdmission, type CommitVerdict, Writer } from \"./writer.ts\";\nimport { isOwnCollection } from \"./collection-alias.ts\";\n\nconst PATCH_ID_RESOLUTION = \"Omit `_id` from the patch, or pass the row's own `_id`.\";\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 `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\n/**\n * A materialised row: `T` plus the string `_id` it is stored under, the\n * shape the public read terminals return.\n *\n * @internal\n */\ntype Row<T extends DocumentData> = T & { _id: string };\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 /** The rows read; empty under {@link ReadOptions.countOnly}. */\n readonly rows: Row<T>[];\n /** How many rows the read selected: `rows.length`, or the count under `countOnly`. */\n readonly count: number;\n readonly manifestPointer: string;\n readonly fresh: boolean;\n}\n\n/**\n * Serialise a {@link CurrentJson} head into an opaque wire cursor.\n * `tail` is the DISCOVERED tail (defaults to `json.tail_hint` when no\n * probe has run). Physical snapshot keys feed the digest but never\n * cross the HTTP boundary.\n *\n * @internal — exported for `query.test.ts`.\n */\nconst manifestPointerDigest = (seed: string): string => {\n let hash = 0xcbf29ce484222325n;\n for (let i = 0; i < seed.length; i++) {\n hash ^= BigInt(seed.charCodeAt(i));\n hash = (hash * 0x100000001b3n) & 0xffffffffffffffffn;\n }\n return hash.toString(36).padStart(13, \"0\");\n};\n\nexport const serializeManifestPointer = (json: CurrentJson, tail = json.tail_hint): string =>\n `m1:${manifestPointerDigest(\n [\n json.snapshot ?? MANIFEST_POINTER_EMPTY_SNAPSHOT,\n json.log_seq_start,\n json.tail_hint,\n json.snapshot_bytes,\n json.snapshot_rows,\n tail,\n ].join(\"|\"),\n )}`;\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 (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, { countOnly: true });\n return res.count;\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 opts?: ReadOptions,\n): Promise<ReadResult<T>> => {\n return runRead<T>(ctx, state, opts);\n};\n\n/** Options for a read terminal. */\nexport interface ReadOptions {\n /**\n * The caller returns only the row count, so the output bound does not\n * apply. The read counts matches without materialising rows: `rows` is\n * empty and `count` carries the result, cut by `limit` as `all()` is.\n */\n readonly countOnly?: boolean;\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 * `id` is checked by {@link assertReadDocId} before any I/O.\n *\n * @internal — router uses this to preserve `_meta` envelope;\n * mirrors {@link runAllWithMeta} and {@link Collection.get}.\n */\nexport const runByIdWithMeta = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n id: string,\n): Promise<ReadResult<T>> => {\n assertReadDocId(id);\n return await 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; the writer holds no\n * per-commit state, so this costs nothing.\n */\nconst writerFor = (ctx: CollectionReadContext): Writer =>\n new Writer({\n storage: ctx.storage,\n currentJsonKey: `${ctx.collectionPrefix}/current.json`,\n });\n\n/**\n * The collection state a pre-commit read folded: `current.json`, the\n * snapshot rows and every tail entry on top of them. Present whenever the\n * read loaded the snapshot; the write verbs pass it to\n * {@link admitWrites}.\n */\ninterface FoldedState {\n readonly head: CurrentJson;\n readonly base: ReadonlyMap<string, DocumentData>;\n readonly tail: readonly LogEntry[];\n}\n\n/**\n * Throw the refusal `decision` carries: `MaintenancePending` when the\n * pending tail would make room once it folds, after dispatching one forced\n * fold pass (G6, fold-then-refuse) through the request's maintenance\n * dispatch, so on Cloudflare it runs in `ctx.waitUntil` like any write\n * tick; otherwise `CapacityExceeded`. Under `BAERLY_MAINTENANCE_DISABLE`\n * nothing can fold, so the refusal stays `CapacityExceeded`.\n *\n * @param tail The log tail the decision folded through.\n */\nconst throwRefusal = async (\n ctx: CollectionReadContext,\n decision: Extract<CapacityDecision, { refusal: BaerlyError }>,\n tail: number,\n): Promise<never> => {\n if (decision.foldFreesRoom && getCurrentContext()?.maintenance?.disabled !== true) {\n // Nothing committed, so the tick's GC cadence window is empty and the\n // forced fold is its only phase.\n await dispatchWriteTick({\n storage: ctx.storage,\n currentJsonKey: `${ctx.collectionPrefix}/current.json`,\n collection: ctx.collectionName,\n prevSeq: tail,\n observedTail: tail,\n forceFold: true,\n });\n throw maintenancePending(ctx.collectionName);\n }\n throw decision.refusal;\n};\n\n/** What {@link admitWrites} hands a verb for its commits, in plan order. */\ninterface Admission {\n /**\n * Whether the batch's last commit forces its write tick: the writes\n * leave the collection at its growth-refusal point.\n */\n readonly forceMaintenance: boolean;\n /** The commit-time re-check for the next planned write's commit. */\n next(): CommitAdmission;\n /** Record that the next planned write committed as `entry`. */\n committed(entry: LogEntry): void;\n /**\n * Record that the next planned write's commit threw {@link RowSkipped}:\n * it committed nothing, and the batch moves on to the write after it.\n */\n skipped(): void;\n /**\n * Run the batch's forced write tick (G6) when its last planned write was\n * skipped: that write's commit would have carried the tick, so the rows\n * that did commit under pressure would otherwise leave the fold undone.\n * The verb calls it once after its commit loop.\n */\n settle(): Promise<void>;\n /**\n * Stamp the early capacity warning (G7) on the canonical line, from the\n * latest decision: the pre-commit one, or the last commit-time re-check.\n * The verb calls it once its commits have landed, so a write that\n * throws carries no warning.\n */\n warn(): void;\n}\n\n/**\n * One write a verb plans, as {@link admitWrites} takes it.\n *\n * A planned `U` or `D` is re-decided at commit time against the newest\n * version of its row (PostgreSQL READ COMMITTED's EvalPlanQual): if any\n * entry for its `_id` committed after the verb's read, the write is decided\n * from that version instead of the one the read returned. A `D` of the row\n * in that window skips the write (the commit throws {@link RowSkipped}),\n * even when a later `I` re-created the `_id`: that is a different row the\n * verb never read. Otherwise, for a `U`, `rebase` re-derives the post-image\n * from the newest version, or returns `undefined` to skip the row; without\n * `rebase` the planned post-image commits as is (last writer wins). For a\n * `D`, `stillMatches` re-evaluates the verb's predicate on the newest\n * version, and the row is skipped when it no longer matches.\n */\ninterface VerbWrite {\n readonly planned: PlannedWrite;\n readonly rebase?: (latest: DocumentData) => Promise<DocumentData | undefined>;\n readonly stillMatches?: (latest: DocumentData) => boolean;\n}\n\n/**\n * Thrown from an admission check when the row a planned `U` / `D` targets\n * was deleted after the verb's read, or no longer qualifies for it. The\n * writer propagates it before the committing create, so nothing commits;\n * the verb that planned the write catches it (`update` / `delete` leave the\n * row out of their count, `replace` throws `NotFound`). Never escapes\n * `query.ts`.\n */\nclass RowSkipped extends Error {\n constructor(docId: string) {\n super(`row ${JSON.stringify(docId)} changed under the write`);\n this.name = \"RowSkipped\";\n }\n}\n\n/**\n * The newest version of `docId` among `entries` (every entry committed\n * after the verb's read, in seq order): `\"gone\"` when any of them deletes\n * it, its newest post-image when one rewrote it, `undefined` when none\n * touched it.\n */\nconst newestVersion = (\n entries: readonly LogEntry[],\n collection: string,\n docId: string,\n): DocumentData | \"gone\" | undefined => {\n let newest: DocumentData | undefined;\n for (const entry of entries) {\n if (!isOwnCollection(entry.collection, collection) || entry.doc_id !== docId) {\n continue;\n }\n if (entry.op === \"D\" || entry.after === undefined) {\n return \"gone\";\n }\n newest = entry.after;\n }\n return newest;\n};\n\n/** A never-provisioned collection: no snapshot, nothing folded. */\nconst EMPTY_HEAD = { snapshot_rows: 0, snapshot_bytes: 0, log_seq_start: 0 } as const;\n\n/**\n * Admit `writes` against the serving host's fold ceiling before any commit\n * (see `./capacity.ts`), throwing as {@link throwRefusal} does when they\n * would grow the collection past it.\n *\n * The returned admission re-runs the verb's decisions at commit time.\n * Each commit passes `next()` to `Writer.commit`, which hands back every\n * log entry in `[fromSeq, seq)`: the entries this decision has not seen.\n *\n * - **Row (EvalPlanQual).** A planned `U` / `D` whose row any entry\n * committed after the read touched (in this window, or in an earlier\n * row's window of the same batch) is re-decided from the newest version,\n * or skipped; see {@link VerbWrite}. A rebased post-image is the verdict's `body`,\n * so the writer commits it.\n * - **Capacity (main-10 G5-race).** An empty window with no rebase means\n * nothing intervened, so the decision stands as made and nothing is\n * recomputed. Otherwise the decision re-runs over the read's tail plus\n * the window, for the planned writes not yet committed (this one with\n * its rebased post-image), and a refusal throws before the committing\n * create, so concurrent growth writes that each passed this check cannot\n * together pass the ceiling.\n *\n * Each `committed(entry)` moves `fromSeq` past this batch's own commit, so\n * the writer reads only entries this decision has not seen.\n *\n * With no folded state (an unprovisioned collection), the collection is empty,\n * so the pre-commit check is skipped; a re-check starts from an empty\n * collection.\n *\n * @param read The pre-commit read: its folded state, and `tail`, the\n * first empty log slot it folded through.\n */\nconst admitWrites = async (\n ctx: CollectionReadContext,\n read: { readonly folded?: FoldedState; readonly tail: number },\n verbWrites: readonly VerbWrite[],\n): Promise<Admission> => {\n const { folded } = read;\n const writes = verbWrites.map((w) => w.planned);\n let forceMaintenance = false;\n let warning: CapacityWarning | undefined;\n if (folded !== undefined) {\n const decision = capacityDecision({\n collection: ctx.collectionName,\n head: folded.head,\n base: folded.base,\n tail: folded.tail,\n writes,\n ceilings: currentFoldCeilings(),\n });\n if (decision.refusal !== undefined) {\n return await throwRefusal(ctx, decision, read.tail);\n }\n forceMaintenance = decision.pressure;\n warning = decision.warning;\n }\n const head = folded?.head ?? EMPTY_HEAD;\n const base = folded?.base ?? new Map<string, DocumentData>();\n // Every entry the decision has seen so far, in seq order: the read's\n // tail, then `sinceRead`.\n const seen: LogEntry[] = [...(folded?.tail ?? [])];\n // The entries committed after the read that this decision has seen.\n const sinceRead: LogEntry[] = [];\n let fromSeq = read.tail;\n let pending = 0;\n // The window of the latest `check` call: on commit, `[fromSeq, seq)`.\n let lastWindow: readonly LogEntry[] = [];\n // The latest decision's G6 pressure, and the batch's last own commit.\n let pressure = forceMaintenance;\n let lastCommitted: LogEntry | undefined;\n let lastSkipped = false;\n const check = async (\n window: readonly LogEntry[],\n tail: number,\n ): Promise<CommitVerdict | undefined> => {\n lastWindow = window;\n const { planned, rebase, stillMatches } = verbWrites[pending]!;\n let rebased: DocumentData | undefined;\n if (planned.op !== \"I\") {\n const newest = newestVersion([...sinceRead, ...window], ctx.collectionName, planned.docId);\n if (newest === \"gone\") {\n throw new RowSkipped(planned.docId);\n }\n if (newest !== undefined && stillMatches !== undefined && !stillMatches(newest)) {\n throw new RowSkipped(planned.docId);\n }\n if (newest !== undefined && rebase !== undefined) {\n rebased = await rebase(newest);\n if (rebased === undefined) {\n throw new RowSkipped(planned.docId);\n }\n }\n }\n if (window.length === 0 && rebased === undefined) {\n return undefined;\n }\n const tailNow = [...seen, ...sinceRead, ...window];\n const remaining = writes.slice(pending);\n if (rebased !== undefined) {\n remaining[0] = { ...planned, after: rebased };\n }\n const decision = capacityDecision({\n collection: ctx.collectionName,\n head,\n base,\n tail: tailNow,\n writes: remaining.map((write) => withLiveBefore(write, ctx.collectionName, tailNow)),\n ceilings: currentFoldCeilings(),\n });\n if (decision.refusal !== undefined) {\n return await throwRefusal(ctx, decision, tail);\n }\n // Re-derive the forced tick (G6) from the state the commit lands on.\n // It rides the batch's last commit only, as the pre-commit flag does.\n warning = decision.warning;\n pressure = decision.pressure;\n return {\n forceMaintenance: decision.pressure && pending === writes.length - 1,\n ...(rebased !== undefined && { body: rebased }),\n };\n };\n return {\n forceMaintenance,\n next: () => {\n lastWindow = [];\n return { fromSeq, check };\n },\n committed: (entry) => {\n sinceRead.push(...lastWindow, entry);\n fromSeq = entry.seq + 1;\n pending++;\n lastCommitted = entry;\n lastSkipped = false;\n },\n skipped: () => {\n // `fromSeq` stays put, so the next row's window re-reads the\n // skipped row's window; nothing is recorded twice.\n pending++;\n lastSkipped = true;\n },\n settle: async () => {\n if (\n !lastSkipped ||\n lastCommitted === undefined ||\n !pressure ||\n getCurrentContext()?.maintenance?.disabled === true\n ) {\n return;\n }\n await dispatchWriteTick({\n storage: ctx.storage,\n currentJsonKey: `${ctx.collectionPrefix}/current.json`,\n collection: ctx.collectionName,\n prevSeq: lastCommitted.seq,\n observedTail: lastCommitted.seq + 1,\n forceFold: true,\n });\n },\n warn: () => {\n if (warning !== undefined && writes.length > 0) {\n noteCapacityWarning(warning);\n }\n },\n };\n};\n\n/**\n * `write` with `before` re-read from the latest entry for its row in\n * `tail`, when there is one: an intervening commit may have changed the\n * row, so growth (G3) is judged against the row as it now stands. A row an\n * intervening `D` removed has no `before`, which counts as growth (fails\n * closed).\n */\nconst withLiveBefore = (\n write: PlannedWrite,\n collection: string,\n tail: readonly LogEntry[],\n): PlannedWrite => {\n if (write.op !== \"U\") {\n return write;\n }\n for (let i = tail.length - 1; i >= 0; i--) {\n const entry = tail[i]!;\n if (isOwnCollection(entry.collection, collection) && entry.doc_id === write.docId) {\n const { before: _stale, ...rest } = write;\n return entry.op === \"D\" || entry.after === undefined\n ? rest\n : { ...rest, before: entry.after };\n }\n }\n return write;\n};\n\n/**\n * `Collection.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`. The first `I` for an `_id` wins:\n * when a live row already holds the `_id`, the insert throws\n * non-retriable `BaerlyError{code:\"AlreadyExists\"}` and commits nothing.\n * A row committed before the pre-commit check read is caught there,\n * without a writer round-trip; one committed concurrently, after that\n * read, is caught by the writer's insert guard, which reads the log\n * window the check could not see. So of concurrent inserts of one `_id`,\n * at most one commits (exactly one, absent storage failures) and the\n * others throw `AlreadyExists` — matches the\n * locked `Collection.insert` contract\n * (`packages/protocol/src/collection-api.ts`).\n *\n * The emitted `LogEntry` has `op:\"I\"` and `after === {...doc, _id}`\n * (today's per-doc-replace model).\n *\n * **SDK-minted replay.** `opts.mintedId` marks `_id` as minted by an SDK\n * client rather than chosen by the caller; only the HTTP insert route\n * sets it (from the body's `mintedId`), and `Collection.insert` never\n * does. With it set, a live row for `_id` equal to `{...doc, _id}`\n * (`insertReplaysRow`: key order ignored) is this insert's own earlier\n * success, resent after a lost response: the call returns `{ _id }` and\n * commits nothing, whether the check read or the writer's insert guard\n * finds the row. A live row with any other body still throws\n * `AlreadyExists`. \"Live\" covers a `U`: a body equal to a later update's\n * post-image also replays. A caller-chosen `_id` never replays, even onto\n * an identical row, so a run-once guard like\n * `insert({ _id: \"migration-x\", done: true })` has at most one winner.\n *\n * @throws BaerlyError code=\"AlreadyExists\" — a live row holds `_id`,\n * committed before or concurrently with this call (and, with\n * `mintedId`, its body differs). `err._id` is the `_id`. Not retriable.\n * @throws BaerlyError code=\"InvalidConfig\" — `doc` holds a value JSON\n * cannot store as written (see `assertDocumentValues`), the post-image\n * `{ ...doc, _id }` encodes to more than `MAX_DOCUMENT_BYTES` (see\n * `assertDocumentSize`), the supplied\n * `_id` is present and not a string (`null` included), the resolved `_id` fails\n * {@link assertDocId} (key-segment rule, an unpaired surrogate, or not NFC), or `opts.mintedId`\n * is set and is not the resolved `_id`. Checked before I/O.\n * @throws BaerlyError code=\"WriteConflict\" — a rejected storage precondition\n * `Writer.commit()` does not resolve, or log retention retired part of the\n * window the insert guard had to read; nothing was committed. Retriable.\n * @throws BaerlyError code=\"AmbiguousCommit\" — a committing create may be\n * durable, but its outcome could not be resolved. The row may or may not\n * have been inserted. Not retriable-by-default; see `Writer.commit`.\n * @throws BaerlyError code=\"SchemaError\" — `doc` nests deeper than\n * `MAX_DOCUMENT_DEPTH` (see `assertDocumentValues`), checked before I/O;\n * or from the per-collection `SchemaValidator` threaded via\n * `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 /** @internal — set only by the HTTP insert route. */\n opts?: { readonly mintedId?: string },\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 // A present, non-string `_id` is a caller bug, refused before it could be\n // replaced by a minted one.\n const supplied = doc[\"_id\"];\n callerFacingCheck(() => {\n assertInsertIdType(supplied);\n assertDocumentValues(doc, \"insert\");\n });\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 callerFacingCheck(() => assertDocId(_id));\n const mintedId = opts?.mintedId;\n if (mintedId !== undefined && mintedId !== _id) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `insert: mintedId ${JSON.stringify(mintedId)} is not the document _id ${JSON.stringify(_id)}`,\n );\n }\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 callerFacingCheck(() => assertDocumentSize(body, \"insert\"));\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: a live row at the check read's\n // tail `T0` throws `AlreadyExists` with no writer round-trip. The\n // writer's guard trusts this check for every entry below `T0`, so\n // insert uniqueness rests on the authoritative fold, as every read's\n // membership does.\n const existing = await runReadRows<DocumentData>(ctx, {\n wire: { clauses: [{ op: \"eq\", field: \"_id\", value: _id }] },\n order: undefined,\n limit: 1,\n });\n const live = existing.rows[0];\n if (live !== undefined) {\n if (mintedId !== undefined && insertReplaysRow(body, live.doc)) {\n recordInsertReplay(ctx.collectionName);\n return { _id };\n }\n throw insertAlreadyExists(ctx.collectionName, _id);\n }\n const admission = await admitWrites(ctx, existing, [\n { planned: { op: \"I\", docId: _id, after: body } },\n ]);\n\n // Single-attempt at the verb level; log-create contention is resolved\n // inside `Writer.commit()`, and its errors surface unchanged. The\n // insert guard makes the writer check the log window `[T0, seq)` this\n // read could not see, so of concurrent inserts of one `_id` only the\n // first `I` commits and the rest throw `AlreadyExists`.\n await writerFor(ctx).commit({\n op: \"I\",\n collection: ctx.collectionName,\n docId: _id,\n body,\n insertGuard: { absentBelowSeq: existing.tail, replayIdentical: mintedId !== undefined },\n admission: admission.next(),\n ...(admission.forceMaintenance && { forceMaintenance: true }),\n });\n admission.warn();\n\n return { _id };\n};\n\n/**\n * The `doc_id` that `update` / `delete` commit a materialised row under,\n * after checking that the row's own `_id` is that same string. Every\n * stored `I` / `U` post-image names its storage key; a row whose `_id` is\n * missing, not a string, or a different id is stored corruption (an older\n * release let a patch strip or re-key `_id`). Committing it anyway would\n * duplicate the row under its `_id`, or tombstone a key that does not\n * hold it, so it fails loud instead. `replace(id, doc)` repairs such a\n * row: it forces `_id` to `id`.\n *\n * @throws BaerlyError code=\"InvalidResponse\" — the row's `_id` is not the\n * string it is stored under.\n */\nconst storedRowId = <T extends DocumentData>(\n row: StoredRow<T>,\n verb: \"update\" | \"delete\",\n): string => {\n const id = row.doc[\"_id\"];\n if (id !== row.docId) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `Query.${verb}: stored row ${JSON.stringify(row.docId)} carries _id ${\n typeof id === \"string\" ? JSON.stringify(id) : `of type ${typeof id}`\n }; repair it with replace(id, doc)`,\n );\n }\n return row.docId;\n};\n\n/**\n * Reject a merge patch that would change a row's `_id`. A patch whose\n * top-level `_id` is present (not `undefined`, which `merge` treats as\n * absent) must equal the row's id: an equal `_id` keeps a full-document\n * round-trip patch working, while any other value — including `null`,\n * which would strip `_id` — is a caller bug. Unlike `replace`, which takes\n * the id as a separate argument and forces it onto the document, a patch\n * has no separate id to fall back on, so forcing it would hide the bug.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — the patch names a different `_id`.\n */\nconst assertPatchKeepsId = (patch: unknown, docId: string): void => {\n if (patch === null || typeof patch !== \"object\" || Array.isArray(patch)) {\n return;\n }\n if (!Object.hasOwn(patch, \"_id\")) {\n return;\n }\n const patchId = (patch as DocumentData)[\"_id\"];\n if (patchId !== undefined && patchId !== docId) {\n throw markCallerFacing(\n new BaerlyError(\n \"InvalidConfig\",\n `Query.update: a patch cannot change _id (row ${JSON.stringify(docId)}); omit _id from the patch`,\n { resolution: PATCH_ID_RESOLUTION },\n ),\n );\n }\n};\n\n/**\n * `applyMergePatch(row, patch)` as `update` commits it, validated against the\n * collection's schema.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — the post-image holds a value\n * JSON cannot store as written (see `assertDocumentValues`), or encodes\n * to more than `MAX_DOCUMENT_BYTES` (see `assertDocumentSize`).\n * @throws BaerlyError code=\"SchemaError\" — the merge produced `undefined`,\n * the post-image nests deeper than `MAX_DOCUMENT_DEPTH`, or the schema\n * rejected the post-image.\n */\nconst mergeAndValidate = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n row: DocumentData,\n patch: MergePatch<T>,\n): Promise<DocumentData> => {\n const merged = applyMergePatch(row, patch as Partial<DocumentData>);\n if (merged === undefined) {\n // `applyMergePatch(target, patch)` returns undefined only when patch is\n // null at the root. `MergePatch<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(row[\"_id\"])}`,\n );\n }\n // A value JSON would coerce or drop is refused before admission and any\n // write. An `undefined` member is absent, as it is in the HTTP form of\n // the patch, which `JSON.stringify` dropped it from.\n callerFacingCheck(() => assertDocumentValues(merged, \"update\", { undefinedMembersAbsent: true }));\n // The post-image, not the patch, is size-checked: a small patch can grow\n // a row past the cap, and a row stored over it may still shrink.\n callerFacingCheck(() => assertDocumentSize(merged, \"update\"));\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.\n if (ctx.schema !== undefined) {\n await validateOrThrow(ctx.schema, merged, {\n collection: ctx.collectionName,\n verb: \"update\",\n });\n }\n return merged;\n};\n\n/**\n * `Query.update` implementation. Materialises the predicate/order/\n * limit-filtered match set, applies RFC 7396 `applyMergePatch(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: each affected row\n * commits independently — the document is the atomic unit; there is no\n * multi-row batch.\n *\n * **Concurrent writes to a matched row (EvalPlanQual).** When another\n * write to a matched row commits between this read and the row's own\n * commit, the patch is re-applied to that newest version and the\n * predicate re-evaluated on it (`limit` / `order` are not); a row that\n * was deleted there, or no longer matches, is skipped and not counted in\n * `modified`. See {@link VerbWrite}.\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=\"WriteConflict\" — one row's commit hit a rejected\n * storage precondition `Writer.commit()` does not resolve. The\n * partial-progress `modified` count is NOT returned in that case.\n * @throws BaerlyError code=\"AmbiguousCommit\" — one row's committing create\n * may be durable, but its outcome could not be resolved. Rows before it in\n * the batch are already applied and that row's own fate is unknown; the\n * partial-progress `modified` count is NOT returned. Re-read rows by `_id`\n * before deciding whether to resume; absence does not prove a create failed.\n * See `Writer.commit`.\n * @throws BaerlyError code=\"SchemaError\" — `applyMergePatch(prev, patch)` produced\n * `undefined` (defensive — `MergePatch<T>` cannot be `null` at the\n * root in the type system), the patch (checked before I/O) or a merged\n * post-image nests deeper than `MAX_DOCUMENT_DEPTH`, or the schema\n * rejected a post-image; at a\n * row's commit (re-applied to a newer version) rows before it are\n * already applied.\n * @throws BaerlyError code=\"InvalidConfig\" — the patch (checked before\n * I/O) or a merged post-image holds a value JSON cannot store as written\n * (see `assertDocumentValues`; an `undefined` member is absent), a merged\n * post-image encodes to more than `MAX_DOCUMENT_BYTES` (see\n * `assertDocumentSize`; a row stored larger may still shrink), or the\n * patch names an `_id` other than the row's (see {@link assertPatchKeepsId}), or the row's\n * `_id` holds an unpaired surrogate or is not NFC (see {@link assertDocId}). Checked for every matched\n * row, with schema validation, before any row commits.\n * @throws BaerlyError code=\"CapacityExceeded\" — the batch would grow the\n * collection past the serving host's fold ceiling (see `./capacity.ts`);\n * decided before any row commits, and re-checked at each row's commit\n * when a concurrent write landed since (see {@link admitWrites}), in\n * which case rows before it are already applied. Also thrown when the\n * request's storage budget runs out (the request ledger, including the\n * writer's commit-resolution reserve): rows before the refused one are\n * applied, it and the rows after it are not, and nothing is ambiguous.\n * The partial-progress `modified` count is NOT returned.\n * @throws BaerlyError code=\"InvalidResponse\" — a matched stored row's\n * `_id` is not the string it is stored under.\n */\nconst runUpdate = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n state: QueryState<T>,\n patch: MergePatch<T>,\n): Promise<{ modified: number }> => {\n // The patch is also checked before any I/O. `applyMergePatch` treats a `Date` or\n // `Map` patch value as an object to merge field by field, so over an\n // object field it would vanish from the post-image instead of being\n // refused there. `undefined` members are absent, as in the post-image.\n callerFacingCheck(() => assertDocumentValues(patch, \"update\", { undefinedMembersAbsent: true }));\n const read = await runReadRows<T>(ctx, state);\n const { rows } = read;\n // Merge and validate every row first, so the per-row checks and the\n // capacity check decide the batch whole, before its first row commits.\n // Only the commit-time re-checks can stop the batch part-way: the\n // capacity re-check, or a `SchemaError` re-applying the patch to a newer\n // version of a row.\n const planned: Array<{ docId: string; before: DocumentData; merged: DocumentData }> = [];\n for (const row of rows) {\n const doc = row.doc;\n const docId = storedRowId(row, \"update\");\n assertPatchKeepsId(patch, docId);\n // An update re-mints the row under `docId`, which must be NFC, so a\n // row an earlier release stored under a non-NFC id is refused here,\n // before schema validation; it stays readable and deletable.\n assertDocId(docId);\n const merged = await mergeAndValidate(ctx, doc as DocumentData, patch);\n planned.push({ docId, before: doc as DocumentData, merged });\n }\n // Re-derive a row's post-image from a version committed after this\n // read: the predicate must still hold, then the same merge and schema\n // check as above.\n const stillMatches = state.wire === undefined ? undefined : compileWire(state.wire);\n const rebase = async (latest: DocumentData): Promise<DocumentData | undefined> => {\n if (stillMatches !== undefined && !stillMatches(latest)) {\n return undefined;\n }\n return await mergeAndValidate(ctx, latest, patch);\n };\n const admission = await admitWrites(\n ctx,\n read,\n planned.map((p) => ({\n planned: { op: \"U\", docId: p.docId, after: p.merged, before: p.before },\n rebase,\n })),\n );\n let modified = 0;\n // Atomicity stays per row: a commit failure on row N leaves rows\n // 0..N-1 applied. A forced tick rides the batch's last commit only, so\n // the batch runs one forced fold, not one per row.\n for (const [i, { docId, merged }] of planned.entries()) {\n let entry: LogEntry;\n try {\n ({ entry } = await writerFor(ctx).commit({\n op: \"U\",\n collection: ctx.collectionName,\n docId,\n body: merged,\n admission: admission.next(),\n ...(admission.forceMaintenance && i === planned.length - 1 && { forceMaintenance: true }),\n }));\n } catch (error) {\n if (error instanceof RowSkipped) {\n admission.skipped();\n continue;\n }\n throw error;\n }\n admission.committed(entry);\n modified++;\n }\n await admission.settle();\n admission.warn();\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 * A replace racing another write to the row stays last-writer-wins: an\n * update committed after this read is overwritten. A delete committed\n * there is not undone: the replace commits nothing and throws `NotFound`\n * (see {@link VerbWrite}).\n *\n * @throws BaerlyError code=\"NotFound\" — no row exists at `id`, including\n * one a concurrent delete removed after this call's read.\n * @throws BaerlyError code=\"InvalidConfig\" — `id` fails\n * {@link assertDocId} (key-segment rule, an unpaired surrogate, or not NFC), or `doc` holds a\n * value JSON cannot store as written (see `assertDocumentValues`), or\n * `{ ...doc, _id: id }` encodes to more than `MAX_DOCUMENT_BYTES` (see\n * `assertDocumentSize`). Checked before I/O.\n * @throws BaerlyError code=\"SchemaError\" — `doc` nests deeper than\n * `MAX_DOCUMENT_DEPTH` (checked before I/O), or the post-image is\n * rejected by the collection's bound validator.\n * @throws BaerlyError code=\"WriteConflict\" — a rejected storage precondition\n * `Writer.commit()` does not resolve; nothing was committed.\n * @throws BaerlyError code=\"AmbiguousCommit\" — a committing create may be\n * durable, but its outcome could not be resolved, so the replace may or may\n * not have been applied. Re-read the row by `id` before deciding whether to\n * retry; absence does not prove the create failed. See `Writer.commit`.\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 (log `doc_id`). Same boundary as `runInsert`.\n callerFacingCheck(() => assertDocId(id));\n callerFacingCheck(() => assertDocumentValues(doc, \"replace\"));\n const body: DocumentData = { ...(doc as DocumentData), _id: id };\n callerFacingCheck(() => assertDocumentSize(body, \"replace\"));\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 read = await runReadRows<T>(ctx, state);\n const current = read.rows[0];\n if (current === undefined) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\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 const admission = await admitWrites(ctx, read, [\n { planned: { op: \"U\", docId: id, after: body, before: current.doc as DocumentData } },\n ]);\n try {\n await writerFor(ctx).commit({\n op: \"U\",\n collection: ctx.collectionName,\n docId: id,\n body,\n admission: admission.next(),\n ...(admission.forceMaintenance && { forceMaintenance: true }),\n });\n } catch (error) {\n if (error instanceof RowSkipped) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n throw error;\n }\n admission.warn();\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 * **Concurrent writes to a matched row (EvalPlanQual).** As in\n * `runUpdate`: when another write to a matched row commits between this\n * read and the row's own commit, the predicate is re-evaluated on that\n * newest version. A row deleted there (including by a racing delete, or\n * deleted and re-inserted), or no longer matching, is skipped and not\n * counted in `deleted`. See {@link VerbWrite}.\n *\n * @throws BaerlyError code=\"WriteConflict\" — one row's commit hit a rejected\n * storage precondition `Writer.commit()` does not resolve. The\n * partial-progress `deleted` count is NOT returned\n * in that case.\n * @throws BaerlyError code=\"AmbiguousCommit\" — one row's committing create\n * may be durable, but its outcome could not be resolved. Rows before it in\n * the batch are already tombstoned and that row's own fate is unknown; the\n * partial-progress `deleted` count is NOT returned. Re-read rows by `_id`\n * before deciding whether to resume. See `Writer.commit`.\n * @throws BaerlyError code=\"CapacityExceeded\" — as in `runUpdate`: the\n * batch would grow past the fold ceiling (a delete can when a pending\n * fold cannot make progress), or the request's storage budget ran out\n * part-way. Rows before the refused one are tombstoned, it and the rows\n * after it are not; the partial-progress `deleted` count is NOT returned.\n * @throws BaerlyError code=\"InvalidResponse\" — a matched stored row's\n * `_id` is not the string it is stored under.\n */\nconst runDelete = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n state: QueryState<T>,\n): Promise<{ deleted: number }> => {\n const read = await runReadRows<T>(ctx, state);\n const docIds = read.rows.map((row) => storedRowId(row, \"delete\"));\n const stillMatches = state.wire === undefined ? undefined : compileWire(state.wire);\n const admission = await admitWrites(\n ctx,\n read,\n docIds.map((docId) => ({ planned: { op: \"D\", docId }, stillMatches })),\n );\n let deleted = 0;\n // As in `runUpdate`, a forced tick rides the batch's last commit only\n // (or `settle()`, when that row is skipped).\n for (const [i, docId] of docIds.entries()) {\n let entry: LogEntry;\n try {\n ({ entry } = await writerFor(ctx).commit({\n op: \"D\",\n collection: ctx.collectionName,\n docId,\n admission: admission.next(),\n ...(admission.forceMaintenance && i === docIds.length - 1 && { forceMaintenance: true }),\n }));\n } catch (error) {\n if (error instanceof RowSkipped) {\n admission.skipped();\n continue;\n }\n throw error;\n }\n admission.committed(entry);\n deleted++;\n }\n await admission.settle();\n admission.warn();\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 opts?: ReadOptions,\n): Promise<ReadResult<T>> => {\n // The host's read envelope admits the read (see `read-admission.ts`).\n const budget = new ReadBudget(ctx.collectionName);\n const countOnly = opts?.countOnly === true;\n const { rows, count, manifestPointer, fresh } = await runReadRows(ctx, state, budget, countOnly);\n if (!countOnly) {\n budget.admitOutput(rows.length);\n }\n return { rows: rows.map((row) => row.doc), count, manifestPointer, fresh };\n};\n\n/** A folded row of `T` paired with its storage key (see {@link StoredDoc}). */\ntype StoredRow<T extends DocumentData> = StoredDoc<Row<T>>;\n\n/**\n * {@link runRead}, keeping each row's storage key. Every call, a write\n * verb's pre-commit read included, records its work (see\n * {@link recordReadWork}).\n */\nconst runReadRows = async <T extends DocumentData>(\n ctx: CollectionReadContext,\n state: QueryState<T>,\n // A write verb's pre-commit read is bounded by the request ledger only.\n budget: ReadBudget = new ReadBudget(ctx.collectionName, {}),\n // Count matches instead of materialising rows (see `ReadOptions`).\n countOnly = false,\n): Promise<{\n readonly rows: StoredRow<T>[];\n /** Rows selected after predicate and limit: `rows.length`, or the count under `countOnly`. */\n readonly count: number;\n readonly manifestPointer: string;\n readonly fresh: boolean;\n /**\n * The log tail this read folded through: the first empty slot its\n * probe found, or `0` when the collection is not provisioned. Before\n * predicate, order and limit are applied, the fold contains every live\n * row through this tail.\n */\n readonly tail: number;\n /** The folded state, for the write verbs' capacity check. */\n readonly folded?: FoldedState;\n}> => {\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 recordReadWork(ctx.collectionName, 0, 0, 0);\n return { rows: [], count: 0, manifestPointer: \"m1:0000000000000\", fresh, tail: 0 };\n }\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 budget.admitHead(head.json);\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 onBody: budget.chargeTailBody,\n });\n const probe = await probeReadTail(ctx.storage, ctx.collectionPrefix, probeFrom, {\n pool: budget.requestPool,\n onBody: budget.chargeTailBody,\n refusal: budget.probeRefusal,\n });\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 (an `applyMergePatch(prev, post)` would\n // carry forward keys the writer dropped).\n // D: tombstone — remove from the map.\n // Every post-image the writer commits carries its `doc_id` as a string\n // `_id`, which is what lets the fold be typed `Row<T>`.\n const docs = new Map<string, Row<T>>(baseDocs as Map<string, Row<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. Otherwise one pass over the fold builds only\n // the matching rows; a count builds none, since order cannot change it.\n const fastId = singleIdFromPredicate(state.wire);\n let rows: StoredRow<T>[] = [];\n let count: number;\n if (countOnly && fastId === undefined) {\n // ── Steps 5-6 for a count: `limit` cuts it as it cuts `rows`. ───\n count = limitedLength(countMatches(docs, state.wire), state.limit);\n } else {\n if (fastId !== undefined) {\n const hit = docs.get(fastId);\n rows = hit === undefined ? [] : [{ docId: fastId, doc: hit }];\n } else {\n rows = filterRows(docs, state.wire);\n }\n\n // ── Step 5. Apply order (with a small `limit`, a bounded top-k). ─\n if (state.order !== undefined) {\n rows = orderRows(rows, state.order, state.limit);\n }\n\n // ── Step 6. Apply limit (`rows` is this read's own array). ──────\n count = rows.length = limitedLength(rows.length, state.limit);\n }\n\n // Counts the fold already holds: `docs` is not touched after Step 3, so\n // its size is still the live set before predicate, order and limit.\n recordReadWork(\n ctx.collectionName,\n baseDocs.size + entries.length + probe.entries.length,\n docs.size,\n count,\n );\n\n return {\n rows,\n count,\n manifestPointer: serializeManifestPointer(head.json, tail),\n fresh,\n tail,\n folded: { head: head.json, base: baseDocs, tail: [...entries, ...probe.entries] },\n };\n};\n\n/**\n * Emit one read's work onto the request's canonical line (the\n * `db.read.*` counters; units in `@baerly/protocol`'s `MetricsRecorder`\n * catalog). Takes counts the read already holds, so it adds no storage\n * call and no pass over the rows. Outside an observability scope it\n * returns before allocating anything; inside one it adds three\n * recorder rows per read.\n *\n * @param decoded Snapshot rows plus log entries decoded by the fold.\n * @param live Documents live after the fold, before predicate and limit.\n * @param returned Rows left after predicate, order and limit.\n */\nconst recordReadWork = (\n collection: string,\n decoded: number,\n live: number,\n returned: number,\n): void => {\n const recorder = getCurrentContext()?.recorder;\n if (recorder === undefined) {\n return;\n }\n const labels = { collection };\n recorder.counter(\"db.read.decoded_entries_total\", decoded, labels);\n recorder.counter(\"db.read.live_documents_total\", live, labels);\n recorder.counter(\"db.read.returned_rows_total\", returned, labels);\n};\n","/**\n * Manifest and log read seams over a {@link Db}: the collection read\n * context the HTTP router drives, and the `current.json` / log reads the\n * `/v1/since` handler makes. Module functions rather than `Db` methods so\n * the manifest and probe types stay off the public `Db` class; reached\n * outside this package through `@baerly/server/_internal/kernel`.\n *\n * Kept apart from `./db.ts` so the HTTP entry imports these without\n * pulling in the `Db` class and the collection API.\n */\n\nimport {\n type BaerlyConfig,\n BaerlyError,\n certifiedDeleteFloor,\n type CurrentJson,\n type CurrentJsonRead,\n decodeJsonBytes,\n logDeleteFloorOf,\n logObjectKey,\n type LogEntry,\n logSeqStartOf,\n readCurrentJson,\n type SchemaValidator,\n type Storage,\n} from \"@baerly/protocol\";\nimport { isOwnCollection } from \"./collection-alias.ts\";\nimport type { Db } from \"./db.ts\";\nimport { probeTailChunk, probeTailFrom, type TailProbeChunk } from \"./log-tail.ts\";\nimport { assertNameSegment } from \"./path-segment.ts\";\nimport type { CollectionReadContext } from \"./query.ts\";\n\n/**\n * Physical-key prefix for a `(app, tenant)` pair. Trailing slash is\n * part of the prefix so a caller's `list(\"\")` resolves to\n * `list(\"app/<app>/tenant/<tenant>/\")` and cannot enumerate a sibling\n * tenant whose name shares a prefix.\n */\nconst physicalPrefixFor = (app: string, tenant: string): string => `app/${app}/tenant/${tenant}/`;\n\ninterface DbInternals {\n readonly storage: Storage;\n readonly schemas: ReadonlyMap<string, SchemaValidator>;\n}\n\n/** Private-field accessor, registered by the `Db` static block. */\nlet internalsOf: (db: Db<BaerlyConfig>) => DbInternals;\n\n/** Called once, from the `Db` static block. */\nexport const registerDbInternals = (accessor: (db: Db<BaerlyConfig>) => DbInternals): void => {\n internalsOf = accessor;\n};\n\n/**\n * Build a freshly-seeded {@link CollectionReadContext} for `name`. The\n * HTTP router uses this so it can drive `runAllWithMeta` directly\n * (the return shape carries the manifest-pointer cursor used to\n * pack `_meta` onto the read response envelope). Application\n * callers should keep using\n * {@link Db.collection}; the chainable terminals destructure the cursor\n * out and discard it to keep the locked `Query<T>` signature.\n *\n * Runs the same `name`-validation guard as {@link Db.collection}.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `name` is empty,\n * contains `/`, is `\".\"` or `\"..\"`, contains control characters,\n * starts with the reserved `\"_\"` prefix, exceeds 256 bytes, or is\n * not in Unicode Normalization Form C.\n * @internal\n */\nexport const collectionReadContext = (\n db: Db<BaerlyConfig>,\n name: string,\n): CollectionReadContext => {\n assertKeySegment(name, \"collection\", \"Db.collection\");\n const schema = internalsOf(db).schemas.get(name);\n return {\n storage: internalsOf(db).storage,\n collectionPrefix: `${physicalPrefixFor(db.app, db.tenant)}manifests/${name}`,\n collectionName: name,\n ...(schema !== undefined ? { schema } : {}),\n };\n};\n\n/**\n * Read + parse this `Db`'s `manifests/<collection>/current.json`. Returns\n * `null` when the collection has not been provisioned yet (no\n * `current.json` exists). Throws `BaerlyError{code:\"InvalidResponse\"}`\n * on a malformed body — same contract as the underlying\n * {@link readCurrentJson} helper in `@baerly/protocol`.\n *\n * Backs the `/v1/since` long-poll handler in\n * `packages/server/src/http/since.ts`; that handler needs the parsed\n * `CurrentJson` plus an ETag for the follow-up reads.\n *\n * @internal — typed seam for the HTTP handler; app code should use\n * the collection API.\n */\nexport const getCurrentJson = async (\n db: Db<BaerlyConfig>,\n collection: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead | null> => {\n // Defensive at the db layer so ALL callers are covered — including\n // the `/v1/since` handler, whose only inline screen catches empty /\n // `/` and lets `..` / control bytes through into this key.\n assertNameSegment(collection, \"collection\");\n const key = `${physicalPrefixFor(db.app, db.tenant)}manifests/${collection}/current.json`;\n return readCurrentJson(internalsOf(db).storage, key, opts);\n};\n\n/**\n * Read + parse one `LogEntry` by `seq` from\n * `manifests/<collection>/log/<seq>.json`. Returns `null`\n * when the entry is missing — this typically means the GC sweeper\n * deleted the entry between a `readCurrentJson` and this GET (the\n * `/v1/since` handler treats the race as silent and skips the\n * entry). Throws `BaerlyError{code:\"InvalidResponse\"}` on a body\n * that isn't valid JSON.\n *\n * `current` is the manifest this read is floored against — pass the\n * same one the `seq` was derived from. It is a parameter rather than\n * caller-enforced discipline so a new caller cannot introduce a\n * sub-floor read: entries below `current.log_seq_start` are folded\n * into the snapshot and may already be reclaimed (invariant 5 in\n * `docs/spec/sync-protocol.md`).\n *\n * @throws BaerlyError code=\"Internal\" — `seq` is below\n * `current.log_seq_start`, or below the certified prefix bound\n * `current.log_delete_floor` (a distinct message: the object is\n * gone, not merely reclaimable).\n *\n * @throws BaerlyError code=\"InvalidConfig\" — the entry names a\n * canonically-equivalent but byte-different collection (a\n * legacy non-NFC spelling on R2); see `isOwnCollection`.\n *\n * @internal — typed seam for the HTTP handler; app code should use\n * the collection API.\n */\nexport const getLogEntry = async (\n db: Db<BaerlyConfig>,\n collection: string,\n seq: number,\n current: CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<LogEntry | null> => {\n // Defensive at the db layer so ALL callers are covered — same\n // rationale as `getCurrentJson`; the `/v1/since` poll reaches here.\n // Path validation runs FIRST: a traversal attempt is a security\n // boundary and must not be reclassified as an invariant violation.\n assertNameSegment(collection, \"collection\");\n assertAtOrAboveLogFloor(\"getLogEntry\", seq, current);\n const key = logObjectKey(`${physicalPrefixFor(db.app, db.tenant)}manifests/${collection}`, seq);\n const got = await internalsOf(db).storage.get(key, opts);\n if (got === null) {\n return null;\n }\n let parsed: unknown;\n try {\n parsed = decodeJsonBytes(got.body);\n } catch (error) {\n throw new BaerlyError(\"InvalidResponse\", `log entry at ${key}: body is not valid JSON`, {\n cause: error,\n });\n }\n const entry = parsed as LogEntry;\n // On R2 an NFC name addresses a legacy non-NFC spelling's objects;\n // the change feed refuses them as every read does.\n isOwnCollection(entry.collection, collection);\n return entry;\n};\n\n/**\n * Forward-probe the TRUE committed log tail from `hint` (a lower\n * bound, typically `tail_hint`). Backs the `/v1/since` end-bound.\n *\n * `hint` stays a caller-chosen lower bound — the probe is defined\n * from an arbitrary starting point at or above the floor, and every\n * other consumer starts at `max(log_seq_start, tail_hint)`. What\n * `current` adds is that the floor cannot be forgotten (invariant 5\n * in `docs/spec/sync-protocol.md`).\n *\n * @throws BaerlyError code=\"Internal\" — `hint` is below\n * `current.log_seq_start`, or below the certified prefix bound\n * `current.log_delete_floor` (a distinct message: the object is\n * gone, not merely reclaimable).\n *\n * @internal — typed seam for the HTTP handler.\n */\nexport const probeLogTail = async (\n db: Db<BaerlyConfig>,\n collection: string,\n hint: number,\n current: CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<number> => {\n assertNameSegment(collection, \"collection\");\n assertAtOrAboveLogFloor(\"probeLogTail\", hint, current);\n const logPrefix = `${physicalPrefixFor(db.app, db.tenant)}manifests/${collection}`;\n const { tail } = await probeTailFrom(internalsOf(db).storage, logPrefix, hint, opts);\n return tail;\n};\n\n/**\n * Forward-probe at most `cap` committed log entries from `hint` and\n * return them. Unlike {@link probeLogTail}, reaching `cap` is not an\n * error: the chunk comes back as `kind: \"at-least\"`, a prefix of the\n * entries past `hint`, so a caller with a bounded request budget can\n * deliver it and resume after its last entry. A slot GET the request\n * ledger refuses ends the chunk the same way, keeping the entries read\n * before it. Each slot is one GET; size `cap` with `forwardProbeCap`.\n *\n * @throws BaerlyError code=\"Internal\" — `hint` is below the floor, as\n * for {@link probeLogTail}.\n * @throws BaerlyError code=\"InvalidResponse\" — an occupied slot does\n * not hold valid JSON.\n * @throws BaerlyError code=\"InvalidConfig\" — an entry names a\n * canonically-equivalent but byte-different collection, as for\n * {@link getLogEntry}.\n *\n * @internal — typed seam for the HTTP handler.\n */\nexport const probeLogChunk = async (\n db: Db<BaerlyConfig>,\n collection: string,\n hint: number,\n current: CurrentJson,\n opts: { cap: number; signal?: AbortSignal },\n): Promise<TailProbeChunk> => {\n assertNameSegment(collection, \"collection\");\n assertAtOrAboveLogFloor(\"probeLogChunk\", hint, current);\n const logPrefix = `${physicalPrefixFor(db.app, db.tenant)}manifests/${collection}`;\n const chunk = await probeTailChunk(internalsOf(db).storage, logPrefix, hint, {\n ...opts,\n stopOnRefusal: true,\n });\n // As for getLogEntry: refuse a legacy non-NFC spelling's entries.\n for (const entry of chunk.entries) {\n isOwnCollection(entry.collection, collection);\n }\n return chunk;\n};\n\n/**\n * Guard a log-read seq against both floors on the manifest it was\n * derived from.\n *\n * Entries below `log_seq_start` have been folded into the snapshot\n * (invariant 5 in `docs/spec/sync-protocol.md`) and may be reclaimed at\n * any time, so a sub-floor read is never a legitimate request — it is\n * either a stale seq the caller failed to screen, or a caller that\n * never screened at all. Both are protocol-invariant violations by\n * internal code, hence `Internal` rather than `InvalidConfig`: no\n * client input reaches these seams unscreened (`/v1/since` rejects a\n * sub-floor cursor with `CursorExpired` before ever getting here).\n *\n * Below `log_delete_floor` the contiguous prefix is certified deleted,\n * so the object is not merely *reclaimable* but already *reclaimed*.\n * The two floors get distinct messages. Same code, because both are the\n * same class of caller bug; different wording, because an operator\n * reading the throw has to know whether the bytes are recoverable.\n *\n * The floors arrive as the whole `CurrentJson` rather than as bare\n * numbers so neither can be invented independently of the manifest.\n *\n * Loud on purpose. PostgreSQL removed `old_snapshot_threshold` in PG17\n * because a fixed reclamation window that let a reader proceed\n * *silently* produced wrong answers; Oracle's `ORA-01555` is the same\n * trade and survives because it throws.\n */\nconst assertAtOrAboveLogFloor = (seam: string, seq: number, current: CurrentJson): void => {\n const floor = logSeqStartOf(current);\n // The delete floor is checked FIRST, and clamped.\n //\n // First, because `log_delete_floor <= log_seq_start` is a transition\n // invariant: any seq below the delete floor is also below the fold\n // floor, so an arm appended after the check below would be unreachable\n // dead code. Ordering it here changes no accept/reject outcome — only\n // which diagnostic wins — and lets the more specific one win.\n //\n // Clamped, because that `<= log_seq_start` bound is transition-scoped\n // and NOT enforced by the single-state read guard (deliberately: the\n // guard sits on `admin restore`'s own path, so failing it would leave\n // an out-of-bound floor unrepairable). An out-of-bound value therefore\n // arrives here off disk, and unclamped it would report an entry that is\n // present as already deleted.\n const storedDeleteFloor = logDeleteFloorOf(current);\n const deleteFloor = certifiedDeleteFloor(current);\n // `deleteFloor === 0` means no deleted prefix is certified, so this arm\n // has nothing to say and must stay silent: a negative seq against a\n // zero floor is a fold-floor rejection, and claiming its nonexistent\n // object was reclaimed would be the misdiagnosis this floor prevents.\n if (deleteFloor > 0 && seq < deleteFloor) {\n // Render the stored value too when the clamp bit, so an operator is\n // not told the field holds a number it does not hold.\n const clamped =\n storedDeleteFloor === deleteFloor\n ? \"\"\n : ` (stored log_delete_floor=${storedDeleteFloor}, clamped to log_seq_start=${floor})`;\n throw new BaerlyError(\n \"Internal\",\n `${seam}: seq ${seq} is below the certified delete floor ${deleteFloor}${clamped}; the log object is GONE — it has been reclaimed, not merely made reclaimable`,\n );\n }\n if (seq < floor) {\n throw new BaerlyError(\n \"Internal\",\n `${seam}: seq ${seq} is below the fold floor log_seq_start=${floor}; entries beneath the floor are folded into the snapshot and may already be reclaimed`,\n );\n }\n};\n\n/**\n * Guard an app, tenant, or collection name used as a path-segment in the\n * bucket-key encoding. Routes through {@link assertNameSegment}: the\n * shared {@link assertPathSegment} rule (empty / `\"/\"` / `\".\"`|`\"..\"` /\n * C0-C1 control / leading `\"_\"` (ADR-003) / overlong) plus Unicode\n * Normalization Form C, all as `BaerlyError{code:\"InvalidConfig\"}`.\n * `role` and `verb` are baked into the message so the caller doesn't\n * need to format their own.\n *\n * Used by {@link Db.create} (twice — `app`, `tenant`) and\n * {@link collectionReadContext} (once — `name`).\n *\n * @internal\n */\nexport const assertKeySegment = (value: string, role: string, verb: string): void => {\n assertNameSegment(value, role, verb);\n};\n"],"mappings":";;;;;;;;;;AAGA,MAAM,cAAc,IAAI,YAAY;AAIpC,MAAM,2BAA2B,kCAAkC,mBAAmB;;;;;;AAOtF,MAAM,uBAAuB,MAAc,UAAsC;CAC/E,IAAI,KAAK,SAAS,KAAK,OACrB;CAEF,MAAM,QAAQ,YAAY,OAAO,IAAI,CAAC,CAAC;CACvC,OAAO,QAAQ,QAAQ,QAAQ,KAAA;AACjC;;;;;;;;;;;;;;;;;AAkBA,MAAa,sBAAsB,OAAgB,SAAuB;CACxE,MAAM,QAAQ,oBAAoB,KAAK,UAAU,KAAK,GAAG,kBAAkB;CAC3E,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,YACR,iBACA,GAAG,KAAK,4BAA4B,MAAM,2BAA2B,mBAAmB,+BACxF,EAAE,YAAY,yBAAyB,CACzC;AAEJ;;;;;;;;;;;;;;;;;;;;;;;ACoEA,SAAgB,eAAe,GAAc,GAAuB;CAClE,MAAM,UAAyC,CAAC,CAAC,GAAG,CAAC,CAAC;CACtD,OAAO,QAAQ,SAAS,GAAG;EACzB,MAAM,CAAC,MAAM,SAAS,QAAQ,IAAI;EAClC,IAAI,SAAS,OACX;EAEF,IAAI,OAAO,SAAS,YAAY,OAAO,UAAU,YAAY,SAAS,QAAQ,UAAU,MACtF,OAAO;EAET,IAAI,MAAM,QAAQ,IAAI,GAAG;GACvB,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,KAAK,WAAW,MAAM,QACjD,OAAO;GAIT,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAC/B,QAAQ,KAAK,CAAC,KAAK,IAAK,MAAM,EAAG,CAAC;GAEpC;EACF;EACA,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO;EAET,MAAM,OAAO,OAAO,KAAK,IAAI;EAC7B,IA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