Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
F5 owner phrases: per-page statement cache and no-op skip
garrytan683a4cb08c25
diff --git a/docs/guides/owner-phrases.md b/docs/guides/owner-phrases.mdindex 1ab442ad3d..93d88edfe7 100644--- a/docs/guides/owner-phrases.md+++ b/docs/guides/owner-phrases.md@@ -156,7 +156,12 @@ The rules below are general to any brain. Each line is covered by a test row inowner-phrase version changes. Windows are rebuilt from every page's storedstatements on each pass, and links are diffed against them. So a windowchange alone relinks exactly the documents it affects, and a deleted or- edited evidence page withdraws its windows.+ edited evidence page withdraws its windows. Parsed statements are cached+ per page under a key of the rules version and the source's account and+ person names, so a pass reparses only edited pages (or every page after a+ name change). A pass that scanned nothing skips the rebuild when its+ inputs hash (rules, names, entity pages, pack, scanned pages and the+ source's other links) is unchanged.Every pass reports `links`, `documents`, `unresolved`, `ambiguous` and`windows` under `mentions.owner_phrases` in `gbrain extract --stale --json`.diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 7acdec8515..d98061ce60 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -103,8 +103,8 @@ const ROWS: readonly Row[] = [['op_checkpoint_paths', 'out_of_scope', 'no_memory_text', 'op fingerprint path'],['op_checkpoints', 'out_of_scope', 'no_memory_text', 'op fingerprint completed_keys'],['open_loops', 'swept', 'open_loops', 'source_id dedup_key loop_type counterparty_slug counterparty_source_id counterparty_email summary evidence thread_id page_slug status detector closed_by'],- ['owner_phrase_page_state', 'out_of_scope', 'probed_reported', 'source_id readings cues descriptors hits', 'cues hits'],- ['owner_phrase_status', 'out_of_scope', 'no_memory_text', 'source_id state window_hash error'],+ ['owner_phrase_page_state', 'out_of_scope', 'probed_reported', 'source_id readings cues descriptors hits statements statements_key', 'cues hits statements'],+ ['owner_phrase_status', 'out_of_scope', 'no_memory_text', 'source_id state window_hash inputs_hash error'],['owner_phrase_windows', 'out_of_scope', 'probed_reported', 'source_id group_key account_slugs owner_key owner_name descriptors evidence evidence_page_ids', 'owner_name evidence'],['page_aliases', 'out_of_scope', 'probed_reported', 'source_id alias_norm slug origin alias_text', 'alias_text'],['page_facts_reconcile', 'out_of_scope', 'no_memory_text', 'outcome'],diff --git a/src/core/mentions/owner-phrase/pass.ts b/src/core/mentions/owner-phrase/pass.tsindex aad8ea1ea3..40f927c82f 100644--- a/src/core/mentions/owner-phrase/pass.ts+++ b/src/core/mentions/owner-phrase/pass.ts@@ -30,8 +30,8 @@ import { canonicalTypeOf, type MentionPolicy, type PackTypes } from '../policy.timport { siblingVerdict } from '../siblings.ts';import { titleName } from '../aliases.ts';import { OWNER_PHRASE_SCAN_VERSION, scanPage, type CueLine, type PhraseHit } from './scan.ts';-import { buildNameIndex, findNames, parseStatements, type NameEntry, type Statement } from './statements.ts';-import { accountDescriptors, buildWindows, resolvePhrase, type OwnerWindow } from './windows.ts';+import { buildNameIndex, findNames, parseStatements, OWNER_PHRASE_RULES_VERSION, type NameEntry, type Statement } from './statements.ts';+import { accountDescriptors, buildWindows, resolvePhrase, windowsByFirstName, type OwnerWindow } from './windows.ts';export const OWNER_PHRASE_KEY = 'mentions.owner_phrases';/** Group key prefix of an account named in a statement that has no page (statements.ts); never stored or linked. */@@ -78,7 +78,8 @@ export interface OwnerPhrasePassOpts {}interface EntityRow { id: number; slug: string; type: string | null; title: string | null; identity: string | null }-interface StateRow { page_id: number; slug: string; page_date: string | null; readings: string[]; agent: boolean; cues: unknown; descriptors: string[]; hits: unknown }+interface StateRow { page_id: number; slug: string; page_date: string | null; readings: string[]; agent: boolean; cues: unknown; descriptors: string[]; hits: unknown;+ statements?: unknown; statements_key?: string | null }function json<T>(value: unknown): T {return (typeof value === 'string' ? JSON.parse(value) : value) as T;@@ -133,7 +134,7 @@ async function scanDuePages(engine: BrainEngine, sourceId: string, deadline: numFROM jsonb_to_recordset(($3::jsonb)->'rows') AS x(id int, rev text, page_date text, readings jsonb, agent boolean, cues jsonb, descriptors jsonb, hits jsonb)ON CONFLICT (page_id) DO UPDATE SET revision = EXCLUDED.revision, version = EXCLUDED.version, page_date = EXCLUDED.page_date,readings = EXCLUDED.readings, agent = EXCLUDED.agent, cues = EXCLUDED.cues, descriptors = EXCLUDED.descriptors, hits = EXCLUDED.hits,- scanned_at = EXCLUDED.scanned_at`,+ statements = NULL, statements_key = NULL, scanned_at = EXCLUDED.scanned_at`,[sourceId, OWNER_PHRASE_SCAN_VERSION], [{ rows }]);scanned += rows.length;}@@ -163,6 +164,8 @@ export interface OwnerPhraseModel {windows: OwnerWindow[];descriptors: Map<string, Set<string>>;links: Array<{ from_id: number; from_slug: string; to_slug: string; context: string; evidence: number[]; line: number; windows: OwnerWindow[] }>;+ /** Statements parsed this build (pages whose cached statements were missing or keyed to other name inputs), to store under `key`. */+ statementCache: { key: string; writes: Array<{ page_id: number; statements: Statement[] }> };counters: Omit<OwnerPhraseCounters, 'links' | 'documents' | 'windows'>;}@@ -200,7 +203,7 @@ export async function buildOwnerPhraseModel(engine: BrainEngine, opts: Pick<Owneconst personIndex = buildNameIndex(personEntries);states ??= await engine.executeRaw<StateRow>(- `SELECT s.page_id, p.slug, s.page_date::text AS page_date, s.readings, s.agent, s.cues, s.descriptors, s.hits+ `SELECT s.page_id, p.slug, s.page_date::text AS page_date, s.readings, s.agent, s.cues, s.descriptors, s.hits, s.statements, s.statements_keyFROM owner_phrase_page_state s JOIN pages p ON p.id = s.page_idWHERE s.source_id = $1 AND p.deleted_at IS NULLAND (jsonb_array_length(s.cues) > 0 OR jsonb_array_length(s.hits) > 0 OR cardinality(s.descriptors) > 0)@@ -217,18 +220,26 @@ export async function buildOwnerPhraseModel(engine: BrainEngine, opts: Pick<Ownefor (const [g, set] of descriptors) for (const d of set) descriptorGroups.set(d, new Set([...(descriptorGroups.get(d) ?? []), g]));const descriptorAccounts = new Map<string, Set<string>>([...descriptorGroups].map(([d, gs]) => [d, gs.size === 1 ? new Set([[...gs][0]!]) : new Set(gs)]));+ const nameKey = (entries: NameEntry[]) => entries.map(e => [e.slug, e.tokens, e.caseTokens ?? null]).sort((a, b) => String(a[0]).localeCompare(String(b[0])) || JSON.stringify(a).localeCompare(JSON.stringify(b)));+ const statementsKey = createHash('sha256').update(JSON.stringify([OWNER_PHRASE_RULES_VERSION, nameKey(accountEntries), nameKey(personEntries), [...accountSlugs].sort(),+ [...descriptorAccounts].map(([d, gs]) => [d, [...gs].sort()]).sort((a, b) => String(a[0]).localeCompare(String(b[0])))])).digest('hex').slice(0, 16);const statements: Statement[] = [];+ const writes: OwnerPhraseModel['statementCache']['writes'] = [];for (const s of states) {const cues = json<CueLine[]>(s.cues);if (!cues.length) continue;- statements.push(...parseStatements(cues, {+ if (s.statements_key === statementsKey && s.statements != null) { statements.push(...json<Statement[]>(s.statements)); continue; }+ const parsed = parseStatements(cues, {page: { id: Number(s.page_id), slug: s.slug, date: s.page_date, agent: s.agent },selfAccount: accountSlugs.has(s.slug) ? s.slug : null,accounts: accountIndex, persons: personIndex, descriptorAccounts,- }));+ });+ statements.push(...parsed);+ writes.push({ page_id: Number(s.page_id), statements: parsed });}const windows = buildWindows(statements, groupOf);const descriptorsOf = (g: string) => descriptors.get(g) ?? (isPageless(g) ? accountDescriptors([g.slice(PAGELESS.length)], []) : new Set<string>());+ const candidatesFor = windowsByFirstName(windows);const links: OwnerPhraseModel['links'] = [];const counters = { unresolved: 0, ambiguous: 0 };@@ -239,7 +250,7 @@ export async function buildOwnerPhraseModel(engine: BrainEngine, opts: Pick<Ownefor (const hit of hits) {const named = findNames(hit.owner, accountIndex);if (named.length && named[0]!.start === 0 && named[0]!.end === hit.owner.length) continue;- const r = resolvePhrase(hit, s.page_date, s.readings ?? [], windows, descriptorsOf);+ const r = resolvePhrase(hit, s.page_date, s.readings ?? [], candidatesFor(hit.owner), descriptorsOf);if (r.linked && r.accounts.every(isPageless)) { counters.unresolved++; continue; }if (!r.linked) {if (r.reason === 'ambiguous' || r.reason === 'readings_disagree') counters.ambiguous++;@@ -254,7 +265,29 @@ export async function buildOwnerPhraseModel(engine: BrainEngine, opts: Pick<Owne}}}- return { windows: windows.filter(w => !isPageless(w.group)), descriptors, links, counters };+ return { windows: windows.filter(w => !isPageless(w.group)), descriptors, links, counters, statementCache: { key: statementsKey, writes } };+}++/**+ * Everything a pass reads besides page scans that are due: the rules version,+ * the source's linkable names, its entity pages, the pack and sibling policy,+ * the set of live scanned pages and the source's other links (a pair another+ * link covers gets no owner-phrase link). A pass that scanned nothing and finds the+ * same hash skips the rebuild (its stored windows and links are current).+ */+async function inputsHash(engine: BrainEngine, opts: Pick<OwnerPhrasePassOpts, 'sourceId' | 'gazetteer' | 'types' | 'pack' | 'policy'>): Promise<string> {+ const names: unknown[] = [];+ for (const bucket of opts.gazetteer.values()) for (const e of bucket) if (e.source_id === opts.sourceId) names.push([e.slug, e.title, e.tokens, e.caseTokens ?? null, e.matchText ?? null]);+ names.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));+ const [sig] = await engine.executeRaw<{ e: string; s: string; l: string }>(+ `SELECT (SELECT count(*) || ':' || COALESCE(sum(id), 0) || ':' || COALESCE(max(updated_at)::text, '') FROM pages+ WHERE source_id = $1 AND deleted_at IS NULL AND type = ANY($2::text[])) AS e,+ (SELECT count(*) || ':' || COALESCE(sum(s.page_id), 0) || ':' || COALESCE(max(s.scanned_at)::text, '') FROM owner_phrase_page_state s+ JOIN pages p ON p.id = s.page_id WHERE s.source_id = $1 AND p.deleted_at IS NULL) AS s,+ (SELECT count(*) || ':' || COALESCE(max(l.id), 0) FROM links l JOIN pages f ON f.id = l.from_page_id+ WHERE f.source_id = $1 AND l.link_kind IS DISTINCT FROM 'owner_phrase') AS l`, [opts.sourceId, opts.types]);+ return createHash('sha256').update(JSON.stringify([OWNER_PHRASE_RULES_VERSION, OWNER_PHRASE_SCAN_VERSION, opts.types, names, sig?.e, sig?.s, sig?.l,+ opts.policy.siblingMerge, opts.pack ?? null])).digest('hex').slice(0, 16);}function windowsHash(windows: OwnerWindow[], privateIds: Set<number>): string {@@ -282,6 +315,15 @@ export async function runOwnerPhrasePass(engine: BrainEngine, opts: OwnerPhrasePconst scan = await scanDuePages(engine, sourceId, opts.deadline, opts.signal);result.scanned = scan.scanned;if (!scan.done) return { ...result, state: 'pending' };+ const inputs = await inputsHash(engine, opts);+ if (!scan.scanned) {+ const [prev] = await engine.executeRaw<{ state: string; inputs_hash: string | null; links: number; documents: number; unresolved: number; ambiguous: number; windows: number }>(+ 'SELECT state, inputs_hash, links, documents, unresolved, ambiguous, windows FROM owner_phrase_status WHERE source_id = $1', [sourceId]);+ if (prev?.state === 'complete' && prev.inputs_hash === inputs) {+ return { ...result, links: Number(prev.links), documents: Number(prev.documents), unresolved: Number(prev.unresolved),+ ambiguous: Number(prev.ambiguous), windows: Number(prev.windows) };+ }+ }const model = await buildOwnerPhraseModel(engine, opts);result.unresolved = model.counters.unresolved;result.ambiguous = model.counters.ambiguous;@@ -295,6 +337,12 @@ export async function runOwnerPhrasePass(engine: BrainEngine, opts: OwnerPhrasePAND (s.page_id IS NULL OR s.revision IS DISTINCT FROM p.knowledge_revision OR s.version IS DISTINCT FROM $2)`,[sourceId, OWNER_PHRASE_SCAN_VERSION]);if (Number(due?.n ?? 0) > 0) return { ...result, state: 'pending' as const };+ if (model.statementCache.writes.length) {+ await executeRawJsonb(tx,+ `UPDATE owner_phrase_page_state s SET statements = x.statements, statements_key = $1+ FROM jsonb_to_recordset(($2::jsonb)->'rows') AS x(page_id int, statements jsonb) WHERE s.page_id = x.page_id`,+ [model.statementCache.key], [{ rows: model.statementCache.writes }]);+ }const privateIds = new Set(evidenceIds.length ? (await tx.executeRaw<{ id: number }>(`SELECT p.id FROM pages p WHERE p.id = ANY($1::int[]) AND NOT ${privatePagesFilterFragment('p')}`, [evidenceIds])).map(r => Number(r.id)) : []);const hash = windowsHash(model.windows, privateIds);@@ -355,12 +403,12 @@ export async function runOwnerPhrasePass(engine: BrainEngine, opts: OwnerPhrasePconst created = add.length ? await tx.addLinksBatch(add, { auditSite: 'extract.mentions' }) : 0; // gbrain-allow-direct-insert: owner-phrase pass — reconciling write of its own owner_phrase rowsconst documents = new Set([...want.values()].map(w => w.link.from_id)).size;await tx.executeRaw(- `INSERT INTO owner_phrase_status (source_id, state, generation, window_hash, windows, links, documents, unresolved, ambiguous, last_pass_at, error, updated_at)- VALUES ($1, 'complete', $2, $3, $4, $5, $6, $7, $8, now(), NULL, now())- ON CONFLICT (source_id) DO UPDATE SET state = 'complete', generation = EXCLUDED.generation, window_hash = EXCLUDED.window_hash,+ `INSERT INTO owner_phrase_status (source_id, state, generation, window_hash, inputs_hash, windows, links, documents, unresolved, ambiguous, last_pass_at, error, updated_at)+ VALUES ($1, 'complete', $2, $3, $9, $4, $5, $6, $7, $8, now(), NULL, now())+ ON CONFLICT (source_id) DO UPDATE SET state = 'complete', generation = EXCLUDED.generation, window_hash = EXCLUDED.window_hash, inputs_hash = EXCLUDED.inputs_hash,windows = EXCLUDED.windows, links = EXCLUDED.links, documents = EXCLUDED.documents, unresolved = EXCLUDED.unresolved,ambiguous = EXCLUDED.ambiguous, last_pass_at = EXCLUDED.last_pass_at, error = NULL, updated_at = now()`,- [sourceId, generation, hash, model.windows.length, want.size, documents, result.unresolved, result.ambiguous]);+ [sourceId, generation, hash, model.windows.length, want.size, documents, result.unresolved, result.ambiguous, inputs]);return { ...result, created, removed: drop.length, links: want.size, documents };});} catch (error) {diff --git a/src/core/mentions/owner-phrase/statements.ts b/src/core/mentions/owner-phrase/statements.tsindex 44db0a8796..0e2205968f 100644--- a/src/core/mentions/owner-phrase/statements.ts+++ b/src/core/mentions/owner-phrase/statements.ts@@ -13,6 +13,9 @@ import { tokenizeForScan } from '../../by-mention.ts';import { RELATIVE_DATE_RE, findDates, type FoundDate } from './dates.ts';import { NAME_STOPWORDS, trimNameRun, type CueLine } from './scan.ts';+/** Bump when the statement grammar changes: cached statements keyed to another version are reparsed. */+export const OWNER_PHRASE_RULES_VERSION = 1;+export type StatementKind = 'takeover' | 'join' | 'ongoing' | 'end' | 'stint' | 'correction';export interface Statement {diff --git a/src/core/mentions/owner-phrase/windows.ts b/src/core/mentions/owner-phrase/windows.tsindex 9f27f6f96b..4dc5974b90 100644--- a/src/core/mentions/owner-phrase/windows.ts+++ b/src/core/mentions/owner-phrase/windows.ts@@ -189,9 +189,22 @@ export function descriptorMatches(descriptors: ReadonlySet<string>, run: string)if (descriptors.has(run)) return true;const words = run.split(' ');if (words.length < 2) return false;- const known = new Set([...descriptors].flatMap(d => d.split(' ')));+ let known = descriptorWords.get(descriptors);+ if (!known) { known = new Set([...descriptors].flatMap(d => d.split(' '))); descriptorWords.set(descriptors, known); }return words.every(w => known.has(w));}+const descriptorWords = new WeakMap<ReadonlySet<string>, Set<string>>();++/** Windows keyed by the owner's first name: every window `ownerMatches` can accept for a surface shares its first word. */+export function windowsByFirstName(windows: OwnerWindow[]): (surface: string) => OwnerWindow[] {+ const index = new Map<string, OwnerWindow[]>();+ for (const w of windows) {+ const key = w.owner.split(/\s+/)[0]!;+ const list = index.get(key);+ if (list) list.push(w); else index.set(key, [w]);+ }+ return surface => index.get(surface.toLowerCase().split(/\s+/)[0]!) ?? [];+}/** Resolve one owner phrase on a document dated `date` (plus its other readings) against the windows (contract lines 9-10). */export function resolvePhrase(hit: Pick<PhraseHit, 'owner' | 'descriptor'>, date: string | null, readings: string[],diff --git a/src/core/schema-migrations/v240-owner-phrase-windows.ts b/src/core/schema-migrations/v240-owner-phrase-windows.tsindex dd2bc26e13..539b950cb1 100644--- a/src/core/schema-migrations/v240-owner-phrase-windows.ts+++ b/src/core/schema-migrations/v240-owner-phrase-windows.ts@@ -37,8 +37,12 @@ export const v240: Migration = {cues JSONB NOT NULL DEFAULT '[]'::jsonb,descriptors TEXT[] NOT NULL DEFAULT '{}',hits JSONB NOT NULL DEFAULT '[]'::jsonb,+ statements JSONB,+ statements_key TEXT,scanned_at TIMESTAMPTZ NOT NULL DEFAULT now());+ ALTER TABLE owner_phrase_page_state ADD COLUMN IF NOT EXISTS statements JSONB;+ ALTER TABLE owner_phrase_page_state ADD COLUMN IF NOT EXISTS statements_key TEXT;CREATE INDEX IF NOT EXISTS owner_phrase_page_state_source_idx ON owner_phrase_page_state (source_id);CREATE TABLE IF NOT EXISTS owner_phrase_windows (id BIGSERIAL PRIMARY KEY,@@ -63,6 +67,7 @@ export const v240: Migration = {state TEXT NOT NULL CHECK (state IN ('complete','pending','failed')),generation BIGINT NOT NULL DEFAULT 0,window_hash TEXT,+ inputs_hash TEXT,windows INTEGER NOT NULL DEFAULT 0,links INTEGER NOT NULL DEFAULT 0,documents INTEGER NOT NULL DEFAULT 0,@@ -72,6 +77,7 @@ export const v240: Migration = {error TEXT,updated_at TIMESTAMPTZ NOT NULL DEFAULT now());+ ALTER TABLE owner_phrase_status ADD COLUMN IF NOT EXISTS inputs_hash TEXT;DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles WHERE rolname=current_user AND rolbypassrls) THENALTER TABLE owner_phrase_page_state ENABLE ROW LEVEL SECURITY;diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex e30ccb4055..ffeb2ef19f 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -2541,7 +2541,9 @@"8 cues jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb","9 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]","10 hits jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",- "11 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "11 statements jsonb/jsonb NULL",+ "12 statements_key text/text NULL",+ "13 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},@@ -2551,14 +2553,15 @@"2 state text/text NOT NULL","3 generation bigint/int8 NOT NULL DEFAULT 0","4 window_hash text/text NULL",- "5 windows integer/int4 NOT NULL DEFAULT 0",- "6 links integer/int4 NOT NULL DEFAULT 0",- "7 documents integer/int4 NOT NULL DEFAULT 0",- "8 unresolved integer/int4 NOT NULL DEFAULT 0",- "9 ambiguous integer/int4 NOT NULL DEFAULT 0",- "10 last_pass_at timestamp with time zone/timestamptz NULL",- "11 error text/text NULL",- "12 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "5 inputs_hash text/text NULL",+ "6 windows integer/int4 NOT NULL DEFAULT 0",+ "7 links integer/int4 NOT NULL DEFAULT 0",+ "8 documents integer/int4 NOT NULL DEFAULT 0",+ "9 unresolved integer/int4 NOT NULL DEFAULT 0",+ "10 ambiguous integer/int4 NOT NULL DEFAULT 0",+ "11 last_pass_at timestamp with time zone/timestamptz NULL",+ "12 error text/text NULL",+ "13 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex e4e6dfcb3b..1a004045fe 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -2541,7 +2541,9 @@"8 cues jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb","9 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]","10 hits jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",- "11 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "11 statements jsonb/jsonb NULL",+ "12 statements_key text/text NULL",+ "13 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},@@ -2551,14 +2553,15 @@"2 state text/text NOT NULL","3 generation bigint/int8 NOT NULL DEFAULT 0","4 window_hash text/text NULL",- "5 windows integer/int4 NOT NULL DEFAULT 0",- "6 links integer/int4 NOT NULL DEFAULT 0",- "7 documents integer/int4 NOT NULL DEFAULT 0",- "8 unresolved integer/int4 NOT NULL DEFAULT 0",- "9 ambiguous integer/int4 NOT NULL DEFAULT 0",- "10 last_pass_at timestamp with time zone/timestamptz NULL",- "11 error text/text NULL",- "12 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "5 inputs_hash text/text NULL",+ "6 windows integer/int4 NOT NULL DEFAULT 0",+ "7 links integer/int4 NOT NULL DEFAULT 0",+ "8 documents integer/int4 NOT NULL DEFAULT 0",+ "9 unresolved integer/int4 NOT NULL DEFAULT 0",+ "10 ambiguous integer/int4 NOT NULL DEFAULT 0",+ "11 last_pass_at timestamp with time zone/timestamptz NULL",+ "12 error text/text NULL",+ "13 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex a8a27b0193..d7e5b2e57d 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -2537,7 +2537,9 @@"8 cues jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb","9 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]","10 hits jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",- "11 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "11 statements jsonb/jsonb NULL",+ "12 statements_key text/text NULL",+ "13 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},@@ -2547,14 +2549,15 @@"2 state text/text NOT NULL","3 generation bigint/int8 NOT NULL DEFAULT 0","4 window_hash text/text NULL",- "5 windows integer/int4 NOT NULL DEFAULT 0",- "6 links integer/int4 NOT NULL DEFAULT 0",- "7 documents integer/int4 NOT NULL DEFAULT 0",- "8 unresolved integer/int4 NOT NULL DEFAULT 0",- "9 ambiguous integer/int4 NOT NULL DEFAULT 0",- "10 last_pass_at timestamp with time zone/timestamptz NULL",- "11 error text/text NULL",- "12 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "5 inputs_hash text/text NULL",+ "6 windows integer/int4 NOT NULL DEFAULT 0",+ "7 links integer/int4 NOT NULL DEFAULT 0",+ "8 documents integer/int4 NOT NULL DEFAULT 0",+ "9 unresolved integer/int4 NOT NULL DEFAULT 0",+ "10 ambiguous integer/int4 NOT NULL DEFAULT 0",+ "11 last_pass_at timestamp with time zone/timestamptz NULL",+ "12 error text/text NULL",+ "13 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex a93007e1b8..9e2ab37648 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -2553,7 +2553,9 @@"8 cues jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb","9 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]","10 hits jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",- "11 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "11 statements jsonb/jsonb NULL",+ "12 statements_key text/text NULL",+ "13 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},@@ -2563,14 +2565,15 @@"2 state text/text NOT NULL","3 generation bigint/int8 NOT NULL DEFAULT 0","4 window_hash text/text NULL",- "5 windows integer/int4 NOT NULL DEFAULT 0",- "6 links integer/int4 NOT NULL DEFAULT 0",- "7 documents integer/int4 NOT NULL DEFAULT 0",- "8 unresolved integer/int4 NOT NULL DEFAULT 0",- "9 ambiguous integer/int4 NOT NULL DEFAULT 0",- "10 last_pass_at timestamp with time zone/timestamptz NULL",- "11 error text/text NULL",- "12 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "5 inputs_hash text/text NULL",+ "6 windows integer/int4 NOT NULL DEFAULT 0",+ "7 links integer/int4 NOT NULL DEFAULT 0",+ "8 documents integer/int4 NOT NULL DEFAULT 0",+ "9 unresolved integer/int4 NOT NULL DEFAULT 0",+ "10 ambiguous integer/int4 NOT NULL DEFAULT 0",+ "11 last_pass_at timestamp with time zone/timestamptz NULL",+ "12 error text/text NULL",+ "13 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 9727946a86..b6759f105b 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -2553,7 +2553,9 @@"8 cues jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb","9 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]","10 hits jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",- "11 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "11 statements jsonb/jsonb NULL",+ "12 statements_key text/text NULL",+ "13 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},@@ -2563,14 +2565,15 @@"2 state text/text NOT NULL","3 generation bigint/int8 NOT NULL DEFAULT 0","4 window_hash text/text NULL",- "5 windows integer/int4 NOT NULL DEFAULT 0",- "6 links integer/int4 NOT NULL DEFAULT 0",- "7 documents integer/int4 NOT NULL DEFAULT 0",- "8 unresolved integer/int4 NOT NULL DEFAULT 0",- "9 ambiguous integer/int4 NOT NULL DEFAULT 0",- "10 last_pass_at timestamp with time zone/timestamptz NULL",- "11 error text/text NULL",- "12 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "5 inputs_hash text/text NULL",+ "6 windows integer/int4 NOT NULL DEFAULT 0",+ "7 links integer/int4 NOT NULL DEFAULT 0",+ "8 documents integer/int4 NOT NULL DEFAULT 0",+ "9 unresolved integer/int4 NOT NULL DEFAULT 0",+ "10 ambiguous integer/int4 NOT NULL DEFAULT 0",+ "11 last_pass_at timestamp with time zone/timestamptz NULL",+ "12 error text/text NULL",+ "13 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 56a315fde2..87338eb5e0 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -2549,7 +2549,9 @@"8 cues jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb","9 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]","10 hits jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",- "11 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "11 statements jsonb/jsonb NULL",+ "12 statements_key text/text NULL",+ "13 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},@@ -2559,14 +2561,15 @@"2 state text/text NOT NULL","3 generation bigint/int8 NOT NULL DEFAULT 0","4 window_hash text/text NULL",- "5 windows integer/int4 NOT NULL DEFAULT 0",- "6 links integer/int4 NOT NULL DEFAULT 0",- "7 documents integer/int4 NOT NULL DEFAULT 0",- "8 unresolved integer/int4 NOT NULL DEFAULT 0",- "9 ambiguous integer/int4 NOT NULL DEFAULT 0",- "10 last_pass_at timestamp with time zone/timestamptz NULL",- "11 error text/text NULL",- "12 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "5 inputs_hash text/text NULL",+ "6 windows integer/int4 NOT NULL DEFAULT 0",+ "7 links integer/int4 NOT NULL DEFAULT 0",+ "8 documents integer/int4 NOT NULL DEFAULT 0",+ "9 unresolved integer/int4 NOT NULL DEFAULT 0",+ "10 ambiguous integer/int4 NOT NULL DEFAULT 0",+ "11 last_pass_at timestamp with time zone/timestamptz NULL",+ "12 error text/text NULL",+ "13 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex f65398efac..a07ea5efb5 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -3629,8 +3629,8 @@"idempotent": true,"name": "owner_phrase_windows","sql": {- "length": 2707,- "sha256": "d02bcdb4bc07f65d7980750ea37e84aa152ac1a65fb7d8f075c24901e521bf49"+ "length": 3030,+ "sha256": "791a738685eaace24e8758e42eb2d76556157a4a20a2cc6545554249dd63b2a8"},"sqlFor": "absent","transaction": "absent",diff --git a/test/owner-phrase-pass.test.ts b/test/owner-phrase-pass.test.tsindex 40b10c4b65..dc012efc06 100644--- a/test/owner-phrase-pass.test.ts+++ b/test/owner-phrase-pass.test.ts@@ -88,9 +88,32 @@ describe('windows and links', () => {expect(Number(aliases[0]!.n)).toBe(0);});- test('a rerun with nothing changed writes nothing', async () => {+ test('a rerun with nothing changed writes nothing; parsed statements are cached under one key; an edited page or a stale key is reparsed', async () => {const r = await sweepOwnerPhrases(engine);- expect(r).toMatchObject({ state: 'complete', created: 0, removed: 0, links: 4 });+ expect(r).toMatchObject({ state: 'complete', created: 0, removed: 0, links: 4, unresolved: 3, ambiguous: 1, windows: 6 });+ const keys = async () => (await engine.executeRaw<{ slug: string; k: string | null }>(+ `SELECT p.slug, s.statements_key AS k FROM owner_phrase_page_state s JOIN pages p ON p.id = s.page_id WHERE jsonb_array_length(s.cues) > 0 ORDER BY 1`));+ const before = await keys();+ expect(before.length).toBeGreaterThan(3);+ expect(new Set(before.map(k => k.k)).size).toBe(1);+ expect(before[0]!.k).not.toBeNull();+ const [status] = await engine.executeRaw<{ inputs_hash: string | null }>('SELECT inputs_hash FROM owner_phrase_status');+ expect(status!.inputs_hash).not.toBeNull();+ await doc(engine, 'updates/nimbus-owner', 'Juniper Example owns Nimbus Example Freight. Renewal is on track.', { date: '2025-01-01' });+ await engine.executeRaw(`UPDATE owner_phrase_page_state SET statements_key = 'stale' WHERE page_id <> (SELECT id FROM pages WHERE slug = 'updates/nimbus-owner') AND statements_key IS NOT NULL`);+ await sweepOwnerPhrases(engine);+ expect(new Set((await keys()).map(k => k.k))).toEqual(new Set([before[0]!.k]));+ expect(await ownerPhraseLinks(engine)).toEqual(snap.trusted);+ });++ test('a link another producer adds for a linked pair replaces the owner-phrase row on the next pass, with no page edited', async () => {+ const [[f], [t]] = await Promise.all(['notes/renewal', ACME].map(slug => engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [slug])));+ await engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, link_source) VALUES ($1, $2, 'mentions', 'manual')`, [f!.id, t!.id]);+ await sweepOwnerPhrases(engine);+ expect(await ownerPhraseLinks(engine)).not.toContain(`notes/renewal -> ${ACME}`);+ await engine.executeRaw(`DELETE FROM links WHERE link_source = 'manual'`);+ await sweepOwnerPhrases(engine);+ expect(await ownerPhraseLinks(engine)).toEqual(snap.trusted);});});