Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): PGLite full ANALYZE after bulk writes; derived_from carries private visibility
garrytanf19705190aef
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 233808f92c..bc2ed4c3c7 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -44,7 +44,27 @@ function derivedPageSql(pageAlias: string): string {*/export function privatePagesFilterFragment(pageAlias: string): string {return `(${privateSnapshotFilterFragment(pageAlias)}- AND NOT ${derivedOriginPrivateSql(pageAlias)})`;+ AND NOT ${derivedOriginPrivateSql(pageAlias)}+ AND NOT ${declaredLineagePrivateSql(pageAlias)})`;+}++/**+ * Declared lineage: a page whose frontmatter `derived_from` names a page (one+ * slug or a list, `.md` optional) that is explicitly `visibility: private` in+ * the same source is private too, whatever its own field says. Summaries,+ * digests and reports written from finance-only or other private material+ * therefore stay behind the same boundary as their inputs. Only an explicitly+ * private input propagates; a missing input does not hide the page.+ */+function declaredLineagePrivateSql(p: string): string {+ return `(jsonb_typeof(${p}.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS (+ SELECT 1 FROM pages declared_origin+ WHERE declared_origin.source_id = ${p}.source_id+ AND declared_origin.frontmatter->>'visibility' = 'private'+ AND declared_origin.slug IN (+ SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text(+ CASE WHEN jsonb_typeof(${p}.frontmatter->'derived_from') = 'array' THEN ${p}.frontmatter->'derived_from'+ ELSE jsonb_build_array(${p}.frontmatter->'derived_from') END) AS declared(slug))))`;}/**diff --git a/src/core/search/projection-statistics.ts b/src/core/search/projection-statistics.tsindex 7d3bbd39f9..889cb4851d 100644--- a/src/core/search/projection-statistics.ts+++ b/src/core/search/projection-statistics.ts@@ -54,7 +54,11 @@ export async function refreshProjectionStatistics(engine: BrainEngine): Promise<await tx.executeRaw("SET LOCAL statement_timeout = '30s'");await tx.executeRaw("SET LOCAL lock_timeout = '2s'");}- await tx.executeRaw('ANALYZE pages(text_projection_revision, knowledge_revision)');+ // PGLite has no autovacuum, so nothing else ever collects planner statistics there. Without them the+ // planner sees empty tables and runs search's graph joins as pages-by-pages nested loops (about 50 s+ // per search on a freshly imported 4,000-page brain; 6 ms after ANALYZE). Postgres keeps the narrow+ // refresh and leaves the rest to autovacuum.+ await tx.executeRaw(engine.kind === 'pglite' ? 'ANALYZE' : 'ANALYZE pages(text_projection_revision, knowledge_revision)');await verifyProjectionStatistics(tx);});return true;diff --git a/test/declared-lineage-visibility.test.ts b/test/declared-lineage-visibility.test.tsnew file mode 100644index 0000000000..3986bad705--- /dev/null+++ b/test/declared-lineage-visibility.test.ts@@ -0,0 +1,92 @@+/**+ * Declared lineage: a page whose `derived_from` frontmatter names a private+ * page is private to remote readers too. Found by gbrain-evals Cat 40, where an+ * unlabeled digest repeated a finance-only discount and remote agents reported+ * it after the labeled memo itself was hidden.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';+import { operationsByName } from '../src/core/operations.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;++const pages = [+ ['finance/discount-memo', 'note', 'wombat finance only discount memo', { visibility: 'private' }],+ ['notes/world-note', 'note', 'wombat ordinary world note', {}],+ ['digests/from-private', 'note', 'wombat digest repeating the discount', { derived_from: ['finance/discount-memo', 'notes/world-note'] }],+ ['digests/from-private-md', 'note', 'wombat digest naming the memo file', { derived_from: 'finance/discount-memo.md' }],+ ['digests/from-world', 'note', 'wombat digest of world material', { derived_from: ['notes/world-note'] }],+ ['digests/from-missing', 'note', 'wombat digest of a page that does not exist', { derived_from: ['notes/never-written'] }],+] as const;+const hidden = ['finance/discount-memo', 'digests/from-private', 'digests/from-private-md'];+const visible = ['notes/world-note', 'digests/from-world', 'digests/from-missing'];++beforeAll(async () => {+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({}); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+ for (const engine of engines) {+ for (const [slug, type, body, frontmatter] of pages) {+ const result = await importFromContent(engine, slug, serializeMarkdown(frontmatter, body, '', { type, title: slug, tags: [] }),+ { noEmbed: true, forceRechunk: true });+ expect(result.status).toBe('imported');+ }+ }+}, 120_000);++afterAll(async () => {+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();+ await closePostgres?.();+});++const ctx = (engine: BrainEngine, remote: boolean) => ({ engine, config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} },+ dryRun: false, remote, sourceId: 'default' }) as never;++describe('derived_from carries private visibility to derived pages', () => {+ test('remote list_pages hides pages derived from a private page; local lists everything', async () => {+ for (const engine of engines) {+ __resetPrivateVisibilityCacheForTests();+ const remote = ((await operationsByName.list_pages.handler(ctx(engine, true), { limit: 100 })) as Array<{ slug: string }>).map(r => r.slug);+ for (const slug of hidden) expect(remote).not.toContain(slug);+ for (const slug of visible) expect(remote).toContain(slug);+ const local = ((await operationsByName.list_pages.handler(ctx(engine, false), { limit: 100 })) as Array<{ slug: string }>).map(r => r.slug);+ for (const slug of [...hidden, ...visible]) expect(local).toContain(slug);+ }+ });++ test('remote get_page refuses a page derived from a private page', async () => {+ for (const engine of engines) {+ __resetPrivateVisibilityCacheForTests();+ for (const slug of ['digests/from-private', 'digests/from-private-md']) {+ await expect(operationsByName.get_page.handler(ctx(engine, true), { slug })).rejects.toThrow('Page not found');+ const local = await operationsByName.get_page.handler(ctx(engine, false), { slug }) as { slug: string };+ expect(local.slug).toBe(slug);+ }+ const world = await operationsByName.get_page.handler(ctx(engine, true), { slug: 'digests/from-world' }) as { slug: string };+ expect(world.slug).toBe('digests/from-world');+ }+ });++ test('remote keyword search does not return derived-private text', async () => {+ for (const engine of engines) {+ __resetPrivateVisibilityCacheForTests();+ const rows = await engine.searchKeyword('wombat', { limit: 50, excludePrivate: true });+ const slugs = rows.map(r => r.slug);+ for (const slug of hidden) expect(slugs).not.toContain(slug);+ expect(slugs).toContain('digests/from-world');+ }+ });+});diff --git a/test/projection-statistics.test.ts b/test/projection-statistics.test.tsindex 0ca7465afd..86c948113a 100644--- a/test/projection-statistics.test.ts+++ b/test/projection-statistics.test.ts@@ -133,3 +133,26 @@ describe('projection migration ledger verification', () => {await verifyProjectionStatistics(engine);}, 60_000);});++describe('PGLite planner statistics after a bulk write', () => {+ test('refresh analyzes every table so joins on source and links see real row counts', async () => {+ const db = new PGlite();+ try {+ await db.exec(`CREATE TABLE pages(id integer PRIMARY KEY, source_id text NOT NULL, frontmatter jsonb,+ text_projection_revision uuid, knowledge_revision uuid);+ CREATE INDEX pages_source_idx ON pages(source_id);+ CREATE TABLE links(from_page_id integer, to_page_id integer);+ INSERT INTO pages SELECT i, 'vault', '{}'::jsonb, NULL, NULL FROM generate_series(1, 3000) i;+ INSERT INTO links SELECT i, i + 1 FROM generate_series(1, 2000) i;`);+ await db.exec(PROJECTION_STATISTICS_SQL.replace(/ANALYZE[^;]*;/, ''));+ expect(await refreshProjectionStatistics(fixtureEngine(db))).toBe(true);+ const stats = await db.query<{ tablename: string; attname: string }>(+ `SELECT tablename, attname FROM pg_stats WHERE (tablename, attname) IN (('pages', 'source_id'), ('links', 'from_page_id'))`);+ expect(stats.rows.length).toBe(2);+ const plan = await db.query<{ 'QUERY PLAN': Array<{ Plan: { 'Plan Rows': number } }> }>(+ `EXPLAIN (FORMAT JSON) SELECT * FROM pages WHERE source_id = ANY('{vault}'::text[])`);+ expect(plan.rows[0]['QUERY PLAN'][0].Plan['Plan Rows']).toBe(3000);+ } finally { await db.close(); }+ }, 30_000);+});+