Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
large pages: oversized backfill sizes and rewrites segmented pages
garrytan56373cd83d3f
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex f63ea62911..35c0afc7dd 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -35,7 +35,7 @@ The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cy- `src/core/page-size-policy.ts` — large pages Wave A: the one page ceiling every raisable ingress bound derives from. `PAGE_MAX_BYTES` (24 MiB: import, sync and the managed sync read, CLI stdin, `content_sanity.bytes_block` default), `PUSH_SCAN_MAX_FILE_BYTES` (25 MiB; no canonical file write may exceed it), `CODE_FILE_MAX_BYTES` (5 MB, code keeps its own bound) and `PAGE_INLINE_MAX_BYTES` (1 MiB) with `isLargePageBytes`: a large page commits with NULL vectors, embeds through the sweep under the per-page cap, uses the title context tier and keeps `LARGE_PAGE_VERSIONS_KEPT` large snapshots. The per-entry-point table is in `docs/guides/memory-boundaries.md#large-page-limits`.- `src/core/page-embedding-budget.ts` — large pages: the per-page embedding spend cap `embed.max_usd_per_page` (default $2; unlimited under `spend.posture tokenmax` when unset) and its ledger `page_embedding_budget` (migration v246; states `open` / `held` / `capped`, spent and reserved USD per embedding signature). `planPageEmbedding(engine, page, stale, { signature, approvedCapUsd })` is called by every paid embedding entry point (embed-stale sweep, `gbrain embed` slug/`--all`/`--stale` paths, the managed embedding effect): small pages are `unmetered`; a held page returns `held` unless the user's approval is passed; otherwise it reserves the newest stale chunks that fit the remaining budget under a row lock and returns a grant to `settle`. A reservation older than an hour counts as spent. The sampled junk check (`assessSampledJunk`) holds a boilerplate large page. Held and capped pages leave the stale queue (`staleChunkWhere`, `listStaleChunks`, embedding-invalidation). `listBudgetLimitedPages` feeds doctor `partial_embedding` and `gbrain embed --held`. #6722 receipts: `pageSizeState` / `readPageSizeStates` / `sizeStateField` give the one `size_state` shape (`deferred` / `partial` / `held` / `skipped`, with reason and bytes) that `put_page` (page-prepare), managed sync (sync-prepare) and `remember` (memory-prepare) receipts carry for a large or embed_skip page; `addSizeState` / `sizeStateLines` build the sync tally `size_states` (managed cursor counts, legacy incremental and full sync) and its output lines. Tests: `test/oversized-backfill.serial.test.ts`, `test/persistence-embedding-effects.test.ts`, `test/size-state-receipts-6722.test.ts`.-- `src/core/oversized-backfill.ts` — large pages upgrade: `runOversizedBackfill` (`gbrain reindex --oversized`, and a two-minute pass in `gbrain post-upgrade` via `printOversizedBackfillUpgradeNotice`) rewrites pages an older gbrain stored chunkless for size (gate-written `embed_skip.reason = oversized`) through the normal write path (canonical owner on a managed brain, as `quarantine clear` does) with `forceRechunk` and no embedding: under the effective `bytes_block` the marker and `content_flag: oversized` are removed; over it (and under the ceiling) a chunkless page keeps both and is only re-chunked for keyword search (`rechunked_over_block`, #6722). CPU-only, keyless-safe, idempotent, resumable. Pages over 1 MiB are held (`upgrade_backfill`) for embedding approval first. The receipt names pages re-indexed, chunks pending, estimated cost and the finish/preview/approve commands.+- `src/core/oversized-backfill.ts` — large pages upgrade: `runOversizedBackfill` (`gbrain reindex --oversized`, and a two-minute pass in `gbrain post-upgrade` via `printOversizedBackfillUpgradeNotice`) rewrites pages an older gbrain stored chunkless for size (gate-written `embed_skip.reason = oversized`) through the normal write path (canonical owner on a managed brain, as `quarantine clear` does) with `forceRechunk` and no embedding: under the effective `bytes_block` the marker and `content_flag: oversized` are removed; over it (and under the ceiling) a chunkless page keeps both and is only re-chunked for keyword search (`rechunked_over_block`, #6722). A segmented page is sized by `body_bytes` and re-indexed from its materialized snapshot (`materializedSnapshot`, Wave B PR 2; `test/large-pages/oversized-backfill-segmented.test.ts`). CPU-only, keyless-safe, idempotent, resumable. Pages over 1 MiB are held (`upgrade_backfill`) for embedding approval first. The receipt names pages re-indexed, chunks pending, estimated cost and the finish/preview/approve commands.- `src/core/extraction-watermark.ts` — large pages A7: no silent head-only page extraction. `planExtraction(body, stored, { cap, pipeline, emptyTail })` decides what one extraction reads: the whole body when it fits `cap` (`full`); the text past a stored watermark when the body still starts with exactly the watermarked prefix (`tail`; UTF-8 byte offset + sha256 of the prefix + `EXTRACTION_PIPELINE_VERSION`), its newest `cap` characters when the tail is longer (receipt `tail_window`, never starting inside a surrogate pair, snapped to a line start in the first tenth); otherwise the head (`truncateUtf8`) with receipt `head` and reason `no_watermark` / `prefix_changed` / `version_changed` / `no_new_text`. An empty tail is a skip (`facts_backstop`) or a head re-read (`extract_atoms`, after a cap rise). `readPageWatermark` (by source + slug, fail-soft), `commitExtractionPlan` (after a successful extraction: the watermark moves to the end of the planned body; a full read clears `input_truncated`, a truncated read replaces it, a complete tail read keeps the gap an earlier read left) and `setExtractionReceipt` (the conversation-facts size skip, no watermark) write `page_extraction_state` (migration v247; hashes, offsets and counts only, rows cascade with the page). Doctor `extraction_input_truncated` reads the receipts. Tests: `test/extraction-watermark.test.ts`, `test/extraction-watermark-facts.test.ts`, `test/extraction-watermark-atoms.test.ts`.- `src/core/env-number.ts` — numeric env-var resolution with ONE shared warn-once memo. `resolveEnvNumber(varName, fallback, {unit?})` (positive numbers only; zero/negative/garbage → warn once + fallback), `resolveHoursEnv` (hours unit pre-applied), `warnOnceForEnv(varName, message)` for disabled-unless-set vars that need the same memo without the fallback shape (e.g. `GBRAIN_EXTRACTION_LAG_FAIL_PCT`). Lives in core because `source-health.ts` needs the hours resolver for the staleness ceiling while `doctor.ts` already imports FROM `source-health.ts` — reaching back would cycle, and duplicating would fork the memo so one bad var warns twice. `doctor.ts` re-exports it as `_resolveEnvNumber` for `sync.ts`'s dynamic import. `_resetEnvNumberWarnedForTests()` is a test seam.diff --git a/src/core/oversized-backfill.ts b/src/core/oversized-backfill.tsindex 3c92ffdfd9..6d397d3236 100644--- a/src/core/oversized-backfill.ts+++ b/src/core/oversized-backfill.ts@@ -41,12 +41,14 @@ import { PAGE_MAX_BYTES, isLargePageBytes } from './page-size-policy.ts';import { estimatePageEmbedUsd, holdPageEmbedding } from './page-embedding-budget.ts';import { currentEmbeddingSignature } from './embedding.ts';import type { PageType } from './types.ts';+import { materializedSnapshot } from './persistence/segmented-apply.ts';/** The `page_embedding_budget.reason` a backfilled large page waits under. */export const BACKFILL_HOLD_REASON = 'upgrade_backfill';const OVERSIZED_MARKER_SQL = `p.deleted_at IS NULL AND p.frontmatter->'${EMBED_SKIP_KEY}'->>'reason' = 'oversized'`;-const PAGE_BYTES_SQL = `(octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))`;+/** A segmented page (Wave B) has no body columns: its size is `body_bytes`. */+const PAGE_BYTES_SQL = `(CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END)`;/** Under the block (marker removed), or over it, under the ceiling and chunkless (re-chunked, marker kept). $1 is the block. */const CANDIDATE_SQL = `(${PAGE_BYTES_SQL} <= $1 OR (${PAGE_BYTES_SQL} <= ${PAGE_MAX_BYTES} AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)))`;@@ -95,7 +97,8 @@ async function countMarked(engine: BrainEngine, block: number, sourceId: string/** Rewrite one page re-chunked with no embedding: without its size-gate markers under the block, with them kept over it. */async function reindexPage(engine: BrainEngine, page: Candidate, managed: boolean, overBlock: boolean): Promise<void> {- const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });+ // Every candidate is within the single-string ceiling, so a segmented body is read back whole and rewritten through the segmented write path.+ const snapshot = await materializedSnapshot(engine, await engine.readPageSnapshot(page.slug, { sourceId: page.source_id }));if (!snapshot || snapshot.page.id !== page.id) return;const fm = { ...((snapshot.page.frontmatter ?? {}) as Record<string, unknown>) };if ((fm[EMBED_SKIP_KEY] as { reason?: unknown } | undefined)?.reason !== 'oversized') return;diff --git a/test/large-pages/oversized-backfill-segmented.test.ts b/test/large-pages/oversized-backfill-segmented.test.tsnew file mode 100644index 0000000000..d19011cced--- /dev/null+++ b/test/large-pages/oversized-backfill-segmented.test.ts@@ -0,0 +1,79 @@+/**+ * Wave B: the oversized-page backfill (`gbrain reindex --oversized`) on+ * segmented pages.+ *+ * 1. Protects: a segmented page carrying the gate's `embed_skip: oversized`+ * marker is sized by `pages.body_bytes` (its row has no body columns):+ * while it is over the block it counts in `over_block` and is left alone;+ * once the block is raised above it, it is a candidate, and the backfill+ * rewrites it through the segmented write path without the marker, holds+ * its embedding for approval, and leaves it sealed, segmented, byte-identical+ * and keyword-searchable.+ * 2. Fails when: the size SQL reads `compiled_truth` (NULL for a segmented+ * page, so the page is never counted or rewritten), or the rewrite reads+ * the page's throwing body getters (`page_body_segmented`).+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { isEmbedSkipped } from '../../src/core/embed-skip.ts';+import { parseMarkdown } from '../../src/core/markdown.ts';+import { runOversizedBackfill, BACKFILL_HOLD_REASON } from '../../src/core/oversized-backfill.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';+import { conversationPage } from '../helpers/conversation-page.ts';+import { reconstructedPage } from '../helpers/segmented-page-checks.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-backfill-segmented-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, HOME: home, GBRAIN_AUDIT_DIR: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const NEEDLE = 'zqxbackfillneedle';+const content = conversationPage(2 * 1024 * 1024, { seed: 81, needles: [{ at: 0.6, word: NEEDLE }] });++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ for (const engine of engines) await engine.disconnect();+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++test('a marked segmented page is sized by body_bytes, counted over the block, then rewritten without the marker under it', async () => withEnv(env, async () => {+ for (const engine of engines) {+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.setConfig('content_sanity.bytes_block', '500000');+ expect((await importFromContent(engine, 'notes/backfill', content, { noEmbed: true })).status).toBe('imported');+ const before = await reconstructedPage(engine, 'notes/backfill');+ expect(before.page.body_storage).toBe('segmented');+ expect(isEmbedSkipped(before.page.frontmatter)).toBe(true);++ const over = await runOversizedBackfill(engine, { dryRun: true });+ expect(over).toMatchObject({ candidates: 0, over_block: 1 });++ await engine.unsetConfig('content_sanity.bytes_block');+ expect(await runOversizedBackfill(engine, { dryRun: true })).toMatchObject({ candidates: 1, over_block: 0, held_for_approval: 1 });+ const receipt = await runOversizedBackfill(engine);+ expect(receipt).toMatchObject({ candidates: 1, reindexed: 1, held_for_approval: 1, remaining: 0, failed: [] });++ const after = await reconstructedPage(engine, 'notes/backfill');+ expect(after.page.id).toBe(before.page.id);+ expect(after.page.body_storage).toBe('segmented');+ expect(isEmbedSkipped(after.page.frontmatter)).toBe(false);+ expect(after.body).toEqual(before.body);+ expect(after.body.compiled_truth).toBe(parseMarkdown(content, 'notes/backfill.md').compiled_truth);+ expect(after.page.content_hash).toBe(after.hash);+ expect(after.page.text_projection_revision).toBe(after.page.knowledge_revision);+ const [budget] = await engine.executeRaw<{ state: string; reason: string }>('SELECT state, reason FROM page_embedding_budget WHERE page_id=$1', [after.page.id]);+ expect(budget).toMatchObject({ state: 'held', reason: BACKFILL_HOLD_REASON });+ expect((await engine.searchKeyword(NEEDLE, { limit: 10 })).map(hit => hit.slug)).toContain('notes/backfill');+ expect(await runOversizedBackfill(engine, { dryRun: true })).toMatchObject({ candidates: 0, over_block: 0 });+ }+}), 300_000);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 163998e07a..16a55a8e21 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -66,6 +66,7 @@ test/lane-apply-pipelining.test.tstest/large-pages/chunk-visibility.test.tstest/large-pages/managed-streamed-import.test.tstest/large-pages/managed-sync-segmented-rename.test.ts+test/large-pages/oversized-backfill-segmented.test.tstest/large-pages/segment-vector-reuse.test.tstest/large-pages/segmented-body-unreachable.test.tstest/large-pages/segmented-derived-work.test.ts