Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B PR3 lane 3b2: append uploads commit through admitPageAppend; uploads over 24 MiB commit through the segmented streamed import

garrytanb49a74923013
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index 20a7fc00b2..6f824d2d62 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -23,8 +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 lane 3a's seam (`admitStagedAppend`).
-- `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). `prepareStagedUpload` (called from `preparePageMutation`) reads the sealed parts back, verifies them against the reference and prepares the put_page as if the content had been sent; its publication marks the session committed in the same transaction. Pages up to PAGE_MAX_BYTES.
+- `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/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/scripts/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjs
index 37ba1298e8..caae43ee50 100644
--- a/scripts/check-core-guard-coverage.mjs
+++ b/scripts/check-core-guard-coverage.mjs
@@ -48,6 +48,7 @@ const EXEMPT = {
'src/core/facts/conversation-relink.ts': 'sets entity_slug on database-only conversation fact rows; page text is unchanged',
'src/core/cycle/extract-facts.ts': 'fence reconcile and deleted-page expiry write fact rows only; page text is unchanged',
'src/core/cycle/extract-takes.ts': 'takes reextract writes take rows only; page text is unchanged',
+ 'src/core/persistence/upload-streamed.ts': 'an upload over the single-string ceiling refuses when the page is or would become always-loaded core (the guard renders it whole); smaller uploads go through preparePageMutation',
'src/core/persistence/page-edit.ts': 'segmented edit_page splices through page-append.ts prepareSegmentedSpliceMutation, which declines an always-loaded core page to preparePageMutation; the splice never changes frontmatter',
'src/core/repair/take-supersession.ts': 'reprojection writes takes.superseded_by only; fence edits go through put_page (preparePageMutation)',
};
diff --git a/src/core/ops/page-upload.ts b/src/core/ops/page-upload.ts
index abd889e1f6..b439396389 100644
--- a/src/core/ops/page-upload.ts
+++ b/src/core/ops/page-upload.ts
@@ -25,6 +25,10 @@ import { sha256 } from '../persistence/digest.ts';
import { isTerminal, type Principal } 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';
+import { contentRefusalError, loadImportSanityConfig } from '../import-screen.ts';
+import { DEFAULT_WRITE_GATE_CONFIG, writeGateApplies } from '../write-gate.ts';
+import { admitPageAppend } from '../persistence/page-append.ts';
import {
abortUpload, appendPart, expireIfLapsed, partBytes, partMaxFrameBytes, partSha256, readUpload, readUploadByRequest, reserveUpload,
sealUpload, stagedSha256, transitionUploads, uploadExpired, uploadNotFound, uploadPartFrameBytes, type StagingBodyRef, type UploadMode, type UploadRow,
@@ -86,6 +90,26 @@ function invalidParam(message: string, suggestion: string): OperationError {
return opError('invalid_params', message, suggestion);
}
+/**
+ * A body over the single-string ceiling: create and replace go up to the brain's page ceiling (pages.max_bytes, the
+ * engine ceiling by default) through the segmented streamed preparation; an append stays within the ceiling (lane 3a
+ * reads appended text whole). A remote writer is refused at once where the write gate applies to an agent-written page,
+ * since the gate scans a whole body and commit would refuse the same way.
+ */
+async function assertLargeUploadAdmissible(ctx: OperationContext, mode: UploadMode, total: number): Promise<void> {
+ const ceiling = mode === 'append' ? PAGE_MAX_BYTES : Math.max(PAGE_MAX_BYTES, (await readPageBodyPolicy(ctx.engine)).maxBytes);
+ if (total > ceiling) {
+ throw opError('request_too_large', contentSizeHold(total, ceiling)!.message, mode === 'append'
+ ? `Nothing was staged. An append upload carries at most ${PAGE_MAX_BYTES} bytes; append the text in several uploads.`
+ : `Nothing was staged. Pages up to ${ceiling} bytes are stored and searchable on this brain; split the content into smaller pages.`);
+ }
+ if (ctx.remote !== false && mode !== 'append' && writeGateApplies('agent_written', (await loadImportSanityConfig(ctx.engine)).writeGate ?? DEFAULT_WRITE_GATE_CONFIG)) {
+ throw contentRefusalError({ code: 'file_too_large', message: `Page too large (${total} bytes) for this writer: the write gate scans an agent-written page whole, and a page over ${PAGE_MAX_BYTES} bytes is never held whole.` },
+ `Nothing was staged. Split the content into pages of at most ${PAGE_MAX_BYTES} bytes; whether agent-written pages may skip the write gate (write_gate.agent_mode) is the brain host operator's decision.`,
+ { legacy_error: 'request_too_large' });
+ }
+}
+
const begin_page_upload: Operation = {
name: 'begin_page_upload',
idempotent: true,
@@ -115,10 +139,7 @@ const begin_page_upload: Operation = {
if (typeof total !== 'number' || !Number.isSafeInteger(total) || total < 1) {
throw invalidParam('total_bytes must be a positive whole number of bytes.', 'Pass the UTF-8 byte length of the complete content.');
}
- if (total > PAGE_MAX_BYTES) {
- throw opError('request_too_large', contentSizeHold(total, PAGE_MAX_BYTES)!.message,
- `Nothing was staged. Pages up to ${PAGE_MAX_BYTES} bytes are stored and searchable; send a smaller page.`);
- }
+ if (total > PAGE_MAX_BYTES) await assertLargeUploadAdmissible(ctx, mode, total);
if (typeof p.sha256 !== 'string' || !SHA256_HEX.test(p.sha256)) throw invalidParam('sha256 must be 64 hex characters.', 'Pass the hex SHA-256 of the complete content\'s UTF-8 bytes.');
if (p.request_id === undefined) throw invalidParam('request_id is required.', 'Pass a new UUID; send the same request_id again only to resume this upload.');
const clientRequestId = parseWriteRequestId(p.request_id)!;
@@ -261,13 +282,6 @@ const abort_page_upload: Operation = {
},
};
-/** Lane 3a's `admitPageAppend` with this session as the appended text; wired at integration. */
-async function admitStagedAppend(_ctx: OperationContext, _input: { slug: string; source_id: string; request_id: string; body_ref: StagingBodyRef;
- region: 'auto'; separator: 'auto'; preconditions: { expected_revision?: string } }): Promise<Record<string, unknown>> {
- throw opError('unavailable', 'Committing an append upload is not available in this build; nothing was written.',
- 'Abort this upload, then append the text with append_page in parts no larger than one request.');
-}
-
const commit_page_upload: Operation = {
name: 'commit_page_upload',
idempotent: true,
@@ -306,8 +320,12 @@ const commit_page_upload: Operation = {
}
const bodyRef: StagingBodyRef = { kind: 'staging', staging_id: row.id, sha256: row.declared_sha256, bytes: row.declared_bytes };
if (row.mode === 'append') {
- return admitStagedAppend(ctx, { slug: row.slug, source_id: row.source_id, request_id: row.client_request_id, body_ref: bodyRef, region: 'auto', separator: 'auto',
- preconditions: row.base_revision ? { expected_revision: row.base_revision } : {} });
+ try {
+ return await admitPageAppend(ctx, { slug: row.slug, source_id: row.source_id, request_id: row.client_request_id, body_ref: bodyRef,
+ ...(row.base_revision ? { expected_revision: row.base_revision } : {}), ...(p.wait_ms !== undefined ? { wait_ms: p.wait_ms } : {}) }, { stagedBody: true });
+ } finally {
+ await settleCommit(ctx, principal, row).catch(() => undefined);
+ }
}
const params: Record<string, unknown> = { slug: row.slug, source_id: row.source_id, request_id: row.client_request_id, body_ref: bodyRef,
...(row.mode === 'replace' ? { expected_revision: row.base_revision } : {}),
diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.ts
index e2f7ffd5c3..540308a2d3 100644
--- a/src/core/page-body/streamed-import.ts
+++ b/src/core/page-body/streamed-import.ts
@@ -101,7 +101,13 @@ type StreamedImportOptions = {
* `put`, and `head` replaces the file's first `skip` bytes after its BOM (capture's merged frontmatter). The
* caller passes `<slug>.md` as the relative path.
*/
- content?: { head?: { skip: number; bytes: Uint8Array }; provenance?: { source_kind: string | null; source_uri: string | null; ingested_via: string | null } };
+ content?: { head?: { skip: number; bytes: Uint8Array }; provenance?: { source_kind: string | null; source_uri: string | null; ingested_via: string | null };
+ /**
+ * A remote writer's page (commit_page_upload, upload-streamed.ts): `gate` names the tier the write gate assesses
+ * from the page's frontmatter (put_page's, not the source owner's), gate-owned markers are stripped as put_page
+ * strips them, and `stamp` writes the server's trust marker into the frontmatter.
+ */
+ writer?: { gate(frontmatter: Record<string, unknown>): Promise<StreamedGateInput>; stamp(frontmatter: Record<string, unknown>): void } };
/**
* A managed import's preparation (import-prepare.ts): the file must hash to
* `sha256` (the admitted bytes), the page base is the caller's snapshot, and
@@ -116,6 +122,9 @@ type StreamedImportOptions = {
prepare(prepared: StreamedPreparedImport): Promise<ImportResult> };
};
+/** The write gate's input for a streamed page: the tier it assesses and the write's origin. */
+export type StreamedGateInput = Awaited<ReturnType<typeof ownerSourceGateInput>>;
+
/** A coordinated streamed import ready to publish: no parsed body strings exist, only the page's frontmatter. */
export type StreamedPreparedImport = Omit<PreparedContentImport, 'parsedPage'> & { frontmatter: Record<string, unknown> };
@@ -356,8 +365,10 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
const read = (start: number, end: number) => readChecked(file, bom, prefix, size, digests, drift, start, end);
parsed.title = sanitizeText(parsed.title);
delete parsed.frontmatter[QUARANTINE_OVERRIDE_KEY];
- const writeGate = await ownerSourceGateInput(engine, sourceId, parsed.frontmatter);
- stripGateOwnedMarkers(parsed, { preserveGateMarkers: true, writeGate });
+ const writer = opts.content?.writer;
+ const writeGate = writer ? await writer.gate(parsed.frontmatter) : await ownerSourceGateInput(engine, sourceId, parsed.frontmatter);
+ stripGateOwnedMarkers(parsed, { preserveGateMarkers: !writer, writeGate });
+ writer?.stamp(parsed.frontmatter);
const sanity = await loadImportSanityConfig(engine);
if (writeGateApplies(writeGate.tier, sanity.writeGate ?? DEFAULT_WRITE_GATE_CONFIG)) return hold(slug, size, `the write gate scans the whole body of a ${writeGate.tier} page`);
const bodyBytes = scan.truthBytes + (scan.timelineBytes ? 1 + scan.timelineBytes : 0);
diff --git a/src/core/persistence/page-append.ts b/src/core/persistence/page-append.ts
index 80d9c4c550..ac1d7e3622 100644
--- a/src/core/persistence/page-append.ts
+++ b/src/core/persistence/page-append.ts
@@ -151,12 +151,12 @@ function parseAppendInput(input: AppendPageInput): AppendIntent {
* Admit one append (append_page, and lane 3b's commit_page_upload for mode 'append' with `body_ref`) and wait for its
* receipt as put_page does. A `tail_changed` refusal carries the current tail digest when the caller may see it.
*/
-export async function admitPageAppend(ctx: OperationContext, input: AppendPageInput): Promise<Record<string, unknown>> {
+export async function admitPageAppend(ctx: OperationContext, input: AppendPageInput, opts: { stagedBody?: true } = {}): Promise<Record<string, unknown>> {
const intent = parseAppendInput(input);
const params = { slug: input.slug, ...(input.source_id !== undefined ? { source_id: input.source_id } : {}), request_id: input.request_id,
...(input.wait_ms !== undefined ? { wait_ms: input.wait_ms } : {}), ...intent };
try {
- return await submitPageMutation(ctx, { operation: 'append_page', params });
+ return await submitPageMutation(ctx, { operation: 'append_page', params, ...opts });
} catch (error) {
if (!(error instanceof OperationError) || (error.canonical ?? error.code) !== 'tail_changed') throw error;
const sourceId = String(error.receiptFields?.source_id ?? input.source_id ?? ctx.sourceId ?? 'default');
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index d882fc750b..db7801194d 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -264,8 +264,9 @@ export async function preparePageAdmission(ctx: OperationContext,
}
}
const bodyRefKind = (input.params.body_ref as { kind?: unknown } | null | undefined)?.kind;
- if (Object.hasOwn(input.params, 'body_ref') && (input.operation !== 'put_page' || Object.hasOwn(input.params, 'content')
- || (input.stagedBody === true ? bodyRefKind !== 'staging' : input.managedFileImport !== true || bodyRefKind !== 'input_file'))) {
+ const staged = input.stagedBody === true && ['put_page', 'append_page'].includes(input.operation) && bodyRefKind === 'staging';
+ const imported = input.managedFileImport === true && input.operation === 'put_page' && bodyRefKind === 'input_file';
+ if (Object.hasOwn(input.params, 'body_ref') && ((!staged && !imported) || Object.hasOwn(input.params, 'content') || Object.hasOwn(input.params, 'text'))) {
throw new OperationError('invalid_params', 'body_ref is reserved for commit_page_upload.',
'Drop body_ref and send the page as content; a page larger than one request goes through begin_page_upload, upload_page_part and commit_page_upload.');
}
diff --git a/src/core/persistence/page-upload.ts b/src/core/persistence/page-upload.ts
index 31cfebe58a..b252a6d9b4 100644
--- a/src/core/persistence/page-upload.ts
+++ b/src/core/persistence/page-upload.ts
@@ -9,13 +9,14 @@
* sessions under the counter row locks, so a session a cascade removed never
* keeps its capacity.
*
- * A commit admits an ordinary put_page whose intent carries
- * `body_ref: {kind: 'staging', staging_id, sha256, bytes}` instead of the
- * content; `prepareStagedUpload` reads the sealed parts back, verifies them
- * against the reference and prepares the put_page as if the content had been
- * sent, so every put_page rule (remote sanitizing, trust, the timeline
- * omission and shrink guards, the revision check under the page lock) applies.
- * Pages up to the single-string ceiling (PAGE_MAX_BYTES) commit this way.
+ * A commit admits an ordinary put_page (or, for mode append, an append_page)
+ * whose intent carries `body_ref: {kind: 'staging', staging_id, sha256, bytes}`
+ * instead of the text; `withStagedUpload` binds the preparation to the sealed
+ * session and commits it in the write's publication. A put_page body within the
+ * single-string ceiling (PAGE_MAX_BYTES) is read back and prepared as if the
+ * content had been sent, so every put_page rule (remote sanitizing, trust, the
+ * timeline omission and shrink guards, the revision check under the page lock)
+ * applies; a larger one streams through upload-streamed.ts.
*/
import { createHash } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
@@ -27,6 +28,7 @@ import { ENSURE_COUNTERS_SQL, LOCK_COUNTERS_SQL } from './journal.ts';
import { BRAIN_STAGED_KEY, RELEASE_STAGED_CTE, readUploadLimits, stagedCounterKeys, stagedQuotaExhausted } from './limits.ts';
import type { Principal, SqlEngine, WriteRequest } from './model.ts';
import { timelineSectionOf } from './timeline-omission.ts';
+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
export type UploadMode = 'create' | 'replace' | 'append';
export type UploadState = 'open' | 'sealed' | 'prepared' | 'committed' | 'aborted' | 'expired';
@@ -243,16 +245,28 @@ export function isStagingBodyRef(value: unknown): value is StagingBodyRef {
return !!ref && typeof ref === 'object' && ref.kind === 'staging' && typeof ref.staging_id === 'string' && typeof ref.sha256 === 'string' && Number.isSafeInteger(ref.bytes);
}
+/** @internal Work counters of the staged-body readers: whole-body strings built, streamed preparations, largest part held. */
+export const stagedUploadWork = { wholeTexts: 0, streamed: 0, largestPart: 0 };
+
+/** The staged parts of a body reference in order, one part at a time; null at a gap. */
+export async function* stagedUploadParts(engine: SqlEngine, ref: StagingBodyRef): AsyncIterable<Uint8Array | null> {
+ for (let part = 0, at = 0; at < ref.bytes; part++) {
+ const [stored] = await engine.executeRaw<{ byte_start: unknown; body: Uint8Array }>(
+ 'SELECT byte_start, body FROM page_body_staging_parts WHERE staging_id = $1::uuid AND part_no = $2', [ref.staging_id, part]);
+ if (!stored || Number(stored.byte_start) !== at) { yield null; return; }
+ stagedUploadWork.largestPart = Math.max(stagedUploadWork.largestPart, stored.body.byteLength);
+ at += stored.body.byteLength;
+ yield stored.body;
+ }
+}
+
/** The staged page text a body reference names, verified against its byte count and sha256; null when it no longer matches. */
export async function stagedUploadText(engine: SqlEngine, ref: StagingBodyRef): Promise<string | null> {
- const parts = await engine.executeRaw<{ part_no: unknown; byte_start: unknown; body: Uint8Array }>(`SELECT part_no, byte_start, body FROM page_body_staging_parts
- WHERE staging_id = $1::uuid ORDER BY part_no`, [ref.staging_id]);
- let at = 0;
+ stagedUploadWork.wholeTexts++;
const buffers: Buffer[] = [];
- for (const [index, part] of parts.entries()) {
- if (Number(part.part_no) !== index || Number(part.byte_start) !== at) return null;
- buffers.push(Buffer.from(part.body.buffer, part.body.byteOffset, part.body.byteLength));
- at += part.body.byteLength;
+ for await (const part of stagedUploadParts(engine, ref)) {
+ if (!part) return null;
+ buffers.push(Buffer.from(part.buffer, part.byteOffset, part.byteLength));
}
const body = Buffer.concat(buffers);
if (body.byteLength !== ref.bytes || createHash('sha256').update(body).digest('hex') !== ref.sha256) return null;
@@ -262,25 +276,20 @@ export async function stagedUploadText(engine: SqlEngine, ref: StagingBodyRef):
interface Publishable { apply(tx: BrainEngine, preimage?: never): Promise<Record<string, unknown>> }
/**
- * Preparation of a put_page whose intent names a sealed upload session: the session must still be the sealed upload
- * of the request's principal, source and slug, and its parts must match the reference. `prepare` gets the request with
- * the staged text as its content (and the timeline section put_page admission records for content); its publication
- * re-checks the session under a row lock, and the same transaction marks it committed and releases its reservation.
+ * A write whose intent names a sealed upload session (put_page, or append_page with mode append): the session must
+ * still be the sealed upload of the request's principal, source and slug, matching the reference. `prepare` builds the
+ * write; its publication re-checks the session under a row lock, and the same transaction marks it committed and
+ * releases its reservation.
*/
-export async function prepareStagedUpload<T extends Publishable>(engine: BrainEngine, row: WriteRequest, prepare: (row: WriteRequest) => Promise<T>): Promise<T> {
- const intent = row.intent as Record<string, unknown>;
- const ref = intent.body_ref as StagingBodyRef;
+export async function withStagedUpload<T extends Publishable>(engine: BrainEngine, row: WriteRequest, prepare: (ref: StagingBodyRef) => Promise<T>): Promise<T> {
+ const ref = (row.intent as Record<string, unknown>).body_ref as StagingBodyRef;
const [staging] = await engine.executeRaw<{ state: string; principal_kind: string; principal_id: string; source_id: string; slug: string; declared_bytes: unknown; sha: string }>(
`SELECT state, principal_kind, principal_id, source_id, slug, declared_bytes, encode(declared_sha256, 'hex') AS sha FROM page_body_stagings
WHERE id = $1::uuid AND kind = 'upload'`, [ref.staging_id]);
if (!staging || staging.principal_kind !== row.principal_kind || staging.principal_id !== row.principal_id || staging.source_id !== row.source_id
|| staging.slug !== row.slug || Number(staging.declared_bytes) !== ref.bytes || staging.sha !== ref.sha256) throw bodyStagingGoneError(row.slug, ref.staging_id, null);
if (staging.state !== 'sealed') throw bodyStagingGoneError(row.slug, ref.staging_id, staging.state);
- const content = await stagedUploadText(engine, ref);
- if (content === null) throw bodyStagingGoneError(row.slug, ref.staging_id, null);
- const { body_ref: _ref, ...rest } = intent;
- const prepared = await prepare({ ...row, intent: { ...rest, content,
- ...(rest.kind === undefined && rest.timeline_section === undefined ? { timeline_section: timelineSectionOf(content, row.slug) } : {}) } });
+ const prepared = await prepare(ref);
const apply = prepared.apply.bind(prepared);
prepared.apply = async (tx, preimage) => {
const [held] = await tx.executeRaw<{ state: string }>('SELECT state FROM page_body_stagings WHERE id = $1::uuid FOR UPDATE', [ref.staging_id]);
@@ -291,3 +300,25 @@ export async function prepareStagedUpload<T extends Publishable>(engine: BrainEn
};
return prepared;
}
+
+/** `prepare` under withStagedUpload when the request's intent names an upload session (an append upload), else as is. */
+export async function withStagedBodyIf<T extends Publishable>(engine: BrainEngine, row: WriteRequest, prepare: () => Promise<T>): Promise<T> {
+ return isStagingBodyRef(row.intent?.body_ref) ? withStagedUpload(engine, row, prepare) : prepare();
+}
+
+/**
+ * Preparation of a put_page whose intent names a sealed upload session. A body within the single-string ceiling
+ * (PAGE_MAX_BYTES) is read back and `prepare` gets the request with it as its content (and the timeline section put_page
+ * admission records for content), so every put_page rule applies; a larger body streams from its parts through the
+ * segmented import (upload-streamed.ts) and is never held as one string.
+ */
+export async function prepareStagedUpload<T extends Publishable>(engine: BrainEngine, row: WriteRequest, prepare: (row: WriteRequest) => Promise<T>): Promise<T> {
+ return withStagedUpload(engine, row, async ref => {
+ if (ref.bytes > PAGE_MAX_BYTES) return (await import('./upload-streamed.ts')).prepareStreamedUpload(engine, row, ref) as unknown as Promise<T>;
+ const content = await stagedUploadText(engine, ref);
+ if (content === null) throw bodyStagingGoneError(row.slug, ref.staging_id, null);
+ const { body_ref: _ref, ...rest } = row.intent as Record<string, unknown>;
+ return prepare({ ...row, intent: { ...rest, content,
+ ...(rest.kind === undefined && rest.timeline_section === undefined ? { timeline_section: timelineSectionOf(content, row.slug) } : {}) } });
+ });
+}
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index bcbebed017..498fc4a5ff 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -103,7 +103,7 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest
if (row.operation === 'relink_facts') return (await import('../facts/relink-publish.ts')).prepareRelinkMutation(e, row, cfg);
if (['takes_add','takes_update','takes_supersede','takes_resolve','takes_remove'].includes(row.operation)) return (await import('./takes-prepare.ts')).prepareTakesMutation(e,row,cfg);
if (['add_tag','remove_tag','add_timeline_entry'].includes(row.operation)) return prepareSemanticPageMutation(e, row, cfg);
- if (row.operation === 'append_page') return (await import('./page-append.ts')).prepareAppendMutation(e, row, cfg, signal, clock);
+ if (row.operation === 'append_page') return (await import('./page-upload.ts')).withStagedBodyIf(e, row, async () => (await import('./page-append.ts')).prepareAppendMutation(e, row, cfg, signal, clock));
if (['put_page','capture','delete_page','restore_page','revert_version','edit_page'].includes(row.operation)) return preparePageMutation(e, row, cfg, undefined, signal,
{ coordinated: await writeSwitchOn(e, 'single_write_group').catch(() => true), clock });
throw new OperationError('unsupported_mutation_protocol', 'No compatible mutation preparer is registered for this operation.', `Request ${row.request_id} (${row.operation}) was accepted by a gbrain version whose preparer this one lacks, so it has not run. Run gbrain upgrade on every host that serves this brain; the request stays journaled and resumes after the upgrade.`);
diff --git a/src/core/persistence/upload-streamed.ts b/src/core/persistence/upload-streamed.ts
new file mode 100644
index 0000000000..8e1c20d092
--- /dev/null
+++ b/src/core/persistence/upload-streamed.ts
@@ -0,0 +1,109 @@
+/**
+ * Wave B (spec 6.2): the preparation of a committed upload over the single-string ceiling (PAGE_MAX_BYTES). The sealed
+ * parts are spooled, one part at a time, into a private file that the segmented streamed import reads in its two
+ * passes (page-body/streamed-import.ts, the reader `put --file` and managed imports use); the import verifies the
+ * admitted sha256, stages the segments, and the spool is removed before publication, which reads only the staged rows.
+ * No step holds the body as one string.
+ *
+ * Trust follows put_page: a remote writer's frontmatter and channel name the tier the write gate assesses and the tier
+ * the page row ends with (min of writer and stored), and its gate-owned markers are stripped. The write gate scans a
+ * whole body, so where it applies to that tier this refuses (`file_too_large`) as a put_page over the ceiling would;
+ * a trusted local writer takes the source owner's tier, as a local `put --file` streamed on an unmanaged brain does. A
+ * page bound to a worktree publishes database-only (`db_only`): its canonical file is not written from this path. An
+ * always-loaded core page (before or after) refuses: the core guard renders the page whole.
+ */
+import { lstat, mkdtemp, open, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readPageBodyPolicy } from '../page-body/limits.ts';
+import { importStreamedMarkdownFile, type StreamedPreparedImport } from '../page-body/streamed-import.ts';
+import { assertPageRevision } from '../page-state/types.ts';
+import { contentRefusalError, PAGE_OVER_LIMIT_SUGGESTION } from '../import-screen.ts';
+import { pageGateTrust, pageWriteTrust, stampPageTrustMarker, storedPageTier } from '../trust/page-write.ts';
+import type { WriteTrust } from '../trust/tier.ts';
+import { sizeStateField } from '../page-embedding-budget.ts';
+import { coreMarking } from '../core-memory.ts';
+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
+import { bodyStagingGoneError } from '../engine-sql/page-body.ts';
+import { ownerSourceGateInput, writeTrustOfGate } from './attribution.ts';
+import { pageDatabaseOnlyPublication } from './page-prepare.ts';
+import { pageIdentityError } from './page-identity.ts';
+import { remoteLinkHint } from './page-advisories.ts';
+import { stagedUploadParts, stagedUploadWork, type StagingBodyRef } from './page-upload.ts';
+import type { PreparedMutation } from './coordinator.ts';
+import type { WriteRequest } from './model.ts';
+
+const text = (value: unknown) => (typeof value === 'string' ? value : null);
+
+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);
+ if (!policy.segmented || ref.bytes > policy.maxBytes) {
+ throw contentRefusalError({ code: 'file_too_large', message: `Page too large (${ref.bytes} bytes): segmented page storage (pages.segmented_storage) is off or the page is over pages.max_bytes (${policy.maxBytes}).` },
+ PAGE_OVER_LIMIT_SUGGESTION, { legacy_error: 'request_too_large' });
+ }
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+ assertPageRevision(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;
+ 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-'));
+ let ready: StreamedPreparedImport | undefined;
+ let result: Awaited<ReturnType<typeof importStreamedMarkdownFile>>;
+ try {
+ const path = join(dir, 'page.md');
+ const spool = await open(path, 'wx', 0o600);
+ try {
+ for await (const part of stagedUploadParts(engine, ref)) {
+ if (!part) throw bodyStagingGoneError(row.slug, ref.staging_id, null);
+ await spool.write(part);
+ }
+ } finally { await spool.close(); }
+ const stat = await lstat(path);
+ if (stat.size !== ref.bytes) throw bodyStagingGoneError(row.slug, ref.staging_id, null);
+ stagedUploadWork.streamed++;
+ result = await importStreamedMarkdownFile(engine, path, `${row.slug}.md`, { sourceId: row.source_id, noEmbed: true, inferFrontmatter: false,
+ content: { provenance: { source_kind: text(p.source_kind), source_uri: text(p.source_uri), ingested_via: text(p.ingested_via) },
+ ...(remote ? { writer: {
+ gate: async (frontmatter: Record<string, unknown>) => {
+ trust = pageWriteTrust(row, frontmatter);
+ const gate = pageGateTrust(row, trust, storedTier);
+ return gate ? { tier: gate.tier, origin: { channel: gate.origin?.channel ?? row.operation }, requestId: null } : ownerSourceGateInput(engine, row.source_id, frontmatter);
+ },
+ stamp: (frontmatter: Record<string, unknown>) => stampPageTrustMarker(row, frontmatter, trust, storedTier),
+ } } : {}) },
+ coordinated: { snapshot, sha256: ref.sha256, slug: row.slug, prepare: async value => { ready = value; return value.result; },
+ owner: { kind: 'put', principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: snapshot?.revision ?? null } } }, stat, policy)
+ .catch(error => { throw error instanceof OperationError && error.code === 'source_changed' ? bodyStagingGoneError(row.slug, ref.staging_id, null) : error; });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ if (!ready) {
+ if (result.refusal?.code === 'file_too_large') throw contentRefusalError(result.refusal, PAGE_OVER_LIMIT_SUGGESTION, { legacy_error: 'request_too_large' });
+ if (result.refusal) throw contentRefusalError(result.refusal, 'Correct the content as the message says, then upload it again with a new request_id.', { legacy_error: 'invalid_params' });
+ throw opError('invalid_params', result.error ?? 'The uploaded page could not be prepared.', `Page ${row.slug} was not written. Fix what the message names, then upload it again with a new request_id.`);
+ }
+ const prepared: StreamedPreparedImport = ready;
+ if (coreMarking(snapshot?.page.frontmatter).core || coreMarking(prepared.frontmatter).core) {
+ throw opError('page_body_segmented', `Page ${row.slug} is (or would become) always-loaded core memory, whose budget renders the page whole, and this upload is over ${PAGE_MAX_BYTES} bytes. Nothing was written.`,
+ 'Write a core page within the single-string ceiling, or drop always_load from its frontmatter.');
+ }
+ if (prepared.observedRevision !== (snapshot?.revision ?? null)) {
+ throw opError('revision_conflict', 'The page changed during upload preparation.', `Page ${row.slug} changed while this upload was prepared, so nothing was written. Read the page and upload again against its current revision.`);
+ }
+ const pageTrust = remote ? trust : writeTrustOfGate(await ownerSourceGateInput(engine, row.source_id, prepared.frontmatter));
+ const mutation: PreparedMutation = { observedRevision: prepared.observedRevision, noop: prepared.noop, ...(pageTrust ? { trust: pageTrust } : {}),
+ ...await pageDatabaseOnlyPublication(engine, row, undefined),
+ ...(prepared.afterCommit ? { afterCommit: prepared.afterCommit } : {}),
+ apply: async (tx, preimage) => {
+ await prepared.apply(tx, preimage);
+ const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+ mutation.postimage = final;
+ return { ...remoteLinkHint(row), status: prepared.noop ? 'skipped' : 'created_or_updated', slug: row.slug, source_id: row.source_id, noop: prepared.noop,
+ chunks: result.chunks, ...(prepared.noop ? {} : await sizeStateField(tx, row.source_id, row.slug, final?.page)) };
+ } };
+ return mutation;
+}
diff --git a/test/cli-page-writes.test.ts b/test/cli-page-writes.test.ts
index 29a0318d5f..843c689812 100644
--- a/test/cli-page-writes.test.ts
+++ b/test/cli-page-writes.test.ts
@@ -139,7 +139,10 @@ for (const backend of testBackends()) {
const text = line.repeat(Math.ceil((1.5 * 1024 * 1024) / Buffer.byteLength(line)));
const appended = await cli(['append', 'notes/big-append', '--file', file('big-append-text.md', text), '--json']);
expect(appended.code, appended.stderr).toBe(0);
- expect((await page('notes/big-append')).compiled_truth).toBe(`# Big append\n\nstart\n${text}`.trimEnd());
+ expect(await stored('notes/big-append')).toMatchObject({ body_storage: 'segmented' });
+ const read = await cli(['get', 'notes/big-append']);
+ expect(read.code, read.stderr).toBe(0);
+ expect(printedBody(read.stdout).trimEnd()).toBe(`# Big append\n\nstart\n${text}`.trimEnd());
}, 300_000);
test('local put --file over the page ceiling on a managed brain goes through an upload session, byte-identical', async () => {
diff --git a/test/large-pages/upload-binding.test.ts b/test/large-pages/upload-binding.test.ts
index 3c491768e2..78310377cb 100644
--- a/test/large-pages/upload-binding.test.ts
+++ b/test/large-pages/upload-binding.test.ts
@@ -287,7 +287,47 @@ for (const kind of testBackends()) {
expect(await counters()).toEqual({ ...Object.fromEntries(Object.keys(await counters()).map(key => [key, [0, 0]])), ...before });
}, 120_000);
- test.todo('append mode commits through lane 3a admitPageAppend with the staged body_ref (wired at integration)', () => {});
+ test('append uploads commit in order through append_page, a second commit replays the receipt, and the reservation is released', async () => {
+ const slug = slugOf();
+ await createPage(slug, pageText('append-base', 2000));
+ const before = await counters();
+ const appended: string[] = [];
+ for (const tag of ['first', 'second']) {
+ const text = `\nAppended ${tag} block. ${`Notes for the ${tag} append. `.repeat(200)}\n`;
+ const session = await begin(slug, text, { mode: 'append' });
+ await send(session.upload_id, cut(text, 3));
+ const receipt = await call('commit_page_upload', { upload_id: session.upload_id });
+ expect(receipt.state).toBe('committed');
+ const again = await call('commit_page_upload', { upload_id: session.upload_id });
+ expect(again.request_id).toBe(receipt.request_id);
+ appended.push(text);
+ }
+ const truth = (await engine.getPage(slug, { sourceId: 'default' }))!.compiled_truth;
+ const first = truth.indexOf('Appended first block.'), second = truth.indexOf('Appended second block.');
+ expect(first).toBeGreaterThan(0);
+ expect(second).toBeGreaterThan(first);
+ expect(truth.split('Notes for the first append.').length - 1).toBe(200);
+ 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(2);
+ const after = await counters();
+ for (const [key, value] of Object.entries(after)) expect([key, value]).toEqual([key, before[key] ?? [0, 0]]);
+ }, 120_000);
+
+ test('an append upload against a stale expected_revision refuses with revision_changed, appends nothing and releases its reservation', async () => {
+ const slug = slugOf();
+ await createPage(slug, pageText('append-stale', 2000));
+ const base = await revisionOf(slug);
+ const before = await counters();
+ const text = `\nStale append. ${'Never lands. '.repeat(100)}\n`;
+ const session = await begin(slug, text, { mode: 'append', expected_revision: base });
+ await send(session.upload_id, cut(text, 2));
+ await call('put_page', { slug, content: pageText('append-moved', 2000), expected_revision: base, request_id: randomUUID() });
+ const refused = await refusal('commit_page_upload', { upload_id: session.upload_id });
+ expect(refused.code).toBe('revision_changed');
+ expect((await engine.getPage(slug, { sourceId: 'default' }))!.compiled_truth).not.toContain('Stale append.');
+ const after = await counters();
+ for (const [key, value] of Object.entries(after)) expect([key, value]).toEqual([key, before[key] ?? [0, 0]]);
+ }, 120_000);
const quotas: Array<[string, string, string, number]> = [
['open sessions per principal', 'persistence.limits.principal_uploads', 'open_uploads', 1],
diff --git a/test/large-pages/upload-over-ceiling.test.ts b/test/large-pages/upload-over-ceiling.test.ts
new file mode 100644
index 0000000000..50fde0dea6
--- /dev/null
+++ b/test/large-pages/upload-over-ceiling.test.ts
@@ -0,0 +1,160 @@
+/**
+ * Wave B PR 3: an upload over the single-string ceiling (PAGE_MAX_BYTES, 24 MiB) commits through the segmented
+ * streamed preparation (persistence/upload-streamed.ts).
+ *
+ * 1. Protects: a 25 MiB create upload lands segmented and reads back byte-identical with the content_hash of exactly
+ * those bytes; a replace above 24 MiB keeps its expected_revision precondition (a moved page refuses with
+ * revision_changed and releases the reservation) and the shrink guard (a 50 MiB page replaced by 24.5 MiB refuses
+ * page_shrink_refused until allow_shrink); no step builds the body as one string (stagedUploadWork: no whole-text
+ * read, one streamed preparation, no part held over 4 MiB); a remote writer under the default write gate is refused
+ * file_too_large at begin, as put_page over the ceiling is, and nothing is staged.
+ * 2. Fails when: begin refuses total_bytes over 24 MiB, commit reads the staged parts back as one string, the revision
+ * or shrink guard is skipped for a large replace, or the write gate is bypassed for an agent-written page.
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set (no embedding, no model calls).
+ */
+import { afterAll, 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 { operations, OperationError, type OperationContext } from '../../src/core/operations.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { stagedUploadWork } from '../../src/core/persistence/page-upload.ts';
+import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';
+import { ContentHashStream } from '../../src/core/page-body/content-hash-stream.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+
+const MiB = 1024 ** 2;
+const PART_CHARS = 3_900_000;
+const op = (name: string) => operations.find(o => o.name === name)!;
+const hex = (text: string) => createHash('sha256').update(Buffer.from(text, 'utf8')).digest('hex');
+/** A synthetic conversation of at least `bytes` ASCII bytes, ending without whitespace (a page body is stored trimmed). */
+function conversation(bytes: number, tag: string): string {
+ const turns: string[] = [`# Conversation ${tag}\n\n`];
+ for (let i = 0, n = 0; n < bytes; i++) {
+ const turn = `**User (${tag} ${i}):** What did we decide about the launch plan for week ${i}?\n\n**Assistant:** ${'We agreed to ship the review checklist first and revisit pricing next week. '.repeat(6)}\n\n`;
+ turns.push(turn);
+ n += turn.length;
+ }
+ return `${turns.join('')}End of conversation ${tag}.`;
+}
+
+for (const kind of testBackends()) {
+ describe(`uploads over the single-string ceiling (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+
+ const ctx = (): OperationContext => ({
+ engine, config: {} as GBrainConfig, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: true, sourceId: 'default',
+ transport: 'http', inboundFrameBytes: 4 * MiB, auth: { token: 'fixture', clientId: 'upload-big', principal: { kind: 'oauth_client', id: 'upload-big' },
+ scopes: ['read', 'write'], sourceId: 'default', allowedSources: ['default'] } } as unknown as OperationContext);
+ const call = async (name: string, params: Record<string, unknown>) => await op(name).handler(ctx(), params) as Record<string, any>;
+ const refusal = async (name: string, params: Record<string, unknown>) => {
+ try { await op(name).handler(ctx(), params); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error(`${name} did not refuse`);
+ };
+ const staged = async (text: string, slug: string, over: Record<string, unknown> = {}) => {
+ const session = await call('begin_page_upload', { slug, mode: 'create', total_bytes: Buffer.byteLength(text), sha256: hex(text), request_id: randomUUID(), ...over });
+ for (let part = 0, at = 0; at < text.length; part++, at += PART_CHARS) {
+ const piece = text.slice(at, at + PART_CHARS);
+ await call('upload_page_part', { upload_id: session.upload_id, part, text: piece, part_sha256: hex(piece) });
+ }
+ return session.upload_id as string;
+ };
+ /** commit_page_upload, repeated (as its pending reply says) until the write ends: a large preparation outlasts one wait. */
+ const commit = async (params: Record<string, unknown>) => {
+ for (let attempt = 0; ; attempt++) {
+ try { return await call('commit_page_upload', { ...params, wait_ms: 30_000 }); }
+ catch (error) { if (!(error instanceof OperationError) || error.code !== 'write_pending' || attempt > 40) throw error; }
+ }
+ };
+ const commitRefusal = async (params: Record<string, unknown>) => {
+ try { await commit(params); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('commit_page_upload did not refuse');
+ };
+ const stored = async (slug: string) => (await engine.executeRaw<{ id: number; body_storage: string; content_hash: string; title: string; type: string; frontmatter: Record<string, unknown> }>(
+ 'SELECT id, body_storage, content_hash, title, type, frontmatter FROM pages WHERE source_id = $1 AND slug = $2', ['default', slug]))[0]!;
+ const expectStoredBody = async (slug: string, text: string) => {
+ const page = await stored(slug);
+ expect(page.body_storage).toBe('segmented');
+ const body = await materializeSegmentedBody(engine, Number(page.id), 'default');
+ expect({ bytes: Buffer.byteLength(body.compiled_truth), sha: hex(body.compiled_truth), timeline: body.timeline }).toEqual({ bytes: Buffer.byteLength(text), sha: hex(text), timeline: '' });
+ const tags = (await engine.executeRaw<{ tag: string }>('SELECT t.tag FROM tags t JOIN pages p ON p.id = t.page_id WHERE p.id = $1 ORDER BY t.tag', [page.id])).map(row => row.tag);
+ const frontmatter = typeof page.frontmatter === 'string' ? JSON.parse(page.frontmatter) : page.frontmatter;
+ expect(ContentHashStream.begin(page).pushTruth(text).finish({ frontmatter, tags })).toBe(page.content_hash);
+ };
+ 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 setConfig = async (key: string, value: string) =>
+ engine.executeRaw('INSERT INTO config (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value', [key, value]);
+ const revisionOf = async (slug: string) => (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 oauth_clients(client_id,client_secret_hash,client_name,scope,source_id)
+ VALUES('upload-big','fixture-hash','upload-client','read write','default') ON CONFLICT (client_id) DO NOTHING`);
+ }, 120_000);
+ afterAll(async () => { await close(); });
+
+ test('under the default write gate a remote writer is refused file_too_large at begin and nothing is staged', async () => {
+ const total = PAGE_MAX_BYTES + MiB;
+ const refused = await refusal('begin_page_upload', { slug: 'notes/gated-huge', mode: 'create', total_bytes: total, sha256: 'a'.repeat(64), request_id: randomUUID() });
+ expect({ code: refused.code, wire: JSON.stringify(refused.toJSON()).includes('file_too_large') }).toEqual({ code: 'request_too_large', wire: true });
+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM page_body_stagings WHERE kind = 'upload'"))[0]!.n).toBe(0);
+ }, 60_000);
+
+ test('a 25 MiB create lands segmented, byte-identical with its content_hash, and no step holds it as one string', async () => {
+ await setConfig('write_gate.agent_mode', 'off');
+ const slug = 'notes/huge-conversation';
+ const text = conversation(25 * MiB, 'create');
+ const before = { ...stagedUploadWork };
+ const prior = await counters();
+ const id = await staged(text, slug);
+ stagedUploadWork.largestPart = 0;
+ const receipt = await commit({ upload_id: id });
+ expect({ state: receipt.state, status: receipt.status }).toEqual({ state: 'committed', status: 'created_or_updated' });
+ expect({ wholeTexts: stagedUploadWork.wholeTexts - before.wholeTexts, streamed: stagedUploadWork.streamed - before.streamed }).toEqual({ wholeTexts: 0, streamed: 1 });
+ expect(stagedUploadWork.largestPart).toBeLessThanOrEqual(4 * MiB);
+ expect(stagedUploadWork.largestPart).toBeGreaterThan(0);
+ await expectStoredBody(slug, text);
+ expect((await commit({ upload_id: id })).request_id).toBe(receipt.request_id);
+ const after = await counters();
+ for (const [key, value] of Object.entries(after)) expect([key, value]).toEqual([key, prior[key] ?? [0, 0]]);
+ }, 600_000);
+
+ test('a replace above 24 MiB commits at its expected_revision and refuses with revision_changed after the page moved', async () => {
+ const slug = 'notes/huge-conversation';
+ const v2 = conversation(25.5 * MiB, 'replace');
+ const id = await staged(v2, slug, { mode: 'replace', expected_revision: await revisionOf(slug) });
+ await commit({ upload_id: id });
+ await expectStoredBody(slug, v2);
+
+ const prior = await counters();
+ const stale = conversation(25 * MiB, 'stale');
+ 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');
+ expect(hex(body.compiled_truth)).toBe(hex(v2));
+ }, 600_000);
+
+ test('the shrink guard applies to a replace above 24 MiB: a 50 MiB page replaced by 24.5 MiB refuses until allow_shrink', async () => {
+ const slug = 'notes/huger-conversation';
+ const original = conversation(50 * MiB, 'original');
+ await commit({ upload_id: await staged(original, slug) });
+ const smaller = conversation(24.5 * MiB, 'smaller');
+ const id = await staged(smaller, slug, { mode: 'replace', expected_revision: await revisionOf(slug) });
+ expect((await commitRefusal({ upload_id: id })).code).toBe('page_shrink_refused');
+ const body = await materializeSegmentedBody(engine, Number((await stored(slug)).id), 'default');
+ expect(hex(body.compiled_truth)).toBe(hex(original));
+ await commit({ upload_id: id, allow_shrink: true });
+ await expectStoredBody(slug, smaller);
+ }, 900_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 8da1aed67e..f1d92bed4b 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -184,6 +184,7 @@ test/large-pages/streamed-import-drift.test.ts
test/large-pages/streamed-sync-origin-b14.test.ts
test/large-pages/stuck-recovery-large.slow.test.ts
test/large-pages/upload-binding.test.ts
+test/large-pages/upload-over-ceiling.test.ts
test/large-pages/v252-master-reader-compat.test.ts
test/link-cross-source.test.ts
test/link-preparation-shared-index.test.ts