Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(large-pages): a projection build holds the page lock one bounded insert at a time, so writes never wait out their 1 s lock_timeout behind it

garrytanad4987cf5afc
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index 8436be63d1..f3a836841b 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -22,7 +22,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).
- `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/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. `PROJECTION_LOCK_HOLD_BYTES` (512 KiB of segments, an occurrence larger than that alone) and `PROJECTION_RETIRE_MAX_ROWS` (2,500 rows) bound what one projection transaction inserts or deletes while it holds the page's key lock (`page-body/ingest.ts` `stageOccurrenceChunks`, `page-body/projection.ts` `retireStaleChunks`), about a tenth of the 1 s `lock_timeout` a write to the page, or a source-exclusive write anywhere on the source (the lock's `page_write_guards` insert key-share locks the source row), waits under in its publication, so a write never waits out its bound behind a background build (`test/large-pages/projection-lock-hold.test.ts`). 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, 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; only a write whose `body_ref` names the session is recorded as its commit, so a begin request_id another write already used attaches nothing. 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; a lapsed session is never sealed, so the brain-wide sum at begin leaves out other principals' lapsed sessions; `expireIfLapsed` reports whether its update changed the row. A session takes at most `uploadPartLimit` parts (64 plus one per 64 KiB declared) unless the part completes it (`upload_too_many_parts`). `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, a facts fence with a non-world row (or one that does not parse; `segmentedFactsFenceView` reads only the fence runs of a segmented page), or timeline rows (without `drop_timeline`) refuses `upload_protected_content`, since put_page's whole-body takes, hidden-facts 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`).
diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.ts
index d6b332309c..d5c63e0a51 100644
--- a/src/core/page-body/ingest.ts
+++ b/src/core/page-body/ingest.ts
@@ -22,7 +22,7 @@ import { readManagedMode } from '../persistence/managed-mode.ts';
import { maintenanceAttribution, principalAttribution } from '../persistence/attribution.ts';
import type { Principal } from '../persistence/model.ts';
import { stepFenceWalk, type FenceWalk } from '../fence-scan.ts';
-import { BODY_LEAD_BYTES, BODY_STAGING_HARD_MS, BODY_STAGING_IDLE_MS, SEGMENTED_CREATE_SEAL_MAX_BYTES, STAGE_BATCH_BYTES } from './limits.ts';
+import { BODY_LEAD_BYTES, BODY_STAGING_HARD_MS, BODY_STAGING_IDLE_MS, PROJECTION_LOCK_HOLD_BYTES, SEGMENTED_CREATE_SEAL_MAX_BYTES, STAGE_BATCH_BYTES } from './limits.ts';
import type { BodyRegion, BodyStagingKind, BodyStorage, JsonObject, ManifestRow, ManifestRowInput, SegmentChunkInput,
SegmentedBodyColumns, SegmentTextInput } from './types.ts';
import { regionTrust, segmentStream, SEGMENTER_VERSION, type StoredRegion } from './segmenter.ts';
@@ -364,9 +364,10 @@ export async function occurrencesWithoutChunks(engine: Pick<BrainEngine, 'execut
/**
* @internal Work stageOccurrenceChunks does, for the projection tests: segment text batches chunked (`batches`) and
- * chunk rows prepared (`chunks`), whoever stages them (a replace's preparation, a create's, or a projection).
+ * chunk rows prepared (`chunks`), whoever stages them (a replace's preparation, a create's, or a projection), and the
+ * most segment bytes one projection transaction staged under the page lock (`heldBytes`, PROJECTION_LOCK_HOLD_BYTES).
*/
-export const segmentChunkWork = { batches: 0, chunks: 0 };
+export const segmentChunkWork = { batches: 0, chunks: 0, heldBytes: 0 };
/**
* Chunk occurrences one text batch at a time (texts read back from
@@ -377,13 +378,13 @@ export const segmentChunkWork = { batches: 0, chunks: 0 };
export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId: number; sourceId: string; slug: string; generation: number;
occurrences: readonly ManifestRowInput[]; title: string; frontmatter: JsonObject; flags: JsonObject; chunking: SegmentChunkingContext;
retiredOccurrences: readonly number[];
- /** Projection: each batch inserts under the page guard, after re-reading which occurrences still lack rows, so two projections never both chunk one;
- * a page whose generation moved past `generation` stops the projection before it inserts. */
+ /** Projection: each batch inserts under the page guard, at most PROJECTION_LOCK_HOLD_BYTES of occurrences per transaction, after re-reading which
+ * occurrences still lack rows, so two projections never both chunk one; a page whose generation moved past `generation` stops the projection before it inserts. */
guarded?: boolean;
/** A create's preparation: the chunks are collected here (its page row does not exist yet) and inserted by the publication. */
hold?: SegmentChunkInput[];
- /** Guarded: runs in each batch's transaction before its insert (the projection renews its claim on the page's queue row);
- * false when the caller lost its claim: that batch inserts nothing and the staging stops. */
+ /** Guarded: runs in each insert transaction before its insert (the projection renews its claim on the page's queue row);
+ * false when the caller lost its claim: that transaction inserts nothing and the staging stops. */
renew?: (tx: BrainEngine) => Promise<boolean> }): Promise<{ rows: number; occurrences: number; indexes: number[] }> {
if (input.chunking.quarantined || !input.occurrences.length) return { rows: 0, occurrences: 0, indexes: [] };
const batchBytes = STAGE_BATCH_BYTES[engine.kind];
@@ -424,17 +425,31 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId
if (input.hold) input.hold.push(...chunks);
else if (chunks.length && !input.guarded) indexes.push(...await engine.stageSegmentChunks(input.pageId, input.generation, chunks));
let moved = false, lost = false;
- if (chunks.length && input.guarded) rows -= chunks.length - await engine.transaction(async tx => {
- await tx.lockPageKeys([{ sourceId: input.sourceId, slug: input.slug }]);
- const [page] = await tx.executeRaw<{ body_generation: number | string }>('SELECT body_generation FROM pages WHERE id=$1', [input.pageId]);
- if (Number(page?.body_generation) !== input.generation) { moved = true; return 0; }
- if (input.renew && !await input.renew(tx)) { lost = true; return 0; }
- const open = new Set((await occurrencesWithoutChunks(tx, input.pageId, input.generation, batch)).map(row => row.occurrenceId));
- const still = chunks.filter(chunk => open.has(chunk.occurrence_id));
- if (still.length) await tx.stageSegmentChunks(input.pageId, input.generation, still);
- return still.length;
- });
- rows += chunks.length;
+ if (input.guarded) {
+ const byOccurrence = new Map<number, SegmentChunkInput[]>();
+ for (const chunk of chunks) {
+ const same = byOccurrence.get(chunk.occurrence_id);
+ if (same) same.push(chunk); else byOccurrence.set(chunk.occurrence_id, [chunk]);
+ }
+ for (let at = 0; at < batch.length && !moved && !lost;) {
+ let stop = at, held = 0;
+ while (stop < batch.length && (stop === at || held + batch[stop]!.byteLen <= PROJECTION_LOCK_HOLD_BYTES)) held += batch[stop++]!.byteLen;
+ const part = batch.slice(at, stop).filter(row => byOccurrence.has(row.occurrenceId));
+ at = stop;
+ if (part.length) rows += await engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId: input.sourceId, slug: input.slug }]);
+ await faultPoint('segmented:projection_insert', { sourceId: input.sourceId, slug: input.slug });
+ const [page] = await tx.executeRaw<{ body_generation: number | string }>('SELECT body_generation FROM pages WHERE id=$1', [input.pageId]);
+ if (Number(page?.body_generation) !== input.generation) { moved = true; return 0; }
+ if (input.renew && !await input.renew(tx)) { lost = true; return 0; }
+ const open = await occurrencesWithoutChunks(tx, input.pageId, input.generation, part);
+ const still = open.flatMap(row => byOccurrence.get(row.occurrenceId)!);
+ if (still.length) await tx.stageSegmentChunks(input.pageId, input.generation, still);
+ segmentChunkWork.heldBytes = Math.max(segmentChunkWork.heldBytes, open.reduce((sum, row) => sum + row.byteLen, 0));
+ return still.length;
+ });
+ }
+ } else rows += chunks.length;
if (moved || lost) break;
done += batch.length;
collectBatchGarbage();
diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.ts
index 0f0df210ea..a29c79e77e 100644
--- a/src/core/page-body/limits.ts
+++ b/src/core/page-body/limits.ts
@@ -67,6 +67,25 @@ export const STAGE_BATCH_BYTES: Readonly<Record<'postgres' | 'pglite', number>>
pglite: 4 * 1024 ** 2,
};
+/**
+ * Segment bytes one projection transaction chunks into rows while it holds the page's key lock (ingest.ts
+ * `stageOccurrenceChunks`, guarded); an occurrence larger than this (up to SEGMENT_MAX_BYTES) goes alone, because an
+ * occurrence's rows commit together: a build resumes at the occurrences that have none. A write to the page takes the
+ * same lock inside its publication under `lock_timeout` 1 s (protocol.ts `declareDurablePersistence`); a longer wait
+ * fails the publication with 55P03 and the write prepares again, which for a file over the single-string ceiling
+ * copies its prior file again. A source-exclusive write anywhere on the source (a managed sync import or checkpoint,
+ * a purge: `SELECT ... FROM sources ... FOR UPDATE`) waits for that transaction too, under the same 1 s bound,
+ * because the transaction's `page_write_guards` insert holds a key-share lock on the source row. The row insert is
+ * nearly all of the hold: about 0.19 s per MiB of segment bytes on an idle 4-core Postgres 16 and 0.29 s on PGLite (a conversation page, ~290 chunk rows per MiB, each with its
+ * `to_tsvector`). A whole STAGE_BATCH_BYTES batch held the lock 0.7 s idle and 1.6 s on a loaded host, past the
+ * writer's bound. At 512 KiB the hold is about 0.1 s on Postgres (0.15 s on PGLite), a tenth of that bound, so a
+ * host ten times slower still publishes the waiting write in one attempt, and the largest occurrence (1 MiB, ~0.2 s)
+ * leaves five times. Between transactions the build releases the lock and the queued write takes it first:
+ * background chunking yields to writes. Each transaction adds a generation read, a claim renewal and one probe per
+ * occurrence (a few ms) per 512 KiB.
+ */
+export const PROJECTION_LOCK_HOLD_BYTES = 512 * 1024;
+
/**
* Chunk rows the generation flip deletes inside the publication transaction; above it the page publishes unsealed and a
* projection job deletes the rest, this many rows per statement. Deleting leaves `idx_chunks_embedding` (HNSW) alone
@@ -76,6 +95,17 @@ export const STAGE_BATCH_BYTES: Readonly<Record<'postgres' | 'pglite', number>>
*/
export const DEFAULT_FLIP_RETIRE_MAX_ROWS = 20_000;
+/**
+ * Chunk rows a projection deletes per transaction while it holds the page's key lock (projection.ts
+ * `retireStaleChunks`), for the same reason as PROJECTION_LOCK_HOLD_BYTES: a write to the page waits for that lock
+ * under its 1 s `lock_timeout`. A delete costs about 25 us per embedded row on Postgres and 44 us on PGLite (the
+ * DEFAULT_FLIP_RETIRE_MAX_ROWS bench above; 18 us and 27 us unembedded), so the flip's 20,000 rows would hold the lock
+ * 0.5 s and 0.9 s idle. 2,500 rows hold it about 0.06 s and 0.11 s, a tenth of the writer's bound. Each statement walks
+ * the page's occurrences from the first until it has its rows (one index probe each, STALE_CHUNKS_SQL), so retiring R
+ * rows of a page of O occurrences takes R / 2,500 + 1 statements of at most O probes each.
+ */
+export const PROJECTION_RETIRE_MAX_ROWS = 2_500;
+
/**
* A segmented create of at most this many body bytes is searchable when its write commits: it chunks during preparation
* (outside the transaction, the chunk inputs held in memory) and its publication inserts the chunk rows, one staging
diff --git a/src/core/page-body/projection.ts b/src/core/page-body/projection.ts
index 5d9f4efedf..78a74316bf 100644
--- a/src/core/page-body/projection.ts
+++ b/src/core/page-body/projection.ts
@@ -37,7 +37,7 @@ import { sealSegmentedPage } from '../persistence/segmented-apply.ts';
import { PROJECTION_RETRY_READY_SQL, SEGMENTED_JOB_PROBES, SEGMENTED_PROJECTION_CLAIM, SEGMENTED_PROJECTION_CLAIMED_SQL, SEGMENTED_PROJECTION_LEASE_SECONDS,
type ProjectionRebuildFailure } from '../page-state/projections.ts';
import { occurrencesWithoutChunks, stageOccurrenceChunks } from './ingest.ts';
-import { DEFAULT_FLIP_RETIRE_MAX_ROWS } from './limits.ts';
+import { PROJECTION_RETIRE_MAX_ROWS } from './limits.ts';
import type { JsonObject } from './types.ts';
import { assertGenerationTiles } from './body-tiling.ts';
@@ -90,8 +90,8 @@ export async function hasStaleChunks(engine: Pick<BrainEngine, 'executeRaw'>, pa
}
/**
- * Delete, in bounded batches, chunk rows the live generation does not hold: other occurrences, inline rows, older
- * duplicates. Each batch re-reads the page under its page lock and deletes only while the page is still segmented at
+ * Delete, in batches of PROJECTION_RETIRE_MAX_ROWS, chunk rows the live generation does not hold: other occurrences, inline
+ * rows, older duplicates. Each batch re-reads the page under its page lock and deletes only while the page is still segmented at
* `generation` (a demotion's inline rows are the page's live chunks); `moved` when it was not.
*/
async function retireStaleChunks(engine: BrainEngine, ref: { sourceId: string; slug: string }, pageId: number, generation: number,
@@ -103,11 +103,11 @@ async function retireStaleChunks(engine: BrainEngine, ref: { sourceId: string; s
const [page] = await tx.executeRaw<{ body_generation: number | string; body_storage: string }>('SELECT body_generation, body_storage FROM pages WHERE id=$1', [pageId]);
if (page?.body_storage !== 'segmented' || Number(page.body_generation) !== generation) return null;
return (await tx.executeRaw<{ id: number }>(`DELETE FROM content_chunks c WHERE c.id=ANY(ARRAY(${STALE_CHUNKS_SQL} LIMIT $4)) RETURNING c.id`,
- [pageId, generation, live, DEFAULT_FLIP_RETIRE_MAX_ROWS])).length;
+ [pageId, generation, live, PROJECTION_RETIRE_MAX_ROWS])).length;
});
if (deleted === null) return { retired, moved: true };
retired += deleted;
- if (deleted < DEFAULT_FLIP_RETIRE_MAX_ROWS) return { retired, moved: false };
+ if (deleted < PROJECTION_RETIRE_MAX_ROWS) return { retired, moved: false };
if (engine.kind === 'pglite') await new Promise(resolve => setImmediate(resolve));
}
}
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index d47fd1d536..6e669d6fbc 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -77,6 +77,9 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
// texts, then its claim renewal and insert), and after a projection staged its chunks (before its seal).
| 'segmented:texts_staged' | 'segmented:manifest_staged' | 'segmented:chunks_staged' | 'segmented:flipped' | 'segmented:projection_batch'
| 'segmented:projection_staged'
+ // Inside each projection insert transaction, once it holds the page's key lock and before it checks the generation and
+ // claim (ingest.ts `stageOccurrenceChunks`): a write to the page that arrives now waits for that transaction.
+ | 'segmented:projection_insert'
// A prior file over the single-string ceiling copied to its before stage (large-file.ts `stageBeforeCopy`): after the copy is
// written under its temporary name (unverified, unflushed: a crash during the copy) and once it is flushed, before its rename.
| 'large_file:stage_copying' | 'large_file:stage_flushed'
diff --git a/test/large-pages/projection-lock-hold.test.ts b/test/large-pages/projection-lock-hold.test.ts
new file mode 100644
index 0000000000..79f0891620
--- /dev/null
+++ b/test/large-pages/projection-lock-hold.test.ts
@@ -0,0 +1,216 @@
+/**
+ * A detached projection build holds its page's key lock for one bounded insert at a time, so a write to the page
+ * publishes in one attempt (#7178 follow-up).
+ *
+ * 1. Protects: a managed import of a new page over 4 MiB replies at commit and builds its projection after; each
+ * insert transaction of that build stages at most PROJECTION_LOCK_HOLD_BYTES of segments under the page lock.
+ * A delete_page of the file-backed page (over the single-string ceiling) submitted while an insert holds the lock
+ * waits for that insert only, inside its publication's 1 s `lock_timeout`, and publishes on its first
+ * preparation: one preparation, no transient interruption, one copy of the prior file to its before stage. An
+ * uninterrupted build still chunks every occurrence and seals. The lock transaction also holds a key-share lock on
+ * the source row (its `page_write_guards` insert), which a source-exclusive publication (a managed sync import,
+ * `SELECT ... FROM sources ... FOR UPDATE`) waits for: a managed sync of a new page over the ceiling beside a small
+ * one imports both in one call, the small page published on its first preparation while the big page's build runs.
+ * 2. Fails when: a build transaction inserts a whole STAGE_BATCH_BYTES batch (4 MiB) under the lock: about 0.7 s on
+ * an idle Postgres and past 1 s on a loaded host, where the waiting delete fails 55P03, prepares again and copies
+ * the 25 MiB file twice (CI run 39528224523: `bytesCopied` exactly twice the file); and every sync import on the
+ * source waits out each batch the same way, so a loaded host's first sync left the small page to its next pass
+ * (`filesImported: 1` on the call that settled, GitHub job 118987907022).
+ * 3. Existing coverage: segmented-delete-restore-file.slow.test.ts deletes a page whose detached build may still run
+ * and failed on a loaded host with two copies; nothing drove the overlap on purpose or bounded the hold.
+ * 4. Seam: the `segmented:projection_insert` fault point (fault-points.ts) inside each insert transaction, after its
+ * page lock; on Postgres the test holds the first insert there until the delete is prepared, so the delete's
+ * publication waits for that insert. `segmentChunkWork.heldBytes` (the largest insert) and `largeFileWork` are
+ * the modules' own work counters. PGLite has one connection, so its arm submits the write without holding.
+ * Runs on PGLite, and on Postgres when DATABASE_URL is set (test/postgres-unit-arms.txt).
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/operations.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { PROJECTION_LOCK_HOLD_BYTES } from '../../src/core/page-body/limits.ts';
+import { segmentChunkWork } from '../../src/core/page-body/ingest.ts';
+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';
+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';
+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { largeFileWork } from '../../src/core/persistence/large-file.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-projection-lock-hold-'));
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const logger = { info() {}, warn() {}, error() {} };
+const body = conversationPage(PAGE_MAX_BYTES + 1024 * 1024, { seed: 7178 });
+
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+/** A loaded host can outlast the reply wait: the same call (same request_id) is repeated until it settles. */
+async function settled<T>(call: () => Promise<T>): Promise<T> {
+ for (;;) {
+ try { return await call(); }
+ catch (error) { if ((error as { code?: string }).code !== 'write_pending') throw error; await Bun.sleep(1000); }
+ }
+}
+
+for (const kind of testBackends()) {
+ describe(`a detached projection build holds the page lock one bounded insert at a time (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+
+ 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();
+ }
+ }, 120_000);
+ afterEach(() => installFaultHook(undefined));
+ afterAll(async () => {
+ await withEnv(env, async () => { await disposePersistenceConsumer(engine); await close(); });
+ });
+
+ async function managedSource(): Promise<{ sourceId: string; root: string; ctx: OperationContext }> {
+ await disposePersistenceConsumer(engine);
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const sourceId = `hold-${randomUUID().slice(0, 8)}`;
+ const root = join(home, sourceId);
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await registerLocalWriter(engine, 'cli');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;
+ return { sourceId, root, ctx };
+ }
+
+ const importPage = async (f: { sourceId: string; root: string }, slug: string) => {
+ writeFileSync(join(f.root, `${slug}.md`), body);
+ return { ...await importManagedFile(engine, join(f.root, `${slug}.md`), `${slug}.md`, { sourceId: f.sourceId, noEmbed: true }) } as Record<string, unknown>;
+ };
+ const pageRow = async (sourceId: string, slug: string) => (await engine.executeRaw<{ deleted: boolean; sealed: boolean; chunks: number; unchunked: number }>(
+ `SELECT deleted_at IS NOT NULL AS deleted, COALESCE(text_projection_revision = knowledge_revision, false) AS sealed,
+ (SELECT count(*)::int FROM content_chunks c WHERE c.page_id = p.id) AS chunks,
+ (SELECT count(*)::int FROM page_body_manifest m WHERE m.page_id = p.id AND m.staging_id IS NULL AND m.gen_to IS NULL
+ AND NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id = p.id AND c.occurrence_id = m.occurrence_id)) AS unchunked
+ FROM pages p WHERE source_id=$1 AND slug=$2`, [sourceId, slug]))[0] ?? null;
+
+ test('a delete submitted while a build insert holds the page lock publishes on its first preparation, copying the file once', () => withEnv(env, async () => {
+ const f = await managedSource();
+ const slug = 'notes/held';
+ let locked!: () => void;
+ const inserting = new Promise<void>(resolve => { locked = resolve; });
+ let release!: () => void;
+ const prepared = new Promise<void>(resolve => { release = resolve; });
+ let deleteRequest: string | undefined;
+ let preparations = 0;
+ installFaultHook(async (point, detail) => {
+ if (detail.sourceId !== f.sourceId) return;
+ if (point === 'consumer:preparing' && detail.operation === 'delete_page') { preparations++; deleteRequest = detail.requestId; return; }
+ if (point === 'publication:prepared' && detail.operation === 'delete_page') { release(); return; }
+ if (point !== 'segmented:projection_insert' || detail.slug !== slug) return;
+ locked();
+ // Postgres: hold this insert, under its page lock, until the delete's publication is about to take that lock.
+ if (kind === 'postgres') await Promise.race([prepared, Bun.sleep(60_000)]);
+ });
+ try {
+ segmentChunkWork.heldBytes = 0;
+ expect(await importPage(f, slug)).toMatchObject({ slug, status: 'imported', searchable: 'pending', projection: 'pending' });
+ await inserting;
+ for (const key of Object.keys(largeFileWork) as Array<keyof typeof largeFileWork>) largeFileWork[key] = 0;
+ const [{ revision }] = await engine.executeRaw<{ revision: string }>('SELECT knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug=$2', [f.sourceId, slug]);
+ const params = { slug, expected_revision: revision, request_id: randomUUID() };
+ const deleted = await settled(() => submitPageMutation(f.ctx, { operation: 'delete_page', params }));
+ expect(deleted).toMatchObject({ status: 'soft_deleted', noop: false });
+ expect(existsSync(join(f.root, `${slug}.md`))).toBe(false);
+ expect(preparations).toBe(1);
+ const [request] = await engine.executeRaw<{ state: string; transient_interruptions: number }>(
+ 'SELECT state, transient_interruptions FROM persistence_requests WHERE request_id=$1', [deleteRequest]);
+ expect(request).toEqual({ state: 'committed', transient_interruptions: 0 });
+ expect(largeFileWork.bytesCopied).toBe(Buffer.byteLength(body));
+ expect(segmentChunkWork.heldBytes).toBeGreaterThan(0);
+ expect(segmentChunkWork.heldBytes).toBeLessThanOrEqual(PROJECTION_LOCK_HOLD_BYTES);
+ } finally {
+ release();
+ installFaultHook(undefined);
+ await disposePersistenceConsumer(engine);
+ }
+ }), 600_000);
+
+ test('an uninterrupted build chunks every occurrence in bounded inserts and seals', () => withEnv(env, async () => {
+ const f = await managedSource();
+ const slug = 'notes/sealed';
+ let inserts = 0;
+ installFaultHook((point, detail) => { if (point === 'segmented:projection_insert' && detail.sourceId === f.sourceId) inserts++; });
+ segmentChunkWork.heldBytes = 0;
+ segmentChunkWork.chunks = 0;
+ expect(await importPage(f, slug)).toMatchObject({ slug, status: 'imported', searchable: 'pending' });
+ await disposePersistenceConsumer(engine);
+ const row = await pageRow(f.sourceId, slug);
+ expect(row).toMatchObject({ deleted: false, sealed: true, unchunked: 0 });
+ expect(row!.chunks).toBe(segmentChunkWork.chunks);
+ expect(segmentChunkWork.heldBytes).toBeLessThanOrEqual(PROJECTION_LOCK_HOLD_BYTES);
+ expect(inserts).toBeGreaterThanOrEqual(Math.ceil(Buffer.byteLength(body) / PROJECTION_LOCK_HOLD_BYTES));
+ }), 600_000);
+ test('a managed sync imports a small page beside a new page over the ceiling in one call while the big page\'s build holds its lock', () => withEnv(env, async () => {
+ await disposePersistenceConsumer(engine);
+ const sourceId = `hold-sync-${randomUUID().slice(0, 8)}`;
+ const root = join(home, sourceId);
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: 'ignore' });
+ git('init', '-q');
+ writeFileSync(join(root, 'notes/huge.md'), body);
+ writeFileSync(join(root, 'notes/small.md'), '---\ntitle: Small\n---\nA small note.\n');
+ git('add', '-A');
+ git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'test content');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}'::jsonb)", [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ let release!: () => void;
+ const prepared = new Promise<void>(resolve => { release = resolve; });
+ let holding = false;
+ const preparations = new Map<string, number>();
+ const slugOf = async (writeId?: string) => (await engine.executeRaw<{ slug: string }>('SELECT slug FROM persistence_requests WHERE id=$1::uuid', [writeId]))[0]?.slug;
+ installFaultHook(async (point, detail) => {
+ if (detail.sourceId !== sourceId) return;
+ if (point === 'consumer:preparing') { const slug = (await slugOf(detail.writeId)) ?? '?'; preparations.set(slug, (preparations.get(slug) ?? 0) + 1); return; }
+ if (point === 'consumer:prepared' && await slugOf(detail.writeId) === 'notes/small') { release(); return; }
+ if (point !== 'segmented:projection_insert' || detail.slug !== 'notes/huge' || holding) return;
+ holding = true;
+ // Postgres: hold this insert, under its page lock, until the small page's write is prepared and about to publish.
+ if (kind === 'postgres') await Promise.race([prepared, Bun.sleep(60_000)]);
+ });
+ try {
+ segmentChunkWork.heldBytes = 0;
+ expect(await performManagedSync(engine, { sourceId, noPull: true, noEmbed: true })).toMatchObject({ status: 'first_sync', filesImported: 2 });
+ expect(holding).toBe(true);
+ expect(preparations.get('notes/small')).toBe(1);
+ const [small] = await engine.executeRaw<{ state: string; transient_interruptions: number }>(
+ "SELECT state, transient_interruptions FROM persistence_requests WHERE source_id=$1 AND slug='notes/small'", [sourceId]);
+ expect(small).toEqual({ state: 'committed', transient_interruptions: 0 });
+ await disposePersistenceConsumer(engine);
+ expect(await pageRow(sourceId, 'notes/huge')).toMatchObject({ deleted: false, sealed: true, unchunked: 0 });
+ expect(segmentChunkWork.heldBytes).toBeLessThanOrEqual(PROJECTION_LOCK_HOLD_BYTES);
+ } finally {
+ release();
+ installFaultHook(undefined);
+ await disposePersistenceConsumer(engine);
+ }
+ }), 600_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 6583180d80..97662f3b43 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -116,6 +116,7 @@ test/large-pages/page-purge-segments.test.ts
test/large-pages/pinned-segmented-reads.test.ts
test/large-pages/projection-claim-ownership.test.ts
test/large-pages/projection-demotion-race.test.ts
+test/large-pages/projection-lock-hold.test.ts
test/large-pages/projection-parity.test.ts
test/large-pages/publication-seal-bounded.test.ts
test/large-pages/purge-fact-inflight-staging.test.ts