Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

flip gate: doctor own-host info only for matched writes, unscannable stored-size read, drop dead doctor branch

garrytan3a34ab4ad94f
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index a782246bd1..6dfa223f42 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`, v258) 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, superseded by a later passing write of this host, as information with its clear time. 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`, v258, 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/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 overlays them whole, refusing `page_body_segmented` above `BLOCK_MAX_BYTES`, 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/src/commands/doctor/checks/segmented-storage.ts b/src/commands/doctor/checks/segmented-storage.ts
index 7ea7ee3d8d..2f6c8204ff 100644
--- a/src/commands/doctor/checks/segmented-storage.ts
+++ b/src/commands/doctor/checks/segmented-storage.ts
@@ -1,7 +1,7 @@
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { agentFix, checkError, doctorVerify, infoCheck } from '../check-fix.ts';
-import { PAGE_BODY_CONFIG_KEYS, parseSegmentedStorage, readPageBodyPolicy, segmentedStorageRequested, segmentedWriterBlockers, SEGMENTED_WRITER_WINDOW_DAYS } from '../../../core/page-body/limits.ts';
+import { PAGE_BODY_CONFIG_KEYS, parseSegmentedStorage, readPageBodyPolicy, segmentedWriterBlockers, SEGMENTED_WRITER_WINDOW_DAYS } from '../../../core/page-body/limits.ts';
import { SEGMENTED_WRITER_FLOOR } from '../../../core/page-body/writer-floor.ts';
import { compareWriterVersions, segmentedGateEvidence, writerVersionBelowFloor } from '../../../core/persistence/writer-versions.ts';
import { existingLocalHostId } from '../../../core/persistence/identity.ts';
@@ -19,9 +19,10 @@ const enableFix = (why: string) => agentFix(['gbrain', 'config', 'set', PAGE_BOD
* ingest-log runs and resident consumers without the segment-reader mark, or stamped below SEGMENTED_WRITER_FLOOR).
* While it is off, pages over 1 MiB are written inline up to 24 MiB; stored segmented pages stay readable. A hold left
* only by this host's own writes from before it upgraded is information with its clear time, not an upgrade fix: this
- * build is at or above the floor, this host has since written with a build that passes the gate (every blocker is
- * older than that write), and no older process of this host still renews its heartbeat. Without a later passing
- * write the same rows cannot be told from an older gbrain still writing on this host, which keeps the warning.
+ * build is at or above the floor, no older process of this host still renews its heartbeat, and for each blocker this
+ * host has since written the same kind of write (role and principal) with a build that passes the gate, every write of
+ * the blocker coming before the first of those. Otherwise the rows may be a second older gbrain on this host (a cron
+ * job, an npx run, a pinned install), which keeps the warning and the upgrade fix.
*/
export async function segmentedStorageCheck(engine: BrainEngine): Promise<Check> {
try {
@@ -36,17 +37,21 @@ export async function segmentedStorageCheck(engine: BrainEngine): Promise<Check>
'disabled_by_choice', enableFix('Turns segmented storage back on: pages over 1 MiB are stored in segments, up to the engine ceiling.'), details);
if (configured === 'invalid') return { name, status: 'warn', details, fix: enableFix('Replaces the unrecognized value with on.'),
message: 'pages.segmented_storage holds an unrecognized value, so segmented page storage is off. Set it to on or off.' };
- if (!segmentedStorageRequested(configured)) return infoCheck(name, 'Segmented page storage is off by default in this release (pages.segmented_storage unset): pages over 1 MiB are stored inline up to 24 MiB; pages already stored in segments stay readable.',
- 'disabled_by_choice', enableFix('Turns segmented storage on: pages over 1 MiB are stored in segments, up to the engine ceiling.'), details);
const hosts = listed.map(row => `host ${row.host_id ?? 'unknown (not recorded)'} (principal ${row.principal}) ${row.role} ${row.version}, last seen ${row.last_seen}`);
const self = blockers.length && (compareWriterVersions(VERSION, SEGMENTED_WRITER_FLOOR) ?? -1) >= 0 ? existingLocalHostId() : null;
const ownOnly = self !== null && blockers.every(row => row.host_id === self && row.last_seen !== null
&& (row.role !== 'resident' || Date.now() - Date.parse(row.last_seen) > CONSUMER_PURGE_MS));
- // This host's newest write that passes the gate: blockers older than it were written before the upgrade.
- const passedAt = ownOnly ? Math.max(-Infinity, ...(await segmentedGateEvidence(engine, SEGMENTED_WRITER_WINDOW_DAYS))
- .filter(row => row.host_id === self && row.segment_reader && row.last_seen && !writerVersionBelowFloor(row.version, SEGMENTED_WRITER_FLOOR))
- .map(row => Date.parse(row.last_seen!))) : -Infinity;
- if (ownOnly && blockers.every(row => Date.parse(row.last_seen!) < passedAt)) {
+ // Per role and principal (an ingest source type, a resident kind, a managed principal), when this host first wrote
+ // it with a build that passes the gate. A blocker is pre-upgrade only if this build has written the same kind of
+ // write and every one of the blocker's writes came before the first of those: anything else may be a second older
+ // gbrain on this host (a cron job, an npx run, a pinned install).
+ const passedFirst = new Map<string, number>();
+ if (ownOnly) for (const row of await segmentedGateEvidence(engine, SEGMENTED_WRITER_WINDOW_DAYS)) {
+ if (row.host_id !== self || !row.segment_reader || !row.first_seen || writerVersionBelowFloor(row.version, SEGMENTED_WRITER_FLOOR)) continue;
+ const key = `${row.role}\0${row.principal}`;
+ passedFirst.set(key, Math.min(passedFirst.get(key) ?? Infinity, Date.parse(row.first_seen)));
+ }
+ if (ownOnly && blockers.every(row => Date.parse(row.last_seen!) < (passedFirst.get(`${row.role}\0${row.principal}`) ?? -Infinity))) {
const clears = new Date(Math.max(...blockers.map(row => Date.parse(row.last_seen!))) + SEGMENTED_WRITER_WINDOW_DAYS * 86_400_000).toISOString();
return infoCheck(name, `Segmented page storage is configured ${configured === 'on' ? 'on' : 'on by default'} but held off until ${clears} by writes this host (${self}) made before it upgraded: ${hosts.join('; ')}${blockers.length > SAMPLE ? ` (first ${SAMPLE} shown)` : ''}. `
+ `This host now runs v${VERSION}, at or above v${SEGMENTED_WRITER_FLOOR}, so nothing needs upgrading; the hold clears ${SEGMENTED_WRITER_WINDOW_DAYS} days after the last of those writes (clears_at), and until then pages over 1 MiB are written inline up to 24 MiB.`,
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 0f0cfbe08b..fc124af27f 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -894,8 +894,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', text: 'A page stored in segments whose facts fence is longer than a segment (so it crosses a forced cut) is now read whole by every trusted reader once its source has a withdrawal: `gbrain export`, the withdrawal mirror and Git walk, the file drift check and the derived passes join the fence\'s segments (up to 8 MiB) and apply the withdrawals to the joined fence, as withdrawal discovery and the purge rewrite already did. Before, they refused with `page_projection_stale`, so a purge committed but its withdrawal mirror failed five times and parked with the purged row still in the canonical file. A fence longer than 8 MiB is recorded as a skipped target (reason `page_body_segmented`) by the mirror and Git walk instead of parking them. A withdrawal mirror whose staging file cannot be written (an I/O error such as EIO or ENOSPC) while the canonical file is unchanged now releases its recovery record and reserved capacity, so other writes and effects on the source\'s worktree proceed and the mirror retries and parks after its attempts like any failed mirror; before, the record held every write on the worktree and the mirror retried every 30 seconds without ever parking. The mirror now renders a segmented page\'s file only when the file exists to be rewritten, the Git walk no longer renders it at all, and both renew their effect claim while they stream the file.' },
{ since: 'TBD', text: 'A managed write whose statements the database ends with a statement timeout or cancel (SQLSTATE 57014, at preparation or inside its publication transaction) now counts each such interruption against `persistence.max_preparation_attempts` (default 2), together with preparations cut off at their deadline, and at the limit ends `failed` with `write_interrupted` (the receipt names the attempts, the limit and the SQLSTATE; a worktree-backed write restores its file first) instead of being released as `database_contention` and prepared again without limit. A single interruption still re-prepares and commits; a lock timeout, serialization failure or deadlock (contention with other writers), a dropped connection or a restarting database is never counted. A foreground write needs a new `request_id`; a managed sync holds the file and moves on (`gbrain sync status` lists the hold with class `page`, safe action `retry`, and the read-only `gbrain sources writer status` diagnosis), and `gbrain sources retry-held` re-admits it. A shared read of a group the database cancels charges no member, and the charge commits with the release of the claim, so a crash between them never counts an interruption twice. `persistence.preparation_deadlines false` turns the counting off with the deadlines.' },
{ since: 'TBD', text: 'Upgrading builds the index `ingest_log_marked_idx` (migration v257): on Postgres online (`CREATE INDEX CONCURRENTLY`; reads and writes go on while it builds), on PGLite as a plain build that holds writes until it ends. It took 0.4 s for 1M `ingest_log` rows on Postgres and 0.5 s on PGLite. The segmented storage writer hold now judges every recent import, sync or connector run and resident process by its version, including those of a gbrain that already records reading segmented pages (v0.60.290.0), and the index keeps that read to the last 7 days of the log: 600 buffers on a 1M-row log, where a scan reads the whole table.' },
- { since: 'TBD', text: 'Upgrading builds the index `pages_segmented_body_bytes_idx` (migration v258) over pages stored in segments: on Postgres online (`CREATE INDEX CONCURRENTLY`), on PGLite as a plain build that holds writes until it ends. With it, the default `persistence.limits.worktree_recovery_bytes` also leaves room for the largest page already stored in segments, deleted pages included: turning `pages.segmented_storage` off or lowering `pages.max_bytes` no longer makes a delete, restore or withdrawal mirror of such a page fail with `request_too_large` (a withdrawn row stayed in its file). A value you set is kept, and a request it cannot hold is refused with `request_too_large` naming both recovery budgets and the bytes it needed.' },
- { since: 'TBD', text: 'Doctor `segmented_storage` no longer tells you to upgrade this host when the only writes holding segmented storage off are this host\'s own from before its upgrade and it has since written with the upgraded gbrain: it reports the hold as information with the time it clears. Another host, or an older `serve` or worker still running on this host, keeps the warning and the `gbrain upgrade` fix.' },
+ { since: 'TBD', text: 'Upgrading builds the index `pages_segmented_body_bytes_idx` (migration v258) over pages stored in segments: on Postgres online (`CREATE INDEX CONCURRENTLY`), on PGLite as a plain build that holds writes until it ends. With it, the default `persistence.limits.worktree_recovery_bytes` also leaves room for the largest page already stored in segments, deleted pages included (while the index is not yet valid, a page at the engine ceiling, so no limit read scans `pages`): turning `pages.segmented_storage` off or lowering `pages.max_bytes` no longer makes a delete, restore or withdrawal mirror of such a page fail with `request_too_large` (a withdrawn row stayed in its file). A value you set is kept, and a request it cannot hold is refused with `request_too_large` naming both recovery budgets and the bytes it needed.' },
+ { since: 'TBD', text: 'Doctor `segmented_storage` no longer tells you to upgrade this host when the only writes holding segmented storage off are this host\'s own from before its upgrade and the upgraded gbrain has since made the same kind of write (the same import or sync type, resident kind or managed principal), after the last of them: it reports the hold as information with the time it clears. Another host, an older `serve` or worker still running on this host, or an older write this build has not matched (a cron job or `npx` run on this host) keeps the warning and the `gbrain upgrade` fix.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/limits.ts b/src/core/persistence/limits.ts
index c9c872263f..cde8093d34 100644
--- a/src/core/persistence/limits.ts
+++ b/src/core/persistence/limits.ts
@@ -1,5 +1,5 @@
import { opError } from '../ops/contract.ts';
-import { PAGE_BODY_CONFIG_KEYS, pageRecoveryBytes } from '../page-body/limits.ts';
+import { PAGE_BODY_CONFIG_KEYS, pageRecoveryBytes, segmentedPageCeiling } from '../page-body/limits.ts';
import { DEFAULT_JOURNAL_LIMITS, type JournalLimits, type SqlEngine } from './model.ts';
import { COMPACTED_HEADROOM_BYTES, RECEIPT_RESERVATION_FLOOR } from './receipt-bytes.ts';
@@ -26,15 +26,26 @@ export function parseJournalConfigValue(key:string,value:string):number {
/**
* Database configuration applies to every server sharing this brain. An unset `worktree_recovery_bytes` defaults to
* room for the largest page `pages.max_bytes` admits and the largest page stored in segments (page-body/limits.ts
- * `pageRecoveryBytes`, never below 256 MiB; the stored maximum is one probe of pages_segmented_body_bytes_idx, v258); an
+ * `pageRecoveryBytes`, never below 256 MiB; the stored maximum is one probe of pages_segmented_body_bytes_idx, v258, or
+ * the engine ceiling while that index is not valid: JOURNAL_LIMITS_SQL); an
* engine that is not PGLite (or a stub without a `kind`) counts as Postgres, the larger ceiling.
*/
+/**
+ * The journal's one config statement. Its last row (key NULL) is the largest page stored in segments, read only while
+ * pages_segmented_body_bytes_idx is valid (the CASE leaves the subquery unexecuted otherwise, so an index the online
+ * v258 build left INVALID never turns each limit read into a scan of pages); 'unindexed' then stands for a page at the
+ * engine ceiling, the most any stored page can hold.
+ */
+export const JOURNAL_LIMITS_SQL=`SELECT key,value FROM config WHERE key LIKE 'persistence.limits.%' OR key IN ('${PAGE_BODY_CONFIG_KEYS.segmentedStorage}','${PAGE_BODY_CONFIG_KEYS.maxBytes}')
+ UNION ALL SELECT NULL,CASE WHEN (SELECT indisvalid FROM pg_index WHERE indexrelid=to_regclass('pages_segmented_body_bytes_idx')) IS TRUE
+ THEN (SELECT max(body_bytes) FROM pages WHERE body_storage='segmented')::text ELSE 'unindexed' END`;
export async function readJournalLimits(engine:SqlEngine & { kind?: string },overrides?:Partial<JournalLimits>):Promise<JournalLimits> {
- const rows=await engine.executeRaw<{key:string|null;value:string|null}>(`SELECT key,value FROM config WHERE key LIKE 'persistence.limits.%' OR key IN ('${PAGE_BODY_CONFIG_KEYS.segmentedStorage}','${PAGE_BODY_CONFIG_KEYS.maxBytes}')
- UNION ALL SELECT NULL,max(body_bytes)::text FROM pages WHERE body_storage='segmented'`);
+ const rows=await engine.executeRaw<{key:string|null;value:string|null}>(JOURNAL_LIMITS_SQL);
+ const kind=engine.kind === 'pglite' ? 'pglite' : 'postgres';
const configured=new Map(rows.filter(row=>row.key!==null && row.value!==null).map(row=>[row.key!,row.value!]));
- const storedSegmented=Number(rows.find(row=>row.key===null)?.value ?? 0);
- const limits={...DEFAULT_JOURNAL_LIMITS,worktreeRecoveryBytes:pageRecoveryBytes(engine.kind === 'pglite' ? 'pglite' : 'postgres',configured.get(PAGE_BODY_CONFIG_KEYS.segmentedStorage) ?? null,
+ const stored=rows.find(row=>row.key===null)?.value ?? null;
+ const storedSegmented=stored==='unindexed' ? segmentedPageCeiling(kind) : Number(stored ?? 0);
+ const limits={...DEFAULT_JOURNAL_LIMITS,worktreeRecoveryBytes:pageRecoveryBytes(kind,configured.get(PAGE_BODY_CONFIG_KEYS.segmentedStorage) ?? null,
configured.get(PAGE_BODY_CONFIG_KEYS.maxBytes) ?? null,DEFAULT_JOURNAL_LIMITS.worktreeRecoveryBytes,storedSegmented)};
for(const key of Object.keys(limits) as Array<keyof JournalLimits>) {
const value=configured.get(journalLimitKey(key));
diff --git a/src/core/persistence/writer-versions.ts b/src/core/persistence/writer-versions.ts
index 8e47d0cee5..56ecdd85a5 100644
--- a/src/core/persistence/writer-versions.ts
+++ b/src/core/persistence/writer-versions.ts
@@ -98,6 +98,8 @@ export interface SegmentedGateWriter {
/** The rows carried the segment-reader mark (migration v254), which only binaries that read segmented pages write. */
segment_reader: boolean;
last_seen: string | null; requests: number;
+ /** The earliest of the rows in the window (a resident: the earliest process start). */
+ first_seen: string | null;
}
/**
@@ -119,26 +121,28 @@ export async function segmentedGateWriters(engine: SqlEngine, days: number, floo
/** Every writer the gate read in the last `days`, passing or not, grouped as `segmentedGateWriters` groups them. */
export async function segmentedGateEvidence(engine: SqlEngine, days: number): Promise<SegmentedGateWriter[]> {
- const rows = await engine.executeRaw<Omit<SegmentedGateWriter, 'version_label' | 'last_seen' | 'requests'> & { last_seen: unknown; requests: number }>(
+ const rows = await engine.executeRaw<Omit<SegmentedGateWriter, 'version_label' | 'last_seen' | 'requests' | 'first_seen'> & { last_seen: unknown; requests: number; first_seen: unknown }>(
`WITH win AS (SELECT now()-($1::double precision*interval '1 day') AS since)
SELECT 'admitter' AS role,r.admitter_host_id::text AS host_id,r.principal_kind||':'||r.principal_id AS principal,r.admitter_version AS version,
- COALESCE(r.admitter_segment_reader,false) AS segment_reader,MAX(r.created_at) AS last_seen,COUNT(*)::integer AS requests
+ COALESCE(r.admitter_segment_reader,false) AS segment_reader,MAX(r.created_at) AS last_seen,COUNT(*)::integer AS requests,
+ MIN(r.created_at) AS first_seen
FROM persistence_requests r CROSS JOIN win WHERE r.created_at>=win.since GROUP BY 2,3,4,5
UNION ALL
SELECT 'consumer',COALESCE(r.consumer_host_id,w.owner_host_id)::text,r.principal_kind||':'||r.principal_id,r.consumer_version,
- COALESCE(r.consumer_segment_reader,false),MAX(COALESCE(r.published_at,r.completed_at)),COUNT(*)::integer
+ COALESCE(r.consumer_segment_reader,false),MAX(COALESCE(r.published_at,r.completed_at)),COUNT(*)::integer,
+ MIN(COALESCE(r.published_at,r.completed_at))
FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id CROSS JOIN win
WHERE r.state='committed' AND COALESCE(r.published_at,r.completed_at)>=win.since GROUP BY 2,3,4,5
UNION ALL
- SELECT 'importer',l.writer_host_id::text,'ingest:'||l.source_type,l.writer_version,false,MAX(l.created_at),COUNT(*)::integer
+ SELECT 'importer',l.writer_host_id::text,'ingest:'||l.source_type,l.writer_version,false,MAX(l.created_at),COUNT(*)::integer,MIN(l.created_at)
FROM ingest_log l CROSS JOIN win WHERE l.writer_segment_reader IS NOT TRUE AND l.created_at>=win.since GROUP BY 2,3,4
UNION ALL
- SELECT 'importer',l.writer_host_id::text,'ingest:'||l.source_type,l.writer_version,true,MAX(l.created_at),COUNT(*)::integer
+ SELECT 'importer',l.writer_host_id::text,'ingest:'||l.source_type,l.writer_version,true,MAX(l.created_at),COUNT(*)::integer,MIN(l.created_at)
FROM ingest_log l CROSS JOIN win WHERE l.writer_segment_reader IS TRUE AND l.created_at>=win.since GROUP BY 2,3,4
UNION ALL
- SELECT 'resident',c.host_id::text,'process:'||c.kind,c.version,COALESCE(c.segment_reader,false),MAX(c.renewed_at),COUNT(*)::integer
+ SELECT 'resident',c.host_id::text,'process:'||c.kind,c.version,COALESCE(c.segment_reader,false),MAX(c.renewed_at),COUNT(*)::integer,MIN(c.started_at)
FROM persistence_consumers c CROSS JOIN win WHERE c.renewed_at>=win.since GROUP BY 2,3,4,5
ORDER BY last_seen DESC`, [days]);
return rows.map(row => ({ role: row.role, host_id: row.host_id, principal: row.principal, version: row.version, version_label: writerVersionLabel(row.version),
- segment_reader: row.segment_reader === true, last_seen: iso(row.last_seen), requests: Number(row.requests) }));
+ segment_reader: row.segment_reader === true, last_seen: iso(row.last_seen), requests: Number(row.requests), first_seen: iso(row.first_seen) }));
}
diff --git a/test/large-pages/recovery-budget-default.test.ts b/test/large-pages/recovery-budget-default.test.ts
index f55a8d8e74..0478310cf5 100644
--- a/test/large-pages/recovery-budget-default.test.ts
+++ b/test/large-pages/recovery-budget-default.test.ts
@@ -6,7 +6,8 @@
* a restore of a page at the ceiling (which reserves its file twice) fits; with the switch off it stays 256 MiB. A
* configured value is kept as the user's choice, and the 1 GiB brain budget already holds the largest default. A
* page already stored in segments keeps the default at twice its body plus headroom after the switch goes off or
- * `pages.max_bytes` is lowered (soft-deleted too, since a restore brings it back).
+ * `pages.max_bytes` is lowered (soft-deleted too, since a restore brings it back). With the size index missing or
+ * INVALID the limit read leaves `pages` unread (EXPLAIN: never executed) and assumes a page at the ceiling.
* 2. Fails when: the default stays a flat 256 MiB under a 256 MiB (Postgres) or 128 MiB (PGLite) ceiling, follows a
* `pages.max_bytes` above the ceiling, drops below 256 MiB for a lowered `pages.max_bytes`, or overrides a configured
* value.
@@ -18,7 +19,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:tes
import type { BrainEngine } from '../../src/core/engine.ts';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { RECOVERY_FILE_HEADROOM_BYTES, SEGMENTED_PAGE_CEILING_BYTES, SEGMENTED_STORAGE_DEFAULT } from '../../src/core/page-body/limits.ts';
-import { readJournalLimits } from '../../src/core/persistence/limits.ts';
+import { JOURNAL_LIMITS_SQL, readJournalLimits } from '../../src/core/persistence/limits.ts';
import { importFromContent } from '../../src/core/import-file.ts';
import { conversationPage } from '../helpers/conversation-page.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
@@ -103,6 +104,26 @@ for (const kind of testBackends()) describe(`worktree recovery default follows t
expect(await worktree()).toBe(OLD_DEFAULT);
}, 120_000);
+ test('with pages_segmented_body_bytes_idx missing or invalid, the default never scans pages: it assumes a stored page at the ceiling', async () => {
+ const slug = 'notes/stored-unindexed';
+ const plan = async () => (await engine.executeRaw<Record<string, string>>(`EXPLAIN (ANALYZE, COSTS OFF) ${JOURNAL_LIMITS_SQL}`)).map(row => Object.values(row)[0]!);
+ const pagesNodes = async () => (await plan()).filter(line => / on pages\b/.test(line));
+ try {
+ expect((await importFromContent(engine, slug, conversationPage(2 * MiB, { seed: 72 }), { noEmbed: true })).status).toBe('imported');
+ await engine.setConfig('pages.segmented_storage', 'off');
+ expect(await worktree()).toBe(OLD_DEFAULT);
+ await engine.executeRaw('DROP INDEX pages_segmented_body_bytes_idx');
+ const nodes = await pagesNodes();
+ expect(nodes.length).toBeGreaterThan(0);
+ for (const line of nodes) expect(line).toContain('never executed');
+ expect(await worktree()).toBe(2 * (ceiling + RECOVERY_FILE_HEADROOM_BYTES));
+ } finally {
+ await engine.executeRaw("CREATE INDEX IF NOT EXISTS pages_segmented_body_bytes_idx ON pages (body_bytes) WHERE body_storage = 'segmented'");
+ await engine.executeRaw('DELETE FROM pages WHERE slug=$1', [slug]);
+ }
+ expect(await worktree()).toBe(OLD_DEFAULT);
+ }, 120_000);
+
test('a configured worktree_recovery_bytes is the user\'s choice', async () => {
await engine.setConfig('pages.segmented_storage', 'on');
await engine.setConfig('persistence.limits.worktree_recovery_bytes', String(OLD_DEFAULT));
diff --git a/test/large-pages/segmented-switch.test.ts b/test/large-pages/segmented-switch.test.ts
index 183051b692..a02554c308 100644
--- a/test/large-pages/segmented-switch.test.ts
+++ b/test/large-pages/segmented-switch.test.ts
@@ -11,8 +11,9 @@
* run (ingest_log), its resident heartbeat and its uncommitted requests all block; this build's do not. An
* unreadable gate blocks, an unparsable stamp blocks, the 7-day window ends between day 6 and day 8, and the gate is
* read once per TTL (work counter) while doctor reads through. A failed read of the switch or `pages.max_bytes` keeps
- * it off (never "unset", which is on). Doctor reports a hold left only by this host's pre-upgrade writes, after a
- * later passing write of this host, as information. (The floor's derivation: segmented-writer-floor.test.ts.)
+ * it off (never "unset", which is on). Doctor reports a hold left only by this host's pre-upgrade writes as
+ * information once this build has made the same kind of write after them; an older gbrain still writing on this host
+ * (a cron import, an npx sync, an older managed admitter) keeps the upgrade warning. (The floor's derivation: segmented-writer-floor.test.ts.)
* 2. Fails when: the default stays off, the gate ignores old or unstamped writers, an explicit `on` overrides the
* gate, a cleared gate keeps writes inline, export sizes stored segmented pages by the write limit, a writer without
* the mark passes on its version, a write path of this build stops marking, or the gate's error, window, parse or
@@ -289,8 +290,12 @@ for (const kind of testBackends()) {
// Until this host writes with a build that passes the gate, the rows cannot be told from an older gbrain still
// writing here: the upgrade warning stays.
expect(await segmentedStorageCheck(engine)).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'upgrade'] } });
- await engine.logIngest({ source_type: 'import', source_ref: 'self-after-upgrade', pages_updated: [], summary: 'this build' });
+ await engine.logIngest({ source_type: 'sync', source_ref: 'self-after-upgrade', pages_updated: [], summary: 'this build' });
expect(Number((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM ingest_log WHERE writer_host_id=$1::uuid AND writer_segment_reader AND writer_version=$2", [self, VERSION]))[0]!.n)).toBe(1);
+ // The lapsed older serve is matched only by a serve of this build started after it (PGLite writes no heartbeat).
+ expect(await segmentedStorageCheck(engine)).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'upgrade'] } });
+ await engine.executeRaw(`INSERT INTO persistence_consumers (host_id, pid, nonce, kind, mode, host_json_path, persistence_home, version, segment_reader)
+ VALUES ($1::uuid, 4343, 'self-new-serve', 'serve', 'full', '/tmp/host.json', '/tmp', $2, true)`, [self, VERSION]);
expect(await segmentedNow()).toBe(false);
const own = await segmentedStorageCheck(engine);
expect(own).toMatchObject({ status: 'ok', severity: 'info', details: { effective: 'off' } });
@@ -316,6 +321,40 @@ for (const kind of testBackends()) {
expect(both.message).toContain(other);
}), 120_000);
+ test('doctor: an older gbrain still writing on this host (a cron import, an npx run) keeps the upgrade warning even after this build wrote', async () => inHome(async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const self = localHostId();
+ const older = '0.60.290.0';
+ const oldRun = (type: string, ref: string, ago: string) => engine.executeRaw(`INSERT INTO ingest_log (source_id, source_type, source_ref, pages_updated, summary, writer_version, writer_host_id, writer_segment_reader, created_at)
+ VALUES ('default', $1, $2, '[]'::jsonb, 'run', $3, $4::uuid, true, now() - $5::interval)`, [type, ref, older, self, ago]);
+ const newRun = (type: string, ref: string, ago: string) => engine.executeRaw(`INSERT INTO ingest_log (source_id, source_type, source_ref, pages_updated, summary, writer_version, writer_host_id, writer_segment_reader, created_at)
+ VALUES ('default', $1, $2, '[]'::jsonb, 'run', $3, $4::uuid, true, now() - $5::interval)`, [type, ref, VERSION, self, ago]);
+ const verdict = async () => { const c = await segmentedStorageCheck(engine); return [c.status, c.fix?.argv?.join(' ') ?? null]; };
+ const warn = ['warn', 'gbrain upgrade'];
+
+ // A cron or npx gbrain on this host that imports, while this build only syncs: nothing this build wrote matches it.
+ await oldRun('import', 'cron-import', '2 hours');
+ await newRun('sync', 'this-build-sync', '1 hour');
+ expect(await verdict()).toEqual(warn);
+ // This build importing later makes the import look pre-upgrade again (the gate cannot tell; doctor says so only then).
+ await newRun('import', 'this-build-import', '1 hour');
+ expect(await verdict()).toEqual(['ok', null]);
+
+ // An older sync that ran after this build's first sync is a second binary, even though this build synced again since.
+ await newRun('sync', 'this-build-sync-again', '0 hours');
+ await oldRun('sync', 'npx-sync', '30 minutes');
+ expect(await verdict()).toEqual(warn);
+ await engine.executeRaw("DELETE FROM ingest_log WHERE source_ref='npx-sync'");
+ expect(await verdict()).toEqual(['ok', null]);
+
+ // A managed write admitted by an older binary on this host, with no managed write of this build: warn.
+ const requests = await requestFixture(engine);
+ const admitted = await requests.admit('npx-page');
+ await editRequest(engine, admitted.id, "admitter_version='0.60.290.0',created_at=now()-interval '3 hours'");
+ expect((await blockersNow()).map(b => b.role)).toContain('admitter');
+ expect(await verdict()).toEqual(warn);
+ }), 120_000);
+
test('explicit off keeps pages inline and doctor reports it as a choice', async () => {
await engine.setConfig('pages.segmented_storage', 'off');
expect((await importFromContent(engine, 'notes/off', content, { noEmbed: true })).status).toBe('imported');