Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): check a snapshot's generation against its own size (#8492)

garrytan3812b86c8768
diff --git a/src/core/page-body/body-tiling.ts b/src/core/page-body/body-tiling.ts
index f2e198541c..81d6b1b7fc 100644
--- a/src/core/page-body/body-tiling.ts
+++ b/src/core/page-body/body-tiling.ts
@@ -46,17 +46,19 @@ export const LIVE_READ_ATTEMPTS = 3;
* when a body is published between the statements; reading the live rows and the page in two statements compared one
* generation's rows with the next one's size and refused a healthy page `page_body_rows_unreadable`. A live read whose
* generation no longer tiles because a publish retired it meanwhile (its rows gone) reads the new live generation, up to
- * LIVE_READ_ATTEMPTS times; an explicit generation, or a live one that did not move, refuses as before.
+ * LIVE_READ_ATTEMPTS times; an explicit generation, or a live one that did not move, refuses as before. `bodyBytes`: the
+ * size the caller read with an explicit generation (a snapshot's body_bytes), checked instead of the size a retained
+ * version records, so a generation whose version was pruned never passes on the prefix the live generation shares.
*/
export async function readTiledManifest(engine: Pick<BrainEngine, 'executeRaw' | 'readManifest'>, pageId: number,
- generation?: number): Promise<{ generation: number | null; rows: ManifestRow[] }> {
+ generation?: number, bodyBytes?: number): Promise<{ generation: number | null; rows: ManifestRow[] }> {
const live = async () => (await engine.executeRaw<{ body_generation: unknown; body_bytes: unknown }>('SELECT body_generation, body_bytes FROM pages WHERE id=$1', [pageId]))[0];
for (let attempt = 1; ; attempt++) {
const page = generation === undefined ? await live() : null;
const at = generation ?? (page ? Number(page.body_generation) : null);
const rows = await engine.readManifest(pageId, at === null ? {} : { generation: at });
try {
- await assertGenerationTiles(engine, pageId, at ?? undefined, rows, page ? Number(page.body_bytes ?? 0) : undefined);
+ await assertGenerationTiles(engine, pageId, at ?? undefined, rows, page ? Number(page.body_bytes ?? 0) : bodyBytes);
return { generation: at, rows };
} catch (error) {
const now = generation === undefined && attempt < LIVE_READ_ATTEMPTS ? await live() : undefined;
diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.ts
index 43dd9c8ea7..495162a7e1 100644
--- a/src/core/page-body/ingest.ts
+++ b/src/core/page-body/ingest.ts
@@ -465,8 +465,8 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId
/** The stored body of `pageId` at `generation` (default live), region by region, one segment at a time. */
export async function* readSegmentedBody(engine: BrainEngine, pageId: number, sourceId: string,
- opts: { generation?: number } = {}): AsyncIterable<{ region: BodyRegion; bytes: Uint8Array }> {
- const { rows } = await readTiledManifest(engine, pageId, opts.generation);
+ opts: { generation?: number; bodyBytes?: number } = {}): AsyncIterable<{ region: BodyRegion; bytes: Uint8Array }> {
+ const { rows } = await readTiledManifest(engine, pageId, opts.generation, opts.bodyBytes);
const batchBytes = STAGE_BATCH_BYTES[engine.kind];
for (let start = 0; start < rows.length;) {
let end = start, bytes = 0;
@@ -483,11 +483,11 @@ export async function* readSegmentedBody(engine: BrainEngine, pageId: number, so
}
/**
- * The whole body of a segmented page as strings, at `opts.generation` (default live). Only for pages within the
- * single-string ceiling (callers check `body_bytes`).
+ * The whole body of a segmented page as strings, at `opts.generation` (default live; `opts.bodyBytes` its known size).
+ * Only for pages within the single-string ceiling (callers check `body_bytes`).
*/
export async function materializeSegmentedBody(engine: BrainEngine, pageId: number, sourceId: string,
- opts: { generation?: number } = {}): Promise<{ compiled_truth: string; timeline: string }> {
+ opts: { generation?: number; bodyBytes?: number } = {}): Promise<{ compiled_truth: string; timeline: string }> {
const parts: Record<BodyRegion, string[]> = { truth: [], timeline: [] };
for await (const part of readSegmentedBody(engine, pageId, sourceId, opts)) parts[part.region].push(utf8.decode(part.bytes));
return { compiled_truth: parts.truth.join(''), timeline: parts.timeline.join('') };
diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.ts
index 513b29652a..1cec0e76de 100644
--- a/src/core/persistence/segmented-apply.ts
+++ b/src/core/persistence/segmented-apply.ts
@@ -40,6 +40,8 @@ import { segmentedPageSearchable } from './searchable.ts';
import { stableJson } from './digest.ts';
import { pageBodyOverCeilingError } from '../page-body/page-shape.ts';
import { assertOriginUnclaimed } from './origin-guard.ts';
+import { OperationError } from '../ops/contract.ts';
+import { PAGE_CHANGED_DURING_PREPARATION_MESSAGE } from './verb-errors.ts';
const BODY_KEYS = new Set(['compiled_truth', 'timeline', 'content']);
@@ -82,7 +84,7 @@ export async function materializedPage<T extends Page>(engine: BrainEngine, page
if (Number(bytes ?? 0) > PAGE_MAX_BYTES) return page;
const copy: Record<string, unknown> = { body_storage: 'segmented' };
for (const key of Object.keys(page)) if (!BODY_KEYS.has(key)) copy[key] = (page as Record<string, unknown>)[key];
- Object.assign(copy, await materializeSegmentedBody(engine, Number(page.id), page.source_id, generation === undefined ? {} : { generation }));
+ Object.assign(copy, await materializeSegmentedBody(engine, Number(page.id), page.source_id, generation === undefined ? {} : { generation, bodyBytes: Number(bytes ?? 0) }));
return copy as T;
}
@@ -95,12 +97,18 @@ export function segmentedOverCeiling(page: { body_storage?: string | null; body_
* `materializedPage` over a snapshot (null passes through), with the read-back body under the snapshot's withdrawal
* ledger, as readPageSnapshot gives an inline page's body: a facts row the ledger withdraws is struck (or, purged,
* dropped), so the body a write merges into or the drift check compares a file with is the one an inline page has.
- * The body is the snapshot's generation (#8492), never one published after it; when that generation's rows are
- * gone the read refuses `page_body_rows_unreadable`.
+ * The body is the snapshot's generation (#8492), never one published after it, checked against the snapshot's
+ * body_bytes. A generation the page has moved past that no longer reads whole refuses `revision_conflict` (prepare
+ * again on a fresh snapshot); an unreadable live generation refuses `page_body_rows_unreadable`.
*/
export async function materializedSnapshot(engine: BrainEngine, snapshot: PageSnapshot | null): Promise<PageSnapshot | null> {
if (!snapshot || bodyStorageOf(snapshot.page) !== 'segmented') return snapshot;
- const page = await materializedPage(engine, snapshot.page, snapshot.bodyGeneration);
+ const page = await materializedPage(engine, snapshot.page, snapshot.bodyGeneration).catch(async error => {
+ if (!(error instanceof OperationError) || error.code !== 'page_body_rows_unreadable' || snapshot.bodyGeneration === undefined) throw error;
+ const [live] = await engine.executeRaw<{ body_generation: unknown }>('SELECT body_generation FROM pages WHERE id=$1', [snapshot.page.id]);
+ if (live && Number(live.body_generation) === snapshot.bodyGeneration) throw error;
+ throw new OperationError('revision_conflict', PAGE_CHANGED_DURING_PREPARATION_MESSAGE, 'Read its current revision and submit the updated intent with a new request_id.');
+ });
if (page === snapshot.page) return snapshot;
Object.assign(page, await overlayCanonicalBodies(engine.executeRaw.bind(engine), page.compiled_truth, page.timeline ?? '', snapshot.withdrawals,
{ sourceId: page.source_id, marker: snapshot.globalPurges }));
diff --git a/test/large-pages/snapshot-body-generation-8492.test.ts b/test/large-pages/snapshot-body-generation-8492.test.ts
index 07f620d118..4c5089efaa 100644
--- a/test/large-pages/snapshot-body-generation-8492.test.ts
+++ b/test/large-pages/snapshot-body-generation-8492.test.ts
@@ -3,35 +3,48 @@
*
* A snapshot holds one revision's title, frontmatter and withdrawal ledger; the drift check, the managed-sync freeze
* screen and local-edit adoption compare a file with it read back whole. The body used to be read from the live
- * generation, so a replacement published after the snapshot gave the old metadata the new body. When the snapshot's
- * generation can no longer be read, the read refuses `page_body_rows_unreadable` instead of answering with the new body.
+ * generation, so a replacement published after the snapshot gave the old metadata the new body. The snapshot's
+ * generation is checked against the snapshot's own body_bytes, so a generation version retention pruned (its changed
+ * tail swept, its unchanged prefix still live) never reads back as a short body. When the snapshot's generation can no
+ * longer be read and the page has moved on, the read refuses `revision_conflict` (prepare again on a fresh snapshot);
+ * an unreadable live generation still refuses `page_body_rows_unreadable`.
*/
import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { importFromContent } from '../../src/core/import-file.ts';
import { materializedSnapshot } from '../../src/core/persistence/segmented-apply.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
const SLUG = 'notes/alice-example';
let engine: PGLiteEngine;
+const lines = (tag: string, n: number) => Array.from({ length: n }, (_, i) => `- ${String(i).padStart(9, '0')} ${tag} acme-example journal line with enough text to fill a segment\n`).join('');
/** Over the inline bound, so the page is stored in segments; `tag` marks the generation's text. */
-const file = (tag: string) => `---\ntitle: Alice Example ${tag}\ntype: concept\n---\n\n${tag} intro.\n\n${
- Array.from({ length: 16_000 }, (_, i) => `- ${String(i).padStart(9, '0')} ${tag} acme-example journal line with enough text to fill a segment\n`).join('')}`;
+const file = (tag: string) => `---\ntitle: Alice Example ${tag}\ntype: concept\n---\n\n${tag} intro.\n\n${lines(tag, 16_000)}`;
+/** The same prefix on every generation; only the last lines change. */
+const tailFile = (tail: string) => `---\ntitle: Alice Example\ntype: concept\n---\n\nShared intro.\n\n${lines('shared', 16_000)}${lines(tail, 40)}`;
const page = async () => (await engine.executeRaw<{ id: number; body_storage: string; body_generation: number }>(
'SELECT id, body_storage, body_generation FROM pages WHERE source_id=$1 AND slug=$2', ['default', SLUG]))[0]!;
+const put = (content: string) => importFromContent(engine, SLUG, content, { sourceId: 'default', noEmbed: true });
+const coordinated = (sql: string, params: unknown[]) =>
+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));
beforeAll(async () => {
engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
await engine.setConfig('pages.segmented_storage', 'on');
}, 120_000);
afterAll(async () => { await engine.disconnect(); });
-beforeEach(async () => { await engine.executeRaw('DELETE FROM pages'); });
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.setConfig('versions.segmented_max_per_page', '50');
+});
async function snapshotThenReplace() {
- await importFromContent(engine, SLUG, file('genone'), { sourceId: 'default', noEmbed: true });
+ await put(file('genone'));
const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!;
expect({ storage: (await page()).body_storage, generation: snapshot.bodyGeneration }).toEqual({ storage: 'segmented', generation: 1 });
- await importFromContent(engine, SLUG, file('gentwo'), { sourceId: 'default', noEmbed: true });
+ await put(file('gentwo'));
expect(Number((await page()).body_generation)).toBe(2);
return snapshot;
}
@@ -44,9 +57,36 @@ test('a snapshot read back whole keeps its own generation\'s body after a replac
expect(read.page.compiled_truth).not.toContain('gentwo');
}, 120_000);
-test('a snapshot whose generation is no longer readable refuses instead of reading the newer body', async () => {
+test('a snapshot whose generation was pruned to its live prefix never reads back short', async () => {
+ await engine.setConfig('versions.segmented_max_per_page', '1');
+ await put(tailFile('tailone'));
+ const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!;
+ const whole = (await materializedSnapshot(engine, snapshot))!.page.compiled_truth;
+ expect(whole).toContain('tailone');
+ await put(tailFile('tailtwo'));
+ await put(tailFile('tailthree'));
+ const { id } = await page();
+ const [left] = await engine.executeRaw<{ versions: number; covered: number }>(`SELECT
+ (SELECT count(*)::int FROM page_versions WHERE page_id=$1 AND body_generation=1) AS versions,
+ (SELECT COALESCE(sum(byte_len), 0)::int FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NULL AND gen_from<=1 AND (gen_to IS NULL OR gen_to>1)) AS covered`, [id]);
+ expect(left!.versions).toBe(0);
+ expect(left!.covered).toBeGreaterThan(0);
+ expect(left!.covered).toBeLessThan(Number(snapshot.page.body_bytes));
+ const read = materializedSnapshot(engine, snapshot).then(s => s!.page.compiled_truth.length);
+ await expect(read).rejects.toMatchObject({ code: 'revision_conflict' });
+}, 180_000);
+
+test('a snapshot whose generation is no longer readable refuses as a page that changed, not as unreadable rows', async () => {
const snapshot = await snapshotThenReplace();
- await engine.executeRaw('DELETE FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NOT NULL', [(await page()).id]);
+ await coordinated('DELETE FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NOT NULL', [(await page()).id]);
+ const read = materializedSnapshot(engine, snapshot).then(s => s!.page.compiled_truth.slice(0, 12));
+ await expect(read).rejects.toMatchObject({ code: 'revision_conflict' });
+}, 120_000);
+
+test('a snapshot of the live generation whose rows are unreadable still refuses page_body_rows_unreadable', async () => {
+ await put(file('genone'));
+ const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!;
+ await coordinated('DELETE FROM page_body_manifest WHERE page_id=$1 AND seq=1 AND staging_id IS NULL', [(await page()).id]);
const read = materializedSnapshot(engine, snapshot).then(s => s!.page.compiled_truth.slice(0, 12));
await expect(read).rejects.toMatchObject({ code: 'page_body_rows_unreadable' });
}, 120_000);