Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(facts): withdrawal discovery folds each text once (#6270)

time-attack90fba7ac4710
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 6c764bc98d..4582fccc17 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -18,7 +18,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/facts/queue.ts:FactsQueue.drainPending` — method `drainPending({timeout?: number}): Promise<{drained, unfinished}>`. Semantically distinct from `shutdown()` (which calls `this.internalAbort.abort()` and would abort the very facts:absorb worker trying to log its post-completion event). Drain lets in-flight finish; only the wait is bounded. Default timeout `1000ms` so commands that don't enqueue facts pay one fast 0ms check before exit. `src/cli.ts` op-dispatch finally block awaits `getFactsQueue().drainPending({timeout: 1000})` BEFORE `engine.disconnect()`. Lazy-import keeps the facts-queue module off the hot path for ops that never touch it. Prevents a trailing `'No database connection'` line after `gbrain capture` (a post-page-write facts:absorb outliving the CLI process). Pinned by `test/facts-queue-drain-pending.test.ts` (4 cases: empty fast-path, in-flight settled without abort, unfinished count on timeout, default timeout = 1000ms).
-- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`. `recordFactWithdrawal(…, { semanticReview })` also queues a `withdraw` review row in `decide_review_queue` inside the same transaction when `decide.slots.conflict.review_withdraw` is on (unset counts as on; `reviewWithdrawOn`) and the caller did not opt out, and runs every `registerWithdrawalInvalidation` hook in that transaction for projections beyond pages and chunks. `src/core/facts/similar-active.ts` — `similarActiveAfterForget`: after a committed `forget`, up to five active facts with the same source, entity and visibility (world only for remote callers) at cosine >= 0.80 to the withdrawn fact's stored embedding, returned as ids and scores with the overnight review state and a `next` line (zero model calls; pinned by `test/decide/review-withdraw.serial.test.ts`).
+- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (one `lower(text) LIKE ALL(patterns)` fold per text with `%`, `_` and `\` escaped, #6270; necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`. `recordFactWithdrawal(…, { semanticReview })` also queues a `withdraw` review row in `decide_review_queue` inside the same transaction when `decide.slots.conflict.review_withdraw` is on (unset counts as on; `reviewWithdrawOn`) and the caller did not opt out, and runs every `registerWithdrawalInvalidation` hook in that transaction for projections beyond pages and chunks. `src/core/facts/similar-active.ts` — `similarActiveAfterForget`: after a committed `forget`, up to five active facts with the same source, entity and visibility (world only for remote callers) at cosine >= 0.80 to the withdrawn fact's stored embedding, returned as ids and scores with the overnight review state and a `next` line (zero model calls; pinned by `test/decide/review-withdraw.serial.test.ts`).
- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (per-model threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only on `memory/unattributed` and, through the intent's opt-in `attribute_fallback` flag, which only writeSingleFact sets, keeps the resolver's fallback slug as `entity_slug` with no row number, so dedup and withdrawal checks stay per entity; the facts backstop never sets it and keeps those rows unattributed). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims. A fence append refused because the page's facts fence does not parse cleanly rethrows the typed `fenceRefusal` (`invalid_fence` / `target_fence_malformed`). On an unmanaged brain, #6398 (fix wave 13): when the page's file is missing but a source-scoped row exists (live, with a vanished `source_path` file, or tombstoned), `writeFactsToFence` returns `stubGuardBlocked` with audit reason `db_only_page` and the caller records the facts DB-only, so no stub overwrites the DB body or resurrects a deleted page; an unreadable row returns `fenceWriteFailed`; the #4872 page mirror runs only for a body read from a real file. Doctor `stub_guard_24h` (`commands/doctor/checks/local-audits.ts`) counts `unprefixed`, `fallback_resolution` and `db_only_page` separately; `db_only_page` never feeds the WARN threshold. Tests: `test/fence-write-db-only.test.ts`, `test/doctor-stub-guard.test.ts`.
- `src/core/facts/managed-fact-write.ts` — `publishManagedEntityFacts(engine, sourceId, entity, facts)` builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt; `attributeFallback` sets the intent's `attribute_fallback`), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; `managedFactWritePreflight` runs the same session checks before a caller's model call.
diff --git a/src/core/facts/withdrawal-discovery.ts b/src/core/facts/withdrawal-discovery.ts
index 3be3d74686..4fb907d9a6 100644
--- a/src/core/facts/withdrawal-discovery.ts
+++ b/src/core/facts/withdrawal-discovery.ts
@@ -55,7 +55,9 @@ export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: s
FROM jsonb_to_recordset($2::text::jsonb) w(visibility text,fact_hash text,subject text,claim text)
) SELECT * FROM w`,
[sourceId, JSON.stringify(claims.map(c => ({ visibility: c.visibility, fact_hash: c.fact_hash, subject: c.subject ?? '*', claim: c.claim ?? null })))]);
- const keys = JSON.stringify(keyed.map(k => ({ ...k, tokens: k.norm ? k.norm.split(' ').filter(Boolean) : [] })));
+ const keys = JSON.stringify(keyed.map(k => ({ ...k,
+ patterns: (k.norm ? k.norm.split(' ').filter(Boolean) : []).map(token => `%${token.replace(/[\\%_]/g, '\\$&')}%`),
+ })));
const subjects = keyed.some(k => k.subject === '*') ? null : [...new Set(keyed.map(k => k.subject))];
const affected = new Set<number>();
const provenance = await engine.executeRaw<{ id: number }>(`SELECT DISTINCT p.id
@@ -78,13 +80,13 @@ export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: s
for (const row of matches) affected.add(row.id);
if (affected.size > WITHDRAWAL_LIMITS.targets) await refuseAffected(engine, sourceId, affected);
};
- const shortlist = (text: string) => `NOT EXISTS (SELECT 1 FROM jsonb_array_elements_text(k.tokens) t(v) WHERE strpos(lower(${text}),t.v)=0)`;
+ const shortlist = (text: string) => `lower(${text}) LIKE ALL(k.patterns)`;
for (let after = 0; ;) {
if (performance.now() > deadline) refuse();
const pages = await engine.executeRaw<{ id: number; slug: string; compiled_truth: string; timeline: string }>(`SELECT p.id,p.slug,p.compiled_truth,p.timeline FROM pages p
WHERE p.source_id=$1 AND p.id>$3 AND ($5::text[] IS NULL OR p.slug=ANY($5::text[]))
AND (strpos(p.compiled_truth,'gbrain:facts:')>0 OR strpos(p.timeline,'gbrain:facts:')>0)
- AND EXISTS (SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) k(subject text,tokens jsonb)
+ AND EXISTS (SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) k(subject text,patterns text[])
WHERE (k.subject='*' OR k.subject=p.slug) AND ((${shortlist('p.compiled_truth')}) OR (${shortlist('p.timeline')})))
ORDER BY p.id LIMIT $4`, [sourceId, keys, after, WITHDRAWAL_LIMITS.batch, subjects]);
await match(pages.flatMap(page => [page.compiled_truth, page.timeline].flatMap(body => [
@@ -99,7 +101,7 @@ export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: s
const chunks = await engine.executeRaw<{ id: number; page_id: number; slug: string; chunk_text: string }>(`SELECT c.id,c.page_id,p.slug,c.chunk_text
FROM content_chunks c JOIN pages p ON p.id=c.page_id
WHERE p.source_id=$1 AND c.id>$3 AND ($5::text[] IS NULL OR p.slug=ANY($5::text[]))
- AND EXISTS (SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) k(subject text,tokens jsonb)
+ AND EXISTS (SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) k(subject text,patterns text[])
WHERE (k.subject='*' OR k.subject=p.slug) AND ${shortlist('c.chunk_text')})
ORDER BY c.id LIMIT $4`, [sourceId, keys, after, WITHDRAWAL_LIMITS.batch, subjects]);
await match(chunks.flatMap(chunk => {
diff --git a/test/e2e/withdrawal-discovery-literal-postgres.test.ts b/test/e2e/withdrawal-discovery-literal-postgres.test.ts
new file mode 100644
index 0000000000..15ff8dd9c5
--- /dev/null
+++ b/test/e2e/withdrawal-discovery-literal-postgres.test.ts
@@ -0,0 +1,2 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+await registerPostgresTests(() => import('../withdrawal-discovery-literal.test.ts'));
diff --git a/test/withdrawal-discovery-literal.test.ts b/test/withdrawal-discovery-literal.test.ts
new file mode 100644
index 0000000000..7619ce9015
--- /dev/null
+++ b/test/withdrawal-discovery-literal.test.ts
@@ -0,0 +1,109 @@
+/**
+ * #6270: withdrawal discovery shortlists candidate text with one escaped
+ * `lower(text) LIKE ALL(patterns)` fold; the exact fingerprint stays the decider.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { discoverWithdrawalTargets } from '../src/core/facts/withdrawal-discovery.ts';
+import { renderFactsTable, FACTS_FENCE_END } from '../src/core/facts-fence.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+for (const backend of testBackends()) describe(`literal withdrawal ${backend}`, () => {
+let engine: BrainEngine, close: () => Promise<void>;
+const sourceId = 'literal-withdrawal-example';
+const otherSource = 'literal-withdrawal-other';
+const foldSource = 'literal-withdrawal-folding';
+const fence = (claim: string, visibility: 'world' | 'private' = 'world') => renderFactsTable([
+ { rowNum: 1, claim, visibility, kind: 'fact', confidence: 1, notability: 'medium', active: true },
+]);
+beforeAll(async () => {
+ if (backend === 'postgres') {
+ const fixture = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engine = fixture.engine; close = fixture.close;
+ } else {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect();
+ }
+ for (const id of [sourceId, otherSource, foldSource]) await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [id]);
+}, 120_000);
+afterAll(() => close());
+
+async function page(slug: string, body: string, chunk: string, source = sourceId) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body, timeline: '' }, { sourceId: source });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_text: chunk, chunk_source: 'compiled_truth' }], { sourceId: source });
+}
+async function discover(claim: string, subject = '*', visibility = 'world') {
+ const [row] = await engine.executeRaw<{ hash: string }>('SELECT gbrain_fact_fingerprint($1) AS hash', [claim]);
+ return (await discoverWithdrawalTargets(engine, sourceId, [{ claim, subject, visibility, fact_hash: row.hash }])).map(p => p.slug);
+}
+
+test('literal symbols and punctuation preserve exact stale-chunk matches and exclude near matches', async () => {
+ const claim = 'C++ and C# use Node.js, not C; 50% alpha_beta \\ paths.';
+ await page('notes/literal', 'Original prose without derived fence', claim.toUpperCase());
+ await page('notes/near', '', 'C and C use Nodejs not C 50 alpha beta paths');
+ await page('notes/same-other-source', '', claim, otherSource);
+ expect(await discover(claim)).toEqual(['notes/literal']);
+});
+test('all tokens are only a shortlist: reordered and extra-token chunks do not match', async () => {
+ const claim = 'literal precision token delta';
+ await page('notes/ordered', '', claim);
+ await page('notes/reordered', '', 'delta token precision literal');
+ await page('notes/extra', '', claim + ' unrelated');
+ expect(await discover(claim)).toEqual(['notes/ordered']);
+});
+test('subject and visibility continue to fence page evidence', async () => {
+ const claim = 'visibility sentinel precise';
+ await page('notes/private', fence(claim, 'private'), 'Unrelated stale chunk');
+ await page('notes/world', fence(claim), 'Unrelated stale chunk');
+ expect(await discover(claim, '*', 'private')).toEqual(['notes/private']);
+ expect(await discover(claim, 'notes/world')).toEqual(['notes/world']);
+});
+test('multiple withdrawal claims retain complete candidate union', async () => {
+ const claims = ['union alpha sentinel', 'union beta sentinel'];
+ for (const [n, claim] of claims.entries()) await page('notes/union-' + n, '', claim);
+ const rows = [];
+ for (const claim of claims) {
+ const [row] = await engine.executeRaw<{ hash: string }>('SELECT gbrain_fact_fingerprint($1) AS hash', [claim]);
+ rows.push({ claim, subject: '*', visibility: 'world', fact_hash: row.hash });
+ }
+ expect((await discoverWithdrawalTargets(engine, sourceId, rows)).map(p => p.slug)).toEqual(['notes/union-0', 'notes/union-1']);
+});
+test('a matching malformed fence still refuses complete discovery', async () => {
+ const claim = 'ambiguous matching sentinel';
+ const malformed = fence(claim).replace(FACTS_FENCE_END, '');
+ expect(malformed).not.toContain(FACTS_FENCE_END);
+ await page('notes/malformed', malformed, 'Unrelated stale chunk');
+ await expect(discover(claim)).rejects.toMatchObject({ code: 'withdrawal_provenance' });
+});
+test('empty claim list remains a no-op', async () => {
+ expect(await discoverWithdrawalTargets(engine, sourceId, [])).toEqual([]);
+});
+// #6270: the shortlist folds each candidate text once, not once per claim token.
+// A transaction-local lower() shim counts executed folds; the fingerprint functions
+// call pg_catalog.lower and bypass it. This pins the work bound, not query spelling or speed.
+test('the shortlist folds each candidate chunk once while exact verification still decides', async () => {
+ const claim = 'the example user prefers project updates by email on weekday mornings';
+ const count = 8;
+ for (let n = 0; n < count; n++) {
+ await page(`notes/folding-${n}`, '', n === 0 ? claim.toUpperCase() : claim + ' synthetic padding'.repeat(64), foldSource);
+ }
+ const [key] = await engine.executeRaw<{ hash: string }>('SELECT gbrain_fact_fingerprint($1) AS hash', [claim]);
+ await engine.executeRaw('CREATE TABLE public.withdrawal_fold_counter(folds integer NOT NULL)');
+ await engine.executeRaw('INSERT INTO public.withdrawal_fold_counter VALUES (0)');
+ await engine.executeRaw(`CREATE FUNCTION public.lower(value text) RETURNS text LANGUAGE plpgsql VOLATILE AS $fn$
+ BEGIN UPDATE public.withdrawal_fold_counter SET folds = folds + 1; RETURN pg_catalog.lower(value); END $fn$`);
+ try {
+ const targets = await engine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL search_path = public, pg_catalog');
+ return discoverWithdrawalTargets(tx, foldSource, [{ claim, fact_hash: key.hash, subject: '*', visibility: 'world' }]);
+ });
+ expect(targets.map(t => t.slug)).toEqual(['notes/folding-0']);
+ const [work] = await engine.executeRaw<{ folds: number }>('SELECT folds FROM public.withdrawal_fold_counter');
+ expect(work.folds).toBe(count);
+ } finally {
+ await engine.executeRaw('DROP FUNCTION public.lower(text)');
+ await engine.executeRaw('DROP TABLE public.withdrawal_fold_counter');
+ }
+});
+});