Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): run purge refusal and withdrawal stamp once per INSERT statement (#7105)
garrytan678aeb7f411d
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 2576ab87b6..34a2d24634 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 (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. One facts fence a forced cut splits is checked as one batch; over 16,384 rows or 8 MiB it refuses with reason `split_fence_rows`, naming the page and the fence (`test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts`). 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`). Segmented affected pages are struck segment by segment through `rewriteLiveSegmentedFences` (a new generation whose flip replaces only the rewritten occurrences' chunks); discovery also scans live manifest rows with `facts_slots`, reading only each slot's bytes, and joins a fence a forced cut split from its slots' bytes (`splitFactsFences`; above `PAGE_MAX_BYTES` it refuses with `page_body_segmented`), so a private row, which never reaches chunks, is found wherever the cut falls.+- `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. One facts fence a forced cut splits is checked as one batch; over 16,384 rows or 8 MiB it refuses with reason `split_fence_rows`, naming the page and the fence (`test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts`). 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 triggers (once per INSERT statement since v263, per row on UPDATE); they prevent 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`). Segmented affected pages are struck segment by segment through `rewriteLiveSegmentedFences` (a new generation whose flip replaces only the rewritten occurrences' chunks); discovery also scans live manifest rows with `facts_slots`, reading only each slot's bytes, and joins a fence a forced cut split from its slots' bytes (`splitFactsFences`; above `PAGE_MAX_BYTES` it refuses with `page_body_segmented`), so a private row, which never reaches chunks, is found wherever the cut falls.- `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/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.mdindex a1bb99e49c..a64ab5c70b 100644--- a/docs/architecture/key-files/memory-purge.md+++ b/docs/architecture/key-files/memory-purge.md@@ -9,7 +9,8 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu- `src/core/belief/purge.ts` — the purge half of the belief ledger (BELIEF_LEDGER.md 6.5). Every fact or page purge bumps `sources.purge_epoch` (`bumpPurgeEpoch`; an append prepared at an older epoch with `preparedEpoch` refuses `belief_stale_preparation`) and runs three passes inside the purge transaction: `redactPurgedKeys` (the purged keys, by `claim_fp` and page lifetime, keep skeletons: value, value_hash and prior_hash null, `purged`), `redactCarryingFields` (keyset batches of 1000 reading only the carrying fields of fact, take and link events, matched in JS by `quotes` over `claimForms`, never SQL `lower()`/`strpos`: each carrying field from `CARRYING_FIELDS` that quotes a purged claim, plain or fence-escaped, becomes `REDACTION_MARKER(<purge request>)` and is listed in `redacted_fields`; a later event's prior_hash naming the old hash names the new one) with `registerLiveCarriers` (a surviving row whose field quotes the claim enters `belief_redactions` with its field hash, so its next event writes the marker until an explicit owner edit sets a different value: `publicationBeliefOptions` marks `ownerEdit` only on a local `put_page`, `edit_page`, `takes_update` or `takes_resolve` with no internal intent kind, and append still needs `OWNER_TIER_FLOOR`) and, for a fact purge, `registerVersionCarriers` (the retained versions still quoting the claim, registered under the keys the backfill gives them). A claim shorter than 8 characters quotes a field only as a word in spaced scripts (`ceo` does not match `herbaceous`; CJK and markup still match), and `appendDerivedHidden` (one `derived.hidden` per key the derivation walk hid; `readBeliefHistory` then hides that key's earlier events and every backfill event of it). A page purge's claims come from `pagePurgeClaims`: the page's facts and takes, every retained version's fence rows and every claim in its lifetimes' events, unbounded. `releaseSuppressedFields` is the owner release `trust confirm` runs (`belief_redactions.released_hash`); every release, there or in an owner-edit append, appends one `redaction.released` (`redactionReleasedDraft`: fields, purge requests and released hashes, never the text) in the publication `released_by` names. The receipt's `ledger` block reports the counts and `derived_walk`; a truncated walk withholds certification of its coverage interval (`coverage-report.ts`). Purge-verify's ledger report is a JS keyset scan too: a missed carrying field is `incomplete`, another subject's recorded value quoting the claim is `out_of_scope` with `field@key` items. Seam: `__setPurgeRedactionFaultForTests`. Probes: `test/belief-ledger-purge.test.ts` (both engines).- `src/core/belief/purge-mirror.ts` — the text-free purge mirror `<brain home>/.gbrain/purge-events.jsonl` (0600, fsynced): an `intent` line before the purge commits (`appendPurgeIntent`; request, source and incarnation, scope, fingerprints, content hashes, lifetimes, epoch; never claim text; an unwritable mirror refuses the purge with the typed `purge_mirror_unwritable`, with or without a ledger) and a `committed` line after (`appendPurgeCommitted`, best effort; a page purge writes it from the coordinator's `afterCommit`, so it does not depend on the op handler finishing). `restorePgliteBackup` (`gbrain backup restore --purge-mirror <absolute path>` names a mirror other than the brain home's) replays every committed purge newer than the archive inside its transaction (`replayPurgesInRestore`: tombstones, row removal (a fact-scope replay rewrites page bodies and versions through `rewritePageBodies` / `redactPageVersions`, then runs `purgeSegmentStorage` with each claim's `stagingsHoldingClaim`; a page-scope replay deletes the page through `deletePageWithSegments`, so segment texts that held the purged content go in the replay, as in the purge), the three passes, the derived rows hidden again with `derived.hidden` cause `restore_replay`, one `fact.purged`/`page.purged` with cause `restore_replay`; a page-scope replay matches pages by content hash or lifetime, never by slug alone; an archive from before the ledger, no `belief_events`, replays tombstones and row removal and reports `ledger: 'absent'`; an intent whose request already has tombstones is skipped), records each as `complete`, `partial` (no restored row held the text, or the derivation walk could not run) or `unverified` (intent without committed line, not replayed), returns `purge_replay` in the receipt and adds a reconnect warning unless the state is `none` or `complete`; an unreadable mirror is `unavailable`. `coverage.restored` carries the outcome, which `readRestorePurgeReplay` reads back for the doctor. A Postgres restore runs `gbrain beliefs replay-purges --archived-at <iso> (--purge-mirror <abs path> | --from-url-env <VAR>) [--apply]` (`src/commands/beliefs-replay-purges.ts`; dry run by default: `replayPurges` runs the replay in a transaction that rolls back), whose database source `purgeLinesFromDatabase` rebuilds the intents from every pre-restore tombstone (not bounded by `purged_at`, the purge transaction's start) and skips those the archive already holds. Seam: `__setPurgeReplayFaultForTests`. Probes: `test/belief-ledger-restore.test.ts`; segment storage after a replay: `test/large-pages/purge-replay-segments.test.ts` (both engines).- `src/core/facts/purge-overlay.ts` — purge mode of the import overlay: `dropPurgedFenceRows` drops facts-fence rows matching `fact_purges` and takes-fence rows matching `take_purges` (the takes fence re-renders with its reservation rows plus the dropped numbers reserved, so a purged number is never reused; pinned by `test/purge-overlay-reservations.test.ts`) (subject = page slug; malformed fences left to the withdrawal diagnostics, which refuse a purged claim inside one). Called first by `preserveWithdrawnFenceRows`, so `import-file.ts` needs no change; the snapshot overlay (`page-state/snapshot.ts`) and export (`export-snapshot.ts`) carry purge tombstones as `PageWithdrawal.purged`, which `overlayWithdrawalBody` drops instead of striking.-- `src/core/facts/purge-schema.ts` — `MEMORY_PURGE_SCHEMA_SQL` (schema.sql fragment: `fact_purges`, `take_purges`, `page_purges` keyed `(source_id, content_hash)`, `derivation_inputs`, `needs_rederive`) and `MEMORY_PURGE_GUARD_SQL` (migration only): `facts_refuse_purged`, `takes_refuse_purged` and `pages_refuse_purged` raise `P0001 purged_content: …` (mapped to typed `purged_content` by `persistence/publication-failure.ts`) instead of skipping the row, whatever `expired_at` says. The pages guard has no column list so it never pins columns. `FACT_PURGE_LOOKUP_INDEX_SQL` (migration v231, CONCURRENTLY on Postgres) adds `fact_purges_subject_idx` (a page's own tombstones, the '*' lookup by fingerprint) and the partial `fact_purges_all_subjects_idx` (subject '*' only, for the snapshot marker count).+- `src/core/facts/purge-schema.ts` — `MEMORY_PURGE_SCHEMA_SQL` (schema.sql fragment: `fact_purges`, `take_purges`, `page_purges` keyed `(source_id, content_hash)`, `derivation_inputs`, `needs_rederive`) and `MEMORY_PURGE_GUARD_SQL` (migration only): `facts_refuse_purged`, `takes_refuse_purged` and `pages_refuse_purged` raise `P0001 purged_content: …` (mapped to typed `purged_content` by `persistence/publication-failure.ts`) instead of skipping the row, whatever `expired_at` says. The pages guard has no column list so it never pins columns. Since migration v263 `facts_refuse_purged` fires on UPDATE only; the facts insert check runs once per statement in `facts/insert-guard-schema.ts`. `FACT_PURGE_LOOKUP_INDEX_SQL` (migration v231, CONCURRENTLY on Postgres) adds `fact_purges_subject_idx` (a page's own tombstones, the '*' lookup by fingerprint) and the partial `fact_purges_all_subjects_idx` (subject '*' only, for the snapshot marker count).+- `src/core/facts/insert-guard-schema.ts` — `FACT_INSERT_GUARD_SQL` (migration v263, #7105): one statement-level `facts_guard_inserted` trigger (`AFTER INSERT ... REFERENCING NEW TABLE AS inserted_facts`, function `gbrain_guard_inserted_facts`) runs both facts insert guards once per statement instead of once per row. It takes `FOR SHARE` on each inserted source row, refuses a statement whose rows match a `fact_purges` tombstone with the same `P0001 purged_content` message and `{table, hash8}` detail (the first matching row in insertion order, whatever its `expired_at`), then stamps inserted active rows that match `fact_withdrawals` (v2 or v1 fingerprint) with `expired_at = min(withdrawn_at)` and a clamped `valid_until`, by an UPDATE of just those rows. A ledger with no row for the inserted sources costs one index probe. Transition tables cannot take a column list, so `facts_refuse_purged` and `facts_preserve_withdrawal` stay per-row for UPDATE (`BEFORE UPDATE OF ...`). Differences from the per-row insert guards: a row ON CONFLICT DO NOTHING skips is not checked (it is not written either); a row that another per-row BEFORE trigger (for example `managed_writer_guard`) also refuses reports that refusal first; a stamped row of an unattributed write gets `last_written_at` from the stamping UPDATE. Pinned by `test/facts-insert-guards-7105.test.ts` (guard calls and firings per statement, and the same refusals and stamps as the per-row guards re-installed in a rolled-back transaction, both engines).- `src/core/page-state/snapshot.ts` — a page snapshot lists only the page's own `fact_purges` tombstones; subject-'*' ones come back as `PageSnapshot.globalPurges` (count, latest `purged_at`, world-only flag; absent at count 0). `resolveGlobalPurges` turns the marker into purge withdrawals for the fence rows of whatever text is overlaid (stored page, incoming file in `page-prepare.ts`, `overlayCanonicalBodies`), on the caller's query. Reconcile pins/preimages and extract-atoms page-state hashing carry the marker, so a new '*' purge invalidates them and an artifact without it reads stale. Alias resolution: `readPageSnapshot` with `resolveAlias` first runs the exact-slug statement (an exact hit outranks every alias), then, on a miss or for `requireUnambiguous`, one `WITH chosen` statement whose candidates are a UNION ALL of the exact-slug probe and an alias-join probe (`slug_aliases` → `pages` on `(source_id, canonical_slug)`, `p.slug<>$1` keeps the branches disjoint so `count(*) OVER ()` still counts pages). #6281: never `slug=$1 OR EXISTS(alias)`, which read every page of every readable source; `page-snapshot-alias-plan.test.ts` pins fewer than 100 `pages` rows per statement from EXPLAIN on both engines.- `src/core/facts/derivation-inputs.ts` — `recordDerivationInputs(tx, {table, id, sourceId}, inputs)`: complete derived-row → input edges, written by derivers in the deriving transaction (`write_origin` keeps only a display sample). `derivedRowsFrom` walks edges breadth-first (bounded, reports `truncated`); `hideDerivedRows` expires facts, deactivates takes, soft-deletes pages and upserts `needs_rederive`.- `src/core/deletion-inventory.ts` — the deletion-target registry: every table with a text, JSON, bytes, array, lexeme or vector column, classed `swept`, `retained_inactive` or `out_of_scope` (`probed_reported` with probe columns, `text_free_ledger`, `secret_material`, `no_memory_text`), plus on-disk stores and out-of-reach residuals. `test/deletion-inventory.test.ts` fails on any unlisted text-bearing column of a fresh schema and pins the AGENTS.md "never promise physical erasure" line.diff --git a/src/core/facts/insert-guard-schema.ts b/src/core/facts/insert-guard-schema.tsnew file mode 100644index 0000000000..d25e71ccd2--- /dev/null+++ b/src/core/facts/insert-guard-schema.ts@@ -0,0 +1,77 @@+/**+ * Set-based insert guards on facts (#7105). One statement-level AFTER INSERT+ * trigger reads the statement's inserted rows from a transition table and+ * applies both insert-time guards once per statement instead of once per row:+ *+ * - Purge refusal (purge-schema.ts `gbrain_refuse_purged_fact`): an inserted+ * row whose fingerprint has a fact_purges tombstone for its source,+ * visibility and subject ('*' or its entity_slug) aborts the statement with+ * the same P0001 `purged_content` message and `{table, hash8}` detail,+ * whatever its expired_at. When several rows match, the detail names the+ * first one in insertion order, as the per-row trigger did.+ * - Withdrawal preservation (withdrawal-schema.ts+ * `gbrain_preserve_fact_withdrawal`): an inserted active row matching a+ * fact_withdrawals row (v2 or v1 fingerprint) is stamped expired_at =+ * min(withdrawn_at) and valid_until = LEAST(valid_until, withdrawn_at), by+ * an UPDATE of just those rows at the end of the inserting statement.+ *+ * Both take the per-row guards' lock: FOR SHARE on each inserted source row+ * before the ledgers are read, so an insert still serializes with a purge or+ * a withdrawal that holds the source FOR UPDATE. A ledger with no row for the+ * inserted sources costs one index probe, not a fingerprint per row.+ *+ * Transition tables cannot be combined with a column list, so updates keep+ * the per-row BEFORE UPDATE OF triggers under their old names and functions;+ * only the insert half moves here. A statement trigger sees only the rows the+ * statement wrote: a row ON CONFLICT DO NOTHING skipped is not checked (it is+ * not saved either). Installed by migration v263.+ */+export const FACT_INSERT_GUARD_TRIGGER = 'facts_guard_inserted';+export const FACT_INSERT_GUARD_FUNCTION = 'gbrain_guard_inserted_facts';++export const FACT_INSERT_GUARD_SQL = `+CREATE OR REPLACE FUNCTION gbrain_guard_inserted_facts() RETURNS trigger+ LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$+ DECLARE purged TEXT;+ BEGIN+ PERFORM s.id FROM sources s WHERE s.id IN (SELECT i.source_id FROM inserted_facts i) ORDER BY s.id FOR SHARE OF s;+ IF EXISTS (SELECT 1 FROM fact_purges p WHERE p.source_id IN (SELECT i.source_id FROM inserted_facts i)) THEN+ WITH n AS MATERIALIZED (+ SELECT row_number() OVER () AS ord, i.source_id, i.visibility, i.entity_slug, gbrain_fact_fingerprint(i.fact) AS fact_hash+ FROM inserted_facts i)+ SELECT n.fact_hash INTO purged FROM n+ WHERE EXISTS (SELECT 1 FROM fact_purges p WHERE p.source_id = n.source_id AND p.visibility = n.visibility+ AND p.subject IN ('*', n.entity_slug) AND p.fact_hash = n.fact_hash)+ ORDER BY n.ord LIMIT 1;+ IF purged IS NOT NULL THEN+ RAISE EXCEPTION USING ERRCODE = 'P0001',+ MESSAGE = 'purged_content: this claim was purged from this source and cannot be saved again',+ DETAIL = json_build_object('table', 'facts', 'hash8', left(purged, 8))::text;+ END IF;+ END IF;+ IF EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id IN (SELECT i.source_id FROM inserted_facts i WHERE i.expired_at IS NULL)) THEN+ WITH n AS MATERIALIZED (+ SELECT i.id, i.source_id, i.visibility, i.entity_slug,+ gbrain_fact_fingerprint(i.fact) AS fact_hash, gbrain_fact_fingerprint_v1(i.fact) AS fact_hash_v1+ FROM inserted_facts i WHERE i.expired_at IS NULL),+ m AS (+ SELECT n.id, min(w.withdrawn_at) AS withdrawn_at FROM n JOIN fact_withdrawals w+ ON w.source_id = n.source_id AND w.visibility = n.visibility+ AND w.subject IN ('*', n.entity_slug) AND w.fact_hash IN (n.fact_hash, n.fact_hash_v1)+ GROUP BY n.id)+ UPDATE facts f SET expired_at = m.withdrawn_at, valid_until = LEAST(COALESCE(f.valid_until, m.withdrawn_at), m.withdrawn_at)+ FROM m WHERE f.id = m.id;+ END IF;+ RETURN NULL;+ END+ $fn$;+DROP TRIGGER IF EXISTS facts_guard_inserted ON facts;+CREATE TRIGGER facts_guard_inserted AFTER INSERT ON facts REFERENCING NEW TABLE AS inserted_facts+ FOR EACH STATEMENT EXECUTE FUNCTION gbrain_guard_inserted_facts();+DROP TRIGGER IF EXISTS facts_refuse_purged ON facts;+CREATE TRIGGER facts_refuse_purged BEFORE UPDATE OF fact, source_id, visibility, entity_slug ON facts+ FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact();+DROP TRIGGER IF EXISTS facts_preserve_withdrawal ON facts;+CREATE TRIGGER facts_preserve_withdrawal BEFORE UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON facts+ FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal();+`;diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 59b7090582..7c10d71c56 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 262;+export const LATEST_SCHEMA_VERSION = 263;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex a86757a665..8f8345a134 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -263,6 +263,7 @@ import { v259 } from './v259-ingest-log-marked-index.ts';import { v260 } from './v260-segmented-page-size-index.ts';import { v261 } from './v261-persistence-request-transient-retries.ts';import { v262 } from './v262-commit-notifier.ts';+import { v263 } from './v263-set-based-fact-insert-guards.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -524,4 +525,5 @@ export const MIGRATIONS: Migration[] = [v260,v261,v262,+ v263,];diff --git a/src/core/schema-migrations/v263-set-based-fact-insert-guards.ts b/src/core/schema-migrations/v263-set-based-fact-insert-guards.tsnew file mode 100644index 0000000000..49fd0bde90--- /dev/null+++ b/src/core/schema-migrations/v263-set-based-fact-insert-guards.ts@@ -0,0 +1,17 @@+import type { Migration } from './types.ts';+import { FACT_INSERT_GUARD_SQL } from '../facts/insert-guard-schema.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// #7105: the facts purge refusal and withdrawal stamp run once per INSERT+// statement (one AFTER INSERT ... REFERENCING NEW TABLE trigger,+// facts/insert-guard-schema.ts) instead of once per inserted row. The per-row+// facts_refuse_purged and facts_preserve_withdrawal triggers keep their+// functions and now fire on UPDATE only. Trigger DDL only: no row changes.+export const v263: Migration = {+ version: 263,+ name: 'set_based_fact_insert_guards',+ idempotent: true,+ sql: FACT_INSERT_GUARD_SQL,+};diff --git a/test/facts-insert-guards-7105.test.ts b/test/facts-insert-guards-7105.test.tsnew file mode 100644index 0000000000..436023810d--- /dev/null+++ b/test/facts-insert-guards-7105.test.ts@@ -0,0 +1,246 @@+/**+ * #7105: the facts purge refusal and withdrawal stamp run once per INSERT+ * statement, not once per inserted row (facts/insert-guard-schema.ts,+ * migration v263).+ *+ * Protects:+ * 1. Work count. A 6,000-row bulk insert calls the guard functions once per+ * statement (12 statements of 500), counted by pg_stat_xact_user_functions+ * inside the inserting transaction; a managed put of a 6,000-row fence fires+ * guard triggers once per statement, counted by a twin of every guard+ * trigger that records each firing. Regression: two per-row BEFORE INSERT+ * triggers called their functions 12,000 times for 6,000 rows, about 0.75 s+ * of the publish (the 5 s publish wait in+ * facts-publication-large-fence-6898 missed under gate load).+ * 2. Semantics. The same batch, run under the per-row guards (re-installed+ * from their original SQL inside a rolled-back transaction) and under the+ * statement guard, ends identically: the same P0001 purged_content refusal+ * and detail for a batch carrying a purged claim, and the same stamped+ * expired_at / valid_until for a batch carrying withdrawn rows. Updates+ * still go through the per-row guards.+ * Runs on PGLite, and on Postgres when DATABASE_URL is set+ * (test/postgres-unit-arms.txt).+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MEMORY_PURGE_GUARD_SQL } from '../src/core/facts/purge-schema.ts';+import { FACT_WITHDRAWAL_SCHEMA_STATEMENTS } from '../src/core/facts/withdrawal-schema.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const SLUG = 'people/alice-example';+const GUARD_FUNCTIONS = ['gbrain_refuse_purged_fact', 'gbrain_preserve_fact_withdrawal', 'gbrain_guard_inserted_facts'];+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-facts-guards-7105-db-'));+let closePostgres: (() => Promise<void>) | undefined;++beforeAll(async () => {+ const backends = testBackends();+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); 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;+ }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); rmSync(dataDir, { recursive: true, force: true });+});++const claim = (i: number) => `Claim ${i} about the widget-co supply chain and its quarterly planning cadence`;+const T = (iso: string) => new Date(iso);+const row = (i: number, over: Record<string, unknown> = {}) => ({ fact: claim(i), kind: 'fact' as const, source: 'fixture',+ visibility: 'private' as const, entity_slug: SLUG as string | null, source_markdown_slug: SLUG, row_num: i, valid_from: T('2020-01-01T00:00:00Z'), ...over });++async function newSource(engine: BrainEngine): Promise<string> {+ const id = `guards-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [id]);+ return id;+}++const rollback = new Error('rollback');+/** Runs fn in a transaction that always rolls back; perRow re-installs the original per-row INSERT guards first. */+async function inRolledBack<T>(engine: BrainEngine, perRow: boolean, fn: (tx: BrainEngine) => Promise<T>): Promise<T> {+ let out: T | undefined;+ try {+ await engine.transaction(async tx => {+ if (perRow) {+ await tx.executeRaw('DROP TRIGGER IF EXISTS facts_guard_inserted ON facts');+ await tx.runMigration(0, MEMORY_PURGE_GUARD_SQL);+ for (const statement of FACT_WITHDRAWAL_SCHEMA_STATEMENTS) await tx.executeRaw(statement);+ }+ out = await fn(tx);+ throw rollback;+ });+ } catch (error) { if (error !== rollback) throw error; }+ return out as T;+}++/** Runs one write under a savepoint and returns 'ok' or the refusal it raised. */+async function refusal(tx: BrainEngine, write: () => Promise<unknown>): Promise<{ code?: string; message: string; detail?: string } | 'ok'> {+ await tx.executeRaw('SAVEPOINT guard_attempt');+ try { await write(); await tx.executeRaw('RELEASE SAVEPOINT guard_attempt'); return 'ok'; } catch (e) {+ await tx.executeRaw('ROLLBACK TO SAVEPOINT guard_attempt');+ const err = e as { code?: string; message: string; detail?: string };+ return { code: err.code, message: err.message, detail: err.detail };+ }+}++const iso = (d: unknown) => d == null ? null : new Date(d as string).toISOString();++test('a 6,000-row bulk insert calls the guard functions once per statement, not once per row', async () => {+ for (const engine of engines) {+ const sourceId = await newSource(engine);+ const rows = Array.from({ length: 6000 }, (_, i) => row(i + 1));+ const calls = await engine.transaction(async tx => {+ await tx.executeRaw("SET LOCAL track_functions = 'pl'");+ const read = async () => Object.fromEntries((await tx.executeRaw<{ funcname: string; calls: number }>(+ 'SELECT funcname, calls::int AS calls FROM pg_stat_xact_user_functions WHERE funcname = ANY($1::text[])', [GUARD_FUNCTIONS]))+ .map(r => [r.funcname, Number(r.calls)]));+ const before = await read();+ expect((await tx.insertFacts(rows, { source_id: sourceId })).inserted).toBe(6000);+ const after = await read();+ return Object.fromEntries(GUARD_FUNCTIONS.map(name => [name, (after[name] ?? 0) - (before[name] ?? 0)]));+ });+ // 6,000 rows in statements of 500.+ expect(calls).toEqual({ gbrain_refuse_purged_fact: 0, gbrain_preserve_fact_withdrawal: 0, gbrain_guard_inserted_facts: 12 });+ }+}, 120_000);++test('a managed put of a 6,000-row fence fires the guard triggers once per insert statement', async () => {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-facts-guards-7105-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `guards-${randomUUID().slice(0, 8)}`;+ const twins: string[] = [];+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, async () => {+ await engine.executeRaw('CREATE TABLE IF NOT EXISTS guard_firings_7105 (trigger_name text, level text)');+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION count_guard_firing_7105() RETURNS trigger LANGUAGE plpgsql AS $fn$+ BEGIN INSERT INTO guard_firings_7105 VALUES (TG_ARGV[0], TG_LEVEL); IF TG_LEVEL = 'ROW' THEN RETURN NEW; END IF; RETURN NULL; END $fn$`);+ const guards = await engine.executeRaw<{ name: string; def: string }>(`SELECT t.tgname AS name, pg_get_triggerdef(t.oid) AS def+ FROM pg_trigger t JOIN pg_proc p ON p.oid = t.tgfoid+ WHERE t.tgrelid = 'facts'::regclass AND NOT t.tgisinternal AND p.proname = ANY($1::text[])`, [GUARD_FUNCTIONS]);+ expect(guards.length).toBeGreaterThan(0);+ for (const guard of guards) {+ twins.push(`zz_count_${guard.name}`);+ await engine.executeRaw(guard.def.replace(`CREATE TRIGGER ${guard.name} `, `CREATE TRIGGER zz_count_${guard.name} `)+ .replace(/EXECUTE FUNCTION \S+\(\)$/, `EXECUTE FUNCTION count_guard_firing_7105('${guard.name}')`));+ }+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ await engine.setConfig('sync.write_through', 'true');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const fence = `## Facts\n\n<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+${Array.from({ length: 6000 }, (_, i) => `| ${i + 1} | ${claim(i + 1)} | fact | 1.0 | private | medium | 2020-01-01 | | chat | |`).join('\n')}+<!--- gbrain:facts:end -->\n`;+ await submitPageMutation({ engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true },+ dryRun: false, logger: { info() {}, warn() {}, error() {} } } as any,+ { operation: 'put_page', params: { slug: SLUG, content: `---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n\n${fence}`, request_id: randomUUID() } });+ const [{ n }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE source_id=$1', [sourceId]);+ expect(Number(n)).toBe(6000);+ const firings = await engine.executeRaw<{ trigger_name: string; level: string; n: number }>(+ 'SELECT trigger_name, level, count(*)::int AS n FROM guard_firings_7105 GROUP BY 1, 2 ORDER BY 1, 2');+ // 6,000 fence rows in insert statements of 500; no per-row firing.+ expect(firings.map(f => [f.trigger_name, f.level, Number(f.n)])).toEqual([['facts_guard_inserted', 'STATEMENT', 12]]);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ for (const twin of twins) await engine.executeRaw(`DROP TRIGGER IF EXISTS ${twin} ON facts`);+ await engine.executeRaw('DROP TABLE IF EXISTS guard_firings_7105');+ rmSync(dir, { recursive: true, force: true });+ }+ }+}, 300_000);++test('a batch insert carrying a purged claim is refused exactly as the per-row guard refused it', async () => {+ for (const engine of engines) {+ const sourceId = await newSource(engine);+ const arm = (perRow: boolean) => inRolledBack(engine, perRow, async tx => {+ const tomb = (i: number, subject: string) => tx.executeRaw(+ `INSERT INTO fact_purges(source_id, visibility, subject, fact_hash) VALUES ($1, 'private', $2, gbrain_fact_fingerprint($3))`,+ [sourceId, subject, claim(i)]);+ await tomb(530, '*'); await tomb(560, SLUG); await tomb(20, 'people/other-example');+ const fp = async (i: number) => (await tx.executeRaw<{ h: string }>('SELECT gbrain_fact_fingerprint($1) AS h', [claim(i)]))[0]!.h;+ // 600 rows, two statements: the purged claims are in the second, a withdrawn one in the first.+ await tx.executeRaw(`INSERT INTO fact_withdrawals(source_id, visibility, subject, fact_hash) VALUES ($1, 'private', '*', gbrain_fact_fingerprint($2))`, [sourceId, claim(5)]);+ const insert = (rows: ReturnType<typeof row>[]) => refusal(tx, () => tx.insertFacts(rows, { source_id: sourceId }));+ const batch = await insert(Array.from({ length: 600 }, (_, i) => row(i + 1)));+ const landed = await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE source_id=$1', [sourceId]);+ const expiredRow = await insert([row(900, { fact: claim(530), expired_at: T('2024-01-01T00:00:00Z') })]);+ const otherSubject = await insert([row(901, { fact: claim(20) })]);+ const subjectless = await insert([row(902, { fact: claim(560), entity_slug: null })]);+ const [{ id }] = await tx.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND row_num=901', [sourceId]);+ const update = await refusal(tx, () => tx.executeRaw('UPDATE facts SET fact=$1 WHERE id=$2', [claim(530), id]));+ return { batch, landed: Number(landed[0]!.n), expiredRow, otherSubject, subjectless, update, hash8: (await fp(530)).slice(0, 8) };+ });+ const perRow = await arm(true), statement = await arm(false);+ const refused = { code: 'P0001', message: 'purged_content: this claim was purged from this source and cannot be saved again' };+ expect(statement.batch).toMatchObject(refused);+ // The first purged row in insertion order (530, then 560) names the refusal.+ expect(JSON.parse((statement.batch as { detail: string }).detail)).toEqual({ table: 'facts', hash8: statement.hash8 });+ expect(statement.landed).toBe(0);+ expect(statement.expiredRow).toMatchObject({ code: 'P0001', message: refused.message });+ expect(statement.otherSubject).toBe('ok');+ expect(statement.subjectless).toBe('ok');+ expect(statement.update).toMatchObject({ code: 'P0001', message: refused.message });+ expect(statement).toEqual(perRow);+ }+}, 120_000);++test('a batch insert carrying withdrawn rows is stamped exactly as the per-row guard stamped it', async () => {+ for (const engine of engines) {+ const sourceId = await newSource(engine);+ const arm = (perRow: boolean) => inRolledBack(engine, perRow, async tx => {+ const withdraw = (i: number, subject: string, at: string, opts: { v1?: boolean; visibility?: string } = {}) => tx.executeRaw(+ `INSERT INTO fact_withdrawals(source_id, visibility, subject, fact_hash, withdrawn_at)+ VALUES ($1, $2, $3, ${opts.v1 ? 'gbrain_fact_fingerprint_v1' : 'gbrain_fact_fingerprint'}($4), $5::timestamptz)`,+ [sourceId, opts.visibility ?? 'private', subject, claim(i), at]);+ await withdraw(10, '*', '2023-01-01T00:00:00Z');+ await withdraw(520, SLUG, '2023-02-01T00:00:00Z', { v1: true });+ await withdraw(30, 'people/other-example', '2023-03-01T00:00:00Z');+ await withdraw(40, '*', '2023-04-01T00:00:00Z'); await withdraw(40, SLUG, '2023-03-15T00:00:00Z');+ await withdraw(50, '*', '2023-05-01T00:00:00Z');+ await withdraw(60, '*', '2023-06-01T00:00:00Z', { visibility: 'world' });+ await withdraw(70, '*', '2023-07-01T00:00:00Z'); await withdraw(71, SLUG, '2023-07-01T00:00:00Z');+ const rows = Array.from({ length: 600 }, (_, i) => row(i + 1));+ rows[9] = row(10, { valid_until: T('2025-01-01T00:00:00Z') });+ rows[519] = row(520, { valid_until: T('2022-01-01T00:00:00Z') });+ rows[49] = row(50, { expired_at: T('2024-06-01T00:00:00Z') });+ rows[69] = row(70, { entity_slug: null }); rows[70] = row(71, { entity_slug: null });+ expect((await tx.insertFacts(rows, { source_id: sourceId })).inserted).toBe(600);+ const [{ id }] = await tx.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND row_num=100', [sourceId]);+ await tx.executeRaw('UPDATE facts SET fact=$1 WHERE id=$2', [claim(10), id]);+ return (await tx.executeRaw<{ row_num: number; fact: string; entity_slug: string | null; expired_at: unknown; valid_until: unknown }>(+ 'SELECT row_num, fact, entity_slug, expired_at, valid_until FROM facts WHERE source_id=$1 ORDER BY row_num', [sourceId]))+ .map(r => ({ row_num: Number(r.row_num), fact: r.fact, entity_slug: r.entity_slug, expired_at: iso(r.expired_at), valid_until: iso(r.valid_until) }));+ });+ const perRow = await arm(true), statement = await arm(false);+ const stamped = Object.fromEntries(statement.filter(r => r.expired_at).map(r => [r.row_num, [r.expired_at, r.valid_until]]));+ expect(stamped).toEqual({+ 10: ['2023-01-01T00:00:00.000Z', '2023-01-01T00:00:00.000Z'],+ 40: ['2023-03-15T00:00:00.000Z', '2023-03-15T00:00:00.000Z'],+ 50: ['2024-06-01T00:00:00.000Z', null],+ 70: ['2023-07-01T00:00:00.000Z', '2023-07-01T00:00:00.000Z'],+ 100: ['2023-01-01T00:00:00.000Z', '2023-01-01T00:00:00.000Z'],+ 520: ['2023-02-01T00:00:00.000Z', '2022-01-01T00:00:00.000Z'],+ });+ expect(statement).toEqual(perRow);+ }+}, 120_000);diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 57cc49c2d4..328a8ae447 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -512,6 +512,7 @@"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0421df939e8bec4aeaeb73b3dcdba6ff6fd74f0231169d2a07e42eba7e0070ed","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",@@ -4064,8 +4065,9 @@"content_chunks.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.content_chunks REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","content_chunks.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.content_chunks REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","fact_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.fact_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",- "facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",- "facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()",+ "facts.facts_guard_inserted": "CREATE TRIGGER facts_guard_inserted AFTER INSERT ON public.facts REFERENCING NEW TABLE AS inserted_facts FOR EACH STATEMENT EXECUTE FUNCTION gbrain_guard_inserted_facts()",+ "facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",+ "facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged BEFORE UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()","facts.gbrain_write_attribution": "CREATE TRIGGER gbrain_write_attribution BEFORE INSERT OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_write_attribution()","facts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","facts.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.facts REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex a3bc6f9413..0d6678ec95 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -512,6 +512,7 @@"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0421df939e8bec4aeaeb73b3dcdba6ff6fd74f0231169d2a07e42eba7e0070ed","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",@@ -4064,8 +4065,9 @@"content_chunks.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.content_chunks REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","content_chunks.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.content_chunks REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","fact_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.fact_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",- "facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",- "facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()",+ "facts.facts_guard_inserted": "CREATE TRIGGER facts_guard_inserted AFTER INSERT ON public.facts REFERENCING NEW TABLE AS inserted_facts FOR EACH STATEMENT EXECUTE FUNCTION gbrain_guard_inserted_facts()",+ "facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",+ "facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged BEFORE UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()","facts.gbrain_write_attribution": "CREATE TRIGGER gbrain_write_attribution BEFORE INSERT OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_write_attribution()","facts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","facts.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.facts REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 07a278725a..522697bbcd 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -512,6 +512,7 @@"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0421df939e8bec4aeaeb73b3dcdba6ff6fd74f0231169d2a07e42eba7e0070ed","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",@@ -4060,8 +4061,9 @@"content_chunks.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.content_chunks REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","content_chunks.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.content_chunks REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","fact_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.fact_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",- "facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",- "facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()",+ "facts.facts_guard_inserted": "CREATE TRIGGER facts_guard_inserted AFTER INSERT ON public.facts REFERENCING NEW TABLE AS inserted_facts FOR EACH STATEMENT EXECUTE FUNCTION gbrain_guard_inserted_facts()",+ "facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",+ "facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged BEFORE UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()","facts.gbrain_write_attribution": "CREATE TRIGGER gbrain_write_attribution BEFORE INSERT OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_write_attribution()","facts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","facts.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.facts REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 93d370b3b0..0cd96d5dd8 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -515,6 +515,7 @@"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0421df939e8bec4aeaeb73b3dcdba6ff6fd74f0231169d2a07e42eba7e0070ed","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",@@ -4056,8 +4057,9 @@"config.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((((old.key ~~ 'trust.%'::text) OR (new.key ~~ 'trust.%'::text)) AND ((old.key IS DISTINCT FROM new.key) OR (old.value IS DISTINCT FROM new.value)))) EXECUTE FUNCTION gbrain_bump_trust_generation()","content_chunks.chunk_search_vector_trigger": "CREATE TRIGGER chunk_search_vector_trigger BEFORE INSERT OR UPDATE OF chunk_text, doc_comment, symbol_name_qualified ON public.content_chunks FOR EACH ROW EXECUTE FUNCTION update_chunk_search_vector()","fact_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.fact_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",- "facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",- "facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()",+ "facts.facts_guard_inserted": "CREATE TRIGGER facts_guard_inserted AFTER INSERT ON public.facts REFERENCING NEW TABLE AS inserted_facts FOR EACH STATEMENT EXECUTE FUNCTION gbrain_guard_inserted_facts()",+ "facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",+ "facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged BEFORE UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()","facts.gbrain_write_attribution": "CREATE TRIGGER gbrain_write_attribution BEFORE INSERT OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_write_attribution()","facts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","facts.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.facts DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.trust_tier IS DISTINCT FROM new.trust_tier)) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 2173978614..dffadeaeac 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -515,6 +515,7 @@"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0421df939e8bec4aeaeb73b3dcdba6ff6fd74f0231169d2a07e42eba7e0070ed","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",@@ -4056,8 +4057,9 @@"config.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((((old.key ~~ 'trust.%'::text) OR (new.key ~~ 'trust.%'::text)) AND ((old.key IS DISTINCT FROM new.key) OR (old.value IS DISTINCT FROM new.value)))) EXECUTE FUNCTION gbrain_bump_trust_generation()","content_chunks.chunk_search_vector_trigger": "CREATE TRIGGER chunk_search_vector_trigger BEFORE INSERT OR UPDATE OF chunk_text, doc_comment, symbol_name_qualified ON public.content_chunks FOR EACH ROW EXECUTE FUNCTION update_chunk_search_vector()","fact_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.fact_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",- "facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",- "facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()",+ "facts.facts_guard_inserted": "CREATE TRIGGER facts_guard_inserted AFTER INSERT ON public.facts REFERENCING NEW TABLE AS inserted_facts FOR EACH STATEMENT EXECUTE FUNCTION gbrain_guard_inserted_facts()",+ "facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",+ "facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged BEFORE UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()","facts.gbrain_write_attribution": "CREATE TRIGGER gbrain_write_attribution BEFORE INSERT OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_write_attribution()","facts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","facts.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.facts DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.trust_tier IS DISTINCT FROM new.trust_tier)) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex f75e6f272e..76e415b6e3 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -515,6 +515,7 @@"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0421df939e8bec4aeaeb73b3dcdba6ff6fd74f0231169d2a07e42eba7e0070ed","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",@@ -4052,8 +4053,9 @@"config.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((((old.key ~~ 'trust.%'::text) OR (new.key ~~ 'trust.%'::text)) AND ((old.key IS DISTINCT FROM new.key) OR (old.value IS DISTINCT FROM new.value)))) EXECUTE FUNCTION gbrain_bump_trust_generation()","content_chunks.chunk_search_vector_trigger": "CREATE TRIGGER chunk_search_vector_trigger BEFORE INSERT OR UPDATE OF chunk_text, doc_comment, symbol_name_qualified ON public.content_chunks FOR EACH ROW EXECUTE FUNCTION update_chunk_search_vector()","fact_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.fact_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",- "facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",- "facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()",+ "facts.facts_guard_inserted": "CREATE TRIGGER facts_guard_inserted AFTER INSERT ON public.facts REFERENCING NEW TABLE AS inserted_facts FOR EACH STATEMENT EXECUTE FUNCTION gbrain_guard_inserted_facts()",+ "facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",+ "facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged BEFORE UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()","facts.gbrain_write_attribution": "CREATE TRIGGER gbrain_write_attribution BEFORE INSERT OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_write_attribution()","facts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","facts.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.facts DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.trust_tier IS DISTINCT FROM new.trust_tier)) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 15d79af331..8964a25060 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -63,6 +63,7 @@ test/extract-timeline-from-meetings-managed.test.tstest/extraction-watermark-atoms.test.tstest/fact-fence-adoption-exits.test.tstest/fact-purge-lookup-timeout-6511.test.ts+test/facts-insert-guards-7105.test.tstest/facts-publication-large-fence-6898.test.tstest/fence-repair-receipts.test.tstest/forecast-journal.test.ts