Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge capy/large-pages-segmented-reads (b75a69a6d: master v0.60.264.0, lanes I and F) into capy/large-pages-fixH

garrytan20f9919c81fa
diff --cc src/core/behavior-change-notice.ts
index 1d520ddd09,40ba7f4289..ba60c7c935
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@@ -660,15 -718,14 +718,16 @@@ export const BEHAVIOR_CHANGES: Readonly
{ since: 'TBD', text: '`delete_page` (soft and `purge: true`), `restore_page`, `gbrain delete` and `gbrain restore` now work on a page over 24 MiB on a source backed by files: the file is compared with the page by digest, streamed, and a file edited on disk still refuses as before. Restoring such a page clears its deletion without re-importing it and writes its file back from the database; the 25 MiB pre-push scan cap on written files still applies, and a core page or an external_untrusted writer still refuses.' },
{ since: 'TBD', text: 'A write that stores a page in segments says in its receipt whether search sees it: `searchable: true` when it commits (every new page up to 4 MiB and every rewrite), or `searchable: "pending"` for a larger new page while its chunks are built after commit, with `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`get_write_request`) until it says `searchable: true`. A new page up to 4 MiB was previously searchable only once a post-commit build finished.' },
{ since: 'TBD', text: '`gbrain projections drain` now builds pages stored in segments whose post-commit build never ran or died, skipping one another process is still building (claim renewed within 60 s), so a brain with no resident writer can make a large new page searchable. A pending receipt\'s `searchable_fix` names it as the fallback after the re-read wait, and doctor `text_projection_readiness` counts such pages (`segmented_pending`) and points to it.' },
- { since: 'TBD', text: 'The maintenance sweep (`gbrain sweep`, the serve idle sweep) links a page stored in segments on its own after the inline pages, smallest first, and stops reading one at its time budget; a page that does not fit is skipped with reason `budget_deferred:segmented_page`, left for `gbrain extract --stale`, and later sweeps in the same process skip it (`segmented_page_deferred`) until it changes. Derived passes over a page stored in segments no longer refuse a page of short lines or dated bullets over 8 MiB with `page_body_segmented`.' },
+ { since: 'TBD', text: 'The maintenance sweep (`gbrain sweep`, the serve idle sweep) links a page stored in segments on its own after the inline pages, smallest first, and stops reading one at its time budget; a page that does not fit, though it started with at least half of the sweep\'s budget, is skipped with reason `budget_deferred:segmented_page`, left for `gbrain extract --stale`, and later sweeps in the same process leave it out (`segmented_page_deferred`) until it changes, so the pages behind it are still reached; one that started with less is left for the next sweep (`budget_exhausted:links_timeline`). Derived passes over a page stored in segments, timeline retraction over its earlier versions (the timeline orphan prune, `gbrain extract timeline --source db` and doctor `timeline_orphans`) included, no longer refuse a page of short lines or dated bullets over 8 MiB with `page_body_segmented`.' },
- { since: 'TBD', text: 'Deleting and restoring a page over 24 MiB on a source backed by files is now lossless up to the page ceiling (`pages.max_bytes`). `restore_page` and `gbrain restore` write the file back byte for byte by streaming it from the stored segments into its staging file, including a file over the 25 MiB pre-push scan cap (the restore used to refuse with `request_too_large`, so the file a soft delete had removed could not be put back on disk). A delete or restore that replaces or removes a file over 24 MiB keeps the prior file as a staged copy beside it (a hidden `.<sha256>.tmp.before-<uuid>` file) until the write commits, named in its recovery record by path and SHA-256 instead of embedded in it: the record stays a few hundred bytes, the recovery reservation counts the file once (a 90 MiB delete used to need 283 MB against the 256 MiB `persistence.limits.worktree_recovery_bytes` budget and was refused), and a crash between removing the file and committing renames the copy back. A page whose file plus its staging does not fit that budget (a Postgres page near the 256 MiB ceiling) is still refused with `request_too_large` before anything is touched. `gbrain repair stuck-recovery` refuses such a recovery with `recovery_large_file_unsupported` (resolve it by hand; the resident writer finishes it).' },
+ { since: 'TBD', text: 'Deleting and restoring a page over 24 MiB on a source backed by files is now lossless up to the page ceiling (`pages.max_bytes`). `restore_page` and `gbrain restore` write the file back byte for byte by streaming it from the stored segments into its staging file, including a file over the 25 MiB pre-push scan cap (the restore used to refuse with `request_too_large`, so the file a soft delete had removed could not be put back on disk). A delete or restore that replaces or removes a file over 24 MiB keeps the prior file as a staged copy beside it (a hidden `.<sha256>.tmp.before-<uuid>` file) until the write commits, named in its recovery record by path and SHA-256 instead of embedded in it: the record stays a few hundred bytes, the recovery reservation counts the file once (a 90 MiB delete used to need 283 MB against the 256 MiB `persistence.limits.worktree_recovery_bytes` budget and was refused), and a crash between removing the file and committing renames the copy back. A page whose file plus its staging does not fit that budget (a Postgres page near the 256 MiB ceiling) is still refused with `request_too_large` before anything is touched. The copy is written under a temporary name and renamed once it is complete and flushed, so a crash while it is being copied leaves nothing the recovery waits on: recovery removes a copy that never got its name, and drops a copy that is incomplete while the file still holds its prior bytes. `gbrain repair stuck-recovery` lists such a recovery as refused with `recovery_large_file_unsupported` (resolve it by hand; the resident writer finishes it) and still previews the other recoveries of the source.' },
{ since: 'TBD', text: 'A page purge (`delete_page` with `purge: true`, `gbrain delete --purge` and the 72-hour hard delete of soft-deleted pages) of a page stored in segments no longer breaks another page\'s write that is still being prepared with some of the same text: the purge keeps exactly the segment texts such a write staged, and still deletes every other text only the purged page used. `restore_page` of a page over 24 MiB whose old chunks were still waiting to be removed returns `projection: "pending"` and makes the page searchable once they are gone, instead of showing the old text in search.' },
{ since: 'TBD', text: 'Chunks of a page stored in segments keep a Markdown heading with the text after it, so a section appended after a full last chunk re-embeds only its own chunk (was two). Inline pages chunk as before.' },
{ 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: '`gbrain get` against a remote brain of a page too large for one response holds one window in memory instead of the whole page: the windows wait in a temp file readable only by you in the system temp directory (`TMPDIR`), as large as the page and removed when the command ends, until their size and sha256 verify. Nothing prints before they do, as before. `--json` still refuses a page over 24 MiB.' },
+ { since: 'TBD', text: 'A streamed `gbrain import` or `gbrain sync` of a Markdown file over 24 MiB (`pages.segmented_storage` on) checks every block it stores against the sha256 its first read of the file recorded. A file rewritten during the import that keeps its size and modification time is now held as `file_too_large` ("the file changed while it was imported (import it again)") instead of being stored as the first version\'s frontmatter over the second version\'s body.' },
+ { 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 --cc src/core/page-body/segment-blocks.ts
index a46e46727d,ce7680a0f5..c394abd031
--- a/src/core/page-body/segment-blocks.ts
+++ b/src/core/page-body/segment-blocks.ts
@@@ -22,9 -22,8 +22,10 @@@
import type { BrainEngine } from '../engine.ts';
import { opError } from '../ops/contract.ts';
import { SEGMENT_MAX_BYTES } from './limits.ts';
- import { bodyRowWork, openSegmentedBody, readBodyRange, trustedSegments } from './read-range.ts';
-import { bodyRowWork, confirmBodyPin, openSegmentedBody, readBodyRange, trustedSegments, type BodyPin, type TrustedSegment } from './read-range.ts';
-import { cutBlocked } from './segmenter.ts';
++import { bodyRowWork, confirmBodyPin, openSegmentedBody, readBodyRange, trustedSegments, type BodyPin } from './read-range.ts';
+import { ledgerApplies } from './segment-ledger.ts';
+import { cutBlocked, SEGMENTER_VERSION } from './segmenter.ts';
++import { assertGenerationTiles } from './body-tiling.ts';
import { readEntryState } from './entry-state.ts';
import type { BodyRegion } from './types.ts';
@@@ -186,77 -130,36 +187,79 @@@ export async function* bodyBlocks(engin
let j = i;
while (j + 1 < rows.length && forced.has(rows[j]!.seq)) j++;
bodyRowWork.visits += j - i + 1;
- if (opts.want && !opts.want({ seqs: rows.slice(i, j + 1).map(row => row.seq), first: i === 0 })) {
+ const run = rows.slice(i, j + 1);
+ i = j + 1;
+ if (opts.want && !opts.want({ seqs: run.map(row => row.seq), first: run[0] === rows[0] })) {
at = NaN;
- i = j + 1;
continue;
}
- let parts: Buffer[] = [];
- let start = rows[i]!.byteStart;
- let previous: Uint8Array | null = null;
- const flush = (end: number): BodyBlock => {
- const text = Buffer.concat(parts).toString('utf8');
- collect(end - start);
- segmentedPassWork.bytes += end - start;
- segmentedPassWork.blocks += text.length;
+ const stop = opts.stop;
+ const read: Array<{ sha256: Uint8Array; entryState: unknown }> = [];
+ const segments = async function* (): AsyncIterable<CutSegment> {
+ for await (const seg of trustedSegments(engine, body, run, stop && (() => { if (stop()) throw new BodyReadStopped(page.slug); }))) {
+ bodyRowWork.visits++;
+ read.push({ sha256: seg.row.sha256, entryState: seg.entryState });
+ yield { byteStart: seg.row.byteStart, byteLen: seg.row.byteLen, raw: seg.raw, entryState: seg.entryState, texts: seg.pieces.map(piece => piece.text) };
+ }
+ };
+ for await (const text of runBlocks(segments(), run[0]!.byteStart, { slug: page.slug, sourceId: body.sourceId }, body.stale, collect)) {
const block = { region, text, at };
at += text.length;
- parts = [];
- start = end;
- return block;
- };
- const stop = opts.stop;
- for await (const seg of trustedSegments(engine, body, rows.slice(i, j + 1), stop && (() => { if (stop()) throw new BodyReadStopped(page.slug); }))) {
- bodyRowWork.visits++;
- if (previous && freshAfterForcedCut(previous, seg, body.stale)) yield flush(seg.row.byteStart);
- const end = seg.row.byteStart + seg.row.byteLen;
- if (end - start > BLOCK_MAX_BYTES) throw blockTooLargeError(page.slug, body.sourceId, end - start);
- for (const piece of seg.pieces) parts.push(Buffer.from(piece.text, 'utf8'));
- previous = seg.raw;
+ yield block;
}
- yield flush(rows[j]!.byteStart + rows[j]!.byteLen);
+ runKeys?.add(runKey(region, body.stale, read));
+ }
+ }
+}
+
+/**
+ * @internal Retained-generation reads, for the bounded-work test: bytes of the runs a retained generation read
+ * (`bytes`) and of the runs it skipped because a run with the same key was already read (`skipped`). Counts, not time.
+ */
+export const retainedGenerationWork = { bytes: 0, skipped: 0 };
+
+/**
+ * The stored text of a retained segmented generation (a segmented page_versions row references a generation; its body
+ * columns are NULL) as `${compiled_truth}\n${timeline}`, cut into blocks as bodyBlocks cuts the live body (runBlocks),
- * from the generation's manifest rows, so a page demoted inline since still yields its segmented versions. A run whose
++ * from the generation's manifest rows, so a page demoted inline since still yields its segmented versions. Rows that do
++ * not tile the version's body_bytes refuse with page_body_rows_unreadable (body-tiling.ts) before any text is read. A run whose
+ * key is in `seen` (a run of the live body read without an overlay, or of a generation read before) is skipped, and
+ * each run read is added to it. `stop` is asked before each segment read, as in bodyBlocks.
+ */
+export async function* retainedGenerationBlocks(engine: Pick<BrainEngine, 'executeRaw' | 'readManifest' | 'readSegmentTexts'>,
+ page: { id: number; slug: string; sourceId: string }, generation: number,
+ opts: { seen?: Set<string>; stop?: () => boolean } = {}): AsyncIterable<string> {
+ const rows = await engine.readManifest(page.id, { generation });
++ await assertGenerationTiles(engine, page.id, generation, rows);
+ const [state] = await engine.executeRaw<{ segmenter_version: number | null }>('SELECT segmenter_version FROM pages WHERE id=$1', [page.id]);
+ const stale = Number(state?.segmenter_version) !== SEGMENTER_VERSION;
+ const collect = readGarbageCollector();
+ for (const [n, region] of (['truth', 'timeline'] as const).entries()) {
+ if (n > 0) yield '\n';
+ const own = rows.filter(row => row.region === region);
+ for (let i = 0; i < own.length;) {
+ let j = i;
+ while (j + 1 < own.length && own[j]!.cutKind === 'forced') j++;
+ const run = own.slice(i, j + 1);
i = j + 1;
+ const bytes = run.reduce((sum, row) => sum + row.byteLen, 0);
+ const key = runKey(region, stale, run);
+ if (opts.seen?.has(key)) {
+ retainedGenerationWork.skipped += bytes;
+ continue;
+ }
+ opts.seen?.add(key);
+ retainedGenerationWork.bytes += bytes;
+ const segments = async function* (): AsyncIterable<CutSegment> {
+ for (const row of run) {
+ if (opts.stop?.()) throw new BodyReadStopped(page.slug);
+ const hex = Buffer.from(row.sha256).toString('hex');
+ const raw = (await engine.readSegmentTexts(page.sourceId, [row.sha256])).get(hex);
+ if (raw === undefined) throw new Error(`Segment text of page ${page.id} generation ${generation} is missing.`);
+ yield { byteStart: row.byteStart, byteLen: row.byteLen, raw, entryState: toJson(row.entryState), texts: [utf8.decode(raw)] };
+ }
+ };
+ yield* runBlocks(segments(), run[0]!.byteStart, page, stale, collect);
}
}
}
diff --cc src/core/timeline-extract.ts
index 598aa617b7,25a232a1e7..5a400b375c
--- a/src/core/timeline-extract.ts
+++ b/src/core/timeline-extract.ts
@@@ -313,24 -225,31 +313,35 @@@ export async function retractRemovedTim
const versions = await engine.executeRaw<{ compiled_truth: string | null; timeline: string | null; body_storage: string; page_id: number; generation: number | null }>(
`SELECT DISTINCT v.compiled_truth, v.timeline, v.body_storage, v.page_id, v.body_generation AS generation FROM page_versions v JOIN pages p ON p.id = v.page_id
WHERE p.source_id = $1 AND p.slug = $2`, [sourceId, slug]);
+ const wanted = new Set(extra.map(tupleKey));
const produced = new Set<string>();
// #6226: rows the older citation reading filed for this text or a stored version.
- const superseded = new Set(typeof current === 'string' ? supersededCitationTimeline(current).map(tupleKey) : current.superseded);
+ const superseded = new Set(typeof current === 'string' ? supersededCitationTimeline(current).map(tupleKey)
+ : [...wanted].filter(key => current.superseded.has(key)));
const addText = (text: string) => {
- for (const key of markdownTimelineKeys(text, slug)) produced.add(key);
- for (const entry of supersededCitationTimeline(text)) superseded.add(tupleKey(entry));
+ for (const key of markdownTimelineKeys(text, slug)) if (wanted.has(key)) produced.add(key);
+ for (const entry of supersededCitationTimeline(text)) if (wanted.has(tupleKey(entry))) superseded.add(tupleKey(entry));
};
+ const seen = new Set(typeof current === 'string' ? [] : current.runs ?? []);
for (const version of versions) {
if (version.body_storage !== 'segmented') { addText(`${version.compiled_truth}\n${version.timeline ?? ''}`); continue; }
- for await (const block of retainedGenerationBlocks(engine, { id: Number(version.page_id), slug, sourceId }, Number(version.generation))) addText(block);
+ for await (const block of retainedGenerationBlocks(engine, { id: Number(version.page_id), slug, sourceId }, Number(version.generation),
+ { seen, ...(opts.stop ? { stop: opts.stop } : {}) })) addText(block);
}
- const orphans = extra.filter(row => produced.has(tupleKey(row)) || (superseded.has(tupleKey(row)) && hasExtractorDetail(row)))
+ const found = extra.filter(row => produced.has(tupleKey(row)) || (superseded.has(tupleKey(row)) && hasExtractorDetail(row)))
.map(({ detail: _detail, ...row }) => row);
- if (!orphans.length || opts.dryRun) return orphans;
+ if (!found.length) return [];
+ // W1 #6783 §12 (a): a row more trusted than the page's restatement, or held by an open contest, stays; the owner decides.
+ const [{ contestHeldRows, heldRows }, { derivedWriteTrust }, { storedTrustTier }] = await Promise.all([
+ import('./trust/fence-guard.ts'), import('./trust/taint.ts'), import('./trust/tier.ts')]);
+ const [page] = await engine.executeRaw<{ id: number; trust_tier: string | null }>('SELECT id, trust_tier FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, slug]);
+ const writer = derivedWriteTrust({ channel: 'derive:timeline', inputs: page ? [{ table: 'pages', id: Number(page.id), tier: storedTrustTier(page.trust_tier) }] : [], projection: true }).tier;
+ const held = await heldRows(engine as BrainEngine, 'timeline_entries', found.map(row => Number(row.id)), { writer, pending: true });
+ const orphans = found.filter(row => !held.has(Number(row.id)));
+ if (opts.dryRun) return orphans;
+ await contestHeldRows(engine as BrainEngine, { sourceId, slug, table: 'timeline_entries', proposer: 'timeline_reconcile', writer,
+ rows: [...held].map(([id, tier]) => ({ id, tier, change: 'removed' as const })) });
+ if (!orphans.length) return orphans;
await engine.executeRaw(
`DELETE FROM timeline_entries WHERE id IN (SELECT jsonb_array_elements_text($1::text::jsonb)::int)`,
[JSON.stringify(orphans.map(row => row.id))]);
diff --cc test/postgres-unit-arms.txt
index a0d85597b4,d6dc61be9a..9e97e726ff
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@@ -113,9 -118,9 +119,10 @@@ test/large-pages/segmented-loser-chunks
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-retained-blocks.test.ts
test/large-pages/segmented-search-dedup.test.ts
test/large-pages/segmented-shrink-below-ceiling.test.ts
test/large-pages/segmented-storage-visibility.test.ts