Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Lane F N5: every byte-producing segmented reader requires rows that tile the generation body_bytes

garrytan707f75315607
diff --git a/docs/guides/windowed-reads.md b/docs/guides/windowed-reads.md
index 53722d01ec..a9460d75d3 100644
--- a/docs/guides/windowed-reads.md
+++ b/docs/guides/windowed-reads.md
@@ -147,11 +147,15 @@ the entity was named or inferred from the fact.
## page_body_rows_unreadable
A read of a segmented page found manifest rows that do not cover the page's
-stored body: they must run from byte 0 to the page's `body_bytes` without a
-gap. The usual cause is a database role that can read the page row but not
-its segment rows (a row-level security policy or grant on `pages` only); a
-damaged database is the other. gbrain returns nothing rather than an empty or
-truncated page. The brain host's operator gives the reading role the same
+stored body: they must run from byte 0 to the page's `body_bytes` (a retained
+version's own `body_bytes` for an older generation) without a gap. The usual
+cause is a database role that can read the page row but not its segment rows
+(a row-level security policy or grant on `pages` only); a damaged database is
+the other. gbrain returns nothing rather than an empty or truncated page, and
+every reader that produces the body checks it: `get_page`, `fetch`, export,
+backup and restore file writes, body digests, fence rewrites and purges, and
+timeline extraction. An export with such a page fails instead of writing a
+short file. The brain host's operator gives the reading role the same
access to `page_body_manifest` and `page_segment_texts` it has to `pages`;
`gbrain doctor --json` checks the segment tables.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 044e932ba9..2d79720476 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -667,7 +667,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'TBD', text: 'The pre-push secret scan (`gbrain sources push` and the automatic pushes) now scans a staged file over 25 MiB in bounded 8 Mi-character windows streamed from git, instead of refusing the push as `blocked_unscannable`: a clean large file pushes, and one holding a secret is refused as `blocked_secrets` naming its file and line. A staged file over 512 MiB still refuses as `blocked_unscannable`.' },
{ since: 'TBD', text: 'On Postgres, title search, the source-scoped vector scan, the chunk windows search reads around its hits and `get_page` now read the new `page_body_manifest` table for every page, inline ones included, whether or not `pages.segmented_storage` is on. A database role that neither owns the tables nor bypasses row level security needs `SELECT` on it, or those reads fail with `permission_denied` (42501). Row level security is on for the new segment tables (`page_segment_texts`, `page_body_manifest`, `page_body_stagings`, `page_body_staging_parts`, `page_view_digests`) and is re-enabled on every schema replay, as for `pages`, so a role without a policy reads none of their rows. Grant the table together with the source-scoped policies in docs/ENGINES.md ("Segmented page tables"), never with an open policy, or the role reads every source\'s segment text. A runtime role that owns the tables or bypasses row level security, the default setup, needs nothing.' },
{ since: 'TBD', text: 'MCP `get_page` of a page stored in segments no longer reports `size.body_bytes` or `size.body_lines` (the stored body) to a remote caller, and its `page_body_segmented` refusal names the size of the body that caller may read, as for an inline page; the difference told how much text privacy fences and withdrawals hide. A local `gbrain get` still reports both.' },
- { since: 'TBD', text: 'Reads of a page stored in segments that follow an authorization (MCP `get_page` windows, outlines, sizes and its whole-body refusal, `fetch`, evidence windows and the `entity` card excerpt) now read the revision they authorized: a page edited, made private or dropped below the caller\'s `min_trust` mid-read refuses with `revision_changed` (or `page_not_found`) instead of returning the newer body, and evidence falls back to the hit chunk. A segmented page whose segment rows the reader cannot see, or that has a gap, refuses with the new `page_body_rows_unreadable` instead of reading as empty. `purge_fact` now aborts a write in flight that staged a text holding the purged claim (its publish refuses `body_staging_expired`), segment maintenance keeps every text a live write staged, a page purge of an inline page no longer reports other pages\' segments as incomplete, and MCP `get_versions` reports a segmented version\'s readable size as `total_bytes` instead of its stored `body_bytes`.' },
+ { since: 'TBD', text: 'Reads of a page stored in segments that follow an authorization (MCP `get_page` windows, outlines, sizes and its whole-body refusal, `fetch`, evidence windows and the `entity` card excerpt) now read the revision they authorized: a page edited, made private or dropped below the caller\'s `min_trust` mid-read refuses with `revision_changed` (or `page_not_found`) instead of returning the newer body, and evidence falls back to the hit chunk. A segmented page whose segment rows the reader cannot see, or that has a gap or a missing tail, refuses with the new `page_body_rows_unreadable` in every reader that produces its body (MCP reads, export, backup and restore file writes, body digests, fence rewrites) instead of reading as empty or short; an export with such a page fails. `purge_fact` now aborts a write in flight that staged a text holding the purged claim (its publish refuses `body_staging_expired`), segment maintenance keeps every text a live write staged, a page purge of an inline page no longer reports other pages\' segments as incomplete, and MCP `get_versions` reports a segmented version\'s readable size as `total_bytes` instead of its stored `body_bytes`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/page-body/body-tiling.ts b/src/core/page-body/body-tiling.ts
new file mode 100644
index 0000000000..c20fcc53a9
--- /dev/null
+++ b/src/core/page-body/body-tiling.ts
@@ -0,0 +1,45 @@
+/**
+ * Wave B PR 2 (N5): a segmented body is read only when its manifest rows tile it. The rows of a generation must run
+ * from byte 0 without a gap and sum to that generation's body_bytes (the page's for the live generation, its
+ * segmented version's for a retained one). A role that sees the page row but not its manifest rows, or rows that
+ * went missing, would otherwise read as a short or empty body: an export, digest or rewrite of it would succeed and
+ * be wrong. Checked from the row metadata before any text is read, so it costs one pass over the rows.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { opError } from '../ops/contract.ts';
+
+export interface RowSpan { byteStart: number; byteLen: number }
+
+/** Throws page_body_rows_unreadable unless `rows` (in seq order) tile [0, total); a null total checks only a gapless start at 0. */
+export function assertRowsTile(rows: readonly RowSpan[], at: { slug: string; sourceId: string; total: number | null }): void {
+ let end = 0;
+ for (const row of rows) {
+ if (row.byteStart !== end) { end = -1; break; }
+ end += row.byteLen;
+ }
+ if (end >= 0 && (at.total === null ? rows.length > 0 : end === at.total)) return;
+ throw opError('page_body_rows_unreadable', `Page ${at.slug} (source ${at.sourceId}): the segment rows readable here do not cover its ${at.total ?? 'stored'}-byte body, so nothing was read.`,
+ 'Give the role that reads the brain the same access to page_body_manifest and page_segment_texts it has to pages, then read again.',
+ { detail: JSON.stringify({ rows: rows.length, covered_bytes: end >= 0 ? end : null, body_bytes: at.total }) });
+}
+
+/**
+ * body_bytes of generation `generation` of a segmented page: the page's when it is live, else the segmented version
+ * that references it (null when none does: nothing records that generation's size).
+ */
+export async function generationBodyBytes(engine: Pick<BrainEngine, 'executeRaw'>, page: { id: number; body_generation: unknown; body_bytes: unknown },
+ generation: number): Promise<number | null> {
+ if (generation === Number(page.body_generation)) return Number(page.body_bytes ?? 0);
+ const [version] = await engine.executeRaw<{ body_bytes: number | string | null }>(`SELECT body_bytes FROM page_versions
+ WHERE page_id=$1 AND body_generation=$2 AND body_storage='segmented' AND body_bytes IS NOT NULL ORDER BY id DESC LIMIT 1`, [page.id, generation]);
+ return version ? Number(version.body_bytes) : null;
+}
+
+/** The tiling check for a reader that read `rows` of `generation` (default live) through readManifest. */
+export async function assertGenerationTiles(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, generation: number | undefined, rows: readonly RowSpan[]): Promise<void> {
+ const [page] = await engine.executeRaw<{ id: number; slug: string; source_id: string; body_generation: unknown; body_bytes: unknown }>(
+ 'SELECT id, slug, source_id, body_generation, body_bytes FROM pages WHERE id=$1', [pageId]);
+ if (!page) return;
+ const at = generation ?? Number(page.body_generation);
+ assertRowsTile(rows, { slug: page.slug, sourceId: page.source_id, total: await generationBodyBytes(engine, { ...page, id: pageId }, at) });
+}
diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.ts
index 3a97098c50..33361611bf 100644
--- a/src/core/page-body/ingest.ts
+++ b/src/core/page-body/ingest.ts
@@ -34,6 +34,7 @@ import { newFenceChunkBudget } from '../markdown-chunks.ts';
import { loadFenceChunkOverlay } from '../eligibility/fence-overlay.ts';
import { withdrawalFenceBlocks } from '../facts/withdrawal-overlay.ts';
import { overlaySegmentText, readBodyLedger, type BodyLedger } from './segment-ledger.ts';
+import { assertGenerationTiles } from './body-tiling.ts';
const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
@@ -438,6 +439,7 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId
export async function* readSegmentedBody(engine: BrainEngine, pageId: number, sourceId: string,
opts: { generation?: number } = {}): AsyncIterable<{ region: BodyRegion; bytes: Uint8Array }> {
const rows = await engine.readManifest(pageId, opts.generation === undefined ? {} : { generation: opts.generation });
+ await assertGenerationTiles(engine, pageId, opts.generation, rows);
const batchBytes = STAGE_BATCH_BYTES[engine.kind];
for (let start = 0; start < rows.length;) {
let end = start, bytes = 0;
diff --git a/src/core/page-body/projection.ts b/src/core/page-body/projection.ts
index 6024193e91..589d134ffd 100644
--- a/src/core/page-body/projection.ts
+++ b/src/core/page-body/projection.ts
@@ -31,6 +31,7 @@ import { PROJECTION_RETRY_READY_SQL, SEGMENTED_JOB_PROBES, SEGMENTED_PROJECTION_
import { occurrencesWithoutChunks, stageOccurrenceChunks } from './ingest.ts';
import { DEFAULT_FLIP_RETIRE_MAX_ROWS } from './limits.ts';
import type { JsonObject } from './types.ts';
+import { assertGenerationTiles } from './body-tiling.ts';
export interface SegmentedProjectionResult { chunks: number; retired: number; sealed: boolean }
@@ -111,6 +112,7 @@ async function buildClaimedProjection(engine: BrainEngine, ref: { sourceId: stri
const generation = Number(page.body_generation);
const pageId = Number(page.id);
const liveRows = await engine.readManifest(pageId);
+ await assertGenerationTiles(engine, pageId, generation, liveRows);
const { retired, moved } = await retireStaleChunks(engine, ref, pageId, generation, liveRows.map(row => Number(row.occurrenceId)));
if (moved) return { chunks: 0, retired, sealed: false };
const frontmatter = page.frontmatter ?? {};
diff --git a/src/core/page-body/read-range.ts b/src/core/page-body/read-range.ts
index 5a7ffad620..6df7a268e8 100644
--- a/src/core/page-body/read-range.ts
+++ b/src/core/page-body/read-range.ts
@@ -37,6 +37,7 @@ import { credentialSafeProjection } from '../credential-projection.ts';
import { loadFenceChunkOverlay, markFenceChunk, renderFenceLowTier, type FenceChunkOverlay, type FenceLowTierRow } from '../eligibility/fence-overlay.ts';
import { withdrawalFenceBlocks } from '../facts/withdrawal-overlay.ts';
import { regionTrust } from './ingest.ts';
+import { assertRowsTile, generationBodyBytes } from './body-tiling.ts';
import { readBodyLedger, overlaySegmentText, type BodyLedger } from './segment-ledger.ts';
import { SEGMENTER_VERSION, type FactsSlot, type OutlineHeading, type StoredRegion } from './segmenter.ts';
import { overlaidPieces, projectionStaleError, projectSegment, type ProjectedPiece, type SegmentProjection } from './segment-projection.ts';
@@ -184,37 +185,20 @@ export async function openSegmentedBody(engine: BrainEngine, opts: { pageId: num
WHERE m.page_id=$1 AND m.staging_id IS NULL AND m.gen_from<=$2 AND (m.gen_to IS NULL OR m.gen_to>$2) ORDER BY m.seq`, [opts.pageId, generation]);
const slug = String(page.slug);
const sourceId = String(page.source_id);
- assertRowsTile(rows, slug, sourceId, opts.pin && generation === Number(page.body_generation) ? Number(page.body_bytes ?? 0) : null);
+ const bodyRows = rows.map(r => ({
+ seq: Number(r.seq), occurrenceId: Number(r.occurrence_id), region: r.region as BodyRegion, sha256: bytesOf(r.sha256),
+ byteStart: Number(r.byte_start), byteLen: Number(r.byte_len), lineStart: Number(r.line_start), lineCount: Number(r.line_count), staticProjBytes: Number(r.static_proj_bytes),
+ staticProjLines: Number(r.static_proj_lines), outlineCount: Number(r.outline_count), hasFacts: r.has_facts === true, hasDate: r.has_date === true,
+ }));
+ assertRowsTile(bodyRows, { slug, sourceId, total: await generationBodyBytes(engine, { id: opts.pageId, body_generation: page.body_generation, body_bytes: page.body_bytes }, generation) });
const ledger = opts.ledger ?? await readBodyLedger(engine, sourceId, slug);
return {
pageId: opts.pageId, sourceId, slug, generation, bodyBytes: Number(page.body_bytes ?? 0), bodyLines: Number(page.body_lines ?? 0), truthBytes: Number(page.truth_bytes ?? 0),
flags: (toJson(page.body_flags) ?? {}) as JsonObject, ledger, stale: Number(page.segmenter_version) !== SEGMENTER_VERSION, ...(opts.pin ? { pin: opts.pin } : {}),
- rows: rows.map(r => ({
- seq: Number(r.seq), occurrenceId: Number(r.occurrence_id), region: r.region as BodyRegion, sha256: bytesOf(r.sha256),
- byteStart: Number(r.byte_start), byteLen: Number(r.byte_len), lineStart: Number(r.line_start), lineCount: Number(r.line_count), staticProjBytes: Number(r.static_proj_bytes),
- staticProjLines: Number(r.static_proj_lines), outlineCount: Number(r.outline_count), hasFacts: r.has_facts === true, hasDate: r.has_date === true,
- })),
+ rows: bodyRows,
};
}
-/**
- * The generation's rows must run from byte 0 without a gap, and for a pinned (authorized) read of the live generation to
- * its body_bytes (`total`): a role that sees the page row but not its manifest rows, or rows missing, would otherwise
- * read as a short or empty body. A trusted unpinned reader sees every row, so it checks only that they start at 0 and
- * leave no gap.
- */
-function assertRowsTile(rows: Array<Record<string, unknown>>, slug: string, sourceId: string, total: number | null): void {
- let end = 0;
- for (const row of rows) {
- if (Number(row.byte_start) !== end) { end = -1; break; }
- end += Number(row.byte_len);
- }
- if (end >= 0 && (total === null ? rows.length > 0 : end === total)) return;
- throw opError('page_body_rows_unreadable', `Page ${slug} (source ${sourceId}): the segment rows readable here do not cover its ${total ?? 'stored'}-byte body, so nothing was read.`,
- "Give the role that reads the brain the same access to page_body_manifest and page_segment_texts it has to pages, then read again.",
- { detail: JSON.stringify({ rows: rows.length, covered_bytes: end >= 0 ? end : null, body_bytes: total }) });
-}
-
/** After a pinned read, before its text is returned: the page is still at the pin and still admits the caller. */
export async function confirmBodyPin(engine: BrainEngine, body: SegmentedBody): Promise<void> {
if (!body.pin) return;
diff --git a/src/core/page-body/segment-rewrite.ts b/src/core/page-body/segment-rewrite.ts
index 3b2e4caa7c..591ea9dce3 100644
--- a/src/core/page-body/segment-rewrite.ts
+++ b/src/core/page-body/segment-rewrite.ts
@@ -23,6 +23,7 @@ import { pageBodySegmentedError } from './page-shape.ts';
import { ContentHashStream } from './content-hash-stream.ts';
import type { StoredRegion } from './segmenter.ts';
import type { BodyRegion, JsonObject, ManifestRow } from './types.ts';
+import { assertGenerationTiles } from './body-tiling.ts';
/** Rewrites one fence (the text of a stored facts or takes region, markers included), given the body region holding it; called in body order. */
export type FenceTransform = (fence: string, at: { region: BodyRegion }) => Promise<string>;
@@ -152,6 +153,7 @@ export async function rewriteLiveSegmentedFences(tx: BrainEngine, pageId: number
if (page?.body_storage !== 'segmented') return null;
const sourceId = page.source_id, slug = page.slug, frontmatter = page.frontmatter ?? {};
const rows = await tx.readManifest(pageId);
+ await assertGenerationTiles(tx, pageId, undefined, rows);
const units = await changedUnits(tx, sourceId, rows, transform);
if (!units.length) return null;
const generation = Number(page.body_generation);
@@ -189,6 +191,7 @@ export async function rewriteSegmentedGeneration(tx: BrainEngine, pageId: number
if (!page) return null;
const sourceId = page.source_id;
const rows = await tx.readManifest(pageId, { generation });
+ await assertGenerationTiles(tx, pageId, generation, rows);
const units = await changedUnits(tx, sourceId, rows, transform);
if (!units.length) return null;
// Rebuilding rows in place is for retained generations only: the live one changes by a flip (rewriteLiveSegmentedFences),
@@ -224,6 +227,7 @@ export async function rewriteSegmentedGeneration(tx: BrainEngine, pageId: number
export async function rewrittenContentHash(engine: BrainEngine, pageId: number, sourceId: string, generation: number, transform: FenceTransform,
meta: { title: unknown; type: unknown; frontmatter: Record<string, unknown>; tags: string[] }): Promise<string | null> {
const rows = await engine.readManifest(pageId, { generation });
+ await assertGenerationTiles(engine, pageId, generation, rows);
const units = await changedUnits(engine, sourceId, rows, transform);
if (!units.length) return null;
const hash = ContentHashStream.begin(meta);
diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.ts
index e4413db084..2126a88ecd 100644
--- a/src/core/timeline-extract.ts
+++ b/src/core/timeline-extract.ts
@@ -16,6 +16,7 @@ import { isDatedTimelineLine, supersededInlineCitationEntries } from './timeline
import type { BrainEngine } from './engine.ts';
import { firstMaterializedMarkerIndex } from './timeline-marker.ts';
import { BLOCK_MAX_BYTES, blockTooLargeError, bodyBlocks, detachedValue, segmentedPassWork } from './page-body/segment-blocks.ts';
+import { assertGenerationTiles } from './page-body/body-tiling.ts';
export interface ExtractedTimelineEntry {
slug: string;
@@ -166,9 +167,10 @@ export async function segmentedTimelineText(engine: Pick<BrainEngine, 'executeRa
* read from the generation's manifest rows, so a page demoted inline since still yields its segmented versions.
* Counts its bytes and units in segmentedPassWork.
*/
-async function* retainedGenerationBlocks(engine: Pick<BrainEngine, 'readManifest' | 'readSegmentTexts'>,
+async function* retainedGenerationBlocks(engine: Pick<BrainEngine, 'executeRaw' | 'readManifest' | 'readSegmentTexts'>,
page: { id: number; slug: string; sourceId: string }, generation: number): AsyncIterable<string> {
const rows = await engine.readManifest(page.id, { generation });
+ await assertGenerationTiles(engine, page.id, generation, rows);
for (const [n, region] of (['truth', 'timeline'] as const).entries()) {
if (n > 0) yield '\n';
const own = rows.filter(row => row.region === region);
diff --git a/test/large-pages/pinned-segmented-reads.test.ts b/test/large-pages/pinned-segmented-reads.test.ts
index f9511f1982..47275fd131 100644
--- a/test/large-pages/pinned-segmented-reads.test.ts
+++ b/test/large-pages/pinned-segmented-reads.test.ts
@@ -33,6 +33,14 @@ import { readCardIdentity } from '../../src/core/verbs/entity-card-identity.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
import { testBackends } from '../helpers/test-backends.ts';
import { importSegmented } from '../helpers/segmented-privacy-fixture.ts';
+import { existsSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runExport } from '../../src/commands/export.ts';
+import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';
+import { storedBodyDigests } from '../../src/core/page-body/body-digests.ts';
+import { readBodyLedger } from '../../src/core/page-body/segment-ledger.ts';
+import { withEnv } from '../helpers/with-env.ts';
const SECRET = ['zz', 'secret', 'pinned', 'token'].join('');
const NEEDLE = 'zzpinneedle';
@@ -95,6 +103,19 @@ async function raced(seam: 'open' | 'read', flip: () => Promise<void>, read: ()
}
}
+const home = mkdtempSync(join(tmpdir(), 'gbrain-pinned-reads-'));
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+/** `gbrain export --dir out`; a non-zero exit throws with what it printed. */
+async function quietExport(out: string): Promise<void> {
+ const { log, error } = console;
+ const exit = process.exit;
+ const messages: string[] = [];
+ console.log = console.error = (...args: unknown[]) => { messages.push(args.join(' ')); };
+ process.exit = ((code: number) => { throw new Error(`EXIT:${code} ${messages.join('\n')}`); }) as never;
+ try { await withEnv({ GBRAIN_HOME: home }, () => runExport(engine, ['--dir', out])); } finally { console.log = log; console.error = error; process.exit = exit; }
+}
+
const refused = (outcome: Outcome) => ({ ok: outcome.ok, code: outcome.code, leaked: outcome.text.includes(SECRET) });
async function freshReadIsMissing(slug: string) {
@@ -218,6 +239,22 @@ for (const kind of testBackends()) {
expect(outcome).toBe('page_body_rows_unreadable');
}, 240_000);
+ test('a live manifest that lost its trailing row: export, materialize and the stored body digest refuse, never a short body', async () => {
+ const { slug, id } = await page();
+ const intact = join(home, `intact-${kind}`);
+ await quietExport(intact);
+ expect(existsSync(join(intact, `${slug}.md`))).toBe(true);
+ await engine.executeRaw(`DELETE FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NULL AND gen_to IS NULL
+ AND seq=(SELECT max(seq) FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NULL AND gen_to IS NULL)`, [id]);
+ const short = join(home, `short-${kind}`);
+ const exported = await quietExport(short).then(() => 'ok', (e: Error) => e.message);
+ expect(exported).toContain(`Page ${slug} (source default): the segment rows readable here do not cover`);
+ expect(existsSync(join(short, `${slug}.md`))).toBe(false);
+ const code = (e: { canonical?: string; code?: string }) => e.canonical ?? e.code;
+ expect(await materializeSegmentedBody(engine, id, 'default').then(() => 'ok', code)).toBe('page_body_rows_unreadable');
+ expect(await storedBodyDigests(engine, id, await readBodyLedger(engine, 'default', slug)).then(() => 'ok', code)).toBe('page_body_rows_unreadable');
+ }, 240_000);
+
// N8: get_versions tells a remote caller a segmented version's projected size, never its stored body_bytes.
test('remote get_versions reports a segmented version by its read projection size, not the stored body_bytes', async () => {
const slug = `notes/pinned-versions-${++n}`;
diff --git a/test/large-pages/segmented-derived-work.test.ts b/test/large-pages/segmented-derived-work.test.ts
index 776023f217..9fd7f955ac 100644
--- a/test/large-pages/segmented-derived-work.test.ts
+++ b/test/large-pages/segmented-derived-work.test.ts
@@ -7,7 +7,8 @@
* commits with a pending chronicle decision; the unmanaged discovery never
* reads a segmented page as `too_short` (which would retire its events);
* execution judges a segmented page within the single-string ceiling and,
- * since PR 2 (lane 2e, full-pass mode), one above it too, from its lead;
+ * since PR 2 (lane 2e, full-pass mode), one above it too, from its lead
+ * (segmented-real-size.slow.test.ts, at that size);
* backfill counts segmented pages as eligible; a remote write's `links`
* effect on a segmented page commits its mention edges, read block by
* block; the facts backstop queues for a segmented page and a facts-absorb
@@ -187,21 +188,6 @@ describe('Life Chronicle on segmented pages', () => {
}
}, 300_000);
- test('execution judges a segmented page over the single-string ceiling from its lead, without materializing it', async () => {
- for (const engine of engines) {
- await importFromContent(engine, 'meetings/segmented-offsite', meeting('Offsite'), { sourceId: 'default', noEmbed: true });
- const page = await storage(engine, 'meetings/segmented-offsite');
- await upsertChronicleRow(engine, { sourceId: 'default', pageId: page.id, contentHash: page.content_hash, slug: 'meetings/segmented-offsite',
- state: 'pending', reason: null, trigger: 'auto', nextAttemptAt: null });
- await engine.executeRaw('UPDATE pages SET body_bytes=$2 WHERE id=$1', [page.id, PAGE_MAX_BYTES + 1]);
- const judged: string[] = [];
- await runPhaseChronicle(engine, { judge: async (input) => { judged.push(input.body); return { events: [] }; } });
- expect(judged).toHaveLength(1);
- expect(judged[0]!.slice(0, 200)).toBe(body.slice(0, 200));
- expect(await ledger(engine)).toEqual([{ slug: 'meetings/segmented-offsite', state: 'extracted', reason: 'no_events', scheduled: false }]);
- }
- }, 300_000);
-
test('backfill counts a segmented chronicle page as eligible', async () => {
for (const engine of engines) {
await importFromContent(engine, 'meetings/segmented-review', meeting('Review'), { sourceId: 'default', noEmbed: true });
diff --git a/test/large-pages/segmented-real-size.slow.test.ts b/test/large-pages/segmented-real-size.slow.test.ts
new file mode 100644
index 0000000000..0744e1653a
--- /dev/null
+++ b/test/large-pages/segmented-real-size.slow.test.ts
@@ -0,0 +1,114 @@
+/**
+ * Wave B PR 2 fix lane F (N5): the two checks that need a stored segmented page larger than a write or read limit,
+ * on a real page of that size. Moved here from segmented-switch.test.ts and segmented-derived-work.test.ts, which
+ * faked the size by raising pages.body_bytes; a body whose manifest rows do not reach body_bytes now refuses
+ * (page_body_rows_unreadable), as a page that lost rows must.
+ *
+ * 1. Protects: a stored segmented page over the 32 MiB inline export limit still exports while the switch is off;
+ * Life Chronicle execution judges a segmented page over the single-string ceiling (PAGE_MAX_BYTES) from its lead,
+ * without materializing it.
+ * 2. Fails when: export sizes stored segmented pages by the write limit, or chronicle execution skips or materializes
+ * a segmented page over the ceiling.
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromFile } from '../../src/core/import-file.ts';
+import { readPageBodyPolicy, _resetSegmentedWriterGateForTests } from '../../src/core/page-body/limits.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { upsertChronicleRow } from '../../src/core/chronicle/ledger.ts';
+import { runPhaseChronicle } from '../../src/core/cycle/chronicle.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { runExport } from '../../src/commands/export.ts';
+import { conversationBody, conversationPage } from '../helpers/conversation-page.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const MiB = 1024 * 1024;
+const today = new Date().toISOString().slice(0, 10);
+const body = conversationBody(1_200_000, { seed: 61 });
+const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-real-size-'));
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+async function quietExport(engine: BrainEngine, out: string): Promise<void> {
+ const { log, error } = console;
+ const exit = process.exit;
+ const messages: string[] = [];
+ console.log = console.error = (...args: unknown[]) => { messages.push(args.join(' ')); };
+ process.exit = ((code: number) => { throw new Error(`EXIT:${code} ${messages.join('\n')}`); }) as never;
+ try { await runExport(engine, ['--dir', out]); } finally { console.log = log; console.error = error; process.exit = exit; }
+}
+
+async function storage(engine: BrainEngine, slug: string): Promise<{ id: number; body_storage: string; content_hash: string }> {
+ const [row] = await engine.executeRaw<{ id: number; body_storage: string; content_hash: string }>(
+ "SELECT id, body_storage, content_hash FROM pages WHERE source_id='default' AND slug=$1", [slug]);
+ return { ...row!, id: Number(row!.id) };
+}
+
+const ledger = (engine: BrainEngine) => engine.executeRaw<{ slug: string; state: string; reason: string | null; scheduled: boolean }>(
+ 'SELECT slug, state, reason, next_attempt_at IS NOT NULL AS scheduled FROM chronicle_page_state ORDER BY slug, decided_at');
+
+/** A Markdown file of \`head\` then conversation text to about \`bytes\`, written in pieces; imported streamed (switch on). */
+async function importLarge(engine: BrainEngine, slug: string, head: string, bytes: number, seed: number) {
+ const file = join(home, `${slug}-${engine.kind}.md`);
+ mkdirSync(join(file, '..'), { recursive: true });
+ writeFileSync(file, head);
+ for (let written = Buffer.byteLength(head), part = 0; written < bytes; part++) {
+ const piece = `\n\n${conversationBody(Math.min(8 * MiB, bytes - written), { seed: seed + part })}`;
+ appendFileSync(file, piece);
+ written += Buffer.byteLength(piece);
+ }
+ appendFileSync(file, '\n');
+ return importFromFile(engine, file, `${slug}.md`, { noEmbed: true, sourceId: 'default', bodyPolicy: await readPageBodyPolicy(engine) });
+}
+
+for (const kind of testBackends()) {
+ describe(`segmented pages over a size limit, at that size (${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(); }
+ _resetSegmentedWriterGateForTests();
+ }, 120_000);
+ afterAll(async () => withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); await close(); }));
+
+ test('a stored segmented page over the 32 MiB inline export limit still exports while the switch is off', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const content = conversationPage(40 * MiB, { seed: 61 });
+ const file = join(home, `stored-${kind}.md`);
+ writeFileSync(file, content);
+ expect((await importFromFile(engine, file, 'notes/stored.md', { noEmbed: true, sourceId: 'default', bodyPolicy: await readPageBodyPolicy(engine) })).status).toBe('imported');
+ expect((await storage(engine, 'notes/stored')).body_storage).toBe('segmented');
+ await engine.setConfig('pages.segmented_storage', 'off');
+ const out = join(home, `export-${kind}`);
+ await quietExport(engine, out);
+ expect(readFileSync(join(out, 'notes/stored.md'), 'utf8')).toContain(content.trimEnd().slice(-120));
+ }), 900_000);
+
+ test('execution judges a segmented page over the single-string ceiling from its lead, without materializing it', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ await engine.setConfig('chronicle.auto_settle_seconds', '0');
+ await engine.setConfig('chronicle.activated_at', new Date(Date.now() - 60_000).toISOString());
+ const head = `---\ntype: meeting\ntitle: Offsite\ndate: ${today}\n---\n\n${body}`;
+ expect((await importLarge(engine, 'meetings/segmented-offsite', head, PAGE_MAX_BYTES + MiB, 62)).status).toBe('imported');
+ const page = await storage(engine, 'meetings/segmented-offsite');
+ expect(page.body_storage).toBe('segmented');
+ await engine.executeRaw('DELETE FROM chronicle_page_state');
+ await upsertChronicleRow(engine, { sourceId: 'default', pageId: page.id, contentHash: page.content_hash, slug: 'meetings/segmented-offsite',
+ state: 'pending', reason: null, trigger: 'auto', nextAttemptAt: null });
+ const [{ body_bytes }] = await engine.executeRaw<{ body_bytes: number }>('SELECT body_bytes FROM pages WHERE id=$1', [page.id]);
+ expect(Number(body_bytes)).toBeGreaterThan(PAGE_MAX_BYTES);
+ const judged: string[] = [];
+ await runPhaseChronicle(engine, { judge: async (input) => { judged.push(input.body); return { events: [] }; } });
+ expect(judged).toHaveLength(1);
+ expect(judged[0]!.slice(0, 200)).toBe(body.slice(0, 200));
+ expect(await ledger(engine)).toEqual([{ slug: 'meetings/segmented-offsite', state: 'extracted', reason: 'no_events', scheduled: false }]);
+ }), 900_000);
+ });
+}
diff --git a/test/large-pages/segmented-switch.test.ts b/test/large-pages/segmented-switch.test.ts
index f4404562ad..337f39209b 100644
--- a/test/large-pages/segmented-switch.test.ts
+++ b/test/large-pages/segmented-switch.test.ts
@@ -6,7 +6,7 @@
* off, and doctor offers the switch; a writer older than SEGMENTED_WRITER_FLOOR (or unstamped) seen in the last seven days keeps writes
* inline, even with an explicit `on`, and doctor `segmented_storage` names it with an upgrade fix; once that
* observation is gone the next write promotes; an explicit `off` keeps pages inline and reports it as a choice;
- * a stored segmented page over 32 MiB still exports while the switch is off. Every write the gate sees must carry the
+ * (a stored segmented page over 32 MiB exporting while the switch is off is in segmented-real-size.slow.test.ts). Every write the gate sees must carry the
* segment-reader mark (v251): a release at exactly the floor version without it, an older binary's import or sync
* 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
@@ -18,7 +18,7 @@
*/
import { afterAll, beforeAll, beforeEach, describe, expect, setSystemTime, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
-import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../../src/core/engine.ts';
@@ -32,7 +32,6 @@ import { VERSION } from '../../src/version.ts';
import { localHostId } from '../../src/core/persistence/identity.ts';
import { segmentedStorageCheck } from '../../src/commands/doctor/checks/segmented-storage.ts';
import { startConsumerHeartbeat } from '../../src/core/persistence/consumer-heartbeat.ts';
-import { runExport } from '../../src/commands/export.ts';
import { conversationPage } from '../helpers/conversation-page.ts';
import { editRequest, freshBrainFactory, requestFixture } from '../helpers/persistence-request-fixture.ts';
import { testBackends } from '../helpers/test-backends.ts';
@@ -40,15 +39,6 @@ import { withEnv } from '../helpers/with-env.ts';
const content = conversationPage(2 * 1024 * 1024, { seed: 61 });
-async function quietExport(engine: BrainEngine, out: string): Promise<void> {
- const { log, error } = console;
- const exit = process.exit;
- const messages: string[] = [];
- console.log = console.error = (...args: unknown[]) => { messages.push(args.join(' ')); };
- process.exit = ((code: number) => { throw new Error(`EXIT:${code} ${messages.join('\n')}`); }) as never;
- try { await runExport(engine, ['--dir', out]); } finally { console.log = log; console.error = error; process.exit = exit; }
-}
-
async function storage(engine: BrainEngine, slug: string): Promise<string | undefined> {
return (await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug=$1', [slug]))[0]?.body_storage;
}
@@ -124,17 +114,6 @@ for (const kind of testBackends()) {
expect(await segmentedStorageCheck(engine)).toMatchObject({ status: 'ok', details: { effective: 'on' } });
}), 120_000);
- test('a stored segmented page over the 32 MiB inline export limit still exports while the switch is off', async () => {
- await engine.setConfig('pages.segmented_storage', 'on');
- expect((await importFromContent(engine, 'notes/stored', content, { noEmbed: true })).status).toBe('imported');
- expect(await storage(engine, 'notes/stored')).toBe('segmented');
- await engine.executeRaw('UPDATE pages SET body_bytes=$2 WHERE slug=$1', ['notes/stored', 40 * 1024 * 1024]);
- await engine.setConfig('pages.segmented_storage', 'off');
- const out = join(home, `export-${kind}`);
- await quietExport(engine, out);
- expect(readFileSync(join(out, 'notes/stored.md'), 'utf8')).toContain(content.trimEnd().slice(-120));
- }, 120_000);
-
/** The gate as a write reads it, after the per-engine cache is dropped. */
const segmentedNow = async (e: BrainEngine = engine) => { _resetSegmentedWriterGateForTests(); return (await readPageBodyPolicy(e)).segmented; };
const blockersNow = async () => (await segmentedStorageCheck(engine)).details!.blockers as Array<{ role: string; principal: string; version: string; segment_reader: boolean }>;
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 2d528f6c75..b18e5e516b 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -114,6 +114,7 @@ test/large-pages/segmented-loser-chunks.test.ts
test/large-pages/segmented-maintenance-commands.test.ts
test/large-pages/segmented-prior-view.test.ts
test/large-pages/segmented-read-refusals.test.ts
+test/large-pages/segmented-real-size.slow.test.ts
test/large-pages/segmented-remember-refusal.test.ts
test/large-pages/segmented-repair-scans.test.ts
test/large-pages/segmented-search-dedup.test.ts