Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(uploads): review items 1-7, commit-vs-expiry race, upload op ledger and privacy-sweep rows
garrytan929814a8179a
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex 6f824d2d62..92505b6dfe 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -23,9 +23,9 @@ The page-state concurrency foundation under `src/core/page-state/` and the share- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers; every `page_body_segmented` refusal's fix reads the page with `get_page body: 'auto'`), `pageBodyBytes(page)` (`body_bytes` for segmented pages), `pageBodySegmentedError` and `pageBodyOverCeilingError` (the refusal of a fence or timeline write through the put path on a page over 24 MiB; `wholeBodySnapshot` in `persistence/segmented-apply.ts` reads a page within it back as strings and refuses above it: semantic timeline writes, `takes-prepare.ts`, `facts-prepare.ts`, `reconcile-state.ts`, `gbrain core`). Tag writes on a segmented page never read the body: `prepareSegmentedTagMutation` (`persistence/page-prepare.ts`) flips them in metadata over the live manifest (`test/large-pages/segmented-semantic-writes.test.ts`). `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.- `src/core/page-body/limits.ts` — Wave B size classes, ceilings, retention numbers and config keys in one place. `readPageBodyPolicy` is the single question every write asks: `segmented` is the effective `pages.segmented_storage` (unset means `SEGMENTED_STORAGE_DEFAULT`, `on`; `off` or an unrecognized value is off; held off while `segmentedWriterBlockers` finds a recent writer that blocks, and an unreadable gate counts as blocked), `maxBytes` the engine ceiling (256 MiB Postgres, 128 MiB PGLite, lowered by `pages.max_bytes`) while on and `PAGE_MAX_BYTES` while off. Config is read per call; only the writer gate is cached (`SEGMENTED_WRITER_GATE_TTL_MS`, `_resetSegmentedWriterGateForTests`). `chooseBodyStorage` applies the 1 MiB / 512 KiB hysteresis. The writer gate (`segmentedGateWriters` in `persistence/writer-versions.ts`) reads seven days of admitted requests in any state, committed publications, `ingest_log` rows and, on Postgres, `persistence_consumers` heartbeats; a row blocks when its version is below `SEGMENTED_WRITER_FLOOR` (`page-body/writer-floor.ts`: the `since` of the BEHAVIOR_CHANGES row with id `segmented_switch_on`, this build's VERSION while it is `TBD`, so the merge-slot stamp edits only that row) or unparsable, or when it lacks the segment-reader mark (migration v254: `admitter_segment_reader`, `consumer_segment_reader`, `persistence_consumers.segment_reader`, `ingest_log.writer_segment_reader`), because releases 0.60.252.0-0.60.262.0 have no segment readers and a version string cannot tell them apart. Not seen: an older binary's unmanaged single-page write, a run that dies before it logs, and read-only or export use. `pageRecoveryBytes` is the default `persistence.limits.worktree_recovery_bytes` (read by `persistence/limits.ts` `readJournalLimits` in its one config statement): twice the larger of the body the configured switch admits (`segmentedMaxBytes`, or `PAGE_MAX_BYTES` while off) and the largest page stored in segments (deleted pages included; one probe of `pages_segmented_body_bytes_idx`, v260, or the engine ceiling while that index is not valid, so a limit read never scans `pages`) plus `RECOVERY_FILE_HEADROOM_BYTES` per copy, never below 256 MiB, because a restore reserves its file twice; it ignores the writer gate, and turning the switch off or lowering `pages.max_bytes` never strands a stored page. `readPageBodyPolicy` treats a failed read of the switch or `pages.max_bytes` as off, never as unset. Doctor `segmented_storage` reports a hold left only by this host's pre-upgrade writes as information with its clear time when, for each, this build has since made the same kind of write (role and principal, `segmentedGateEvidence` `first_seen`) after it; otherwise (a cron or npx gbrain on the host) it warns. Tests: `test/large-pages/segmented-switch.test.ts`, `test/large-pages/recovery-budget-default.test.ts`, `test/large-pages/recovery-budget-ceiling.slow.test.ts`.-- `src/core/ops/page-upload.ts` — the five upload-session operations (`begin_page_upload`, `upload_page_part`, `get_page_upload`, `commit_page_upload`, `abort_page_upload`; write scope, client slug-fence allowlist). Begin routes the source and slug as put_page does and reserves the declared bytes; every later call re-checks the binding (creating principal, write source inside the read scope, source incarnation, the page id or, for create, a still-absent slug) and answers any mismatch with an `upload_not_found` identical to an unknown id. Commit verifies the bytes and hash, seals the session and submits an ordinary put_page carrying `body_ref` (`stagedBody`), so a second commit replays the first receipt; a replace re-checks `expected_revision` and the shrink guard. Append commits through `admitPageAppend` (persistence/page-append.ts) with the staged `body_ref`. Begin admits create and replace up to the page ceiling (`pages.max_bytes`, the engine ceiling by default) and an append up to PAGE_MAX_BYTES; over PAGE_MAX_BYTES a remote writer is refused `file_too_large` at begin where the write gate applies to an agent-written page.-- `src/core/persistence/page-upload.ts` — upload-session storage: `page_body_stagings` rows of kind `upload` and their raw `page_body_staging_parts`, `part_max_frame_bytes` from the transport's `ctx.inboundFrameBytes` (at most 4 MiB, minus a 4 KiB envelope), part UTF-8 and code-point checks, the staged-quota reservation (limits.ts `stagedCounterKeys`, recounted under the counter locks at begin) and its release on commit, abort or expiry (`transitionUploads` with `RELEASE_STAGED_CTE`; the segment sweep expires lapsed sessions the same way). `withStagedUpload` binds a put_page or append_page preparation to the sealed session and marks it committed in the publication transaction; `prepareStagedUpload` (from `preparePageMutation`) reads a body within PAGE_MAX_BYTES back as put_page content and hands a larger one to upload-streamed.ts. `stagedUploadWork` counts whole-body reads for the memory tests.-- `src/core/persistence/upload-streamed.ts` — a committed upload over PAGE_MAX_BYTES: the sealed parts are spooled one part at a time into a private temporary file that the segmented streamed import (page-body/streamed-import.ts) reads, verifying the admitted sha256; the spool is removed before publication. A remote writer gets put_page's gate and page tier (`content.writer`), so where the write gate applies the commit refuses `file_too_large`; a trusted local writer takes the source owner's tier, as a streamed local `put --file` does. A worktree-bound page publishes database-only (`db_only`).+- `src/core/ops/page-upload.ts` — the five upload-session operations (`begin_page_upload`, `upload_page_part`, `get_page_upload`, `commit_page_upload`, `abort_page_upload`; write scope, client slug-fence allowlist). Begin routes the source and slug as put_page does, runs put_page's grant and visibility authorization before reading the page (a private page answers as a missing one), and reserves the declared bytes; every later call re-checks the binding (creating principal, write source inside the read scope, source incarnation, the page id or, for create, a still-absent slug) and answers any mismatch with an `upload_not_found` identical to an unknown id; abort needs only the creating principal, its source and the slug fences, so a session whose page or incarnation moved can still be freed. A refusal at commit (stale revision, sha mismatch) and a commit whose write ended without committing discard the session. Commit claims the session with an atomic open-to-sealed `sealUpload` before hashing; a call that loses the claim, or finds a lapsed session another call already moved on (`settleLapse`), reads the session again and follows its real state (sealed or committing replays the commit, committed returns the first receipt), so `upload_expired` is answered only when this call expired it (`uploadCommitProbe` is the forced-race seam, `test/large-pages/upload-review.test.ts`). After the hash check commit submits an ordinary put_page carrying `body_ref` (`stagedBody`), so a second commit replays the first receipt; a replace re-checks `expected_revision` and the shrink guard. Append commits through `admitPageAppend` (persistence/page-append.ts) with the staged `body_ref`. Begin admits create and replace up to the page ceiling (`pages.max_bytes`, the engine ceiling by default) and an append up to PAGE_MAX_BYTES; over PAGE_MAX_BYTES a remote writer is refused `file_too_large` at begin where the write gate applies to an agent-written page.+- `src/core/persistence/page-upload.ts` — upload-session storage: `page_body_stagings` rows of kind `upload` and their raw `page_body_staging_parts`, `part_max_frame_bytes` from the transport's `ctx.inboundFrameBytes` (at most 4 MiB, minus a 4 KiB envelope), part UTF-8 and code-point checks, the staged-quota reservation (limits.ts `stagedCounterKeys`, recounted under the counter locks at begin) and its release on commit, abort or expiry (`transitionUploads` with `RELEASE_STAGED_CTE`, which deletes the parts in the same statement; the segment sweep expires lapsed sessions the same way). An open session expires past its idle or hard deadline, a sealed one only past its hard deadline, which sealing extends by one idle period; `expireIfLapsed` reports whether its update changed the row. `withStagedUpload` binds a put_page or append_page preparation to the sealed session and marks it committed in the publication transaction; `prepareStagedUpload` (from `preparePageMutation`) reads a body within PAGE_MAX_BYTES back as put_page content and hands a larger one to upload-streamed.ts. `stagedUploadWork` counts whole-body reads for the memory tests.+- `src/core/persistence/upload-streamed.ts` — a committed upload over PAGE_MAX_BYTES: the sealed parts are spooled one part at a time into a private temporary file that the segmented streamed import (page-body/streamed-import.ts) reads, verifying the admitted sha256; the spool is removed before publication. A remote replace of a page holding a takes fence or timeline rows (without `drop_timeline`) refuses `upload_protected_content`, since put_page's whole-body takes and timeline checks cannot run streamed. A remote writer gets put_page's gate and page tier (`content.writer`), so where the write gate applies the commit refuses `file_too_large`; a trusted local writer takes the source owner's tier, as a streamed local `put --file` does. A worktree-bound page publishes database-only (`db_only`).- `src/core/page-body/read-range.ts` + `segment-projection.ts` + `segment-ledger.ts` — Wave B PR 2 (spec 7.1, 7.3): the segment reader. `openSegmentedBody` reads a page's live manifest rows and its withdrawal ledger (`readBodyLedger`); `readBodyRange(engine, { pageId, space, start, end, audience, region?, body? })` streams pieces one segment text at a time, never the whole body. Remote reads and every projected-space read serve the read projection: `projectSegment` projects whole segments from their stored protected regions (takes, truncated tail and markers out, keys as the projection token, facts regions rendered world-only and credential-projected), after the withdrawal overlay (`overlaySegmentText`; a fence split by a forced cut is omitted for reads; a trusted read (`trustedSegments`) joins the segments it spans, and a segment ending inside a facts marker with the next, and overlays them whole, refusing `page_body_segmented` above `FENCE_MAX_BYTES` (limits.ts: counted from the begin marker through the end marker, the bound withdrawal discovery's `readStoredFence`, the purge rewrite and the file's overlaid digest share), or `page_projection_stale` when the read starts inside the block) and the fence overlay (held and purged rows out, rows below the page tier in the low-tier block after the truth). A transform or stale metadata recomputes the regions from the segment's entry state; with none usable the read refuses `page_projection_stale`, never raw text. Trusted stored-space reads give the overlaid stored stream. `projectedLayout` (cached on the handle), `projectedUnits` (rows and fixed text in projected order, for `page-window/segmented.ts`), `projectedTotals`, `projectedLineStart` and `projectedOutline` (outline from stored metadata, no segment text) locate projected bytes; the concatenation equals `projectPageText` of the joined body byte for byte except where a facts fence is longer than a segment (shows less). The chunker (`segment-chunks.ts`) chunks the same projection, so sealed segmented pages carry `MARKDOWN_CHUNKER_VERSION`; `sealSegmentedPage` indexes the overlaid, sanitized timeline lead. Pinned by `test/large-pages/projection-parity.test.ts`, `remote-window-privacy.test.ts` and `sealed-segmented-search.test.ts` (fixture `test/helpers/segmented-privacy-fixture.ts`).- `src/core/page-body/segment-rewrite.ts` — fence rewrites of a segmented body without holding it as one string (forget strikes, purge drops). Only stored `facts`/`takes` protected regions are decoded and passed, in body order with their region, to a `FenceTransform` (a region crossing forced cuts is joined with its neighbours, refused above `PAGE_MAX_BYTES`). `rewriteLiveSegmentedFences` re-stages the live body through `prepareSegmentedBody` from the segment stream with the changed units replaced and flips it in the caller's transaction (trust tier and soft delete kept; null when nothing changed); `rewriteSegmentedGeneration` rebuilds one retained generation under its own number and updates its versions' hash and size; `rewrittenContentHash` streams the hash of a rewritten generation; `segmentedBodyContains` searches a body segment by segment with the previous segment's tail carried over. Tests: `test/large-pages/purge-segments.test.ts`, `forget-scope.test.ts`, `page-purge-segments.test.ts`.- `src/core/page-body/segment-blocks.ts` + `segment-links.ts` + `segment-takes.ts` — Wave B PR 2 (spec 8, full-pass mode): the derived passes over a segmented body, O(page) work and O(segment) memory, not yet incremental. `bodyBlocks(engine, page, { regions?, separator?, want? })` yields the trusted, withdrawal-overlaid joined body one block at a time (a segment, or a run joined across forced cuts, refused above `BLOCK_MAX_BYTES` (read-range.ts) with `page_body_segmented`; `want` skips a run unread), so each block starts where the parsers start fresh; `truthLead` reads a bounded lead; `readGarbageCollector` forces a collection every 4 MiB read; `detachedValue` copies a result kept past its block so it pins no segment text; `segmentedPassWork` counts the passes' work for the linearity test. `extractSegmentedPageLinks` runs `extractBodyLinks` over each block in a window (`bodyWindows`: the whole blocks before it, 4096 chars after, the headings still open), with the role phrases a first pass found (`segmentedRoleText`), and merges candidates in `extractPageLinks` order, plus the temporal inputs (`TemporalBody`). `parseTakesFenceBlocks` gives `parseTakesFence` of the joined body. Consumers: link preparation and the links effect, stale-links maintenance, source reconciliation, the sweep, `extract links|timeline|takes --source db`, `extract --stale` (the stale list includes segmented pages since PR 2 fix lane J1; test `test/large-pages/segmented-extraction-stale.test.ts`), the mention pass (`pageMentions`), the canonical prior view (`segmentedPriorView`), `segmentedTimelineText`, the chronicle judge and the facts planner (`planSegmentedExtraction`). Tests: `test/large-pages/segmented-derived-parity.test.ts`, `segmented-derived-passes.test.ts`, `segmented-derived-linear.test.ts`, `segmented-derived-memory.slow.test.ts`, `segmented-derived-work.test.ts`. `segment-lines.ts` serves the line-local maintenance scans: `bodyLines` yields the joined text's complete lines a block at a time (a line cut by a block boundary is carried, counted in `segmentedPassWork.carry`), consumed by `gbrain integrity` and `reconcile-links`; `segmentedRegionContains` searches one region for literal markers across block boundaries (repair `connector-fences`). Test: `test/large-pages/segmented-maintenance-commands.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex ab527caefb..56e55467dd 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -4115,6 +4115,16 @@ More: [docs/guides/write-refusals.md#unsupported_path](../../docs/guides/write-r|---|---|---|---|---|---|---|| No open upload session matches this upload_id for this connection. | A session answers only its creating connection, in its source, while the page it began against is unchanged; every other case gets this same answer so an upload_id reveals nothing. | Begin a new upload with begin_page_upload and a new request_id. | agent | `repeat the read that failed` | 1 | no |+### upload_protected_content++<a id="upload_protected_content"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A remote replace upload over 24 MiB was refused because the page holds content it cannot carry over: a takes fence remote reads hide, or timeline rows. | put_page keeps a hidden takes fence and checks omitted timeline rows by comparing whole bodies; an upload over the single-string ceiling is never held whole, so it refuses instead of dropping them. | Replace the page with content of at most 24 MiB through put_page, write it locally on the brain host, or (timeline only) commit with drop_timeline: true when deleting every entry is intended. | agent | `repeat the read that failed` | 1 | no |++Reasons: `takes`, `timeline`.+### upstream<a id="upstream"></a>diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 11a295f147..d75a80e5d4 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -110,6 +110,7 @@ of making a duplicate.| <a id="write_quota_exhausted"></a>`write_quota_exhausted` (exit 12) | `write_quota_exhausted` | A cumulative write cap is full: permanent request ids (`persistence.limits.principal_lifetime_ids` or `brain_lifetime_ids`, `reason: lifetime_ids`) or reserved receipt bytes (`principal_terminal_bytes` or `brain_terminal_bytes`, `reason: terminal_bytes`). `begin_page_upload` refuses the same way at the staged-upload caps: staged bytes (`principal_staged_bytes` or `brain_staged_bytes`, `reason: staged_bytes`) or open sessions (`principal_uploads`, `reason: open_uploads`); those free when a session commits, aborts or expires, so `abort_page_upload` on an abandoned session also helps. `detail` names the limit key. Waiting does not help: ids are permanent and receipt bytes free only as receipts compact. Nothing changed. | Run the `fix` on the brain host: `gbrain config set <key> <value>` (the value covers about one more year at the current rate; undo with `gbrain config unset <key>`), then retry with the same `request_id`. For receipt bytes with reclaimable slack, `gbrain repair receipt-compaction` second previews the retained bytes compaction would free (ids: only the raise helps). Verify with `gbrain doctor --only persistence_capacity --json`. [Runbook](concurrent-writes.md#quota-near-exhaustion). || <a id="upload_not_found"></a>`upload_not_found` | `upload_not_found` | An upload call (`upload_page_part`, `get_page_upload`, `commit_page_upload`, `abort_page_upload`) named a session this connection cannot use: no such `upload_id`, another connection's session, a source outside your grant or since re-created, a page deleted or re-created since begin (for mode `create`, a page now at the slug), or an aborted session. Every case gets the same answer, so an `upload_id` reveals nothing. Nothing was written. | Begin a new upload with `begin_page_upload` and a new `request_id`, then send its parts from part 0. || <a id="upload_expired"></a>`upload_expired` | `upload_expired` | The upload session passed its idle deadline (`persistence.limits.upload_idle_seconds`, 1 hour since its last part) or its hard deadline (`upload_max_seconds`, 24 hours since begin) before it was committed. Its parts were discarded and its staged bytes released; nothing was written. | Run the `fix`: `begin_page_upload` again with a new `request_id` and send every part from part 0. An expired session never resumes. |+| <a id="upload_protected_content"></a>`upload_protected_content` (`reason`: `takes` or `timeline`) | `upload_protected_content` | A remote `commit_page_upload` replacing a page with content over 24 MiB was refused: the page holds a takes fence that remote reads hide (`takes`), or timeline rows (`timeline`). put_page keeps the hidden fence and checks which timeline rows its content omits by comparing whole bodies; a body this size is never held whole, so the upload refuses instead of dropping them. The session was discarded and its staged bytes released; nothing was written. | `takes`: replace the page with content of at most 24 MiB through put_page (which carries the fence over), or ask the user to write it on the brain host. `timeline`: upload again and commit with `drop_timeline: true` only if deleting every timeline entry is intended; otherwise send at most 24 MiB through put_page. || <a id="part_too_large"></a>`part_too_large` | `part_too_large` | An `upload_page_part` call's encoded arguments are over this connection's `part_max_frame_bytes` (its inbound request cap, at most 4 MiB, minus a 4 KiB envelope; `detail` names both sizes). JSON escaping counts quotes, backslashes and control characters at their escaped size. The part was not stored. | Cut the part smaller and send it again with the same part number; `get_page_upload` returns `part_max_frame_bytes` and `next_part`. || <a id="part_splits_code_point"></a>`part_splits_code_point` | `part_splits_code_point` | An `upload_page_part` text starts or ends with half of a surrogate pair, which has no UTF-8 encoding on its own. The part was not stored. | Move the cut before the high surrogate so the pair travels in one part, then send the part again. || <a id="write_quota_insufficient"></a>`write_quota_insufficient` (exit 12) | `write_quota_insufficient` | A bulk run (a managed sync catch-up, a reclone, a repair) estimated from its manifest more new receipts (ids and 16 KiB reservations) than the capacity left before its producer's pause line, so it did not start. Other writes still work. | Run the `gbrain config set <key> <value>` the message prints on the brain host, then rerun the same command. Verify with `gbrain doctor --only persistence_capacity --json`. |diff --git a/src/core/engine-sql/page-body.ts b/src/core/engine-sql/page-body.tsindex ce93e04277..cfb308fb6b 100644--- a/src/core/engine-sql/page-body.ts+++ b/src/core/engine-sql/page-body.ts@@ -408,10 +408,11 @@ export async function sweepSegments(exec: SqlExecutor, opts: SegmentSweepOptionsopts.sourceId !== undefined ? sqlFragment`s.source_id = ${opts.sourceId}` : sqlFragment`TRUE`,], ' AND ');const { rows: expired } = await exec.run<{ n: number }>(sqlFragment`WITH gone AS (UPDATE page_body_stagings s SET state = 'expired', updated_at = ${now}- WHERE s.state = ANY(${LIVE_STAGING_STATES}::text[]) AND (s.idle_expires_at <= ${now} OR s.hard_expires_at <= ${now}) AND ${stagingScope}+ WHERE s.state = ANY(${LIVE_STAGING_STATES}::text[]) AND ${stagingScope}+ AND (s.hard_expires_at <= ${now} OR s.idle_expires_at <= ${now} AND (s.kind <> 'upload' OR s.state = 'open'))AND NOT EXISTS (SELECT 1 FROM persistence_requests r WHERE r.state = ANY(${NON_TERMINAL_REQUEST_STATES}::text[])AND r.intent->'body_ref'->>'staging_id' = s.id::text)- RETURNING s.kind, s.principal_kind, s.principal_id, s.reserved_bytes), ${trustedSql(RELEASE_STAGED_CTE)}+ RETURNING s.id, s.kind, s.principal_kind, s.principal_id, s.reserved_bytes), ${trustedSql(RELEASE_STAGED_CTE)}SELECT count(*)::int AS n FROM gone`);stagingsExpired = Number(expired[0]?.n ?? 0);await exec.run(sqlFragment`DELETE FROM page_body_staging_parts p USING page_body_stagings sdiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex b2e31b9eb9..18b842698f 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -686,6 +686,7 @@ export const CODES = {unsupported_mutation_protocol: { class: 'unavailable', summary: "Prepared mutation does not match its accepted target." },upload_expired: { class: 'caller', summary: "The upload session passed its idle or hard deadline before it was committed, so its parts were discarded and nothing was written.", why: "Open sessions hold staged bytes against per-connection and per-brain quotas; persistence.limits.upload_idle_seconds (1 h) and upload_max_seconds (24 h) bound how long they may.", suggestion: 'Begin the upload again with a new request_id and send every part from part 0.' },upload_not_found: { class: 'caller', summary: "No open upload session matches this upload_id for this connection.", why: "A session answers only its creating connection, in its source, while the page it began against is unchanged; every other case gets this same answer so an upload_id reveals nothing.", suggestion: 'Begin a new upload with begin_page_upload and a new request_id.' },+ upload_protected_content: { class: 'caller', reasons: ['takes', 'timeline'], summary: "A remote replace upload over 24 MiB was refused because the page holds content it cannot carry over: a takes fence remote reads hide, or timeline rows.", why: "put_page keeps a hidden takes fence and checks omitted timeline rows by comparing whole bodies; an upload over the single-string ceiling is never held whole, so it refuses instead of dropping them.", suggestion: 'Replace the page with content of at most 24 MiB through put_page, write it locally on the brain host, or (timeline only) commit with drop_timeline: true when deleting every entry is intended.' },upstream: { class: 'retryable', summary: "Google connect credential error: upstream.", docs: 'docs/guides/google-connect.md#troubleshooting' },upstream_diverged: { class: 'caller', actor: 'agent', summary: "A classic source's pull cannot fast-forward: the checkout has commits that are not on the upstream and the upstream moved forward; local HEAD keeps syncing.", why: "The upstream still contains the commit this checkout last pulled, so nothing was force-pushed: bringing the upstream in beside the local commits loses nothing.", docs: 'docs/guides/troubleshooting.md#upstream-rewritten', suggestion: 'Run gbrain git commit-push --pull --path <checkout>, then gbrain sync --source <id>.' },upstream_rewritten: { class: 'consent', actor: 'user', summary: "A classic source's upstream was force-pushed: the upstream commit the checkout last contained is not in the new upstream history, so the pull cannot fast-forward; local HEAD keeps syncing.", why: "Merging would bring back the commits the force-push removed, so the fix resets the checkout to the new upstream after the user agrees, keeping the old history under a backup ref.", docs: 'docs/guides/troubleshooting.md#upstream-rewritten', suggestion: 'Ask the user, then run the gbrain sources reset-upstream <id> --expect-local <sha> --expect-upstream <sha> command doctor sync_failures prints (preview with --dry-run), then gbrain sync --source <id>.' },diff --git a/src/core/ops/page-upload.ts b/src/core/ops/page-upload.tsindex b439396389..69e08b01db 100644--- a/src/core/ops/page-upload.ts+++ b/src/core/ops/page-upload.ts@@ -20,9 +20,11 @@ import { CONTENT_ORIGIN_PARAM, PAGE_MUTATION_PARAMS, WRITE_WAIT_PARAM } from '..import { parseWriteRequestId } from '../persistence/preconditions.ts';import { isWriteRequestId } from '../persistence/types.ts';import { getWriteRequest } from '../persistence/journal.ts';+import { submissionAuthority } from '../persistence/authority.ts';+import { pageNotVisibleError } from '../persistence/page-visibility.ts';import { assertLargePageAdmission } from '../persistence/large-page-guard.ts';import { sha256 } from '../persistence/digest.ts';-import { isTerminal, type Principal } from '../persistence/model.ts';+import { isTerminal, type Principal, type WriteRequest } from '../persistence/model.ts';import { PAGE_MAX_BYTES } from '../page-size-policy.ts';import { contentSizeHold } from '../markdown.ts';import { readPageBodyPolicy } from '../page-body/limits.ts';@@ -48,26 +50,46 @@ async function callerPrincipal(ctx: OperationContext): Promise<Principal> {* its read scope); the source still active at the incarnation the session began under; and, until the session is* committed, the page it began against (for create: still no page at the slug).*/-function callerMayUse(ctx: OperationContext, principal: Principal, row: UploadRow): boolean {+function callerMayUse(ctx: OperationContext, principal: Principal, row: UploadRow, opts: { ownerOnly?: boolean } = {}): boolean {if (row.principal_kind !== principal.kind || row.principal_id !== principal.id) return false;if (ctx.remote !== false) {const scope = sourceScopeOpts(ctx);const readable = scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : null);if (row.source_id !== (ctx.auth?.sourceId ?? ctx.sourceId ?? 'default') || (readable && !readable.includes(row.source_id))) return false;}+ try {+ enforceClientSlugFence(ctx, row.slug, 'begin_page_upload');+ enforceSubagentSlugFence(ctx, row.slug, 'begin_page_upload');+ } catch { return false; }+ if (opts.ownerOnly) return true;if (row.source_archived !== false || row.current_incarnation !== row.source_incarnation) return false;const uncommitted = row.commit_request_id === null && ['open', 'sealed', 'prepared'].includes(row.state);if (uncommitted && (row.mode === 'create' ? row.current_page_id !== null : row.current_page_id !== row.page_id)) return false;return true;}-async function boundUpload(ctx: OperationContext, principal: Principal, uploadId: unknown, opts: { exec?: OperationContext['engine']; lock?: boolean } = {}): Promise<UploadRow> {+async function boundUpload(ctx: OperationContext, principal: Principal, uploadId: unknown, opts: { exec?: OperationContext['engine']; lock?: boolean; ownerOnly?: boolean } = {}): Promise<UploadRow> {if (!isWriteRequestId(uploadId)) throw uploadNotFound();const row = await readUpload(opts.exec ?? ctx.engine, uploadId.toLowerCase(), { lock: opts.lock });- if (!row || !callerMayUse(ctx, principal, row)) throw uploadNotFound();+ if (!row || !callerMayUse(ctx, principal, row, { ownerOnly: opts.ownerOnly })) throw uploadNotFound();return row;}+/**+ * A lapsed session expires here (`upload_expired`); when another call moved it on first (a commit sealed it), the row+ * is read again and the caller follows its real state instead of reporting an expiry that did not happen.+ */+async function settleLapse(ctx: OperationContext, principal: Principal, row: UploadRow, opts: { ownerOnly?: boolean } = {}): Promise<UploadRow> {+ if (await expireIfLapsed(ctx.engine, row)) throw uploadExpired(row);+ if (!row.lapsed) return row;+ const current = await boundUpload(ctx, principal, row.id, opts);+ if (current.state === 'expired') throw uploadExpired(current);+ return current;+}++/** @internal Forced-race seam of the commit test: runs after commit sealed the session and hashed its parts. */+export const uploadCommitProbe: { afterHash?: (uploadId: string) => Promise<void> } = {};+function sessionStatus(ctx: OperationContext, row: UploadRow) {return { upload_id: row.id, state: row.state, next_part: row.next_part, received_bytes: row.received_bytes, total_bytes: row.declared_bytes,part_max_frame_bytes: partMaxFrameBytes(ctx), expires: row.idle_expires_at < row.hard_expires_at ? row.idle_expires_at : row.hard_expires_at,@@ -158,8 +180,7 @@ const begin_page_upload: Operation = {throw opError('idempotency_conflict', 'This request_id already began a different upload.', 'Begin this upload with a new request_id; reuse a request_id only to resume the same upload.');}if (!callerMayUse(ctx, principal, row)) throw uploadNotFound();- if (await expireIfLapsed(ctx.engine, row)) throw uploadExpired(row);- return sessionStatus(ctx, row);+ return sessionStatus(ctx, await settleLapse(ctx, principal, row));};const prior = await readUploadByRequest(ctx.engine, principal, clientRequestId);if (prior) return resumed(prior);@@ -167,12 +188,15 @@ const begin_page_upload: Operation = {if (!source || source.archived) {throw opError('source_changed', 'The write source is not active.', `Source ${sourceId} is archived or not registered, so nothing was staged. Write to an active source (sources_list shows them).`);}+ // put_page's grant and visibility checks first: a page this caller may not see answers as put_page does, before any read of it.+ await submissionAuthority(ctx, mode === 'append' ? 'append_page' : 'put_page', sourceId, source.incarnation, slug);const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });if (mode === 'create' && snapshot) {throw opError('revision_required', `Page ${slug} already exists, so an upload with mode create cannot write it; nothing was staged.`,"Read the page with get_page body: 'none', then begin with mode replace and its revision as expected_revision.", { fix: pageFix(slug, sourceId) });}if (mode !== 'create' && (!snapshot || snapshot.page.deleted_at)) {+ if (ctx.remote !== false) throw pageNotVisibleError();throw opError('page_not_found', `Page not found: ${slug}`, `An upload with mode ${mode} writes an existing page; begin with mode create to make it.`);}if (mode !== 'create' && want.baseRevision !== null && snapshot!.revision !== want.baseRevision) throw revisionChanged(slug, sourceId);@@ -240,8 +264,8 @@ const upload_page_part: Operation = {return { state: await appendPart(tx, row, bytes, partSha) };});if ('expired' in outcome) {- await expireIfLapsed(ctx.engine, outcome.expired);- throw uploadExpired(outcome.expired);+ const current = await settleLapse(ctx, principal, outcome.expired);+ throw opError('invalid_params', `This upload is ${current.state}, so it takes no more parts.`, 'Commit it with commit_page_upload, or begin a new upload.', { fix: statusFix(current.id) });}return outcome.state;},@@ -257,9 +281,8 @@ const get_page_upload: Operation = {scope: 'write',area: 'pages',handler: async (ctx, p) => {- const row = await boundUpload(ctx, await callerPrincipal(ctx), p.upload_id);- if (await expireIfLapsed(ctx.engine, row)) throw uploadExpired(row);- return sessionStatus(ctx, row);+ const principal = await callerPrincipal(ctx);+ return sessionStatus(ctx, await settleLapse(ctx, principal, await boundUpload(ctx, principal, p.upload_id)));},};@@ -274,10 +297,16 @@ const abort_page_upload: Operation = {area: 'pages',handler: async (ctx, p) => {if (ctx.dryRun) return { dry_run: true, action: 'abort_page_upload', upload_id: p.upload_id };- const row = await boundUpload(ctx, await callerPrincipal(ctx), p.upload_id);- if (await expireIfLapsed(ctx.engine, row)) throw uploadExpired(row);- if (row.state === 'aborted' && row.commit_request_id === null) return { upload_id: row.id, state: 'aborted' };- if (row.state !== 'committed' && row.commit_request_id === null && await abortUpload(ctx.engine, row.id)) return { upload_id: row.id, state: 'aborted' };+ // The creating principal in its source may always abort, even after the page, slug or source incarnation moved on.+ const principal = await callerPrincipal(ctx);+ const row = await settleLapse(ctx, principal, await boundUpload(ctx, principal, p.upload_id, { ownerOnly: true }), { ownerOnly: true });+ if (row.state === 'aborted') return { upload_id: row.id, state: 'aborted' };+ if (row.state !== 'committed' && await abortUpload(ctx.engine, row.id)) return { upload_id: row.id, state: 'aborted' };+ const [request] = row.commit_request_id ? await ctx.engine.executeRaw<Pick<WriteRequest, 'state'>>('SELECT state FROM persistence_requests WHERE id = $1::uuid', [row.commit_request_id]) : [];+ if (row.state !== 'committed' && request && !isTerminal(request)) {+ throw opError('write_pending', 'A commit of this upload is still being written, so it cannot be aborted now.',+ 'Call commit_page_upload again with this upload_id to wait for its result; abort it only if that commit ends without writing.', { fix: statusFix(row.id) });+ }throw opError('invalid_params', 'This upload was already committed, so it cannot be aborted.', 'Read the write with commit_page_upload (it returns the receipt again).', { fix: statusFix(row.id) });},};@@ -301,23 +330,34 @@ const commit_page_upload: Operation = {handler: async (ctx, p) => {if (ctx.dryRun) return { dry_run: true, action: 'commit_page_upload', upload_id: p.upload_id };const principal = await callerPrincipal(ctx);- const row = await boundUpload(ctx, principal, p.upload_id);- const submitted = row.state === 'committed' || row.commit_request_id !== null;- if (!submitted) {- if (await expireIfLapsed(ctx.engine, row)) throw uploadExpired(row);- if (row.state === 'aborted') throw uploadNotFound();- if (row.state === 'open') {- if (row.received_bytes !== row.declared_bytes) {- throw opError('invalid_params', `This upload has ${row.received_bytes} of its ${row.declared_bytes} bytes, so it cannot be committed yet.`,- `Send part ${row.next_part} and the rest, then commit.`, { fix: statusFix(row.id) });- }- if (await stagedSha256(ctx.engine, row) !== row.declared_sha256) {- throw opError('invalid_params', 'The uploaded bytes do not match the sha256 declared at begin, so nothing was written.',- 'Abort this upload, then begin again with the SHA-256 of exactly the content you send.');+ let row = await boundUpload(ctx, principal, p.upload_id);+ const isSubmitted = (r: UploadRow) => r.state === 'committed' || r.commit_request_id !== null;+ if (!isSubmitted(row)) row = await settleLapse(ctx, principal, row);+ // Sealing is the commit's claim: an atomic open -> sealed that takes the session out of idle expiry. A call that+ // loses it (another commit sealed first, or the session ended) reads the session again and follows its real state.+ if (!isSubmitted(row) && row.state === 'open') {+ if (row.received_bytes !== row.declared_bytes) {+ throw opError('invalid_params', `This upload has ${row.received_bytes} of its ${row.declared_bytes} bytes, so it cannot be committed yet.`,+ `Send part ${row.next_part} and the rest, then commit.`, { fix: statusFix(row.id) });+ }+ if (!await sealUpload(ctx.engine, row.id)) row = await boundUpload(ctx, principal, row.id);+ else {+ const hashed = await stagedSha256(ctx.engine, row);+ await uploadCommitProbe.afterHash?.(row.id);+ if (hashed !== row.declared_sha256) {+ await abortUpload(ctx.engine, row.id);+ throw opError('invalid_params', 'The uploaded bytes do not match the sha256 declared at begin, so the upload was discarded and nothing was written.',+ 'Begin again with the SHA-256 of exactly the content you send.');}- await sealUpload(ctx.engine, row.id);+ row = { ...row, state: 'sealed' };}}+ const submitted = isSubmitted(row);+ if (!submitted) {+ if (row.state === 'expired') throw uploadExpired(row);+ if (row.state === 'aborted') throw uploadNotFound();+ if (row.state === 'open') throw opError('write_pending', 'Another call is committing this upload.', 'Call commit_page_upload again with this upload_id.', { fix: statusFix(row.id) });+ }const bodyRef: StagingBodyRef = { kind: 'staging', staging_id: row.id, sha256: row.declared_sha256, bytes: row.declared_bytes };if (row.mode === 'append') {try {@@ -333,7 +373,10 @@ const commit_page_upload: Operation = {...(p.wait_ms !== undefined ? { wait_ms: p.wait_ms } : {}) };if (!submitted && row.mode === 'replace') {const current = await ctx.engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });- if (current?.revision !== row.base_revision) throw revisionChanged(row.slug, row.source_id);+ if (current?.revision !== row.base_revision) {+ await abortUpload(ctx.engine, row.id);+ throw revisionChanged(row.slug, row.source_id);+ }if (ctx.remote !== false) await assertLargePageAdmission(ctx.engine, row.slug, row.source_id, params);}try {diff --git a/src/core/persistence/limits.ts b/src/core/persistence/limits.tsindex ef30616c50..29473667c8 100644--- a/src/core/persistence/limits.ts+++ b/src/core/persistence/limits.ts@@ -130,11 +130,13 @@ export function isStagedCounterKey(key: string): boolean {}/**- * The CTE that releases the reservations of the upload stagings a preceding CTE named `gone` (columns kind,- * principal_kind, principal_id, reserved_bytes) moved out of a live state, locking the counter rows in key order as- * admission does. Constant SQL; the caller ends the statement.+ * The CTE that deletes the parts and releases the reservations of the upload stagings a preceding CTE named `gone`+ * (columns id, kind, principal_kind, principal_id, reserved_bytes) moved out of a live state, in the same statement so+ * capacity is never free while its bytes remain; it locks the counter rows in key order as admission does. Constant+ * SQL; the caller ends the statement.*/-export const RELEASE_STAGED_CTE = `released_keys AS (+export const RELEASE_STAGED_CTE = `released_parts AS (DELETE FROM page_body_staging_parts p USING gone g WHERE p.staging_id = g.id AND g.kind = 'upload' RETURNING 1),+ released_keys AS (SELECT key, SUM(bytes)::bigint AS bytes, SUM(n)::bigint AS n FROM (SELECT 'principal:'||principal_kind||':'||principal_id||':staged' AS key, reserved_bytes AS bytes, 0 AS n FROM gone WHERE kind='upload'UNION ALL SELECT '${BRAIN_STAGED_KEY}', reserved_bytes, 0 FROM gone WHERE kind='upload'@@ -145,14 +147,16 @@ export const RELEASE_STAGED_CTE = `released_keys AS (FROM released_keys d JOIN released_locked l ON l.key=d.key WHERE c.key=d.key RETURNING c.key)`;/**- * `write_quota_exhausted` for an upload-session cap: staged bytes or open sessions. Committing, aborting or letting a+ * `write_quota_exhausted` for an upload-session cap: staged bytes or open sessions. `used` is null for the brain-wide+ * cap, whose usage counts other principals' uploads and is never reported. Committing, aborting or letting a* session expire frees it; the host can raise the cap (reversible).*/-export function stagedQuotaExhausted(resource: string, setting: keyof UploadLimits, used: number, limit: number, need: number,+export function stagedQuotaExhausted(resource: string, setting: keyof UploadLimits, used: number | null, limit: number, need: number,reason: 'staged_bytes' | 'open_uploads'): OperationError {const key = uploadLimitKey(setting);- const value = Math.max(limit * 2, used + need);- return opError('write_quota_exhausted', `Upload capacity exhausted: ${resource} (${used} used of ${limit}, this upload needs ${need}).`,+ const value = Math.max(limit * 2, (used ?? 0) + need);+ const usage = used === null ? `limit ${limit}` : `${used} used of ${limit}`;+ return opError('write_quota_exhausted', `Upload capacity exhausted: ${resource} (${usage}, this upload needs ${need}).`,`Commit or abort your open uploads (abort_page_upload), or let them expire, then begin again with the same request_id. `+ `The brain host can raise the cap: gbrain config set ${key} ${value} (undo with gbrain config unset ${key}).`,{ reason, detail: key.slice('persistence.limits.'.length), docs: 'docs/guides/write-refusals.md#write_quota_exhausted',diff --git a/src/core/persistence/page-upload.ts b/src/core/persistence/page-upload.tsindex b252a6d9b4..708ccd7668 100644--- a/src/core/persistence/page-upload.ts+++ b/src/core/persistence/page-upload.ts@@ -102,7 +102,11 @@ const LIVE = `'{${LIVE_STAGING_STATES.join(',')}}'::text[]`;/** The session `s` is named by an unfinished write (its staged body is a GC root until that write ends). */const REQUEST_HELD_SQL = `EXISTS (SELECT 1 FROM persistence_requests r WHERE r.state IN ('queued','running','recovering')AND r.intent->'body_ref'->>'staging_id' = s.id::text)`;-const LAPSED_SQL = `(s.state = ANY(${LIVE}) AND (s.idle_expires_at <= now() OR s.hard_expires_at <= now()) AND NOT ${REQUEST_HELD_SQL})`;+/**+ * The session `s` expires: an open session past either deadline, a sealed (committing) one only past its hard deadline,+ * which sealing extends by one idle period; never one an unfinished write names. A commit in progress is never expired.+ */+const LAPSED_SQL = `(s.state = ANY(${LIVE}) AND (s.hard_expires_at <= now() OR s.state = 'open' AND s.idle_expires_at <= now()) AND NOT ${REQUEST_HELD_SQL})`;const iso = (value: unknown) => new Date(value as string | Date).toISOString();const toRow = (raw: Record<string, unknown>): UploadRow => ({@@ -134,30 +138,36 @@ export async function readUploadByRequest(exec: SqlEngine, principal: Principal,}/**- * Moves the live upload sessions `where` selects (over alias `s`, binding `params`) to `state` and releases their- * reservations in the same statement; returns how many moved. A commit records its request.+ * Moves the live upload sessions `where` selects (over alias `s`, binding `params`) to `state`, deletes their parts and+ * releases their reservations in the same statement; returns how many moved. A commit records its request.*/export async function transitionUploads(exec: SqlEngine, state: 'aborted' | 'expired' | 'committed', where: string, params: unknown[],opts: { commitRequestId?: string } = {}): Promise<number> {const commit = opts.commitRequestId !== undefined ? `, commit_request_id = $${params.length + 1}::uuid` : '';const [row] = await exec.executeRaw<{ n: number }>(`WITH gone AS (UPDATE page_body_stagings s SET state = '${state}', updated_at = now()${commit}- WHERE s.kind = 'upload' AND s.state = ANY(${LIVE}) AND ${where} RETURNING s.kind, s.principal_kind, s.principal_id, s.reserved_bytes),+ WHERE s.kind = 'upload' AND s.state = ANY(${LIVE}) AND ${where} RETURNING s.id, s.kind, s.principal_kind, s.principal_id, s.reserved_bytes),${RELEASE_STAGED_CTE}SELECT count(*)::int AS n FROM gone`, opts.commitRequestId !== undefined ? [...params, opts.commitRequestId] : params);return Number(row?.n ?? 0);}-/** Expires the session if it lapsed (releasing its reservation); true when it is, or already was, expired. */+/**+ * Expires the session if it lapsed (releasing its reservation); true only when it was already expired or this call+ * expired it. False on a row that moved on meanwhile (a commit sealed it): the caller re-reads it and follows its state.+ */export async function expireIfLapsed(exec: SqlEngine, row: UploadRow): Promise<boolean> {if (row.state === 'expired') return true;if (!row.lapsed) return false;- await transitionUploads(exec, 'expired', `s.id = $1::uuid AND ${LAPSED_SQL}`, [row.id]);- return true;+ return await transitionUploads(exec, 'expired', `s.id = $1::uuid AND ${LAPSED_SQL}`, [row.id]) > 0;}-/** Aborts the live session unless a commit was submitted for it; true when it moved (its bytes released). */+/**+ * Aborts the live session unless a commit holds it: no commit was submitted, or the submitted one ended without+ * committing. True when it moved (its parts deleted and its bytes released).+ */export async function abortUpload(exec: SqlEngine, id: string): Promise<boolean> {- return await transitionUploads(exec, 'aborted', `s.id = $1::uuid AND s.commit_request_id IS NULL AND NOT ${REQUEST_HELD_SQL}`, [id]) > 0;+ return await transitionUploads(exec, 'aborted', `s.id = $1::uuid AND NOT ${REQUEST_HELD_SQL} AND (s.commit_request_id IS NULL+ OR EXISTS (SELECT 1 FROM persistence_requests r WHERE r.id = s.commit_request_id AND r.state IN ('conflict','failed','cancelled')))`, [id]) > 0;}export interface UploadReservation {@@ -187,7 +197,7 @@ export async function reserveUpload(engine: BrainEngine, input: UploadReservatioconst staged = Number(usage?.staged ?? 0), brain = Number(usage?.brain ?? 0), uploads = Number(usage?.uploads ?? 0);if (uploads + 1 > limits.principalUploads) throw stagedQuotaExhausted('open upload sessions for this connection', 'principalUploads', uploads, limits.principalUploads, 1, 'open_uploads');if (staged + input.totalBytes > limits.principalStagedBytes) throw stagedQuotaExhausted('staged upload bytes for this connection', 'principalStagedBytes', staged, limits.principalStagedBytes, input.totalBytes, 'staged_bytes');- if (brain + input.totalBytes > limits.brainStagedBytes) throw stagedQuotaExhausted('staged upload bytes for this brain', 'brainStagedBytes', brain, limits.brainStagedBytes, input.totalBytes, 'staged_bytes');+ if (brain + input.totalBytes > limits.brainStagedBytes) throw stagedQuotaExhausted('staged upload bytes for this brain', 'brainStagedBytes', null, limits.brainStagedBytes, input.totalBytes, 'staged_bytes');await tx.executeRaw(`INSERT INTO page_body_stagings (id, kind, principal_kind, principal_id, client_request_id, source_id, source_incarnation, slug,page_id, mode, base_revision, base_generation, declared_bytes, declared_sha256, reserved_bytes, idle_expires_at, hard_expires_at)VALUES ($1::uuid, 'upload', $2, $3, $4::uuid, $5, $6::uuid, $7, $8::int, $9, $10::uuid, (SELECT body_generation FROM pages WHERE id = $8::int),@@ -233,8 +243,16 @@ export async function stagedSha256(exec: SqlEngine, row: Pick<UploadRow, 'id' |return at === row.received_bytes ? hash.digest('hex') : null;}-export async function sealUpload(exec: SqlEngine, id: string): Promise<void> {- await exec.executeRaw(`UPDATE page_body_stagings SET state = 'sealed', updated_at = now() WHERE id = $1::uuid AND state = 'open'`, [id]);+/**+ * Seals the open session for its commit: no more parts, and no expiry until its hard deadline, which moves to at least+ * one idle period from now so the commit can journal. True when this call sealed it; false when it was no longer open.+ */+export async function sealUpload(exec: SqlEngine, id: string): Promise<boolean> {+ const limits = await readUploadLimits(exec);+ const sealed = await exec.executeRaw<{ id: string }>(`UPDATE page_body_stagings SET state = 'sealed', updated_at = now(),+ hard_expires_at = GREATEST(hard_expires_at, now() + $2::bigint * interval '1 second')+ WHERE id = $1::uuid AND state = 'open' RETURNING id::text AS id`, [id, limits.uploadIdleSeconds]);+ return sealed.length > 0;}/** A journal body reference to a sealed upload session (spec 3.2). */diff --git a/src/core/persistence/upload-streamed.ts b/src/core/persistence/upload-streamed.tsindex 8e1c20d092..bfa59f55a8 100644--- a/src/core/persistence/upload-streamed.ts+++ b/src/core/persistence/upload-streamed.ts@@ -25,6 +25,10 @@ import { pageGateTrust, pageWriteTrust, stampPageTrustMarker, storedPageTier } fimport type { WriteTrust } from '../trust/tier.ts';import { sizeStateField } from '../page-embedding-budget.ts';import { coreMarking } from '../core-memory.ts';+import { TAKES_FENCE_BEGIN } from '../takes-fence.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';+import { inlineRegions } from '../page-body/tail-digest.ts';+import type { PageSnapshot } from '../page-state/types.ts';import { PAGE_MAX_BYTES } from '../page-size-policy.ts';import { bodyStagingGoneError } from '../engine-sql/page-body.ts';import { ownerSourceGateInput, writeTrustOfGate } from './attribution.ts';@@ -37,6 +41,31 @@ import type { WriteRequest } from './model.ts';const text = (value: unknown) => (typeof value === 'string' ? value : null);+/**+ * put_page keeps, for a remote writer, the takes fence remote reads hide (preserveProtectedTakes) and refuses to drop+ * timeline rows its content omits (assertTimelineNotOmitted); both compare whole bodies. Streamed, this refuses+ * instead: a remote replace over the ceiling of a page holding a takes fence, or timeline rows (unless drop_timeline),+ * is `upload_protected_content`. Bounded: one probe of the live manifest and of timeline_entries.+ */+async function assertNothingHiddenDropped(engine: BrainEngine, row: WriteRequest, snapshot: PageSnapshot, p: Record<string, unknown>): Promise<void> {+ const [found] = await engine.executeRaw<{ has_takes: boolean; has_timeline: boolean }>(`SELECT+ EXISTS (SELECT 1 FROM page_body_manifest m JOIN pages pg ON pg.id = m.page_id WHERE m.page_id = $1 AND m.staging_id IS NULL+ AND m.gen_from <= pg.body_generation AND (m.gen_to IS NULL OR m.gen_to > pg.body_generation)+ AND m.protected_regions @> '[{"kind":"takes"}]'::jsonb) AS has_takes,+ EXISTS (SELECT 1 FROM timeline_entries WHERE page_id = $1) AS has_timeline`, [Number(snapshot.page.id)]);+ const inlineTakes = !isSegmentedPage(snapshot.page)+ && Object.values(await inlineRegions(engine, Number(snapshot.page.id))).some(region => region.includes(TAKES_FENCE_BEGIN));+ const reason = found?.has_takes || inlineTakes ? 'takes' : found?.has_timeline && p.drop_timeline !== true ? 'timeline' : null;+ if (!reason) return;+ throw opError('upload_protected_content', reason === 'takes'+ ? `Page ${row.slug} holds a takes fence that remote reads hide, and a remote replace over ${PAGE_MAX_BYTES} bytes cannot carry it over, so nothing was written.`+ : `Page ${row.slug} has timeline rows, and a remote replace over ${PAGE_MAX_BYTES} bytes cannot check which of them its content keeps, so nothing was written.`,+ reason === 'takes'+ ? `Replace the page with content of at most ${PAGE_MAX_BYTES} bytes (put_page keeps the hidden takes fence), or ask the user to write it locally on the brain host.`+ : `Upload the page again and commit it with drop_timeline: true only if deleting every timeline entry of the page is intended; otherwise replace it with content of at most ${PAGE_MAX_BYTES} bytes, which put_page checks entry by entry.`,+ { reason, docs: 'docs/guides/write-refusals.md#upload_protected_content' });+}+export async function prepareStreamedUpload(engine: BrainEngine, row: WriteRequest, ref: StagingBodyRef): Promise<PreparedMutation> {const p = row.intent as Record<string, unknown>;const policy = await readPageBodyPolicy(engine);@@ -48,6 +77,7 @@ export async function prepareStreamedUpload(engine: BrainEngine, row: WriteRequeassertPageRevision(snapshot, { expectedRevision: text(p.expected_revision) });if ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(!!snapshot, 'The accepted page was deleted or recreated.');const remote = row.authority.remote === true;+ if (remote && snapshot && !snapshot.page.deleted_at) await assertNothingHiddenDropped(engine, row, snapshot, p);const storedTier = remote && snapshot ? await storedPageTier(engine, row.source_id, row.slug) : null;let trust: WriteTrust | undefined;const dir = await mkdtemp(join(tmpdir(), 'gbrain-upload-'));diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex e70931d247..00a0b4de62 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6423,7 +6423,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --git a/test/large-pages/upload-binding.test.ts b/test/large-pages/upload-binding.test.tsindex 78310377cb..131a2e1fd9 100644--- a/test/large-pages/upload-binding.test.ts+++ b/test/large-pages/upload-binding.test.ts@@ -142,7 +142,7 @@ for (const kind of testBackends()) {expect(await call('get_page_upload', { upload_id: id })).toMatchObject({ state: 'open', next_part: 0 });const [began] = await engine.executeRaw<{ incarnation: string }>('SELECT source_incarnation::text AS incarnation FROM page_body_stagings WHERE id = $1::uuid', [id]);await engine.executeRaw('UPDATE page_body_stagings SET source_incarnation = $2::uuid WHERE id = $1::uuid', [id, randomUUID()]);- for (const [name, params] of probes) expect(wire(await refusal(name, params(id)))).toBe(wire(await refusal(name, params(missing))));+ for (const [name, params] of probes.filter(([name]) => name !== 'abort_page_upload')) expect(wire(await refusal(name, params(id)))).toBe(wire(await refusal(name, params(missing))));await engine.executeRaw('UPDATE page_body_stagings SET source_incarnation = $2::uuid WHERE id = $1::uuid', [id, began!.incarnation]);expect((await call('abort_page_upload', { upload_id: id })).state).toBe('aborted');}, 120_000);diff --git a/test/large-pages/upload-over-ceiling.test.ts b/test/large-pages/upload-over-ceiling.test.tsindex 50fde0dea6..cccc1358bd 100644--- a/test/large-pages/upload-over-ceiling.test.ts+++ b/test/large-pages/upload-over-ceiling.test.ts@@ -137,7 +137,6 @@ for (const kind of testBackends()) {const staleId = await staged(stale, slug, { mode: 'replace', expected_revision: await revisionOf(slug) });await call('add_tag', { slug, tag: 'moved' });expect((await commitRefusal({ upload_id: staleId })).code).toBe('revision_changed');- await call('abort_page_upload', { upload_id: staleId });const after = await counters();for (const [key, value] of Object.entries(after)) expect([key, value]).toEqual([key, prior[key] ?? [0, 0]]);const body = await materializeSegmentedBody(engine, Number((await stored(slug)).id), 'default');@@ -156,5 +155,25 @@ for (const kind of testBackends()) {await commit({ upload_id: id, allow_shrink: true });await expectStoredBody(slug, smaller);}, 900_000);++ test('a remote replace over 24 MiB of a page with a hidden takes fence or timeline rows refuses upload_protected_content and releases its bytes', async () => {+ const cases: Array<['takes' | 'timeline', string, () => Promise<unknown>]> = [+ ['takes', 'notes/huge-with-takes', () => call('takes_add', { slug: 'notes/huge-with-takes', claim: 'Launch slips to Q3.', kind: 'take', holder: 'world', request_id: randomUUID() })],+ ['timeline', 'notes/huge-with-timeline', () => call('add_timeline_entry', { slug: 'notes/huge-with-timeline', date: '2026-01-02', summary: 'Kickoff held', request_id: randomUUID() })],+ ];+ await setConfig('write_gate.agent_mode', 'off');+ for (const [reason, slug, protect] of cases) {+ await call('put_page', { slug, content: `---\ntitle: Protected ${reason}\ntype: note\n---\n\n# Protected ${reason}\n\nShort page.\n`, request_id: randomUUID(), wait_ms: 30_000 });+ await protect();+ const prior = await counters();+ const before = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ const id = await staged(conversation(25 * MiB, `protected-${reason}`), slug, { mode: 'replace', expected_revision: before!.revision });+ const refused = await commitRefusal({ upload_id: id });+ expect({ reason, code: refused.code, names: refused.message.includes(reason === 'takes' ? 'takes fence' : 'timeline rows') }).toEqual({ reason, code: 'upload_protected_content', names: true });+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision).toBe(before!.revision);+ const after = await counters();+ for (const [key, value] of Object.entries(after)) expect([reason, key, value]).toEqual([reason, key, prior[key] ?? [0, 0]]);+ }+ }, 900_000);});}diff --git a/test/large-pages/upload-review.test.ts b/test/large-pages/upload-review.test.tsnew file mode 100644index 0000000000..c163b7d2a8--- /dev/null+++ b/test/large-pages/upload-review.test.ts@@ -0,0 +1,275 @@+/**+ * Wave B PR 3 review (lane 3b): upload sessions never strand quota, disclose nothing across connections, and refuse+ * malformed input.+ *+ * 1. Protects: begin_page_upload runs put_page's visibility authorization before reading the page, so a remote caller+ * gets the same answer for a private page as for a missing one in replace and append (and create answers as+ * put_page does for an invisible page); every refusal at commit (stale revision, sha mismatch) and every failed+ * commit releases the session's staged bytes without a manual abort; the creating principal can always abort,+ * even after the page, slug or source moved on, while another principal gets upload_not_found; abort after a+ * commit that failed answers aborted, not "already committed"; parts are deleted in the statement that releases+ * their quota; the brain-wide quota refusal names its limit but never the brain's usage; a slug fence the caller+ * gained after begin closes the session to part, status and abort; sha mismatch, an overflowing total_bytes, a lone+ * surrogate and an archived source refuse.+ * 2. Fails when: any of those regress (each was missing at c704bdfc3 unless noted in its test).+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set (no embedding, no model calls).+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { createHash, randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { GBrainConfig } from '../../src/core/config.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { operations, OperationError, type OperationContext } from '../../src/core/operations.ts';+import * as uploadOps from '../../src/core/ops/page-upload.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++const MiB = 1024 ** 2;+const op = (name: string) => operations.find(o => o.name === name)!;+const hex = (text: string) => createHash('sha256').update(Buffer.from(text, 'utf8')).digest('hex');++for (const kind of testBackends()) {+ describe(`upload sessions: review fixes (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let n = 0;++ const ctx = (client = 'review-a', over: Record<string, unknown> = {}): OperationContext => ({+ engine, config: {} as GBrainConfig, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: true, sourceId: 'default',+ transport: 'http', inboundFrameBytes: MiB, auth: { token: 'fixture', clientId: client, principal: { kind: 'oauth_client', id: client },+ scopes: ['read', 'write'], sourceId: 'default', allowedSources: ['default'], ...over } } as unknown as OperationContext);+ const call = async (name: string, params: Record<string, unknown>, c = ctx()) => await op(name).handler(c, params) as Record<string, any>;+ const refusal = async (name: string, params: Record<string, unknown>, c = ctx()) => {+ try { await op(name).handler(c, params); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error(`${name} did not refuse`);+ };+ const wire = (error: OperationError) => JSON.stringify(error.toJSON());+ const slugOf = () => `notes/review-${++n}`;+ const pageText = (tag: string, bytes = 4000) => `---\ntitle: Review ${tag}\ntype: note\n---\n\n# Review ${tag}\n\n${`Planning notes for ${tag}. `.repeat(Math.ceil(bytes / 30))}`;+ const halves = (text: string) => [text.slice(0, Math.ceil(text.length / 2)), text.slice(Math.ceil(text.length / 2))];+ const begin = async (slug: string, text: string, over: Record<string, unknown> = {}, c = ctx()) =>+ await call('begin_page_upload', { slug, mode: 'create', total_bytes: Buffer.byteLength(text), sha256: hex(text), request_id: randomUUID(), ...over }, c);+ const send = async (uploadId: string, parts: string[], c = ctx()) => {+ for (const [part, text] of parts.entries()) await call('upload_page_part', { upload_id: uploadId, part, text, part_sha256: hex(text) }, c);+ };+ const counters = async () => Object.fromEntries((await engine.executeRaw<{ key: string; intent_bytes: unknown; outstanding_count: unknown }>(+ `SELECT key, intent_bytes, outstanding_count FROM persistence_counters WHERE key LIKE '%:staged' OR key LIKE '%:uploads' ORDER BY key`))+ .map(row => [row.key, [Number(row.intent_bytes), Number(row.outstanding_count)]]));+ const expectReleased = async (prior: Record<string, number[]>) => {+ for (const [key, value] of Object.entries(await counters())) expect([key, value]).toEqual([key, prior[key] ?? [0, 0]]);+ };+ const parts = async (id: string) => (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_body_staging_parts WHERE staging_id = $1::uuid', [id]))[0]!.n;+ const createPage = async (slug: string, text = pageText(slug)) => {+ await call('put_page', { slug, content: text, request_id: randomUUID(), wait_ms: 30_000 });+ return (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision;+ };++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES('review-archived','review-archived','{}') ON CONFLICT DO NOTHING");+ for (const client of ['review-a', 'review-b', 'review-c']) {+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_secret_hash,client_name,scope,source_id)+ VALUES($1,'fixture-hash','review-client','read write','default') ON CONFLICT (client_id) DO NOTHING`, [client]);+ }+ }, 120_000);+ afterAll(async () => { await close(); });+ afterEach(async () => {+ await engine.executeRaw('DELETE FROM page_body_stagings');+ await engine.executeRaw("DELETE FROM persistence_counters WHERE key LIKE '%:staged' OR key LIKE '%:uploads'");+ });++ test('a private page answers begin exactly as a missing one in replace and append, and create answers as put_page does', async () => {+ const hidden = slugOf();+ await importFromContent(engine, hidden, `---\ntitle: Hidden\ntype: note\nvisibility: private\n---\n\nPrivate body.\n`, { sourceId: 'default', noEmbed: true });+ const missing = slugOf();+ const text = pageText('probe');+ const params = (slug: string, mode: string) => ({ slug, mode, total_bytes: Buffer.byteLength(text), sha256: hex(text), request_id: randomUUID(),+ ...(mode === 'replace' ? { expected_revision: '00000000-0000-4000-8000-000000000000' } : {}) });+ for (const mode of ['replace', 'append']) {+ const a = await refusal('begin_page_upload', params(hidden, mode));+ const b = await refusal('begin_page_upload', params(missing, mode));+ expect({ mode, wire: wire(a) }).toEqual({ mode, wire: wire(b) });+ }+ const created = await refusal('begin_page_upload', params(hidden, 'create'));+ const put = await refusal('put_page', { slug: hidden, content: text, request_id: randomUUID() });+ expect(wire(created)).toBe(wire(put));+ expect(wire(created)).toBe(wire(await refusal('begin_page_upload', params(missing, 'replace'))));+ }, 120_000);++ test('a replace whose page moved refuses revision_changed at commit and releases its bytes and parts without an abort', async () => {+ const slug = slugOf();+ const base = await createPage(slug);+ const prior = await counters();+ const text = pageText('stale');+ const session = await begin(slug, text, { mode: 'replace', expected_revision: base });+ await send(session.upload_id, halves(text));+ await call('put_page', { slug, content: pageText('moved'), expected_revision: base, request_id: randomUUID(), wait_ms: 30_000 });+ expect((await refusal('commit_page_upload', { upload_id: session.upload_id })).code).toBe('revision_changed');+ await expectReleased(prior);+ expect(await parts(session.upload_id)).toBe(0);+ }, 120_000);++ test('a sha mismatch at commit refuses, discards the session and releases its bytes', async () => {+ const prior = await counters();+ const text = pageText('sha');+ const session = await begin(slugOf(), text, { sha256: hex(`${text}x`) });+ await send(session.upload_id, halves(text));+ const refused = await refusal('commit_page_upload', { upload_id: session.upload_id });+ expect(refused.code).toBe('invalid_params');+ expect(refused.message).toContain('sha256');+ await expectReleased(prior);+ expect(await parts(session.upload_id)).toBe(0);+ }, 120_000);++ test('abort deletes the parts in the statement that releases the quota, and a commit does too', async () => {+ const prior = await counters();+ const text = pageText('parts');+ const aborted = await begin(slugOf(), text);+ await send(aborted.upload_id, halves(text));+ expect(await parts(aborted.upload_id)).toBe(2);+ await call('abort_page_upload', { upload_id: aborted.upload_id });+ expect(await parts(aborted.upload_id)).toBe(0);+ const committed = await begin(slugOf(), text);+ await send(committed.upload_id, halves(text));+ await call('commit_page_upload', { upload_id: committed.upload_id, wait_ms: 30_000 });+ expect(await parts(committed.upload_id)).toBe(0);+ await expectReleased(prior);+ }, 120_000);++ test('the creating principal aborts after its source incarnation changed; another principal gets upload_not_found', async () => {+ const slug = slugOf();+ const base = await createPage(slug);+ const prior = await counters();+ const session = await begin(slug, pageText('gone'), { mode: 'replace', expected_revision: base });+ // The binding breaks as when the source is re-created under the session (its rows keep the old incarnation).+ await engine.executeRaw('UPDATE page_body_stagings SET source_incarnation = $2::uuid WHERE id = $1::uuid', [session.upload_id, randomUUID()]);+ const other = await refusal('abort_page_upload', { upload_id: session.upload_id }, ctx('review-b'));+ expect(wire(other)).toBe(wire(await refusal('abort_page_upload', { upload_id: randomUUID() }, ctx('review-b'))));+ expect((await refusal('get_page_upload', { upload_id: session.upload_id })).code).toBe('upload_not_found');+ expect((await call('abort_page_upload', { upload_id: session.upload_id })).state).toBe('aborted');+ await expectReleased(prior);+ }, 120_000);++ test('abort after a commit that ended without writing answers aborted, not already committed', async () => {+ const slug = slugOf();+ const base = await createPage(slug);+ const text = `\nAppended text. ${'More notes. '.repeat(50)}\n`;+ const session = await begin(slug, text, { mode: 'append', expected_revision: base });+ await send(session.upload_id, halves(text));+ await call('put_page', { slug, content: pageText('moved'), expected_revision: base, request_id: randomUUID(), wait_ms: 30_000 });+ expect((await refusal('commit_page_upload', { upload_id: session.upload_id, wait_ms: 30_000 })).code).toBe('revision_changed');+ // The commit's reply was lost before the session was settled: it is still sealed and names the failed request.+ await engine.executeRaw("UPDATE page_body_stagings SET state = 'sealed' WHERE id = $1::uuid", [session.upload_id]);+ const [row] = await engine.executeRaw<{ commit_request_id: string | null }>('SELECT commit_request_id::text AS commit_request_id FROM page_body_stagings WHERE id = $1::uuid', [session.upload_id]);+ expect(row!.commit_request_id).not.toBeNull();+ expect((await call('abort_page_upload', { upload_id: session.upload_id })).state).toBe('aborted');+ }, 120_000);++ test('the brain-wide quota refusal names its limit but not the staged bytes of other connections', async () => {+ await engine.executeRaw("INSERT INTO config (key, value) VALUES ('persistence.limits.brain_staged_bytes', '9000') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value");+ try {+ const held = pageText('held', 5000);+ await begin(slugOf(), held, {}, ctx('review-b'));+ const refused = await refusal('begin_page_upload', { slug: slugOf(), mode: 'create', total_bytes: 5000, sha256: 'a'.repeat(64), request_id: randomUUID() });+ const json = wire(refused);+ expect(refused.code).toBe('write_quota_exhausted');+ expect(json).toContain('persistence.limits.brain_staged_bytes');+ expect(json).not.toContain(String(Buffer.byteLength(held)));+ expect(json).not.toMatch(/used of/);+ } finally {+ await engine.executeRaw("DELETE FROM config WHERE key = 'persistence.limits.brain_staged_bytes'");+ }+ }, 120_000);++ test('a slug fence the caller gained after begin closes the session to part, status and abort', async () => {+ const slug = slugOf();+ const text = pageText('fenced');+ const session = await begin(slug, text);+ const fenced = ctx('review-a', { boundSlugPrefixes: ['elsewhere/'] });+ const probes: Array<[string, (id: string) => Record<string, unknown>]> = [+ ['upload_page_part', id => ({ upload_id: id, part: 0, text: 'abc', part_sha256: hex('abc') })],+ ['get_page_upload', id => ({ upload_id: id })],+ ['abort_page_upload', id => ({ upload_id: id })],+ ];+ for (const [name, params] of probes) {+ const bound = await refusal(name, params(session.upload_id), fenced);+ expect({ name, code: bound.code }).toEqual({ name, code: 'upload_not_found' });+ expect(wire(bound)).toBe(wire(await refusal(name, params(randomUUID()), fenced)));+ }+ expect(await call('get_page_upload', { upload_id: session.upload_id })).toMatchObject({ state: 'open' });+ }, 120_000);++ test('a commit retried while the first commit is past its hash and the idle deadline passes publishes once and never answers upload_expired', async () => {+ const slug = slugOf();+ const base = await createPage(slug);+ const text = `\nRaced append block. ${'Race notes. '.repeat(80)}\n`;+ const session = await begin(slug, text, { mode: 'append', expected_revision: base });+ await send(session.upload_id, halves(text));+ const probe = (uploadOps as { uploadCommitProbe?: { afterHash?: (id: string) => Promise<void> } }).uploadCommitProbe;+ let release!: () => void;+ const gate = new Promise<void>(resolve => { release = resolve; });+ let reached!: () => void;+ const paused = new Promise<void>(resolve => { reached = resolve; });+ let first: Promise<Record<string, any>>;+ if (probe) {+ probe.afterHash = async id => { if (id === session.upload_id) { reached(); await gate; } };+ first = call('commit_page_upload', { upload_id: session.upload_id, wait_ms: 30_000 });+ await paused;+ } else {+ // A build without the seam: the state commit A leaves at that point (sealed, hashed, not yet journaled).+ await engine.executeRaw("UPDATE page_body_stagings SET state = 'sealed' WHERE id = $1::uuid", [session.upload_id]);+ first = gate.then(() => call('commit_page_upload', { upload_id: session.upload_id, wait_ms: 30_000 }));+ }+ try {+ await engine.executeRaw("UPDATE page_body_stagings SET idle_expires_at = now() - interval '1 second' WHERE id = $1::uuid", [session.upload_id]);+ await engine.sweepSegments({ expireStagings: true });+ const second = await call('commit_page_upload', { upload_id: session.upload_id, wait_ms: 30_000 });+ expect(second.state).toBe('committed');+ release();+ const result = await first;+ expect(result.request_id).toBe(second.request_id);+ } finally {+ release();+ if (probe) delete probe.afterHash;+ }+ const truth = (await engine.getPage(slug, { sourceId: 'default' }))!.compiled_truth;+ expect(truth.split('Raced append block.').length - 1).toBe(1);+ const [requests] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE slug = $1 AND operation = 'append_page'", [slug]);+ expect(requests!.n).toBe(1);+ }, 120_000);++ test('an overflowing part, total_bytes over the ceiling and a lone surrogate refuse', async () => {+ const text = pageText('overflow');+ const session = await begin(slugOf(), text);+ const over = `${text}extra`;+ expect((await refusal('upload_page_part', { upload_id: session.upload_id, part: 0, text: over, part_sha256: hex(over) })).code).toBe('invalid_params');+ expect((await refusal('begin_page_upload', { slug: slugOf(), mode: 'create', total_bytes: 2 ** 40, sha256: 'a'.repeat(64), request_id: randomUUID() })).code).toBe('request_too_large');+ const lone = 'abc\uD800def';+ const surrogate = await refusal('upload_page_part', { upload_id: session.upload_id, part: 0, text: lone, part_sha256: 'a'.repeat(64) });+ expect(surrogate.code).toBe('invalid_params');+ expect(surrogate.message).toContain('surrogate');+ expect(await call('get_page_upload', { upload_id: session.upload_id })).toMatchObject({ next_part: 0, received_bytes: 0 });+ }, 120_000);++ test('an archived source refuses begin; its open session takes no parts but its owner can still abort', async () => {+ const text = pageText('archived');+ const c = ctx('review-c', { sourceId: 'review-archived', allowedSources: ['review-archived'] });+ (c as { sourceId: string }).sourceId = 'review-archived';+ await engine.executeRaw("UPDATE oauth_clients SET source_id = 'review-archived' WHERE client_id = 'review-c'");+ const prior = await counters();+ const session = await begin('notes/archived-upload', text, {}, c);+ await engine.executeRaw("UPDATE sources SET archived = true WHERE id = 'review-archived'");+ try {+ expect((await refusal('begin_page_upload', { slug: 'notes/archived-other', mode: 'create', total_bytes: 10, sha256: hex('0123456789'), request_id: randomUUID() }, c)).code).toBe('source_changed');+ const [first] = halves(text);+ expect((await refusal('upload_page_part', { upload_id: session.upload_id, part: 0, text: first, part_sha256: hex(first!) }, c)).code).toBe('upload_not_found');+ expect((await call('abort_page_upload', { upload_id: session.upload_id }, c)).state).toBe('aborted');+ await expectReleased(prior);+ } finally {+ await engine.executeRaw("UPDATE sources SET archived = false WHERE id = 'review-archived'");+ }+ }, 120_000);+ });+}diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.tsindex d36c72d386..4ea1e697f7 100644--- a/test/operations-coverage-ledger.test.ts+++ b/test/operations-coverage-ledger.test.ts@@ -47,6 +47,11 @@ const LEDGER: Record<string, string> = {capture: 'test/capture-op.test.ts',edit_page: 'test/edit-page.test.ts',append_page: 'test/large-pages/append-concurrency.test.ts',+ begin_page_upload: 'test/large-pages/upload-review.test.ts',+ upload_page_part: 'test/large-pages/upload-binding.test.ts',+ get_page_upload: 'test/large-pages/upload-binding.test.ts',+ commit_page_upload: 'test/large-pages/upload-review.test.ts',+ abort_page_upload: 'test/large-pages/upload-review.test.ts',get_write_request: 'test/persistence-receipt-operations.test.ts',list_write_requests: 'test/persistence-receipt-operations.test.ts',cancel_write_request: 'test/persistence-receipt-operations.test.ts',diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex f1d92bed4b..4de7fd73a1 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -185,6 +185,7 @@ test/large-pages/streamed-sync-origin-b14.test.tstest/large-pages/stuck-recovery-large.slow.test.tstest/large-pages/upload-binding.test.tstest/large-pages/upload-over-ceiling.test.ts+test/large-pages/upload-review.test.tstest/large-pages/v252-master-reader-compat.test.tstest/link-cross-source.test.tstest/link-preparation-shared-index.test.tsdiff --git a/test/remote-privacy-sweep.test.ts b/test/remote-privacy-sweep.test.tsindex 62a7894c4c..b6127c415e 100644--- a/test/remote-privacy-sweep.test.ts+++ b/test/remote-privacy-sweep.test.ts@@ -197,6 +197,14 @@ const PARAM_FACTORY: Record<string, Record<string, unknown>> = {edit_page: { slug: WORLD_FENCE_SLUG, expected_revision: '00000000-0000-4000-8000-000000000000', edits: [{ old_text: 'x', new_text: 'y' }] },// A stale revision on the fence-bearing page: the refusal must not echo it or its tail.append_page: { slug: WORLD_FENCE_SLUG, request_id: '6007a5e0-0000-4000-8000-000000000002', expected_revision: '00000000-0000-4000-8000-000000000000', text: 'fresh sweep append' },+ // An upload replacing the private page: the remote caller cannot see it, so begin answers as put_page does for an+ // invisible page and stages nothing.+ begin_page_upload: { slug: PRIV_PAGE_SLUG, mode: 'replace', total_bytes: 32, sha256: '0'.repeat(64), expected_revision: '00000000-0000-4000-8000-000000000000', request_id: '6007a5e0-0000-4000-8000-000000000003' },+ // A session this caller did not begin: every session op answers upload_not_found.+ upload_page_part: { upload_id: '6007a5e0-0000-4000-8000-000000000004', part: 0, text: 'fresh sweep part', part_sha256: 'af8002248c8537e357edd4eea4a9cacbaf864c4e5e0e7218f4cd808895fe1363' },+ get_page_upload: { upload_id: '6007a5e0-0000-4000-8000-000000000004' },+ commit_page_upload: { upload_id: '6007a5e0-0000-4000-8000-000000000004' },+ abort_page_upload: { upload_id: '6007a5e0-0000-4000-8000-000000000004' },remember: { fact: 'fresh sweep fact', provenance: 'sweep', entity: 'people/sweep-fresh-entity' },capture: { content: 'fresh sweep capture' },add_tag: { slug: WORLD_PAGE_SLUG, tag: 'sweep-tag' },@@ -364,6 +372,13 @@ const EXPECTED_OUTCOME: Record<string, Outcome> = {revert_version: 'error',edit_page: 'error',append_page: 'error',+ // Page uploads: begin on the invisible private page refuses page_not_found like put_page (permission_denied under the+ // read-only federated grant); the session ops refuse upload_not_found in both shapes.+ begin_page_upload: 'error',+ upload_page_part: 'error',+ get_page_upload: 'error',+ commit_page_upload: 'error',+ abort_page_upload: 'error',put_raw_data: 'error',log_ingest: 'error',takes_add: 'ok',