Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(large-pages): lane E — a non-owner write role's embedding effect and no-op kernel run without the segment grants while it sees no segmented chunk

garrytancab4aea2d94d
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 2f82762ac7..0454c71d80 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -323,9 +323,12 @@ policies read `app.scopes` only; the app-layer source filters stay layer 1.
A write role that does not own the tables needs `SELECT, INSERT, UPDATE, DELETE`
on all six, as on any table a migration adds, even while no page is segmented:
-purging soft-deleted pages, the maintenance sweep's facts pass, fact withdrawal
-and doctor's credential check name them. With the policies above it creates
-segmented pages and sees only its sources' rows
+purging soft-deleted pages, fact withdrawal (`forget_fact`, `purge_fact`), the
+maintenance sweep's facts pass, doctor's credential check and the segment
+storage sweep name them. Its ordinary writes (`put_page`, `remember`, sync
+imports, their embedding and the unchanged-file check) do not, while it sees no
+segmented chunk (`test/e2e/segmented-switch-off-write-role.test.ts`). With the
+policies above it creates segmented pages and sees only its sources' rows
(`test/e2e/segmented-rls-scope.test.ts`).
**In engine-sql.** A read in a migrated domain takes a `ScopedRead` when it
diff --git a/llms-full.txt b/llms-full.txt
index 122661f7e2..4f5b8eed16 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5602,9 +5602,12 @@ policies read `app.scopes` only; the app-layer source filters stay layer 1.
A write role that does not own the tables needs `SELECT, INSERT, UPDATE, DELETE`
on all six, as on any table a migration adds, even while no page is segmented:
-purging soft-deleted pages, the maintenance sweep's facts pass, fact withdrawal
-and doctor's credential check name them. With the policies above it creates
-segmented pages and sees only its sources' rows
+purging soft-deleted pages, fact withdrawal (`forget_fact`, `purge_fact`), the
+maintenance sweep's facts pass, doctor's credential check and the segment
+storage sweep name them. Its ordinary writes (`put_page`, `remember`, sync
+imports, their embedding and the unchanged-file check) do not, while it sees no
+segmented chunk (`test/e2e/segmented-switch-off-write-role.test.ts`). With the
+policies above it creates segmented pages and sees only its sources' rows
(`test/e2e/segmented-rls-scope.test.ts`).
**In engine-sql.** A read in a migrated domain takes a `ScopedRead` when it
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 5ee23220d7..f2c76e28d4 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -724,6 +724,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ 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, `get_chunks` and `get_page` read the new `page_body_manifest` table for a page stored in segments. A database role that neither owns the tables nor bypasses row level security needs `SELECT` on it once it can see a chunk of such a page (a segmented page of one of its sources), or those reads fail with `permission_denied` (42501); while it sees none, as while no page is segmented and `pages.segmented_storage` is off, it reads as before without the grant. Row level security is on for the six new segment tables (`page_segment_texts`, `page_body_manifest`, `page_body_stagings`, `page_body_staging_parts`, `page_body_staging_texts`, `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: 'On Postgres, a write role that neither owns the tables nor bypasses row level security needs `SELECT, INSERT, UPDATE, DELETE` on the six segment tables (`page_segment_texts`, `page_body_manifest`, `page_body_stagings`, `page_body_staging_parts`, `page_body_staging_texts`, `page_view_digests`) even while `pages.segmented_storage` is off and no page is segmented, as on any table a migration adds: purging soft-deleted pages (`gbrain pages purge-deleted` and the cycle purge phase), fact withdrawal (`forget_fact`, `purge_fact`), the maintenance sweep\'s facts pass, doctor\'s credential-projection check and the segment storage sweep name them and fail with `permission_denied` (42501) without the grants. Ordinary writes do not need them while the role sees no segmented chunk: `put_page`, `remember`, a sync import, the embedding of the pages they save and the managed sync\'s unchanged-file check run as before. See docs/ENGINES.md ("Segmented page tables") for the grants and the source-scoped policies.' },
{ since: 'TBD', text: '`delete_page` (soft and `purge: true`) of a page stored in segments whose facts fence holds a withdrawn row no longer refuses with `source_changed` ("uncoordinated local edit") while its file is unchanged: a segmented page within 24 MiB is read back with the withdrawal applied, as an inline page is, so it deletes as the same page stored inline does, and `edit_page` edits it with the withdrawn row struck, as for an inline page.' },
{ 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.' },
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 2556ee63f3..d1706ca832 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -49,7 +49,7 @@ import { nativeFileTarget } from './native-file-target.ts';
import { sourceMirrorReadOnly } from './mirror-read-only.ts';
import { isLockOpenFailure } from './native-lock.ts';
import { planPageEmbedding } from '../page-embedding-budget.ts';
-import { chunkGenerationFilter } from '../search/safe-chunks.ts';
+import { chunkGenerationFilter, chunkManifestReads } from '../search/safe-chunks.ts';
const effectStatusFix = (effect: Pick<PersistenceEffect, 'source_id'>): Action => readFix(
`Shows source ${effect.source_id}'s canonical owner with its blocking, retrying and parked effects, read-only.`,
@@ -302,7 +302,7 @@ export async function readEmbeddingEffectProjection(engine: BrainEngine, effect:
const completion = await tx.executeRaw<{ id: number; complete: boolean }>(`SELECT cc.id,
p.embedding_signature=$2 AND cc.${quoteIdentifier(column.name)} IS NOT NULL AND cc.embedded_at IS NOT NULL
AND cc.embedded_text_hash=md5(cc.chunk_text) AND cc.model IS NOT DISTINCT FROM $3 AS complete
- FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE p.id=$1 AND ${chunkGenerationFilter('p', 'cc')}`,
+ FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE p.id=$1 AND ${chunkGenerationFilter('p', 'cc', await chunkManifestReads(engine, tx))}`,
[snapshot.page.id, signature, embeddingCompletionModel(column, signature, model)]);
const complete = new Set(completion.filter(chunk => chunk.complete === true).map(chunk => chunk.id));
const pending = prepared.chunks.filter(chunk => !complete.has(chunk.id));
diff --git a/src/core/persistence/noop-kernel.ts b/src/core/persistence/noop-kernel.ts
index 90d347b9aa..f92eec7d61 100644
--- a/src/core/persistence/noop-kernel.ts
+++ b/src/core/persistence/noop-kernel.ts
@@ -32,7 +32,7 @@ import type { PreparedMutation } from './coordinator.ts';
import { persistenceFileHash } from './coordinator.ts';
import type { WriteRequest } from './model.ts';
import type { PageSnapshot } from '../page-state/types.ts';
-import { belowSafeChunkFence, chunkGenerationFilter } from '../search/safe-chunks.ts';
+import { belowSafeChunkFence, chunkGenerationFilter, chunkManifestReads } from '../search/safe-chunks.ts';
import { fileContentHash } from './large-file.ts';
export interface NoopKernelResult {
@@ -58,10 +58,13 @@ export function screeningRequest(fields: Pick<WriteRequest, 'source_id' | 'sourc
/** What the kernel reads about a live page: its projection state, revision and recorded origin. */
export interface KernelPage { id: number | string; slug: string; chunker_version: number | null; text_projection_revision: string | null; knowledge_revision: string;
mode_pending: boolean; unembedded: boolean; source_path: string | null }
-/** The kernel's page read; callers append the `WHERE` (one page by id, or #6712 PR 1 a prescreened run by slug). */
-export const KERNEL_PAGE_SQL = `SELECT p.id,p.slug,p.chunker_version,p.text_projection_revision::text,p.knowledge_revision::text,p.source_path,
- (p.contextual_retrieval_mode IS NULL AND EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NOT NULL AND ${chunkGenerationFilter('p', 'c')})) AS mode_pending,
- EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NULL AND ${chunkGenerationFilter('p', 'c')}) AS unembedded
+/**
+ * The kernel's page read; callers append the `WHERE` (one page by id, or #6712 PR 1 a prescreened run by slug).
+ * `manifest` is chunkManifestReads: a write role without the segment grants that sees no segmented chunk reads it too.
+ */
+export const kernelPageSql = (manifest: boolean) => `SELECT p.id,p.slug,p.chunker_version,p.text_projection_revision::text,p.knowledge_revision::text,p.source_path,
+ (p.contextual_retrieval_mode IS NULL AND EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NOT NULL AND ${chunkGenerationFilter('p', 'c', manifest)})) AS mode_pending,
+ EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NULL AND ${chunkGenerationFilter('p', 'c', manifest)}) AS unembedded
FROM pages p`;
/**
@@ -75,7 +78,7 @@ export function kernelPageWork(page: KernelPage, input: { sourcePath: string | n
return input.sourcePath !== null && page.source_path !== input.sourcePath ? 'metadata_work' : null;
}
-export async function inspectUnchanged(engine: Pick<BrainEngine, 'executeRaw'>, input: {
+export async function inspectUnchanged(engine: Pick<BrainEngine, 'kind' | 'executeRaw'>, input: {
prepared: PreparedMutation; snapshot: PageSnapshot | null; sourcePath: string | null; databaseOnly: boolean;
/** The publication would queue an embedding effect: a page with unembedded chunks is then not skipped. */
embeddingRequested?: boolean;
@@ -91,7 +94,7 @@ export async function inspectUnchanged(engine: Pick<BrainEngine, 'executeRaw'>,
if (snapshot.page.deleted_at != null) return result('page_deleted');
if (!unchanged) return result('content_changed');
if (observedRevision !== snapshot.revision) return result('revision_moved');
- const [page] = await engine.executeRaw<KernelPage>(`${KERNEL_PAGE_SQL} WHERE p.id=$1 AND p.deleted_at IS NULL`, [snapshot.page.id]);
+ const [page] = await engine.executeRaw<KernelPage>(`${kernelPageSql(await chunkManifestReads(engine))} WHERE p.id=$1 AND p.deleted_at IS NULL`, [snapshot.page.id]);
if (!page) return result('page_missing');
// The page's current revision, read after the preparer ran: a write that landed since the snapshot was read is admitted.
if (page.knowledge_revision != null && page.knowledge_revision !== snapshot.revision) return result('revision_moved');
diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.ts
index cf47e2e3e2..528ec5db9c 100644
--- a/src/core/persistence/sync-waivers.ts
+++ b/src/core/persistence/sync-waivers.ts
@@ -15,7 +15,8 @@ import { isSyncReadBound } from './sync-screen.ts';
import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
import { sha256 } from './digest.ts';
import { startClaimPhase } from './claim-phase.ts';
-import { inspectUnchanged, KERNEL_PAGE_SQL, kernelPageWork, screeningRequest, type KernelPage, type NoopKernelWaiver } from './noop-kernel.ts';
+import { inspectUnchanged, kernelPageSql, kernelPageWork, screeningRequest, type KernelPage, type NoopKernelWaiver } from './noop-kernel.ts';
+import { chunkManifestReads } from '../search/safe-chunks.ts';
import { validateSyncAuthority, type SyncAuthority } from './sync-authority.ts';
import { readSyncFile, type SyncEntry } from './sync-discovery.ts';
import { isImageFilePath } from '../sync.ts';
@@ -283,7 +284,7 @@ export async function waivePrescreenedRun<C extends WaiverCursor & { binding: {
await faultPoint('sync:prescreened', { sourceId: cursor.sourceId });
const binding = await getWorktreeBinding(tx, cursor.sourceId);
if (!binding || String(binding.owner_epoch) !== String(cursor.binding.owner_epoch)) return null;
- const pages = new Map((await tx.executeRaw<KernelPage>(`${KERNEL_PAGE_SQL} WHERE p.source_id=$1 AND p.slug=ANY($2::text[]) AND p.deleted_at IS NULL`,
+ const pages = new Map((await tx.executeRaw<KernelPage>(`${kernelPageSql(await chunkManifestReads(engine, tx))} WHERE p.source_id=$1 AND p.slug=ANY($2::text[]) AND p.deleted_at IS NULL`,
[cursor.sourceId, run.map(entry => entry.slug)])).map(page => [page.slug, page]));
const records = await readSyncImportProvenances(tx, cursor.sourceId, cursor.incarnation, run.map(entry => entry.pageId));
const holds = await heldGitPaths(tx, cursor.sourceId, cursor.incarnation, run.map(entry => entry.path));
diff --git a/test/e2e/segmented-switch-off-write-role.test.ts b/test/e2e/segmented-switch-off-write-role.test.ts
new file mode 100644
index 0000000000..2e3c10d2fa
--- /dev/null
+++ b/test/e2e/segmented-switch-off-write-role.test.ts
@@ -0,0 +1,132 @@
+/**
+ * Ordinary writes while segmented storage is off (Wave B PR 2, fix lane E).
+ *
+ * 1. Protects: "while pages.segmented_storage is off nothing user-visible changes" for a non-owner write role
+ * (LOGIN, NOBYPASSRLS) holding every grant except the six segment tables, on a brain with no segmented page.
+ * put_page (create, update and an unchanged re-put), remember, a managed sync import (first, update, unchanged) and
+ * the embedding effects they queue run for it as before, and a full resync of unchanged files is waived by the no-op
+ * kernel as for the owner. docs/ENGINES.md names the
+ * maintenance paths that do need the grants.
+ * 2. Fails when: an ordinary write path names a segment table although the role can see no segmented chunk row,
+ * so Postgres refuses it with 42501: the embedding effect then never embeds the page (it retries effect_unavailable)
+ * and the no-op kernel's page read fails, so unchanged files are re-admitted instead of waived.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { GBrainConfig } from '../../src/core/config.ts';
+import { operations, type OperationContext } from '../../src/core/operations.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';
+import { localHostId } from '../../src/core/persistence/identity.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';
+import { makeGitFixture } from '../helpers/git-fixture.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';
+import { hasDatabase, setupLegacyEmbeddingDB, teardownDB } from './helpers.ts';
+
+const WRITER = 'gbrain_seg_off_writer_' + randomUUID().replaceAll('-', '').slice(0, 12);
+const SEGMENT_TABLES = ['page_body_manifest', 'page_body_staging_parts', 'page_body_staging_texts', 'page_body_stagings', 'page_segment_texts', 'page_view_digests'];
+
+(hasDatabase() ? describe : describe.skip)('ordinary writes while segmented storage is off (non-owner write role)', () => {
+ let engine: PostgresEngine;
+ let writer: PostgresEngine;
+ let granted: string[] = [];
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-seg-off-writer-'));
+ const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_BACKUP_CHECK: 'off', GBRAIN_SYNC_NO_EXTRACT_NUDGE: '1' };
+ const config = { engine: 'postgres', embedding_disabled: false } as unknown as GBrainConfig;
+ const ctx = (): OperationContext => ({ engine: writer, config, logger: { info() {}, warn() {}, error() {} },
+ dryRun: false, remote: false, sourceId: 'default' }) as unknown as OperationContext;
+ const run = (name: string, params: Record<string, unknown>) => operations.find(o => o.name === name)!.handler(ctx(), params) as Promise<Record<string, unknown>>;
+ const outcome = (p: Promise<unknown>) => p.then(() => 'ok', (e: { code?: string; message?: string }) => 'error ' + (e.code ?? '') + ' ' + String(e.message).slice(0, 120));
+
+ beforeAll(async () => {
+ engine = await setupLegacyEmbeddingDB();
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ values, warnings: [], embeddings: values.map(() => Array(1536).fill(0.1)), usage: { tokens: values.length } })) as never);
+ const password = randomUUID();
+ await engine.executeRaw('CREATE ROLE ' + WRITER + " LOGIN PASSWORD '" + password + "' NOSUPERUSER NOBYPASSRLS");
+ await engine.executeRaw('GRANT USAGE ON SCHEMA public TO ' + WRITER);
+ granted = (await engine.executeRaw<{ t: string }>("SELECT tablename AS t FROM pg_tables WHERE schemaname = 'public' ORDER BY 1")).map(r => r.t).filter(t => !SEGMENT_TABLES.includes(t));
+ await engine.executeRaw('GRANT ALL ON ' + granted.join(', ') + ' TO ' + WRITER);
+ await engine.executeRaw('GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO ' + WRITER);
+ for (const t of granted) await engine.executeRaw('CREATE POLICY ' + WRITER + '_all ON ' + t + ' FOR ALL TO ' + WRITER + ' USING (true) WITH CHECK (true)');
+ await engine.executeRaw('ALTER ROLE ' + WRITER + " SET app.scopes = '*'");
+ const url = new URL(process.env.DATABASE_URL!);
+ url.username = WRITER;
+ url.password = password;
+ writer = new PostgresEngine();
+ await writer.connect({ database_url: url.toString(), poolSize: 4 });
+ }, 300_000);
+
+ afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ if (writer) { await disposePersistenceConsumer(writer); await writer.disconnect(); }
+ if (engine) {
+ await disposePersistenceConsumer(engine);
+ for (const t of granted) await engine.executeRaw('DROP POLICY IF EXISTS ' + WRITER + '_all ON ' + t);
+ await engine.executeRaw('DROP OWNED BY ' + WRITER).catch(() => undefined);
+ await engine.executeRaw('DROP ROLE IF EXISTS ' + WRITER);
+ }
+ await teardownDB();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ test('put_page, remember, a managed sync import and their embedding effects run without the segment grants', async () => withEnv(env, async () => {
+ expect(await engine.getConfig('pages.segmented_storage')).toBeNull();
+ expect(await writer.executeRaw("SELECT current_user AS role, has_table_privilege('page_body_manifest', 'SELECT') AS manifest")).toEqual([{ role: WRITER, manifest: false }]);
+ const slug = 'notes/writer-ledger';
+ const body = (text: string) => '---\ntype: note\ntitle: Writer ledger\n---\n# Writer ledger\n\n' + text + '\n';
+ const revision = async () => String((await run('get_page', { slug, include_content: true })).revision);
+ const seen: Record<string, string> = {};
+ seen.create = await outcome(run('put_page', { slug, content: body('first'), request_id: randomUUID() }));
+ seen.update = await outcome((async () => run('put_page', { slug, content: body('second'), expected_revision: await revision(), request_id: randomUUID() }))());
+ seen.unchanged = await outcome((async () => run('put_page', { slug, content: body('second'), expected_revision: await revision(), request_id: randomUUID() }))());
+ seen.remember = await outcome(run('remember', { fact: 'Alice Example prefers tea', entity: 'people/alice-example', provenance: 'synthetic test note' }));
+
+ const id = 'sync-' + randomUUID().replaceAll('-', '').slice(0, 16);
+ const root = join(home, id);
+ mkdirSync(root);
+ await makeGitFixture(root);
+ const commit = () => { execFileSync('git', ['-C', root, 'add', '.']); execFileSync('git', ['-C', root, 'commit', '-qm', 'fixture']); };
+ writeFileSync(join(root, 'a.md'), '# A\n\nFirst observation.\n');
+ commit();
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const options = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };
+ seen.sync_first = await outcome(performManagedSync(writer, options));
+ writeFileSync(join(root, 'a.md'), '# A\n\nUpdated observation.\n');
+ writeFileSync(join(root, 'b.md'), '# B\n\nSecond page.\n');
+ commit();
+ seen.sync_update = await outcome(performManagedSync(writer, options));
+ seen.sync_noop = await outcome(performManagedSync(writer, options));
+ const revs = async () => JSON.stringify(await engine.executeRaw("SELECT slug, knowledge_revision::text AS r FROM pages WHERE source_id=$1 ORDER BY slug", [id]));
+ const before = await revs();
+ // A full resync of unchanged files runs the no-op kernel, which waives both instead of re-admitting them.
+ const full = await performManagedSync(writer, { ...options, full: true });
+
+ // The embedding effects the writes queued run as the write role, as its own persistence consumer would.
+ await disposePersistenceConsumer(writer);
+ for (let i = 0; i < 5; i++) if (!await runPersistenceEffects(writer, config, { hostId: localHostId(), limit: 32 })) break;
+ const effects = await engine.executeRaw<{ state: string; reason: string | null }>("SELECT e.state, e.error_code AS reason FROM persistence_effects e JOIN persistence_requests r ON r.id = e.request_id WHERE e.kind = 'embedding' AND r.slug = $1", [slug]);
+
+ expect(seen).toEqual({ create: 'ok', update: 'ok', unchanged: 'ok', remember: 'ok', sync_first: 'ok', sync_update: 'ok', sync_noop: 'ok' });
+ const unembedded = (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND cc.embedding IS NULL", [slug]))[0]!.n;
+ expect({ fullResync: { status: full.status, waived: full.waived, revisionsKept: (await revs()) === before },
+ embedding: { effects: effects.length > 0, notCommitted: effects.filter(e => e.state !== 'committed'), unembedded } })
+ .toEqual({ fullResync: { status: 'synced', waived: { imports: 2, deletes: 0 }, revisionsKept: true },
+ embedding: { effects: true, notCommitted: [], unembedded: 0 } });
+ expect(await engine.executeRaw<{ slug: string; body: string }>("SELECT slug, compiled_truth AS body FROM pages WHERE source_id = $1 ORDER BY slug", [id]))
+ .toEqual([{ slug: 'a', body: expect.stringContaining('Updated observation.') }, { slug: 'b', body: expect.stringContaining('Second page.') }]);
+ expect(await engine.executeRaw("SELECT count(*)::int AS n FROM pages WHERE body_storage = 'segmented'")).toEqual([{ n: 0 }]);
+ }), 300_000);
+});