Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(#7632): definers pin pg_catalog, pg_temp; withdrawal and insert guards stay invokers

garrytan1fdd7e88354e
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index a386496e20..930d6d617e 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -390,28 +390,36 @@ segmented chunk (`test/e2e/segmented-switch-off-write-role.test.ts`). With the
policies above it creates segmented pages and sees only its sources' rows
(`test/e2e/segmented-rls-scope.test.ts`).
-**Purge and withdrawal guards.** The seven guard functions that refuse purged content and
-keep withdrawn facts withdrawn read their ledgers (`fact_purges`, `fact_withdrawals`,
-`take_purges`, `page_purges` and the two derivation purge tables) as the role that owns
-them, which ran the migrations: they are `SECURITY DEFINER` with
-`search_path = pg_catalog, public, pg_temp` (migration v276, #7632). Before, they read
-under the writing role's RLS, so a write role with no policy on a ledger saw no purge
-and no withdrawal and stored the claim again. Nothing changes for an owner or a role
-that bypasses RLS, and `anon` / `authenticated` gain nothing: EXECUTE on the guards is
-revoked from them and from PUBLIC, and every guard that refuses a write fires `AFTER ROW`,
-after RLS has accepted the row. The derivation guard is split: its `BEFORE ROW` half
-still runs as the writing role and silently drops a row the role can see a running purge
-sweep would delete, as before, and an `AFTER ROW` definer
-(`gbrain_refuse_stored_purging_derivation`) refuses such a row that was stored anyway
-with `derivation_purge_pending`. A scoped write role with no policy on a ledger is now
-refused, with an error, where it was let through, and learns whether content it supplies
-itself is purged or withdrawn in a source it can already write; the guards also perform two fixed side effects for
-it as the owner (expiring the facts its own statement just inserted when they are
-withdrawn, and adding its page to a running derivation purge's page list). Every other
-gbrain function that pins a search_path now ends it with `pg_temp`. Where the migrating
-role does not own a guard or its table, the migration names it on stderr and leaves it;
-`gbrain doctor` (`guard_functions`) prints the SQL to run as the owner
-(`test/e2e/guard-definer-postgres.test.ts`).
+**Purge and withdrawal guards.** Seven guard functions read the purge and withdrawal
+ledgers (`fact_purges`, `fact_withdrawals`, `take_purges`, `page_purges` and the two
+derivation purge tables) as the role that owns them, which ran the migrations: they are
+`SECURITY DEFINER` with `search_path = pg_catalog, pg_temp` and name every gbrain table
+and function `public.`-qualified (migration v276, #7632). Before, the guards read under the
+writing role's RLS, so a write role with no policy on a ledger saw no purge and no
+withdrawal: it stored a purged claim again or saved a withdrawn fact active. Nothing
+changes for an owner, a role that bypasses RLS or a write role with policies on the
+ledgers, and `anon` / `authenticated` gain nothing: EXECUTE on the definers is revoked
+from them and from PUBLIC, every definer that refuses fires `AFTER ROW` or
+`AFTER STATEMENT`, after RLS has accepted the row, and with `public` off their path a
+role that may create functions in `public` cannot plant an overload the owner then runs.
+The guards that silently correct a row are unchanged and still run as the writing role:
+the derivation drop (`gbrain_refuse_purging_derivation`, `BEFORE ROW`), the
+withdrawn-fact stamp on update (`gbrain_preserve_fact_withdrawal`) and the insert guard
+(`gbrain_guard_inserted_facts`). A row they pass because the role cannot read a ledger
+meets a definer after RLS: `gbrain_refuse_stored_purging_derivation`
+(`derivation_purge_pending`), `gbrain_refuse_unguarded_inserted_facts`
+(`purged_content`, `fact_withdrawn`) or `gbrain_refuse_revived_withdrawn_fact`
+(`fact_withdrawn`). So a scoped write role with no policy on a ledger is now refused, with
+an error, where it was let through, and learns whether content it supplies itself is
+purged or withdrawn in a source it can already write; one guard also performs a fixed
+side effect for it as the owner (adding its page to a running derivation purge's page
+list). Every other gbrain function that pins a search_path now ends it with `pg_temp`.
+Where the migrating role does not own a guard or its table, the migration names it on
+stderr and leaves it; `gbrain doctor` (`guard_functions`) prints the SQL to run as the
+owner. An older gbrain binary booting against the brain re-creates
+`gbrain_mark_derivation_scope_entry` as an invoker and drops `pg_temp` from the functions
+its schema re-creates; `guard_functions` flags both, and the next boot of this release
+restores them (`test/e2e/guard-definer-postgres.test.ts`).
**In engine-sql.** A read in a migrated domain takes a `ScopedRead` when it
runs through this helper and a `LegacyUnscopedRead` when it runs on the pool
diff --git a/docs/guides/rls-and-you.md b/docs/guides/rls-and-you.md
index 9a430dbe59..898b920066 100644
--- a/docs/guides/rls-and-you.md
+++ b/docs/guides/rls-and-you.md
@@ -260,8 +260,8 @@ both with the trigger inert, so a table that relies on either one fails it.
## Function search_path
-Every plpgsql function gbrain installs pins `search_path = pg_catalog, public, pg_temp`,
-so a same-named object in another schema can never change what the function
+Every plpgsql function gbrain installs pins `search_path = pg_catalog, public, pg_temp`
+(`pg_catalog, pg_temp` for the seven guards below), so a same-named object in another schema can never change what the function
reads or writes. `pg_temp` is named last because PostgreSQL otherwise searches the
caller's temporary schema first for tables and views: a session could shadow a table
a function reads with a temporary one of the same name. On an older brain, migration
@@ -270,9 +270,12 @@ changes), and `gbrain doctor` (`guard_functions`) names any function it could no
The seven purge and withdrawal guards are also `SECURITY DEFINER`, so they read the purge
and withdrawal ledgers as their owner whatever the writing role's policies are. EXECUTE on
-them is revoked from PUBLIC, `anon` and `authenticated`, and the guards that raise fire
-after RLS accepts the row, so a role RLS refuses gets the same refusal whether or not the
-content was purged. [docs/ENGINES.md](../ENGINES.md) ("Purge and withdrawal guards") has
+them is revoked from PUBLIC, `anon` and `authenticated`, and they fire after RLS accepts
+the row, so a role RLS refuses gets the same refusal whether or not the content was purged
+or its source is locked. Their path leaves `public` out and they name every gbrain table
+and function `public.`-qualified with exactly typed arguments, so a role that may create
+functions in `public` (Supabase grants that to `anon` and `authenticated` on older
+projects) cannot plant an overload that runs as the owner. [docs/ENGINES.md](../ENGINES.md) ("Purge and withdrawal guards") has
what changes for a scoped write role. The three fact-fingerprint functions
(`gbrain_fact_fingerprint`, `gbrain_fact_fingerprint_v1`,
`gbrain_fact_normalize`) are SQL functions that an index expression uses, so
diff --git a/llms-full.txt b/llms-full.txt
index 35e3f147c7..1a71586055 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5836,28 +5836,36 @@ segmented chunk (`test/e2e/segmented-switch-off-write-role.test.ts`). With the
policies above it creates segmented pages and sees only its sources' rows
(`test/e2e/segmented-rls-scope.test.ts`).
-**Purge and withdrawal guards.** The seven guard functions that refuse purged content and
-keep withdrawn facts withdrawn read their ledgers (`fact_purges`, `fact_withdrawals`,
-`take_purges`, `page_purges` and the two derivation purge tables) as the role that owns
-them, which ran the migrations: they are `SECURITY DEFINER` with
-`search_path = pg_catalog, public, pg_temp` (migration v276, #7632). Before, they read
-under the writing role's RLS, so a write role with no policy on a ledger saw no purge
-and no withdrawal and stored the claim again. Nothing changes for an owner or a role
-that bypasses RLS, and `anon` / `authenticated` gain nothing: EXECUTE on the guards is
-revoked from them and from PUBLIC, and every guard that refuses a write fires `AFTER ROW`,
-after RLS has accepted the row. The derivation guard is split: its `BEFORE ROW` half
-still runs as the writing role and silently drops a row the role can see a running purge
-sweep would delete, as before, and an `AFTER ROW` definer
-(`gbrain_refuse_stored_purging_derivation`) refuses such a row that was stored anyway
-with `derivation_purge_pending`. A scoped write role with no policy on a ledger is now
-refused, with an error, where it was let through, and learns whether content it supplies
-itself is purged or withdrawn in a source it can already write; the guards also perform two fixed side effects for
-it as the owner (expiring the facts its own statement just inserted when they are
-withdrawn, and adding its page to a running derivation purge's page list). Every other
-gbrain function that pins a search_path now ends it with `pg_temp`. Where the migrating
-role does not own a guard or its table, the migration names it on stderr and leaves it;
-`gbrain doctor` (`guard_functions`) prints the SQL to run as the owner
-(`test/e2e/guard-definer-postgres.test.ts`).
+**Purge and withdrawal guards.** Seven guard functions read the purge and withdrawal
+ledgers (`fact_purges`, `fact_withdrawals`, `take_purges`, `page_purges` and the two
+derivation purge tables) as the role that owns them, which ran the migrations: they are
+`SECURITY DEFINER` with `search_path = pg_catalog, pg_temp` and name every gbrain table
+and function `public.`-qualified (migration v276, #7632). Before, the guards read under the
+writing role's RLS, so a write role with no policy on a ledger saw no purge and no
+withdrawal: it stored a purged claim again or saved a withdrawn fact active. Nothing
+changes for an owner, a role that bypasses RLS or a write role with policies on the
+ledgers, and `anon` / `authenticated` gain nothing: EXECUTE on the definers is revoked
+from them and from PUBLIC, every definer that refuses fires `AFTER ROW` or
+`AFTER STATEMENT`, after RLS has accepted the row, and with `public` off their path a
+role that may create functions in `public` cannot plant an overload the owner then runs.
+The guards that silently correct a row are unchanged and still run as the writing role:
+the derivation drop (`gbrain_refuse_purging_derivation`, `BEFORE ROW`), the
+withdrawn-fact stamp on update (`gbrain_preserve_fact_withdrawal`) and the insert guard
+(`gbrain_guard_inserted_facts`). A row they pass because the role cannot read a ledger
+meets a definer after RLS: `gbrain_refuse_stored_purging_derivation`
+(`derivation_purge_pending`), `gbrain_refuse_unguarded_inserted_facts`
+(`purged_content`, `fact_withdrawn`) or `gbrain_refuse_revived_withdrawn_fact`
+(`fact_withdrawn`). So a scoped write role with no policy on a ledger is now refused, with
+an error, where it was let through, and learns whether content it supplies itself is
+purged or withdrawn in a source it can already write; one guard also performs a fixed
+side effect for it as the owner (adding its page to a running derivation purge's page
+list). Every other gbrain function that pins a search_path now ends it with `pg_temp`.
+Where the migrating role does not own a guard or its table, the migration names it on
+stderr and leaves it; `gbrain doctor` (`guard_functions`) prints the SQL to run as the
+owner. An older gbrain binary booting against the brain re-creates
+`gbrain_mark_derivation_scope_entry` as an invoker and drops `pg_temp` from the functions
+its schema re-creates; `guard_functions` flags both, and the next boot of this release
+restores them (`test/e2e/guard-definer-postgres.test.ts`).
**In engine-sql.** A read in a migrated domain takes a `ScopedRead` when it
runs through this helper and a `LegacyUnscopedRead` when it runs on the pool
diff --git a/src/commands/doctor/checks/guard-functions.ts b/src/commands/doctor/checks/guard-functions.ts
index aa1dca5c1a..b2ed6f0f94 100644
--- a/src/commands/doctor/checks/guard-functions.ts
+++ b/src/commands/doctor/checks/guard-functions.ts
@@ -2,9 +2,10 @@
* guard_functions doctor check (#7632): the purge and withdrawal guards read their ledgers as their owner.
*
* Postgres only (PGLite has one role). Fails when one of the seven guards is not SECURITY DEFINER with search_path
- * `pg_catalog, public, pg_temp`, is executable by PUBLIC/anon/authenticated, or is owned by a role that does not
- * bypass RLS on a table it reads; when a raising guard's trigger still fires BEFORE ROW or the derivation guard's
- * AFTER ROW check is missing; or when any gbrain function's search_path still ends without pg_temp.
+ * `pg_catalog, pg_temp` (an older gbrain booting against the brain re-creates gbrain_mark_derivation_scope_entry as
+ * an invoker), is executable by PUBLIC/anon/authenticated, or is owned by a role that does not bypass RLS on a table it
+ * reads; when a guard's trigger is missing or fires BEFORE ROW; or when any gbrain function's search_path still ends
+ * without pg_temp.
* Migration v276 makes every change the migrating role owns and names the rest on stderr: this check carries the SQL
* for them, to run as the owning role. Read-only.
*/
@@ -13,8 +14,8 @@ import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
import { checkError } from '../check-fix.ts';
-import { AFTER_ROW_PURGE_TRIGGERS, DEFINER_GUARDS, GUARD_SEARCH_PATH, LEGACY_SEARCH_PATH_SETTINGS } from '../../../core/guard-definer.ts';
-import { DERIVATION_STORED_GUARD_SQL } from '../../../core/page-body/schema.ts';
+import { DEFINER_GUARDS, GUARD_SEARCH_PATH, LEGACY_SEARCH_PATH_SETTINGS } from '../../../core/guard-definer.ts';
+import { GUARD_FUNCTION_SQL, GUARD_TRIGGERS } from '../../../core/schema-migrations/v276-guard-triggers-security-definer.ts';
interface GuardRow { fn: string; secdef: boolean; pinned: boolean; executable_by: string[]; owner: string; reads_under_rls: string[] }
@@ -38,7 +39,7 @@ export async function guardFunctionProblems(engine: BrainEngine): Promise<{ prob
for (const g of guards) {
if (!g.secdef || !g.pinned) {
problems.push(`${g.fn}() is not SECURITY DEFINER with search_path ${GUARD_SEARCH_PATH}`);
- fix.push(`ALTER FUNCTION ${g.fn}() SECURITY DEFINER SET search_path = ${GUARD_SEARCH_PATH};`);
+ fix.push(GUARD_FUNCTION_SQL[g.fn]!);
}
if (g.executable_by.length > 0) {
problems.push(`${g.fn}() is executable by ${g.executable_by.join(', ')}`);
@@ -46,26 +47,26 @@ export async function guardFunctionProblems(engine: BrainEngine): Promise<{ prob
}
if (g.reads_under_rls.length > 0) {
problems.push(`${g.fn}()'s owner ${g.owner} neither bypasses RLS nor owns ${g.reads_under_rls.join(', ')} unforced, so the guard reads them filtered`);
- fix.push(`/* give ${g.fn}() an owner that bypasses RLS (ALTER FUNCTION ${g.fn}() OWNER TO <owner of the tables>), or ALTER ROLE ${g.owner} BYPASSRLS; */`);
+ fix.push(`/* give ${g.fn}() an owner that bypasses RLS and is not the role gbrain runs as, so that role stays under its policies: ALTER FUNCTION ${g.fn}() OWNER TO <that role>; */`);
}
}
- const triggers = await engine.executeRaw<{ trigger: string; before: boolean }>(
- `SELECT t.tgname AS trigger, (t.tgtype & 2) <> 0 AS before FROM pg_trigger t WHERE NOT t.tgisinternal AND t.tgname = ANY($1::text[])`,
- [[...AFTER_ROW_PURGE_TRIGGERS.map(t => t.trigger), 'page_segment_derivations_refuse_stored_purging']]);
- for (const t of AFTER_ROW_PURGE_TRIGGERS) {
- if (!triggers.some(row => row.trigger === t.trigger && row.before)) continue;
- problems.push(`${t.trigger} on ${t.table} still fires BEFORE ROW`);
- fix.push(t.sql);
- }
- const [derivations] = await engine.executeRaw<{ present: boolean }>(`SELECT to_regclass('page_segment_derivations') IS NOT NULL AS present`);
- if (derivations?.present && !triggers.some(row => row.trigger === 'page_segment_derivations_refuse_stored_purging' && !row.before)) {
- problems.push('page_segment_derivations has no page_segment_derivations_refuse_stored_purging AFTER ROW check');
- fix.push(DERIVATION_STORED_GUARD_SQL);
+ const triggers = await engine.executeRaw<{ table: string; trigger: string; before: boolean | null }>(
+ `SELECT t.name AS table, g.tgname AS trigger, (g.tgtype & 2) <> 0 AS before
+ FROM unnest($1::text[]) AS t(name) JOIN pg_class c ON c.oid = to_regclass(t.name)
+ LEFT JOIN pg_trigger g ON g.tgrelid = c.oid AND NOT g.tgisinternal AND g.tgname = ANY($2::text[])`,
+ [[...new Set(GUARD_TRIGGERS.map(t => t.table))], GUARD_TRIGGERS.map(t => t.trigger)]);
+ for (const t of GUARD_TRIGGERS) {
+ if (!triggers.some(row => row.table === t.table)) continue;
+ const row = triggers.find(r => r.trigger === t.trigger);
+ if (row && !row.before) continue;
+ problems.push(row ? `${t.trigger} on ${t.table} still fires BEFORE ROW` : `${t.table} has no ${t.trigger} AFTER check`);
+ fix.push(`${GUARD_FUNCTION_SQL[t.fn]}\n${t.sql}`);
}
const unpinned = await engine.executeRaw<{ sig: string; path: string }>(
`SELECT p.oid::regprocedure::text AS sig, substr(c.setting, 13) AS path
FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace CROSS JOIN LATERAL unnest(p.proconfig) AS c(setting)
- WHERE n.nspname = 'public' AND c.setting = ANY($1::text[]) ORDER BY 1`, [[...LEGACY_SEARCH_PATH_SETTINGS]]);
+ WHERE n.nspname = 'public' AND c.setting = ANY($1::text[]) AND p.proname <> ALL($2::text[]) ORDER BY 1`,
+ [[...LEGACY_SEARCH_PATH_SETTINGS], DEFINER_GUARDS.map(g => g.fn)]);
if (unpinned.length > 0) {
problems.push(`${unpinned.length} function(s) pin search_path without pg_temp last (${unpinned.map(u => u.sig).join(', ')})`);
fix.push(...unpinned.map(u => `ALTER FUNCTION ${u.sig} SET search_path = ${u.path}, pg_temp;`));
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index e019c72a0b..6408ee601a 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1308,7 +1308,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.464.0', text: 'Security: `gbrain serve --access=read-only` (the `=` form) now sets the read-only ceiling. It passed flag validation before but started the serve with full write access, because only `--access read-only` was read. A config that used the `=` form now gets the read-only tool set and refused mutations it asked for; a repeated `--access` never widens a read-only value, and an invalid value in either form refuses. `--surface=<v>` likewise now sets the serve surface (it was ignored, leaving the full surface), and a repeated `--surface` takes the narrowest value.' },
{ since: '0.60.464.0', text: 'A managed sync pass whose process was killed or crashed now reads `resumable` / `pass_interrupted` in `gbrain sync status` (with an `interrupted` block naming the pass and the dead holder) instead of `pass_unfinished`, and a second killed pass reads `blocked` / `pass_abandoned` at once. `gbrain doctor` `managed_sync_blocked` lists both (warn, fail after an hour). A live pass still committing is no longer counted abandoned because its row is old.' },
// #7632 guard definers. `since` is stamped at the merge slot.
- { since: 'TBD', id: 'guard_triggers_security_definer', text: 'On Postgres, the seven guard functions that refuse purged content and keep withdrawn facts withdrawn now read the purge and withdrawal ledgers as the role that owns them (`SECURITY DEFINER`, `search_path = pg_catalog, public, pg_temp`). Before, they read under the writing role\'s row-level security, so a write role with no policy on a ledger saw no purge and no withdrawal: a purged claim, page, take or derivation was stored again and a withdrawn fact was saved active. Owners, roles that bypass RLS and write roles with policies on the ledgers see no change, and `anon` and `authenticated` gain nothing: EXECUTE on the guards is revoked from PUBLIC, `anon` and `authenticated`, and every guard that refuses a write (`facts_refuse_purged`, `takes_refuse_purged`, `pages_refuse_purged` and the new `page_segment_derivations_refuse_stored_purging`) fires AFTER ROW, so RLS refuses a row before any guard reads a ledger. The derivation guard that silently drops a row a purge sweep would delete still runs as the writing role, BEFORE ROW, as before; a row it cannot see is purged and that RLS accepts is then refused by the new AFTER ROW guard with `derivation_purge_pending`. A scoped write role with no policy on a ledger is now refused, with an error, where it was let through; it learns whether content it supplies itself is purged or withdrawn in a source it can already write; and the guards perform two fixed side effects for it as the owner (expiring the facts its own statement just inserted when they are withdrawn, and adding its page to a running derivation purge\'s page list). Every other gbrain function that pins a search_path now ends it with `pg_temp` (ALTER only, no body changes). Where the migrating role does not own a guard or its table, the migration names it on stderr and leaves it, and `gbrain doctor` (`guard_functions`) prints the SQL to run as the owner.' },
+ { since: 'TBD', id: 'guard_triggers_security_definer', text: 'On Postgres, seven guard functions now read the purge and withdrawal ledgers as the role that owns them (`SECURITY DEFINER`, `search_path = pg_catalog, pg_temp`, every gbrain name `public.`-qualified). Before, the guards read under the writing role\'s row-level security, so a write role with no policy on a ledger saw no purge and no withdrawal: a purged claim, page, take or derivation was stored again and a withdrawn fact was saved active. Owners, roles that bypass RLS and write roles with policies on the ledgers see no change: the guards that silently drop a purging derivation and stamp a withdrawn fact expired still run as the writing role, as before. `anon` and `authenticated` gain nothing: EXECUTE on the definers is revoked from PUBLIC, `anon` and `authenticated`; every definer refuses AFTER ROW or AFTER STATEMENT, so RLS refuses a row before any definer reads a ledger; and with `public` off their path, a role that may create functions in `public` cannot plant an overload the owner then runs. A scoped write role with no policy on a ledger is now refused, with an error (`purged_content`, `fact_withdrawn` or `derivation_purge_pending`), where it was let through; it learns whether content it supplies itself is purged or withdrawn in a source it can already write; and one guard performs a fixed side effect for it as the owner (adding its page to a running derivation purge\'s page list). Every other gbrain function that pins a search_path now ends it with `pg_temp` (ALTER only, no body changes). Where the migrating role does not own a guard or its table, the migration names it on stderr and leaves it, and `gbrain doctor` (`guard_functions`) prints the SQL to run as the owner. An older gbrain binary booting against the brain re-creates `gbrain_mark_derivation_scope_entry` as an invoker and drops `pg_temp` from the functions its schema re-creates; `guard_functions` flags both, and the next boot of this release restores them.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/guard-definer.ts b/src/core/guard-definer.ts
index 62a0799b18..8c5888a256 100644
--- a/src/core/guard-definer.ts
+++ b/src/core/guard-definer.ts
@@ -4,45 +4,52 @@
* The purge and withdrawal guards decide a write by reading another table (a purge or withdrawal ledger). As
* SECURITY INVOKER they read it under the writing role's row-level security, so a role that may write the guarded
* table but has no policy on the ledger read zero rows and the guard let the write through: a purged claim, page,
- * take or derivation was stored again, and a withdrawn fact was saved active. As SECURITY DEFINER they read the
- * ledger as their owner (the role that ran the migrations, which owns the tables and bypasses RLS) whatever the
- * writer's policies are.
+ * take or derivation was stored again, and a withdrawn fact was saved active. The definers below read the ledger as
+ * their owner (the role that ran the migrations, which owns the tables and bypasses RLS) whatever the writer's
+ * policies are.
*
* The trust model around that, each piece pinned by test/e2e/guard-definer-postgres.test.ts:
- * - search_path is pinned with pg_temp LAST. PostgreSQL searches the caller's temp schema first for relations unless
- * the path names it, so without it a caller's temp view named like a ledger would run the caller's code as the
- * owner. Every other gbrain function gets pg_temp appended too (FUNCTION_SEARCH_PATH_HARDENING_SQL): an invoker
- * guard can otherwise be walked past with a temp table named like its ledger.
+ * - A definer runs with search_path = pg_catalog, pg_temp and names every gbrain table and function as public.x.
+ * PostgreSQL never searches pg_temp for functions or operators, and public is off the path, so a role with CREATE
+ * on public (Supabase grants it to anon and authenticated) cannot plant an overload of a built-in the owner then
+ * runs; and pg_temp last keeps a caller's temp table or view named like a ledger out of every relation lookup.
+ * Every other gbrain function gets pg_temp appended (FUNCTION_SEARCH_PATH_HARDENING_SQL): an invoker guard can
+ * otherwise be walked past with a temp table named like its ledger. Those run as the caller, so an overload there
+ * runs with the caller's own rights.
+ * - A definer never writes a table whose triggers run invoker functions: a definer's write fires them as the owner,
+ * with public on their path. Only gbrain_mark_derivation_scope_entry writes (page_segment_derivation_purge_pages,
+ * which has no trigger).
* - EXECUTE is revoked from PUBLIC, anon and authenticated. A trigger function cannot be called directly anyway, and a
* trigger fires whatever the EXECUTE grants are.
- * - A definer never answers before RLS has accepted the row. BEFORE ROW triggers run before RLS WITH CHECK, so a
- * raising definer BEFORE guard would tell a role with a bare INSERT grant (Supabase anon) purged content from any
- * other content. The raising guards fire AFTER ROW. The derivation guard is split: its BEFORE ROW half
- * (gbrain_refuse_purging_derivation) stays SECURITY INVOKER and silently drops a row the writer can see a sweep
- * would delete, as before, so its callers still count the rows it drops; its AFTER ROW half
- * (gbrain_refuse_stored_purging_derivation) is the definer and raises derivation_purge_pending for such a row that
- * was stored anyway, which only a writer RLS accepted and that has no policy on the sweep records reaches.
- * gbrain_preserve_fact_withdrawal stays BEFORE: it never raises, and its stamp is visible only on a row RLS accepted.
+ * - A definer never answers before RLS has accepted the row: BEFORE ROW triggers run before RLS WITH CHECK, so a
+ * definer there would tell a role with a bare INSERT grant (Supabase anon) purged content from other content, or a
+ * locked source from an absent one. Every definer that refuses fires AFTER ROW or AFTER STATEMENT. The guards that
+ * silently correct a row stay master's invokers, BEFORE ROW or writing as the writer: gbrain_refuse_purging_derivation
+ * drops a derivation a sweep would delete, gbrain_preserve_fact_withdrawal stamps a withdrawn fact expired, and
+ * gbrain_guard_inserted_facts refuses purged inserts and stamps withdrawn ones. A row they pass because the writer
+ * cannot read the ledger meets a definer after RLS: gbrain_refuse_stored_purging_derivation
+ * (derivation_purge_pending), gbrain_refuse_unguarded_inserted_facts and gbrain_refuse_revived_withdrawn_fact
+ * (purged_content, fact_withdrawn).
*
- * What a writer gains: the two fixed side effects the definer bodies perform as the owner (expiring the facts its own
- * statement just inserted, adding its page to a running derivation purge's page list) and knowing whether content it
- * supplies is purged or withdrawn in a source it can already write. anon and authenticated gain nothing: RLS refuses
- * their row before any definer reads a ledger. A writer RLS accepts but with no policy on a ledger is refused where it
- * used to fail open, with an error (derivation_purge_pending for a derivation) instead of a silent drop.
+ * What a writer gains: one fixed side effect the owner performs for it (adding its page to a running derivation
+ * purge's page list) and knowing whether content it supplies is purged or withdrawn in a source it can already write.
+ * anon and authenticated gain nothing: RLS refuses their row before any definer reads a ledger. A writer RLS accepts
+ * but with no policy on a ledger is refused where it used to fail open, with an error instead of a silent drop or
+ * stamp.
*/
-/** The seven guards and the tables each reads, besides the one its trigger is on. */
+/** The seven definer guards and the tables each reads, besides the one its trigger is on. */
export const DEFINER_GUARDS = [
- { fn: 'gbrain_guard_inserted_facts', reads: ['fact_purges', 'fact_withdrawals', 'sources'] },
- { fn: 'gbrain_preserve_fact_withdrawal', reads: ['fact_withdrawals', 'sources'] },
+ { fn: 'gbrain_mark_derivation_scope_entry', reads: ['page_segment_derivation_purges', 'page_segment_derivation_purge_pages'] },
{ fn: 'gbrain_refuse_purged_fact', reads: ['fact_purges', 'sources'] },
{ fn: 'gbrain_refuse_purged_page', reads: ['page_purges'] },
{ fn: 'gbrain_refuse_purged_take', reads: ['take_purges', 'pages'] },
+ { fn: 'gbrain_refuse_revived_withdrawn_fact', reads: ['fact_withdrawals', 'sources'] },
{ fn: 'gbrain_refuse_stored_purging_derivation', reads: ['page_segment_derivation_purges', 'pages', 'page_body_manifest'] },
- { fn: 'gbrain_mark_derivation_scope_entry', reads: ['page_segment_derivation_purges', 'page_segment_derivation_purge_pages'] },
+ { fn: 'gbrain_refuse_unguarded_inserted_facts', reads: ['fact_purges', 'fact_withdrawals', 'facts', 'sources'] },
] as const;
-export const GUARD_SEARCH_PATH = 'pg_catalog, public, pg_temp';
+export const GUARD_SEARCH_PATH = 'pg_catalog, pg_temp';
/** The Data API roles Supabase grants EXECUTE on new functions through default privileges. */
const API_ROLES = ['anon', 'authenticated'] as const;
@@ -55,14 +62,122 @@ ${API_ROLES.map(r => ` IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${r}'
END $revoke$;`;
}
-/** Makes one guard a definer with the pinned path and revokes direct EXECUTE. */
-export function definerGuardSql(fn: string): string {
- return `ALTER FUNCTION ${fn}() SECURITY DEFINER SET search_path = ${GUARD_SEARCH_PATH};
-${revokeExecuteSql(fn)}`;
-}
+/** Refuses an update into a purged claim; AFTER ROW, after RLS. Inserts meet gbrain_refuse_unguarded_inserted_facts. */
+const REFUSE_PURGED_FACT_SQL = `CREATE OR REPLACE FUNCTION gbrain_refuse_purged_fact() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path = ${GUARD_SEARCH_PATH} AS $fn$
+BEGIN
+ PERFORM s.id FROM public.sources s WHERE s.id = NEW.source_id FOR SHARE;
+ IF EXISTS (SELECT 1 FROM public.fact_purges p
+ WHERE p.source_id = NEW.source_id AND p.visibility = NEW.visibility
+ AND (p.subject = '*'::text OR p.subject = NEW.entity_slug)
+ AND p.fact_hash = public.gbrain_fact_fingerprint(NEW.fact)) 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'::text, 'facts'::text, 'hash8'::text, left(public.gbrain_fact_fingerprint(NEW.fact), 8))::text;
+ END IF;
+ RETURN NULL;
+END
+$fn$;
+${revokeExecuteSql('gbrain_refuse_purged_fact')}`;
+
+const REFUSE_PURGED_TAKE_SQL = `CREATE OR REPLACE FUNCTION gbrain_refuse_purged_take() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path = ${GUARD_SEARCH_PATH} AS $fn$
+DECLARE src TEXT; subj TEXT;
+BEGIN
+ SELECT p.source_id, p.slug INTO src, subj FROM public.pages p WHERE p.id = NEW.page_id;
+ IF src IS NOT NULL AND EXISTS (SELECT 1 FROM public.take_purges t
+ WHERE t.source_id = src AND (t.subject = '*'::text OR t.subject = subj)
+ AND t.claim_hash = public.gbrain_fact_fingerprint(NEW.claim)) THEN
+ RAISE EXCEPTION USING ERRCODE = 'P0001',
+ MESSAGE = 'purged_content: this take claim was purged from this source and cannot be saved again',
+ DETAIL = json_build_object('table'::text, 'takes'::text, 'hash8'::text, left(public.gbrain_fact_fingerprint(NEW.claim), 8))::text;
+ END IF;
+ RETURN NULL;
+END
+$fn$;
+${revokeExecuteSql('gbrain_refuse_purged_take')}`;
+
+const REFUSE_PURGED_PAGE_SQL = `CREATE OR REPLACE FUNCTION gbrain_refuse_purged_page() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path = ${GUARD_SEARCH_PATH} AS $fn$
+BEGIN
+ -- No column list on the trigger: a column-scoped trigger would pin pages.source_id and content_hash.
+ IF NEW.content_hash IS NOT NULL
+ AND (TG_OP = 'INSERT' OR NEW.content_hash IS DISTINCT FROM OLD.content_hash OR NEW.source_id IS DISTINCT FROM OLD.source_id)
+ AND EXISTS (SELECT 1 FROM public.page_purges p WHERE p.source_id = NEW.source_id AND p.content_hash = NEW.content_hash) THEN
+ RAISE EXCEPTION USING ERRCODE = 'P0001',
+ MESSAGE = 'purged_content: this page content was purged from this source and cannot be saved again',
+ DETAIL = json_build_object('table'::text, 'pages'::text, 'hash8'::text, left(NEW.content_hash, 8))::text;
+ END IF;
+ RETURN NULL;
+END
+$fn$;
+${revokeExecuteSql('gbrain_refuse_purged_page')}`;
-/** The raising guards, AFTER ROW so RLS WITH CHECK runs first. Same events and columns as before. */
-export const AFTER_ROW_PURGE_TRIGGERS = [
+/**
+ * Refuses an update that leaves a withdrawn fact active. gbrain_preserve_fact_withdrawal (BEFORE ROW, invoker) stamps
+ * it expired for a writer that can read fact_withdrawals, so only a writer that cannot meets this.
+ */
+const REFUSE_REVIVED_WITHDRAWN_FACT_SQL = `CREATE OR REPLACE FUNCTION gbrain_refuse_revived_withdrawn_fact() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path = ${GUARD_SEARCH_PATH} AS $fn$
+BEGIN
+ PERFORM s.id FROM public.sources s WHERE s.id = NEW.source_id FOR SHARE;
+ IF EXISTS (SELECT 1 FROM public.fact_withdrawals w
+ WHERE w.source_id = NEW.source_id AND w.visibility = NEW.visibility
+ AND (w.subject = '*'::text OR w.subject = NEW.entity_slug)
+ AND w.fact_hash IN (public.gbrain_fact_fingerprint(NEW.fact), public.gbrain_fact_fingerprint_v1(NEW.fact))) THEN
+ RAISE EXCEPTION USING ERRCODE = 'P0001',
+ MESSAGE = 'fact_withdrawn: this fact was withdrawn from this source and cannot be made active again';
+ END IF;
+ RETURN NULL;
+END
+$fn$;
+${revokeExecuteSql('gbrain_refuse_revived_withdrawn_fact')}`;
+
+/**
+ * Refuses an insert that leaves a purged fact stored or a withdrawn fact active. Fires after facts_guard_inserted
+ * (gbrain_guard_inserted_facts, invoker: it refuses and stamps what the writer can read), so only a writer that cannot
+ * read the ledgers meets it. Reads only: a definer's write would run the facts triggers as the owner.
+ */
+const REFUSE_UNGUARDED_INSERTED_FACTS_SQL = `CREATE OR REPLACE FUNCTION gbrain_refuse_unguarded_inserted_facts() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path = ${GUARD_SEARCH_PATH} AS $fn$
+DECLARE purged TEXT;
+BEGIN
+ PERFORM s.id FROM public.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 public.fact_purges p WHERE p.source_id IN (SELECT i.source_id FROM inserted_facts i)) THEN
+ SELECT n.fact_hash INTO purged FROM (SELECT i.source_id, i.visibility, i.entity_slug, public.gbrain_fact_fingerprint(i.fact) AS fact_hash
+ FROM inserted_facts i) n
+ WHERE EXISTS (SELECT 1 FROM public.fact_purges p WHERE p.source_id = n.source_id AND p.visibility = n.visibility
+ AND p.subject IN ('*'::text, n.entity_slug) AND p.fact_hash = n.fact_hash)
+ 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'::text, 'facts'::text, 'hash8'::text, left(purged, 8))::text;
+ END IF;
+ END IF;
+ IF EXISTS (SELECT 1 FROM public.fact_withdrawals w WHERE w.source_id IN (SELECT i.source_id FROM inserted_facts i)) THEN
+ IF EXISTS (SELECT 1 FROM inserted_facts i JOIN public.facts f ON f.id = i.id
+ WHERE f.expired_at IS NULL AND EXISTS (SELECT 1 FROM public.fact_withdrawals w
+ WHERE w.source_id = f.source_id AND w.visibility = f.visibility AND w.subject IN ('*'::text, f.entity_slug)
+ AND w.fact_hash IN (public.gbrain_fact_fingerprint(f.fact), public.gbrain_fact_fingerprint_v1(f.fact)))) THEN
+ RAISE EXCEPTION USING ERRCODE = 'P0001',
+ MESSAGE = 'fact_withdrawn: this fact was withdrawn from this source and cannot be saved active';
+ END IF;
+ END IF;
+ RETURN NULL;
+END
+$fn$;
+${revokeExecuteSql('gbrain_refuse_unguarded_inserted_facts')}`;
+
+/** The definer guards on facts, takes and pages, by function: CREATE OR REPLACE with the body, then the revoke. */
+export const DEFINER_FUNCTION_SQL: Readonly<Record<string, string>> = {
+ gbrain_refuse_purged_fact: REFUSE_PURGED_FACT_SQL,
+ gbrain_refuse_purged_take: REFUSE_PURGED_TAKE_SQL,
+ gbrain_refuse_purged_page: REFUSE_PURGED_PAGE_SQL,
+ gbrain_refuse_revived_withdrawn_fact: REFUSE_REVIVED_WITHDRAWN_FACT_SQL,
+ gbrain_refuse_unguarded_inserted_facts: REFUSE_UNGUARDED_INSERTED_FACTS_SQL,
+};
+
+/**
+ * Their triggers, all AFTER so RLS refuses a row first. The three purge triggers keep their events and columns; the
+ * two new ones follow facts_guard_inserted and facts_preserve_withdrawal (AFTER STATEMENT triggers fire in name order).
+ */
+export const DEFINER_TRIGGERS = [
{ table: 'facts', trigger: 'facts_refuse_purged', fn: 'gbrain_refuse_purged_fact', sql: `DROP TRIGGER IF EXISTS facts_refuse_purged ON facts;
CREATE TRIGGER facts_refuse_purged AFTER UPDATE OF fact, source_id, visibility, entity_slug ON facts
FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact();` },
@@ -72,6 +187,12 @@ CREATE TRIGGER takes_refuse_purged AFTER INSERT OR UPDATE OF claim, page_id ON t
{ table: 'pages', trigger: 'pages_refuse_purged', fn: 'gbrain_refuse_purged_page', sql: `DROP TRIGGER IF EXISTS pages_refuse_purged ON pages;
CREATE TRIGGER pages_refuse_purged AFTER INSERT OR UPDATE ON pages
FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_page();` },
+ { table: 'facts', trigger: 'facts_refuse_revived_withdrawal', fn: 'gbrain_refuse_revived_withdrawn_fact', sql: `DROP TRIGGER IF EXISTS facts_refuse_revived_withdrawal ON facts;
+CREATE TRIGGER facts_refuse_revived_withdrawal AFTER UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON facts
+ FOR EACH ROW WHEN (NEW.expired_at IS NULL) EXECUTE FUNCTION gbrain_refuse_revived_withdrawn_fact();` },
+ { table: 'facts', trigger: 'facts_refuse_unguarded_inserted', fn: 'gbrain_refuse_unguarded_inserted_facts', sql: `DROP TRIGGER IF EXISTS facts_refuse_unguarded_inserted ON facts;
+CREATE TRIGGER facts_refuse_unguarded_inserted AFTER INSERT ON facts REFERENCING NEW TABLE AS inserted_facts
+ FOR EACH STATEMENT EXECUTE FUNCTION gbrain_refuse_unguarded_inserted_facts();` },
] as const;
/** The search_path settings gbrain functions pinned before #7632, which the hardening completes with pg_temp. */
diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.ts
index c37fd2d2c7..49b372ec03 100644
--- a/src/core/page-body/schema.ts
+++ b/src/core/page-body/schema.ts
@@ -213,7 +213,7 @@ export function derivationHoldsClaimSql(d: string, needles: string, patterns: st
LATERAL (SELECT jsonb_path_query(doc.j, 'strict $.** ? (@.type() == "string")') #>> '{}' AS t
UNION ALL SELECT jsonb_path_query(doc.j, 'strict $.** ? (@.type() == "object").keyvalue().key') #>> '{}') s
WHERE CASE WHEN ${hasWordsSql('s.t', patterns)} THEN EXISTS (SELECT 1 FROM unnest(${needles}::text[]) k(n)
- WHERE strpos(' ' || ${foldSql('gbrain_fact_normalize(s.t)')} || ' ', k.n) > 0) ELSE false END) ELSE false END`;
+ WHERE strpos(' ' || ${foldSql('public.gbrain_fact_normalize(s.t)')} || ' ', k.n) > 0) ELSE false END) ELSE false END`;
}
/**
@@ -223,7 +223,7 @@ export function derivationHoldsClaimSql(d: string, needles: string, patterns: st
* that page's prose still says, and the next derivation would write it back.
*/
export function derivationSweepScopeSql(d: string, p: string, pageIds: string): string {
- return `(${d}.page_id = ANY(${pageIds}::int[]) OR ${p}.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM page_body_manifest m
+ return `(${d}.page_id = ANY(${pageIds}::int[]) OR ${p}.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM public.page_body_manifest m
WHERE m.page_id = ${d}.page_id AND m.occurrence_id = ${d}.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.sha256 = ${d}.segment_sha256))`;
}
@@ -236,7 +236,7 @@ export function derivationSweepScopeSql(d: string, p: string, pageIds: string):
* and otherwise waits a bounded time in a transaction that holds no other lock (segment-derive.ts continueDerivationPurges).
*/
export function derivationScopeLockSql(sourceId: string): string {
- return `hashtextextended('gbrain:derivation-scope:' || ${sourceId}, 0)`;
+ return `hashtextextended('gbrain:derivation-scope:'::text || ${sourceId}, 0::bigint)`;
}
/**
@@ -246,23 +246,49 @@ export function derivationScopeLockSql(sourceId: string): string {
* on the sweep records. It reads them as its owner, so that writer is refused instead of storing the row; a role RLS
* refuses never reaches it, so it learns nothing about a sweep.
*/
-export const DERIVATION_STORED_GUARD_SQL = `CREATE OR REPLACE FUNCTION gbrain_refuse_stored_purging_derivation() RETURNS trigger SECURITY DEFINER SET search_path = ${GUARD_SEARCH_PATH} AS $func$
+export const DERIVATION_STORED_GUARD_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_refuse_stored_purging_derivation() RETURNS trigger SECURITY DEFINER SET search_path = ${GUARD_SEARCH_PATH} AS $func$
BEGIN
- IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id
+ IF EXISTS (SELECT 1 FROM public.page_segment_derivation_purges x JOIN public.pages p ON p.source_id = x.source_id
WHERE p.id = NEW.page_id AND ${derivationSweepScopeSql('NEW', 'p', 'x.page_ids')}
AND ${derivationHoldsClaimSql('NEW', 'x.needles', 'x.patterns')}) THEN
RAISE EXCEPTION USING ERRCODE = 'P0001',
MESSAGE = 'derivation_purge_pending: a fact purge''s sweep of stored derivation results is still running and this row holds its claim',
- DETAIL = json_build_object('table', 'page_segment_derivations')::text;
+ DETAIL = json_build_object('table'::text, 'page_segment_derivations'::text)::text;
END IF;
RETURN NULL;
END
$func$ LANGUAGE plpgsql;
-${revokeExecuteSql('gbrain_refuse_stored_purging_derivation')}
-DROP TRIGGER IF EXISTS page_segment_derivations_refuse_stored_purging ON page_segment_derivations;
+${revokeExecuteSql('gbrain_refuse_stored_purging_derivation')}`;
+
+export const DERIVATION_STORED_GUARD_TRIGGER_SQL = `DROP TRIGGER IF EXISTS page_segment_derivations_refuse_stored_purging ON page_segment_derivations;
CREATE TRIGGER page_segment_derivations_refuse_stored_purging AFTER INSERT OR UPDATE OF output, receipt ON page_segment_derivations
FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_stored_purging_derivation();`;
+/**
+ * The scope-entry trigger function (#7632 definer): notes a page entering a running sweep's scope for every sweep of
+ * its source, as the owner, so a writer without a policy on the sweep records still notes it. It writes only
+ * page_segment_derivation_purge_pages, which has no trigger (a definer's write runs a table's triggers as the owner).
+ */
+export const DERIVATION_SCOPE_ENTRY_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SECURITY DEFINER SET search_path = ${GUARD_SEARCH_PATH} AS $func$
+DECLARE
+ src TEXT;
+ page INTEGER;
+BEGIN
+ IF TG_TABLE_NAME = 'pages' THEN
+ src := NEW.source_id;
+ page := NEW.id;
+ ELSE
+ src := OLD.source_id;
+ page := OLD.page_id;
+ END IF;
+ PERFORM pg_advisory_xact_lock_shared(${derivationScopeLockSql('src')});
+ INSERT INTO public.page_segment_derivation_purge_pages (request_id, page_id)
+ SELECT x.request_id, page FROM public.page_segment_derivation_purges x WHERE x.source_id = src ON CONFLICT DO NOTHING;
+ RETURN NULL;
+END
+$func$ LANGUAGE plpgsql;
+${revokeExecuteSql('gbrain_mark_derivation_scope_entry')}`;
+
/**
* Per-segment derivation watermarks (migration v273): one row per page, pipeline and manifest occurrence, recording
* the segment text and the context (`context_hash`: entry state plus the page-level inputs the pipeline reads) it was
@@ -284,7 +310,7 @@ CREATE TRIGGER page_segment_derivations_refuse_stored_purging AFTER INSERT OR UP
* write, when its occurrence is retired or its page soft-deleted: the triggers on page_body_manifest and pages note the
* page in page_segment_derivation_purge_pages for every sweep of the source, and the sweep checks those pages again
* before it ends. The dropping trigger reads the sweep records as the writer, as RLS lets it; a row it passes unseen
- * that RLS accepts meets DERIVATION_STORED_GUARD_SQL, which reads them as its owner and refuses the write
+ * that RLS accepts meets DERIVATION_STORED_GUARD_FUNCTION_SQL, which reads them as its owner and refuses the write
* (derivation_purge_pending). The scope-entry trigger reads and notes them as its owner (SECURITY DEFINER,
* ../guard-definer.ts). A role RLS refuses meets neither definer, so it learns nothing about a sweep.
*
@@ -340,25 +366,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purge_pages (
page_id INTEGER NOT NULL,
PRIMARY KEY (request_id, page_id)
);
-CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SECURITY DEFINER SET search_path = ${GUARD_SEARCH_PATH} AS $func$
-DECLARE
- src TEXT;
- page INTEGER;
-BEGIN
- IF TG_TABLE_NAME = 'pages' THEN
- src := NEW.source_id;
- page := NEW.id;
- ELSE
- src := OLD.source_id;
- page := OLD.page_id;
- END IF;
- PERFORM pg_advisory_xact_lock_shared(${derivationScopeLockSql('src')});
- INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)
- SELECT x.request_id, page FROM page_segment_derivation_purges x WHERE x.source_id = src ON CONFLICT DO NOTHING;
- RETURN NULL;
-END
-$func$ LANGUAGE plpgsql;
-${revokeExecuteSql('gbrain_mark_derivation_scope_entry')}
+${DERIVATION_SCOPE_ENTRY_FUNCTION_SQL}
DROP TRIGGER IF EXISTS page_body_manifest_derivation_scope_retire ON page_body_manifest;
CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON page_body_manifest
FOR EACH ROW WHEN (OLD.gen_to IS NULL AND NEW.gen_to IS NOT NULL AND OLD.staging_id IS NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
@@ -381,7 +389,8 @@ $func$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS page_segment_derivations_refuse_purging ON page_segment_derivations;
CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON page_segment_derivations
FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation();
-${DERIVATION_STORED_GUARD_SQL}`;
+${DERIVATION_STORED_GUARD_FUNCTION_SQL}
+${DERIVATION_STORED_GUARD_TRIGGER_SQL}`;
/**
* The segment tables hold page text (`page_segment_texts`, `page_body_staging_parts`) or a page's shape and
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 0b5d9ff4e1..e3b18be0b7 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1515,7 +1515,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purge_pages (
page_id INTEGER NOT NULL,
PRIMARY KEY (request_id, page_id)
);
-CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS \$func\$
+CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS \$func\$
DECLARE
src TEXT;
page INTEGER;
@@ -1527,9 +1527,9 @@ BEGIN
src := OLD.source_id;
page := OLD.page_id;
END IF;
- PERFORM pg_advisory_xact_lock_shared(hashtextextended('gbrain:derivation-scope:' || src, 0));
- INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)
- SELECT x.request_id, page FROM page_segment_derivation_purges x WHERE x.source_id = src ON CONFLICT DO NOTHING;
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('gbrain:derivation-scope:'::text || src, 0::bigint));
+ INSERT INTO public.page_segment_derivation_purge_pages (request_id, page_id)
+ SELECT x.request_id, page FROM public.page_segment_derivation_purges x WHERE x.source_id = src ON CONFLICT DO NOTHING;
RETURN NULL;
END
\$func\$ LANGUAGE plpgsql;
@@ -1550,13 +1550,13 @@ CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON pages
CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$
BEGIN
IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id
- WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM page_body_manifest m
+ WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM public.page_body_manifest m
WHERE m.page_id = NEW.page_id AND m.occurrence_id = NEW.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.sha256 = NEW.segment_sha256))
AND CASE WHEN replace(translate(lower(COALESCE(NEW.output::text, '') || ' ' || COALESCE(NEW.receipt::text, '')), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM (VALUES (NEW.output), (NEW.receipt)) doc(j),
LATERAL (SELECT jsonb_path_query(doc.j, 'strict \$.** ? (@.type() == "string")') #>> '{}' AS t
UNION ALL SELECT jsonb_path_query(doc.j, 'strict \$.** ? (@.type() == "object").keyvalue().key') #>> '{}') s
WHERE CASE WHEN replace(translate(lower(s.t), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM unnest(x.needles::text[]) k(n)
- WHERE strpos(' ' || replace(translate(gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN
+ WHERE strpos(' ' || replace(translate(public.gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN
RETURN NULL;
END IF;
RETURN NEW;
@@ -1565,19 +1565,19 @@ END
DROP TRIGGER IF EXISTS page_segment_derivations_refuse_purging ON page_segment_derivations;
CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON page_segment_derivations
FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation();
-CREATE OR REPLACE FUNCTION gbrain_refuse_stored_purging_derivation() RETURNS trigger SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS \$func\$
+CREATE OR REPLACE FUNCTION gbrain_refuse_stored_purging_derivation() RETURNS trigger SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS \$func\$
BEGIN
- IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id
- WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM page_body_manifest m
+ IF EXISTS (SELECT 1 FROM public.page_segment_derivation_purges x JOIN public.pages p ON p.source_id = x.source_id
+ WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM public.page_body_manifest m
WHERE m.page_id = NEW.page_id AND m.occurrence_id = NEW.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.sha256 = NEW.segment_sha256))
AND CASE WHEN replace(translate(lower(COALESCE(NEW.output::text, '') || ' ' || COALESCE(NEW.receipt::text, '')), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM (VALUES (NEW.output), (NEW.receipt)) doc(j),
LATERAL (SELECT jsonb_path_query(doc.j, 'strict \$.** ? (@.type() == "string")') #>> '{}' AS t
UNION ALL SELECT jsonb_path_query(doc.j, 'strict \$.** ? (@.type() == "object").keyvalue().key') #>> '{}') s
WHERE CASE WHEN replace(translate(lower(s.t), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM unnest(x.needles::text[]) k(n)
- WHERE strpos(' ' || replace(translate(gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN
+ WHERE strpos(' ' || replace(translate(public.gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN
RAISE EXCEPTION USING ERRCODE = 'P0001',
MESSAGE = 'derivation_purge_pending: a fact purge''s sweep of stored derivation results is still running and this row holds its claim',
- DETAIL = json_build_object('table', 'page_segment_derivations')::text;
+ DETAIL = json_build_object('table'::text, 'page_segment_derivations'::text)::text;
END IF;
RETURN NULL;
END
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 48da63565e..da812a62d4 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -2261,7 +2261,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purge_pages (
page_id INTEGER NOT NULL,
PRIMARY KEY (request_id, page_id)
);
-CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS \$func\$
+CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS \$func\$
DECLARE
src TEXT;
page INTEGER;
@@ -2273,9 +2273,9 @@ BEGIN
src := OLD.source_id;
page := OLD.page_id;
END IF;
- PERFORM pg_advisory_xact_lock_shared(hashtextextended('gbrain:derivation-scope:' || src, 0));
- INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)
- SELECT x.request_id, page FROM page_segment_derivation_purges x WHERE x.source_id = src ON CONFLICT DO NOTHING;
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('gbrain:derivation-scope:'::text || src, 0::bigint));
+ INSERT INTO public.page_segment_derivation_purge_pages (request_id, page_id)
+ SELECT x.request_id, page FROM public.page_segment_derivation_purges x WHERE x.source_id = src ON CONFLICT DO NOTHING;
RETURN NULL;
END
\$func\$ LANGUAGE plpgsql;
@@ -2296,13 +2296,13 @@ CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON pages
CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$
BEGIN
IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id
- WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM page_body_manifest m
+ WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM public.page_body_manifest m
WHERE m.page_id = NEW.page_id AND m.occurrence_id = NEW.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.sha256 = NEW.segment_sha256))
AND CASE WHEN replace(translate(lower(COALESCE(NEW.output::text, '') || ' ' || COALESCE(NEW.receipt::text, '')), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM (VALUES (NEW.output), (NEW.receipt)) doc(j),
LATERAL (SELECT jsonb_path_query(doc.j, 'strict \$.** ? (@.type() == "string")') #>> '{}' AS t
UNION ALL SELECT jsonb_path_query(doc.j, 'strict \$.** ? (@.type() == "object").keyvalue().key') #>> '{}') s
WHERE CASE WHEN replace(translate(lower(s.t), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM unnest(x.needles::text[]) k(n)
- WHERE strpos(' ' || replace(translate(gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN
+ WHERE strpos(' ' || replace(translate(public.gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN
RETURN NULL;
END IF;
RETURN NEW;
@@ -2311,19 +2311,19 @@ END
DROP TRIGGER IF EXISTS page_segment_derivations_refuse_purging ON page_segment_derivations;
CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON page_segment_derivations
FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation();
-CREATE OR REPLACE FUNCTION gbrain_refuse_stored_purging_derivation() RETURNS trigger SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS \$func\$
+CREATE OR REPLACE FUNCTION gbrain_refuse_stored_purging_derivation() RETURNS trigger SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS \$func\$
BEGIN
- IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id
- WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM page_body_manifest m
+ IF EXISTS (SELECT 1 FROM public.page_segment_derivation_purges x JOIN public.pages p ON p.source_id = x.source_id
+ WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM public.page_body_manifest m
WHERE m.page_id = NEW.page_id AND m.occurrence_id = NEW.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.sha256 = NEW.segment_sha256))
AND CASE WHEN replace(translate(lower(COALESCE(NEW.output::text, '') || ' ' || COALESCE(NEW.receipt::text, '')), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM (VALUES (NEW.output), (NEW.receipt)) doc(j),
LATERAL (SELECT jsonb_path_query(doc.j, 'strict \$.** ? (@.type() == "string")') #>> '{}' AS t
UNION ALL SELECT jsonb_path_query(doc.j, 'strict \$.** ? (@.type() == "object").keyvalue().key') #>> '{}') s
WHERE CASE WHEN replace(translate(lower(s.t), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM unnest(x.needles::text[]) k(n)
- WHERE strpos(' ' || replace(translate(gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN
+ WHERE strpos(' ' || replace(translate(public.gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN
RAISE EXCEPTION USING ERRCODE = 'P0001',
MESSAGE = 'derivation_purge_pending: a fact purge''s sweep of stored derivation results is still running and this row holds its claim',
- DETAIL = json_build_object('table', 'page_segment_derivations')::text;
+ DETAIL = json_build_object('table'::text, 'page_segment_derivations'::text)::text;
END IF;
RETURN NULL;
END
diff --git a/src/core/schema-migrations/v276-guard-triggers-security-definer.ts b/src/core/schema-migrations/v276-guard-triggers-security-definer.ts
index c626cc9cb8..1f5a7487ec 100644
--- a/src/core/schema-migrations/v276-guard-triggers-security-definer.ts
+++ b/src/core/schema-migrations/v276-guard-triggers-security-definer.ts
@@ -4,27 +4,34 @@ import { migrationStatementTimeoutMs } from '../migration-timeout.ts';
import { isLockTimeoutError } from '../retry-matcher.ts';
import { resolveSchemaLockTimeoutMs, schemaLockBlockedError } from '../postgres-engine/schema-lock-timeout.ts';
import {
- AFTER_ROW_PURGE_TRIGGERS, DEFINER_GUARDS, FUNCTION_SEARCH_PATH_HARDENING_SQL, LEGACY_SEARCH_PATH_SETTINGS, definerGuardSql,
+ DEFINER_FUNCTION_SQL, DEFINER_GUARDS, DEFINER_TRIGGERS, FUNCTION_SEARCH_PATH_HARDENING_SQL, LEGACY_SEARCH_PATH_SETTINGS,
} from '../guard-definer.ts';
-import { DERIVATION_STORED_GUARD_SQL } from '../page-body/schema.ts';
+import { DERIVATION_SCOPE_ENTRY_FUNCTION_SQL, DERIVATION_STORED_GUARD_FUNCTION_SQL, DERIVATION_STORED_GUARD_TRIGGER_SQL } from '../page-body/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.
//
// #7632: the purge and withdrawal guards read their ledgers as their owner (SECURITY DEFINER), so a write role without
// a policy on a ledger no longer slips a purged claim, page, take or derivation, or a withdrawn fact, past them. The
-// rest of the change keeps that from widening anyone's reach (src/core/guard-definer.ts): search_path pinned with
-// pg_temp last on every gbrain function, EXECUTE revoked from PUBLIC/anon/authenticated, the raising guards moved to
-// AFTER ROW, and the derivation guard split into its BEFORE ROW invoker drop (unchanged) and an AFTER ROW definer that
-// raises for a row stored anyway, so a definer never answers a role RLS refuses. ALTER and trigger DDL need the owner: a function or table the role does not own is skipped and named
-// on stderr, as v275 does, and doctor's guard_functions check keeps failing with the fix until it is done. Each
-// function and each table is its own short transaction with the migration's statement and lock timeouts.
-const TRIGGERS: ReadonlyArray<{ table: string; trigger: string; fn: string; sql: string }> = [
- ...AFTER_ROW_PURGE_TRIGGERS,
- {
- table: 'page_segment_derivations', trigger: 'page_segment_derivations_refuse_stored_purging', fn: 'gbrain_refuse_stored_purging_derivation',
- sql: DERIVATION_STORED_GUARD_SQL,
- },
+// rest of the change keeps that from widening anyone's reach (src/core/guard-definer.ts): each definer is rewritten with
+// search_path = pg_catalog, pg_temp and every gbrain name schema-qualified, pg_temp is appended to every other gbrain
+// function's path, EXECUTE is revoked from PUBLIC/anon/authenticated, and every definer that refuses fires AFTER ROW or
+// AFTER STATEMENT, so a definer never answers a role RLS refuses. The guards that silently correct a row stay master's
+// invokers. Function and trigger DDL needs the owner: a function or table the role does not own is skipped and named on
+// stderr, as v275 does, and doctor's guard_functions check keeps failing with the fix until it is done. Each function
+// and each table is its own short transaction with the migration's statement and lock timeouts.
+
+/** Every definer guard's CREATE OR REPLACE (body, pinned path, revoke), by function. */
+export const GUARD_FUNCTION_SQL: Readonly<Record<string, string>> = {
+ ...DEFINER_FUNCTION_SQL,
+ gbrain_mark_derivation_scope_entry: DERIVATION_SCOPE_ENTRY_FUNCTION_SQL,
+ gbrain_refuse_stored_purging_derivation: DERIVATION_STORED_GUARD_FUNCTION_SQL,
+};
+
+/** The definer guards' triggers, each AFTER; its table step creates the function and the trigger together. */
+export const GUARD_TRIGGERS: ReadonlyArray<{ table: string; trigger: string; fn: string; sql: string }> = [
+ ...DEFINER_TRIGGERS,
+ { table: 'page_segment_derivations', trigger: 'page_segment_derivations_refuse_stored_purging', fn: 'gbrain_refuse_stored_purging_derivation', sql: DERIVATION_STORED_GUARD_TRIGGER_SQL },
];
async function inShortTransaction(engine: BrainEngine, step: string, sql: string): Promise<void> {
@@ -44,32 +51,36 @@ async function inShortTransaction(engine: BrainEngine, step: string, sql: string
}
/**
- * Moves the guards' triggers, then makes the purge and withdrawal guards definers, and appends pg_temp to every gbrain
- * function's search_path, for what the role owns. A raising guard whose trigger still fires BEFORE ROW stays an
- * invoker, so a definer never answers before RLS; a guard whose table step was skipped is absent and named. Names on stderr what it could not change and returns those names.
+ * For each guard trigger on a table the role owns, creates its definer function and moves or creates the trigger in
+ * one transaction; then rewrites every other definer guard the role owns, unless its trigger still fires BEFORE ROW
+ * (the role could not move it), so a definer never answers before RLS; then appends pg_temp to every gbrain function's
+ * search_path. Names on stderr what it could not change (a guard whose table step was skipped may be absent) and
+ * returns those names.
*/
export async function hardenGuards(engine: BrainEngine, label: string): Promise<string[]> {
const skipped: string[] = [];
+ const done = new Set<string>();
const tables = await engine.executeRaw<{ name: string; owned: boolean | null }>(
`SELECT t.name, pg_has_role(current_user, c.relowner, 'USAGE') AS owned
FROM unnest($1::text[]) AS t(name) JOIN pg_class c ON c.oid = to_regclass(t.name)`,
- [TRIGGERS.map(t => t.table)]);
- const ownedTables = new Set(tables.filter(t => t.owned).map(t => t.name));
- for (const t of TRIGGERS) {
- if (!tables.some(row => row.name === t.table)) continue;
- if (ownedTables.has(t.table)) await inShortTransaction(engine, `${label} on ${t.table}`, t.sql);
- else skipped.push(`${t.trigger} on ${t.table}`);
+ [[...new Set(GUARD_TRIGGERS.map(t => t.table))]]);
+ for (const t of GUARD_TRIGGERS) {
+ const table = tables.find(row => row.name === t.table);
+ if (!table) continue;
+ if (!table.owned) { skipped.push(`${t.trigger} on ${t.table}`); continue; }
+ await inShortTransaction(engine, `${label} on ${t.table}`, `${GUARD_FUNCTION_SQL[t.fn]}\n${t.sql}`);
+ done.add(t.fn);
}
const exposed = new Set((await engine.executeRaw<{ fn: string }>(
`SELECT DISTINCT p.proname AS fn FROM pg_trigger t JOIN pg_proc p ON p.oid = t.tgfoid
WHERE NOT t.tgisinternal AND p.proname = ANY($1::text[]) AND (t.tgtype & 2) <> 0`,
- [TRIGGERS.map(t => t.fn)])).map(r => r.fn));
+ [GUARD_TRIGGERS.map(t => t.fn)])).map(r => r.fn));
const functions = await engine.executeRaw<{ fn: string; owned: boolean | null }>(
`SELECT f.fn, pg_has_role(current_user, p.proowner, 'USAGE') AS owned
FROM unnest($1::text[]) AS f(fn) LEFT JOIN pg_proc p ON p.oid = to_regprocedure(f.fn || '()') ORDER BY f.fn`,
- [DEFINER_GUARDS.map(g => g.fn)]);
+ [DEFINER_GUARDS.map(g => g.fn).filter(fn => !done.has(fn))]);
for (const { fn, owned } of functions) {
- if (owned && !exposed.has(fn)) await inShortTransaction(engine, `${label} on ${fn}()`, definerGuardSql(fn));
+ if (owned && !exposed.has(fn)) await inShortTransaction(engine, `${label} on ${fn}()`, GUARD_FUNCTION_SQL[fn]!);
else skipped.push(`${fn}()`);
}
await inShortTransaction(engine, `${label} search_path`, FUNCTION_SEARCH_PATH_HARDENING_SQL);
diff --git a/src/schema.sql b/src/schema.sql
index fc2d8ffcc8..f106f2394f 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -2257,7 +2257,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purge_pages (
page_id INTEGER NOT NULL,
PRIMARY KEY (request_id, page_id)
);
-CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $func$
+CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $func$
DECLARE
src TEXT;
page INTEGER;
@@ -2269,9 +2269,9 @@ BEGIN
src := OLD.source_id;
page := OLD.page_id;
END IF;
- PERFORM pg_advisory_xact_lock_shared(hashtextextended('gbrain:derivation-scope:' || src, 0));
- INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)
- SELECT x.request_id, page FROM page_segment_derivation_purges x WHERE x.source_id = src ON CONFLICT DO NOTHING;
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('gbrain:derivation-scope:'::text || src, 0::bigint));
+ INSERT INTO public.page_segment_derivation_purge_pages (request_id, page_id)
+ SELECT x.request_id, page FROM public.page_segment_derivation_purges x WHERE x.source_id = src ON CONFLICT DO NOTHING;
RETURN NULL;
END
$func$ LANGUAGE plpgsql;
@@ -2292,13 +2292,13 @@ CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON pages
CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public AS $func$
BEGIN
IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id
- WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM page_body_manifest m
+ WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM public.page_body_manifest m
WHERE m.page_id = NEW.page_id AND m.occurrence_id = NEW.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.sha256 = NEW.segment_sha256))
AND CASE WHEN replace(translate(lower(COALESCE(NEW.output::text, '') || ' ' || COALESCE(NEW.receipt::text, '')), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM (VALUES (NEW.output), (NEW.receipt)) doc(j),
LATERAL (SELECT jsonb_path_query(doc.j, 'strict $.** ? (@.type() == "string")') #>> '{}' AS t
UNION ALL SELECT jsonb_path_query(doc.j, 'strict $.** ? (@.type() == "object").keyvalue().key') #>> '{}') s
WHERE CASE WHEN replace(translate(lower(s.t), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM unnest(x.needles::text[]) k(n)
- WHERE strpos(' ' || replace(translate(gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN
+ WHERE strpos(' ' || replace(translate(public.gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN
RETURN NULL;
END IF;
RETURN NEW;
@@ -2307,19 +2307,19 @@ $func$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS page_segment_derivations_refuse_purging ON page_segment_derivations;
CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON page_segment_derivations
FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation();
-CREATE OR REPLACE FUNCTION gbrain_refuse_stored_purging_derivation() RETURNS trigger SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $func$
+CREATE OR REPLACE FUNCTION gbrain_refuse_stored_purging_derivation() RETURNS trigger SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $func$
BEGIN
- IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id
- WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM page_body_manifest m
+ IF EXISTS (SELECT 1 FROM public.page_segment_derivation_purges x JOIN public.pages p ON p.source_id = x.source_id
+ WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM public.page_body_manifest m
WHERE m.page_id = NEW.page_id AND m.occurrence_id = NEW.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.sha256 = NEW.segment_sha256))
AND CASE WHEN replace(translate(lower(COALESCE(NEW.output::text, '') || ' ' || COALESCE(NEW.receipt::text, '')), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM (VALUES (NEW.output), (NEW.receipt)) doc(j),
LATERAL (SELECT jsonb_path_query(doc.j, 'strict $.** ? (@.type() == "string")') #>> '{}' AS t
UNION ALL SELECT jsonb_path_query(doc.j, 'strict $.** ? (@.type() == "object").keyvalue().key') #>> '{}') s
WHERE CASE WHEN replace(translate(lower(s.t), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM unnest(x.needles::text[]) k(n)
- WHERE strpos(' ' || replace(translate(gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN
+ WHERE strpos(' ' || replace(translate(public.gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN
RAISE EXCEPTION USING ERRCODE = 'P0001',
MESSAGE = 'derivation_purge_pending: a fact purge''s sweep of stored derivation results is still running and this row holds its claim',
- DETAIL = json_build_object('table', 'page_segment_derivations')::text;
+ DETAIL = json_build_object('table'::text, 'page_segment_derivations'::text)::text;
END IF;
RETURN NULL;
END
diff --git a/test/doctor-guard-functions.test.ts b/test/doctor-guard-functions.test.ts
index 1d6d635d30..ce9804e51a 100644
--- a/test/doctor-guard-functions.test.ts
+++ b/test/doctor-guard-functions.test.ts
@@ -5,6 +5,7 @@
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { guardFunctionProblems } from '../src/commands/doctor/checks/guard-functions.ts';
+import { derivationScopeLockSql } from '../src/core/page-body/schema.ts';
describe('guard_functions doctor check (#7632)', () => {
let engine: PGLiteEngine;
@@ -28,11 +29,11 @@ describe('guard_functions doctor check (#7632)', () => {
ALTER FUNCTION gbrain_try_jsonb(text) SET search_path = pg_catalog, public;`);
const { problems, fix } = await guardFunctionProblems(engine);
expect(problems).toEqual([
- 'gbrain_refuse_purged_page() is not SECURITY DEFINER with search_path pg_catalog, public, pg_temp',
+ 'gbrain_refuse_purged_page() is not SECURITY DEFINER with search_path pg_catalog, pg_temp',
'gbrain_refuse_purged_take() is executable by PUBLIC',
'pages_refuse_purged on pages still fires BEFORE ROW',
- 'page_segment_derivations has no page_segment_derivations_refuse_stored_purging AFTER ROW check',
- '2 function(s) pin search_path without pg_temp last (gbrain_refuse_purged_page(), gbrain_try_jsonb(text))',
+ 'page_segment_derivations has no page_segment_derivations_refuse_stored_purging AFTER check',
+ '1 function(s) pin search_path without pg_temp last (gbrain_try_jsonb(text))',
]);
await engine.runMigration(0, fix.join('\n'));
expect(await guardFunctionProblems(engine)).toEqual({ problems: [], fix: [] });
@@ -48,11 +49,41 @@ describe('guard_functions doctor check (#7632)', () => {
CREATE TRIGGER page_segment_derivations_refuse_stored_purging BEFORE INSERT OR UPDATE OF output, receipt ON page_segment_derivations
FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_stored_purging_derivation();`);
const { problems, fix } = await guardFunctionProblems(engine);
- expect(problems).toEqual(['page_segment_derivations has no page_segment_derivations_refuse_stored_purging AFTER ROW check']);
+ expect(problems).toEqual(['page_segment_derivations_refuse_stored_purging on page_segment_derivations still fires BEFORE ROW']);
await engine.runMigration(0, fix.join('\n'));
expect(await guardFunctionProblems(engine)).toEqual({ problems: [], fix: [] });
});
+ // An older gbrain booting against an upgraded brain replays its schema blob, whose CREATE OR REPLACE of the scope-entry
+ // function (as on master before #7632) makes it an invoker again: doctor names it and its fix restores the definer.
+ test('a scope-entry function an older gbrain re-created as an invoker is named, and the fix restores the definer', async () => {
+ await engine.runMigration(0, `CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SET search_path = pg_catalog, public AS $func$
+DECLARE
+ src TEXT;
+ page INTEGER;
+BEGIN
+ IF TG_TABLE_NAME = 'pages' THEN
+ src := NEW.source_id;
+ page := NEW.id;
+ ELSE
+ src := OLD.source_id;
+ page := OLD.page_id;
+ END IF;
+ PERFORM pg_advisory_xact_lock_shared(${derivationScopeLockSql('src')});
+ INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)
+ SELECT x.request_id, page FROM page_segment_derivation_purges x WHERE x.source_id = src ON CONFLICT DO NOTHING;
+ RETURN NULL;
+END
+$func$ LANGUAGE plpgsql;`);
+ const { problems, fix } = await guardFunctionProblems(engine);
+ expect(problems).toEqual(['gbrain_mark_derivation_scope_entry() is not SECURITY DEFINER with search_path pg_catalog, pg_temp']);
+ await engine.runMigration(0, fix.join('\n'));
+ expect(await guardFunctionProblems(engine)).toEqual({ problems: [], fix: [] });
+ const [fn] = await engine.executeRaw<{ secdef: boolean; config: string[] }>(
+ `SELECT prosecdef AS secdef, proconfig AS config FROM pg_proc WHERE oid = 'gbrain_mark_derivation_scope_entry()'::regprocedure`);
+ expect(fn).toEqual({ secdef: true, config: ['search_path=pg_catalog, pg_temp'] });
+ });
+
// Generated by gstack /ship coverage audit (#7642).
// Value: protects=doctor asks for the stored-derivation check only where page_segment_derivations exists, so its fix never
// targets a missing table; fails_when=the to_regclass presence probe is dropped; why_new=every other doctor test has the
diff --git a/test/e2e/guard-definer-postgres.test.ts b/test/e2e/guard-definer-postgres.test.ts
index 9488a97b93..81a79aacae 100644
--- a/test/e2e/guard-definer-postgres.test.ts
+++ b/test/e2e/guard-definer-postgres.test.ts
@@ -20,6 +20,8 @@ import { LATEST_VERSION, runMigrations } from '../../src/core/migrate.ts';
import { guardFunctionProblems } from '../../src/commands/doctor/checks/guard-functions.ts';
import { derivationNeedles } from '../../src/core/page-body/segment-derive.ts';
import { DerivationWriteRefused } from '../../src/core/page-body/derivations.ts';
+import { MEMORY_PURGE_GUARD_SQL } from '../../src/core/facts/purge-schema.ts';
+import { FACT_INSERT_GUARD_SQL } from '../../src/core/facts/insert-guard-schema.ts';
import { v276 } from '../../src/core/schema-migrations/v276-guard-triggers-security-definer.ts';
import { withEnv } from '../helpers/with-env.ts';
@@ -29,9 +31,13 @@ const describeE2E = DATABASE_URL ? describe : describe.skip;
type Sql = ReturnType<typeof postgres>;
type Outcome = { rows: Array<Record<string, unknown>> } | { code: string; message: string };
-const GUARDS = ['gbrain_guard_inserted_facts', 'gbrain_mark_derivation_scope_entry', 'gbrain_preserve_fact_withdrawal', 'gbrain_refuse_purged_fact',
- 'gbrain_refuse_purged_page', 'gbrain_refuse_purged_take', 'gbrain_refuse_stored_purging_derivation'];
-const STORED_GUARD = 'gbrain_refuse_stored_purging_derivation';
+const GUARDS = ['gbrain_mark_derivation_scope_entry', 'gbrain_refuse_purged_fact', 'gbrain_refuse_purged_page', 'gbrain_refuse_purged_take',
+ 'gbrain_refuse_revived_withdrawn_fact', 'gbrain_refuse_stored_purging_derivation', 'gbrain_refuse_unguarded_inserted_facts'];
+/** The definer guards #7632 adds; the rest existed before as invokers. */
+const NEW_GUARDS = ['gbrain_refuse_revived_withdrawn_fact', 'gbrain_refuse_stored_purging_derivation', 'gbrain_refuse_unguarded_inserted_facts'];
+const GUARD_TRIGGER_NAMES = ['facts_refuse_purged', 'facts_refuse_revived_withdrawal', 'facts_refuse_unguarded_inserted', 'pages_refuse_purged',
+ 'page_segment_derivations_refuse_stored_purging', 'takes_refuse_purged'];
+const DEFINER_PATH = ['search_path=pg_catalog, pg_temp'];
const LEDGERS = ['fact_purges', 'fact_withdrawals', 'take_purges', 'page_purges', 'page_segment_derivation_purges', 'page_segment_derivation_purge_pages'];
const API_ROLES = ['anon', 'authenticated'];
@@ -164,16 +170,23 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()
});
});
- test('2. a withdrawn claim stays withdrawn: row insert, deferred (statement) insert, and an update clearing expired_at', async () => {
+ test('2. a withdrawn claim stays withdrawn: an owner is stamped as before; a writer that cannot read the withdrawals is refused on a row insert, a deferred insert and an update clearing expired_at', async () => {
await as(conn, WRITER, async run => {
- expect(rowsOf(await run(`INSERT INTO facts (fact, source) VALUES ($1, 'probe') RETURNING expired_at::text AS at`, [WITHDRAWN_CLAIM])))
- .toEqual([{ at: withdrawnAt }]);
+ expect(failure(await run(`INSERT INTO facts (fact, source) VALUES ($1, 'probe')`, [WITHDRAWN_CLAIM])))
+ .toMatchObject({ code: 'P0001', message: expect.stringContaining('fact_withdrawn:') });
rowsOf(await run(`SET LOCAL gbrain.fact_withdrawal_stamp_deferred = 'on'`));
+ expect(failure(await run(`INSERT INTO facts (fact, source) VALUES ($1, 'probe-deferred')`, [WITHDRAWN_CLAIM])))
+ .toMatchObject({ code: 'P0001', message: expect.stringContaining('fact_withdrawn:') });
+ rowsOf(await run('RESET ROLE'));
const [deferred] = rowsOf(await run(`INSERT INTO facts (fact, source) VALUES ($1, 'probe-deferred') RETURNING id`, [WITHDRAWN_CLAIM]));
rowsOf(await run(`SET LOCAL gbrain.fact_withdrawal_stamp_deferred = 'off'`));
expect(rowsOf(await run('SELECT expired_at::text AS at FROM facts WHERE id = $1', [deferred!.id]))).toEqual([{ at: withdrawnAt }]);
rowsOf(await run('UPDATE facts SET expired_at = NULL, valid_until = NULL WHERE id = $1', [deferred!.id]));
expect(rowsOf(await run('SELECT expired_at::text AS at FROM facts WHERE id = $1', [deferred!.id]))).toEqual([{ at: withdrawnAt }]);
+ rowsOf(await run(`SET LOCAL ROLE ${WRITER}`));
+ expect(failure(await run('UPDATE facts SET expired_at = NULL, valid_until = NULL WHERE id = $1', [deferred!.id])))
+ .toMatchObject({ code: 'P0001', message: expect.stringContaining('fact_withdrawn:') });
+ expect(rowsOf(await run('SELECT expired_at::text AS at FROM facts WHERE id = $1', [deferred!.id]))).toEqual([{ at: withdrawnAt }]);
});
});
@@ -217,7 +230,7 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()
await as(conn, WRITER, async run => {
for (const ledger of LEDGERS) rowsOf(await run(`CREATE TEMP TABLE ${ledger} (LIKE public.${ledger})`));
expect(failure(await run(`INSERT INTO facts (fact, source) VALUES ($1, 'probe')`, [PURGED_CLAIM])).code).toBe('P0001');
- expect(rowsOf(await run(`INSERT INTO facts (fact, source) VALUES ($1, 'probe') RETURNING expired_at::text AS at`, [WITHDRAWN_CLAIM]))).toEqual([{ at: withdrawnAt }]);
+ expect(failure(await run(`INSERT INTO facts (fact, source) VALUES ($1, 'probe')`, [WITHDRAWN_CLAIM]))).toMatchObject({ code: 'P0001', message: expect.stringContaining('fact_withdrawn:') });
expect(failure(await run(`INSERT INTO pages (slug, type, title, compiled_truth, content_hash) VALUES ('notes/again-example', 'note', 't', 'x', $1)`, [PURGED_HASH])).code).toBe('P0001');
expect(failure(await run(`INSERT INTO takes (page_id, row_num, claim, kind, holder) VALUES ($1, 1, $2, 'take', 'alice-example')`, [ids.takes, PURGED_TAKE])).code).toBe('P0001');
const [held, heldOutput] = insertDerivation(JSON.stringify({ text: PURGED_CLAIM }));
@@ -277,7 +290,10 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()
FROM pg_proc p WHERE p.oid = ANY(SELECT to_regprocedure(g || '()') FROM unnest($1::text[]) g) ORDER BY 1`, [GUARDS, API_ROLES]);
const triggers = await c.unsafe<Array<{ trigger: string; timing: string }>>(
`SELECT tgname AS trigger, CASE WHEN (tgtype & 2) <> 0 THEN 'BEFORE' ELSE 'AFTER' END AS timing FROM pg_trigger WHERE NOT tgisinternal
- AND tgname IN ('facts_refuse_purged', 'takes_refuse_purged', 'pages_refuse_purged', 'page_segment_derivations_refuse_purging', 'page_segment_derivations_refuse_stored_purging') ORDER BY 1`);
+ AND tgname = ANY($1::text[]) ORDER BY 1`, [[...GUARD_TRIGGER_NAMES, 'page_segment_derivations_refuse_purging']]);
+ const definers = await c.unsafe<Array<{ fn: string; config: string[] | null }>>(
+ `SELECT p.proname AS fn, p.proconfig AS config FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
+ WHERE n.nspname = 'public' AND p.prosecdef ORDER BY 1`);
const pathsWithoutTemp = await c.unsafe<Array<{ sig: string }>>(
`SELECT p.oid::regprocedure::text AS sig FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace CROSS JOIN LATERAL unnest(p.proconfig) AS s(setting)
WHERE n.nspname = 'public' AND s.setting LIKE 'search_path=%' AND s.setting NOT LIKE '%, pg_temp' ORDER BY 1`);
@@ -285,40 +301,46 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()
guards: guards.map(g => ({ fn: g.fn, secdef: g.secdef, config: g.config, executable_by: g.executable_by })),
triggers: triggers.map(t => ({ trigger: t.trigger, timing: t.timing })),
pathsWithoutTemp: pathsWithoutTemp.map(p => p.sig),
+ definers: definers.map(d => ({ fn: d.fn, config: d.config })),
};
}
const EXPECTED = {
- guards: GUARDS.map(fn => ({ fn, secdef: true, config: ['search_path=pg_catalog, public, pg_temp'], executable_by: [] })),
+ guards: GUARDS.map(fn => ({ fn, secdef: true, config: DEFINER_PATH, executable_by: [] })),
triggers: [
{ trigger: 'facts_refuse_purged', timing: 'AFTER' },
+ { trigger: 'facts_refuse_revived_withdrawal', timing: 'AFTER' },
+ { trigger: 'facts_refuse_unguarded_inserted', timing: 'AFTER' },
{ trigger: 'page_segment_derivations_refuse_purging', timing: 'BEFORE' },
{ trigger: 'page_segment_derivations_refuse_stored_purging', timing: 'AFTER' },
{ trigger: 'pages_refuse_purged', timing: 'AFTER' },
{ trigger: 'takes_refuse_purged', timing: 'AFTER' },
],
pathsWithoutTemp: [],
+ // Every SECURITY DEFINER function in public is one of the guards, with public off its path: a redefinition that
+ // puts public back, or a new definer, fails here.
+ definers: GUARDS.map(fn => ({ fn, config: DEFINER_PATH })),
};
- test('10a. after a fresh install: guards are definers pinned with pg_temp last, not executable by PUBLIC/anon/authenticated, raising triggers AFTER ROW, every pinned search_path ends in pg_temp', async () => {
+ test('10a. after a fresh install: guards are definers pinned to pg_catalog, pg_temp (the only definers in public), not executable by PUBLIC/anon/authenticated, raising triggers AFTER ROW, every pinned search_path ends in pg_temp', async () => {
expect(await catalog(conn)).toEqual(EXPECTED);
});
+ /** Puts a brain back in the shape every brain had before #7632, at the version before it. */
/** Puts a brain back in the shape every brain had before #7632, at the version before it. */
async function rewind(c: Sql): Promise<void> {
await c.unsafe(`
- ${GUARDS.filter(fn => fn !== STORED_GUARD).map(fn => `ALTER FUNCTION ${fn}() SECURITY INVOKER; GRANT EXECUTE ON FUNCTION ${fn}() TO PUBLIC, anon, authenticated;`).join('\n')}
+ ${MEMORY_PURGE_GUARD_SQL}
+ ${FACT_INSERT_GUARD_SQL}
+ GRANT EXECUTE ON FUNCTION gbrain_refuse_purged_fact(), gbrain_refuse_purged_take(), gbrain_refuse_purged_page() TO PUBLIC, anon, authenticated;
+ DROP TRIGGER facts_refuse_revived_withdrawal ON facts;
+ DROP FUNCTION gbrain_refuse_revived_withdrawn_fact();
+ DROP TRIGGER facts_refuse_unguarded_inserted ON facts;
+ DROP FUNCTION gbrain_refuse_unguarded_inserted_facts();
DROP TRIGGER page_segment_derivations_refuse_stored_purging ON page_segment_derivations;
- DROP FUNCTION ${STORED_GUARD}();
- DROP TRIGGER 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 takes_refuse_purged ON takes;
- CREATE TRIGGER takes_refuse_purged BEFORE INSERT OR UPDATE OF claim, page_id ON takes FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_take();
- DROP TRIGGER pages_refuse_purged ON pages;
- CREATE TRIGGER pages_refuse_purged BEFORE INSERT OR UPDATE ON pages FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_page();
- DROP TRIGGER page_segment_derivations_refuse_purging ON page_segment_derivations;
- CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON page_segment_derivations
- FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation();
+ DROP FUNCTION gbrain_refuse_stored_purging_derivation();
+ ALTER FUNCTION gbrain_mark_derivation_scope_entry() SECURITY INVOKER SET search_path = pg_catalog, public;
+ GRANT EXECUTE ON FUNCTION gbrain_mark_derivation_scope_entry() TO PUBLIC, anon, authenticated;
DO $$ DECLARE f RECORD; BEGIN
FOR f IN SELECT p.oid::regprocedure AS sig, substr(s.setting, 13) AS path FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
CROSS JOIN LATERAL unnest(p.proconfig) AS s(setting) WHERE n.nspname = 'public' AND s.setting LIKE 'search_path=%, pg_temp' LOOP
@@ -370,7 +392,7 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()
const { value, stderr } = await capturingStderr(() => runMigrations(notOwner));
expect(value.current).toBe(LATEST_VERSION);
for (const fn of GUARDS) expect(stderr).toContain(`${fn}()`);
- for (const trigger of ['facts_refuse_purged', 'takes_refuse_purged', 'pages_refuse_purged', 'page_segment_derivations_refuse_stored_purging']) expect(stderr).toContain(trigger);
+ for (const trigger of GUARD_TRIGGER_NAMES) expect(stderr).toContain(trigger);
expect(stderr).toContain('left as they were');
// Generated by gstack /ship coverage audit (#7642).
// Value: protects=v276 names on stderr every non-guard function whose search_path it could not finish with pg_temp;
@@ -431,7 +453,7 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()
await engine.connect({ database_url: url });
expect(await guardFunctionProblems(engine)).toEqual({
problems: [`gbrain_refuse_purged_page()'s owner ${weakOwner} neither bypasses RLS nor owns page_purges unforced, so the guard reads them filtered`],
- fix: [`/* give gbrain_refuse_purged_page() an owner that bypasses RLS (ALTER FUNCTION gbrain_refuse_purged_page() OWNER TO <owner of the tables>), or ALTER ROLE ${weakOwner} BYPASSRLS; */`],
+ fix: ['/* give gbrain_refuse_purged_page() an owner that bypasses RLS and is not the role gbrain runs as, so that role stays under its policies: ALTER FUNCTION gbrain_refuse_purged_page() OWNER TO <that role>; */'],
});
await as(conn, WRITER, async run => {
expect(rowsOf(await run(insertPurgedPage, [PURGED_HASH]))).toEqual([{ stored: 1 }]);
@@ -486,16 +508,16 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()
try {
await rewind(brain.conn);
await brain.conn.unsafe(`GRANT USAGE, CREATE ON SCHEMA public TO ${migrator}; GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO ${migrator};
- ${GUARDS.filter(fn => fn !== STORED_GUARD).map(fn => `ALTER FUNCTION ${fn}() OWNER TO ${migrator};`).join('\n')}`);
+ ${GUARDS.filter(fn => !NEW_GUARDS.includes(fn)).map(fn => `ALTER FUNCTION ${fn}() OWNER TO ${migrator};`).join('\n')}`);
const asMigrator = new URL(brain.url);
asMigrator.username = migrator;
asMigrator.password = 'migrator';
await engine.connect({ database_url: asMigrator.toString() });
const { value, stderr } = await capturingStderr(() => runMigrations(engine));
expect(value.current).toBe(LATEST_VERSION);
- for (const fn of [...exposed, STORED_GUARD]) expect(stderr).toContain(`${fn}()`);
+ for (const fn of [...exposed, ...NEW_GUARDS]) expect(stderr).toContain(`${fn}()`);
const after = await catalog(brain.conn);
- expect(after.guards.map(g => [g.fn, g.secdef])).toEqual(GUARDS.filter(fn => fn !== STORED_GUARD).map(fn => [fn, !exposed.includes(fn)]));
+ expect(after.guards.map(g => [g.fn, g.secdef])).toEqual(GUARDS.filter(fn => !NEW_GUARDS.includes(fn)).map(fn => [fn, !exposed.includes(fn)]));
expect(after.triggers.map(t => [t.trigger, t.timing])).toEqual([
['facts_refuse_purged', 'BEFORE'], ['page_segment_derivations_refuse_purging', 'BEFORE'], ['pages_refuse_purged', 'BEFORE'], ['takes_refuse_purged', 'BEFORE'],
]);
@@ -505,13 +527,14 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()
}
}, 300_000);
- test('16. owners, roles that bypass RLS and writers with policies on the sweep records still have the row dropped silently', async () => {
+ test('16. owners, roles that bypass RLS and writers with policies on the ledgers still have a derivation dropped and a withdrawn fact stamped silently', async () => {
const bypass = `gbrain_test_guard_bypass_${suffix}`;
const reader = `gbrain_test_guard_reader_${suffix}`;
await admin!.unsafe(`CREATE ROLE ${bypass} NOLOGIN NOSUPERUSER BYPASSRLS; CREATE ROLE ${reader} NOLOGIN NOSUPERUSER NOBYPASSRLS`);
createdRoles.push(bypass, reader);
await conn.unsafe(`GRANT USAGE ON SCHEMA public TO ${bypass}, ${reader};
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO ${bypass}, ${reader};
+ GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO ${bypass}, ${reader};
DO $$ DECLARE t RECORD; BEGIN
FOR t IN SELECT c.oid::regclass AS rel FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') AND c.relrowsecurity LOOP
@@ -522,6 +545,8 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()
for (const role of [owner!, bypass, reader]) {
await as(conn, role, async run => {
expect({ role, rows: rowsOf(await run(held, [ids.derived, 1, heldOutput])) }).toEqual({ role, rows: [] });
+ expect({ role, rows: rowsOf(await run(`INSERT INTO facts (fact, source) VALUES ($1, 'probe') RETURNING expired_at::text AS at`, [WITHDRAWN_CLAIM])) })
+ .toEqual({ role, rows: [{ at: withdrawnAt }] });
});
}
const engine = new PostgresEngine();
@@ -555,4 +580,66 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()
await conn.unsafe('DROP POLICY gbrain_test_read_pages ON pages');
}
});
+
+ // A writer with CREATE on public (Supabase grants it to anon and authenticated) plants overloads of what the definer
+ // bodies call; each spy raises when it runs as anyone but the writer, so a definer that resolved it shows in the error.
+ test('18. overloads planted in public never run as the owner: hashtextextended, json_build_object, jsonb_path_query, gbrain_fact_fingerprint', async () => {
+ const spy = (signature: string, returns: string, call: string) => `CREATE FUNCTION public.${signature} RETURNS ${returns} LANGUAGE plpgsql AS $f$
+ BEGIN IF current_user <> '${WRITER}' THEN RAISE EXCEPTION 'spy % ran as %', '${signature.split('(')[0]}', current_user; END IF; ${call} END $f$`;
+ await conn.unsafe(`GRANT CREATE ON SCHEMA public TO ${WRITER}`);
+ try {
+ await as(conn, WRITER, async run => {
+ rowsOf(await run(spy('hashtextextended(a text, b integer)', 'bigint', 'RETURN pg_catalog.hashtextextended(a, b::bigint);')));
+ rowsOf(await run(spy('json_build_object(a text, b text, c text, d text)', 'json', 'RETURN pg_catalog.json_build_object(a, b, c, d);')));
+ rowsOf(await run(spy('jsonb_path_query(j jsonb, p text)', 'SETOF jsonb', 'RETURN QUERY SELECT pg_catalog.jsonb_path_query(j, p::jsonpath);')));
+ rowsOf(await run(spy('gbrain_fact_fingerprint(c character varying)', 'text', 'RETURN pg_catalog.md5(c);')));
+ const spied = (o: Outcome) => ('code' in o ? o.message : '').includes('spy ');
+ const softDelete = await run('UPDATE pages SET deleted_at = now() WHERE id = $1 RETURNING id', [ids.derived]);
+ expect({ softDelete: spied(softDelete) ? softDelete : 'ok' }).toEqual({ softDelete: 'ok' });
+ const page = failure(await run(`INSERT INTO pages (slug, type, title, compiled_truth, content_hash) VALUES ('notes/again-example', 'note', 't', 'x', $1)`, [PURGED_HASH]));
+ expect(page.message).toStartWith('purged_content:');
+ const fact = failure(await run(`INSERT INTO facts (fact, source) VALUES ($1, 'probe')`, [PURGED_CLAIM]));
+ expect(fact.message).toStartWith('purged_content:');
+ const [held, heldOutput] = insertDerivation(JSON.stringify({ text: PURGED_CLAIM }));
+ const derivation = failure(await run(held, [ids.takes, 3, heldOutput]));
+ expect(derivation.message).toStartWith('derivation_purge_pending:');
+ });
+ } finally {
+ await conn.unsafe(`REVOKE CREATE ON SCHEMA public FROM ${WRITER}`);
+ }
+ });
+
+ test('19. while a purge holds a source, a role RLS refuses gets the same 42501 inserting a fact into it as into a source that does not exist', async () => {
+ const holder = postgres(url, { max: 1, prepare: false, onnotice: () => {} });
+ const session = await holder.reserve();
+ try {
+ await session.unsafe(`BEGIN; SELECT id FROM sources WHERE id = 'default' FOR UPDATE`);
+ for (const role of API_ROLES) {
+ await as(conn, role, async run => {
+ rowsOf(await run(`SET LOCAL lock_timeout = '1s'`));
+ const insert = (source: string) => run(`INSERT INTO facts (fact, source, source_id) VALUES ('an unrelated claim', 'probe', $1)`, [source]);
+ const locked = failure(await insert('default'));
+ expect({ role, locked }).toEqual({ role, locked: failure(await insert('no-such-source-example')) });
+ expect(locked.code).toBe('42501');
+ });
+ }
+ } finally {
+ await session.unsafe('ROLLBACK').catch(() => {});
+ session.release();
+ await holder.end();
+ }
+ });
+
+ test('20. a purged take claim is refused for the owner on insert and update, and for a writer that cannot read take_purges on update', async () => {
+ const [{ owner }] = await conn.unsafe<Array<{ owner: string }>>('SELECT current_user AS owner');
+ for (const role of [owner!, WRITER]) {
+ await as(conn, role, async run => {
+ const purged = (o: Outcome) => ({ role, ...failure(o) });
+ const refusal = { role, code: 'P0001', message: expect.stringContaining('purged_content: this take claim was purged') };
+ if (role === owner) expect(purged(await run(`INSERT INTO takes (page_id, row_num, claim, kind, holder) VALUES ($1, 7, $2, 'take', 'alice-example')`, [ids.takes, PURGED_TAKE]))).toEqual(refusal);
+ const [take] = rowsOf(await run(`INSERT INTO takes (page_id, row_num, claim, kind, holder) VALUES ($1, 8, 'an unrelated take', 'take', 'alice-example') RETURNING id`, [ids.takes]));
+ expect(purged(await run('UPDATE takes SET claim = $1 WHERE id = $2', [PURGED_TAKE, take!.id]))).toEqual(refusal);
+ });
+ }
+ });
});
diff --git a/test/fact-fingerprint-search-path.test.ts b/test/fact-fingerprint-search-path.test.ts
index ed27b62401..fad93a1b89 100644
--- a/test/fact-fingerprint-search-path.test.ts
+++ b/test/fact-fingerprint-search-path.test.ts
@@ -18,6 +18,7 @@ import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { MIGRATIONS, runMigrations } from '../src/core/migrate.ts';
import { FACT_WITHDRAWAL_SCHEMA_STATEMENTS } from '../src/core/facts/withdrawal-schema.ts';
+import { GUARD_SEARCH_PATH } from '../src/core/guard-definer.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
@@ -73,7 +74,7 @@ for (const kind of testBackends()) {
const unpinned = () => engine.executeRaw<{ sig: string }>(`SELECT p.oid::regprocedure::text AS sig FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace JOIN pg_language l ON l.oid = p.prolang
WHERE n.nspname = 'public' AND l.lanname = 'plpgsql' AND p.proname LIKE 'gbrain\\_%'
- AND NOT (COALESCE(p.proconfig, '{}'::text[]) && ARRAY['search_path=pg_catalog, public', 'search_path=pg_catalog, public, pg_temp'])`);
+ AND NOT (COALESCE(p.proconfig, '{}'::text[]) && ARRAY['search_path=pg_catalog, public', 'search_path=pg_catalog, public, pg_temp', 'search_path=${GUARD_SEARCH_PATH}'])`);
const searchPathMigration = MIGRATIONS.find(m => m.name.endsWith('function_search_path'))!;
const rerunSearchPathMigration = async () => {
expect(searchPathMigration).toBeDefined();
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 56f5f23962..31b24abf34 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -552,19 +552,21 @@
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4f2d679df92779f6941e2378b82d5a9d5fb5cb4fe8d571f4d69801e6f646bde6",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",
- "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
- "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=3f11d09c3b95ae5a066c240caec9a7b068cf206b3ed350420e84cc379ab1cf8a",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=08d7e84882d373c36a1db161eb9eed1da80ceb5d4373f65abc86f4e87e11a54f",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=9b08c031113955862b3bcd9f969c8ba721f7fe5c42aaa9992935fc4e7dd6e5ed",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=875112f8a4a7c22e349f0230c6bf5fd73331c3c54e542c3eaa896d3c21c868a3",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=05de18ee0111c91b4db21f46b6e99b20769ca0d69ec405ad6b48506dc23bbad6",
+ "gbrain_refuse_revived_withdrawn_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=7a383cc3e5c2742020f138aa962696f0e07d76f981295de0c38294a0c33f94ec",
+ "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4a3444d23904f780bb53285e3abc3ce1b079b27bf3faee2ef60b2915ad672146",
+ "gbrain_refuse_unguarded_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=84360ce2ecf76f1dc9aaa00f5e7518531387e4a4bd53285f9ea617b27172bae5",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702",
@@ -4313,6 +4315,8 @@
"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_preserve_withdrawal_insert": "CREATE TRIGGER facts_preserve_withdrawal_insert BEFORE INSERT ON public.facts FOR EACH ROW WHEN (((new.expired_at IS NULL) AND (COALESCE(current_setting('gbrain.fact_withdrawal_stamp_deferred'::text, true), ''::text) <> 'on'::text))) EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",
"facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged AFTER UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()",
+ "facts.facts_refuse_revived_withdrawal": "CREATE TRIGGER facts_refuse_revived_withdrawal AFTER UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW WHEN ((new.expired_at IS NULL)) EXECUTE FUNCTION gbrain_refuse_revived_withdrawn_fact()",
+ "facts.facts_refuse_unguarded_inserted": "CREATE TRIGGER facts_refuse_unguarded_inserted AFTER INSERT ON public.facts REFERENCING NEW TABLE AS inserted_facts FOR EACH STATEMENT EXECUTE FUNCTION gbrain_refuse_unguarded_inserted_facts()",
"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.json
index 517057c3df..64aa8622b6 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -552,19 +552,21 @@
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4f2d679df92779f6941e2378b82d5a9d5fb5cb4fe8d571f4d69801e6f646bde6",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",
- "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
- "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=3f11d09c3b95ae5a066c240caec9a7b068cf206b3ed350420e84cc379ab1cf8a",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=08d7e84882d373c36a1db161eb9eed1da80ceb5d4373f65abc86f4e87e11a54f",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=9b08c031113955862b3bcd9f969c8ba721f7fe5c42aaa9992935fc4e7dd6e5ed",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=875112f8a4a7c22e349f0230c6bf5fd73331c3c54e542c3eaa896d3c21c868a3",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=05de18ee0111c91b4db21f46b6e99b20769ca0d69ec405ad6b48506dc23bbad6",
+ "gbrain_refuse_revived_withdrawn_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=7a383cc3e5c2742020f138aa962696f0e07d76f981295de0c38294a0c33f94ec",
+ "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4a3444d23904f780bb53285e3abc3ce1b079b27bf3faee2ef60b2915ad672146",
+ "gbrain_refuse_unguarded_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=84360ce2ecf76f1dc9aaa00f5e7518531387e4a4bd53285f9ea617b27172bae5",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702",
@@ -4313,6 +4315,8 @@
"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_preserve_withdrawal_insert": "CREATE TRIGGER facts_preserve_withdrawal_insert BEFORE INSERT ON public.facts FOR EACH ROW WHEN (((new.expired_at IS NULL) AND (COALESCE(current_setting('gbrain.fact_withdrawal_stamp_deferred'::text, true), ''::text) <> 'on'::text))) EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",
"facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged AFTER UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()",
+ "facts.facts_refuse_revived_withdrawal": "CREATE TRIGGER facts_refuse_revived_withdrawal AFTER UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW WHEN ((new.expired_at IS NULL)) EXECUTE FUNCTION gbrain_refuse_revived_withdrawn_fact()",
+ "facts.facts_refuse_unguarded_inserted": "CREATE TRIGGER facts_refuse_unguarded_inserted AFTER INSERT ON public.facts REFERENCING NEW TABLE AS inserted_facts FOR EACH STATEMENT EXECUTE FUNCTION gbrain_refuse_unguarded_inserted_facts()",
"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.json
index 888ab14e7d..642dc33bce 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -552,19 +552,21 @@
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4f2d679df92779f6941e2378b82d5a9d5fb5cb4fe8d571f4d69801e6f646bde6",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",
- "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
- "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=3f11d09c3b95ae5a066c240caec9a7b068cf206b3ed350420e84cc379ab1cf8a",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=08d7e84882d373c36a1db161eb9eed1da80ceb5d4373f65abc86f4e87e11a54f",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=9b08c031113955862b3bcd9f969c8ba721f7fe5c42aaa9992935fc4e7dd6e5ed",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=875112f8a4a7c22e349f0230c6bf5fd73331c3c54e542c3eaa896d3c21c868a3",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=05de18ee0111c91b4db21f46b6e99b20769ca0d69ec405ad6b48506dc23bbad6",
+ "gbrain_refuse_revived_withdrawn_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=7a383cc3e5c2742020f138aa962696f0e07d76f981295de0c38294a0c33f94ec",
+ "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4a3444d23904f780bb53285e3abc3ce1b079b27bf3faee2ef60b2915ad672146",
+ "gbrain_refuse_unguarded_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=84360ce2ecf76f1dc9aaa00f5e7518531387e4a4bd53285f9ea617b27172bae5",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702",
@@ -4309,6 +4311,8 @@
"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_preserve_withdrawal_insert": "CREATE TRIGGER facts_preserve_withdrawal_insert BEFORE INSERT ON public.facts FOR EACH ROW WHEN (((new.expired_at IS NULL) AND (COALESCE(current_setting('gbrain.fact_withdrawal_stamp_deferred'::text, true), ''::text) <> 'on'::text))) EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",
"facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged AFTER UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()",
+ "facts.facts_refuse_revived_withdrawal": "CREATE TRIGGER facts_refuse_revived_withdrawal AFTER UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW WHEN ((new.expired_at IS NULL)) EXECUTE FUNCTION gbrain_refuse_revived_withdrawn_fact()",
+ "facts.facts_refuse_unguarded_inserted": "CREATE TRIGGER facts_refuse_unguarded_inserted AFTER INSERT ON public.facts REFERENCING NEW TABLE AS inserted_facts FOR EACH STATEMENT EXECUTE FUNCTION gbrain_refuse_unguarded_inserted_facts()",
"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-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index 04f81d619d..2565d520d0 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -419,10 +419,10 @@
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4f2d679df92779f6941e2378b82d5a9d5fb5cb4fe8d571f4d69801e6f646bde6",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
- "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=3f11d09c3b95ae5a066c240caec9a7b068cf206b3ed350420e84cc379ab1cf8a",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=05de18ee0111c91b4db21f46b6e99b20769ca0d69ec405ad6b48506dc23bbad6",
+ "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4a3444d23904f780bb53285e3abc3ce1b079b27bf3faee2ef60b2915ad672146",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index addd05b8b9..a6a0d75487 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -419,10 +419,10 @@
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4f2d679df92779f6941e2378b82d5a9d5fb5cb4fe8d571f4d69801e6f646bde6",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
- "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=3f11d09c3b95ae5a066c240caec9a7b068cf206b3ed350420e84cc379ab1cf8a",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=05de18ee0111c91b4db21f46b6e99b20769ca0d69ec405ad6b48506dc23bbad6",
+ "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4a3444d23904f780bb53285e3abc3ce1b079b27bf3faee2ef60b2915ad672146",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index e201adb752..bb0d94abbb 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -419,10 +419,10 @@
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4f2d679df92779f6941e2378b82d5a9d5fb5cb4fe8d571f4d69801e6f646bde6",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
- "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=3f11d09c3b95ae5a066c240caec9a7b068cf206b3ed350420e84cc379ab1cf8a",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=05de18ee0111c91b4db21f46b6e99b20769ca0d69ec405ad6b48506dc23bbad6",
+ "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4a3444d23904f780bb53285e3abc3ce1b079b27bf3faee2ef60b2915ad672146",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 58f3842188..7bd7e010cc 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -428,10 +428,10 @@
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4f2d679df92779f6941e2378b82d5a9d5fb5cb4fe8d571f4d69801e6f646bde6",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
- "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=3f11d09c3b95ae5a066c240caec9a7b068cf206b3ed350420e84cc379ab1cf8a",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=05de18ee0111c91b4db21f46b6e99b20769ca0d69ec405ad6b48506dc23bbad6",
+ "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4a3444d23904f780bb53285e3abc3ce1b079b27bf3faee2ef60b2915ad672146",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 2ba03eafe7..eb1595e357 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -555,19 +555,21 @@
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4f2d679df92779f6941e2378b82d5a9d5fb5cb4fe8d571f4d69801e6f646bde6",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",
- "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
- "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=3f11d09c3b95ae5a066c240caec9a7b068cf206b3ed350420e84cc379ab1cf8a",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=08d7e84882d373c36a1db161eb9eed1da80ceb5d4373f65abc86f4e87e11a54f",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=9b08c031113955862b3bcd9f969c8ba721f7fe5c42aaa9992935fc4e7dd6e5ed",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=875112f8a4a7c22e349f0230c6bf5fd73331c3c54e542c3eaa896d3c21c868a3",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=05de18ee0111c91b4db21f46b6e99b20769ca0d69ec405ad6b48506dc23bbad6",
+ "gbrain_refuse_revived_withdrawn_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=7a383cc3e5c2742020f138aa962696f0e07d76f981295de0c38294a0c33f94ec",
+ "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4a3444d23904f780bb53285e3abc3ce1b079b27bf3faee2ef60b2915ad672146",
+ "gbrain_refuse_unguarded_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=84360ce2ecf76f1dc9aaa00f5e7518531387e4a4bd53285f9ea617b27172bae5",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702",
@@ -4305,6 +4307,8 @@
"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_preserve_withdrawal_insert": "CREATE TRIGGER facts_preserve_withdrawal_insert BEFORE INSERT ON public.facts FOR EACH ROW WHEN (((new.expired_at IS NULL) AND (COALESCE(current_setting('gbrain.fact_withdrawal_stamp_deferred'::text, true), ''::text) <> 'on'::text))) EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",
"facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged AFTER UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()",
+ "facts.facts_refuse_revived_withdrawal": "CREATE TRIGGER facts_refuse_revived_withdrawal AFTER UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW WHEN ((new.expired_at IS NULL)) EXECUTE FUNCTION gbrain_refuse_revived_withdrawn_fact()",
+ "facts.facts_refuse_unguarded_inserted": "CREATE TRIGGER facts_refuse_unguarded_inserted AFTER INSERT ON public.facts REFERENCING NEW TABLE AS inserted_facts FOR EACH STATEMENT EXECUTE FUNCTION gbrain_refuse_unguarded_inserted_facts()",
"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.json
index f1da570cc6..acdb8620d5 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -555,19 +555,21 @@
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4f2d679df92779f6941e2378b82d5a9d5fb5cb4fe8d571f4d69801e6f646bde6",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",
- "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
- "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=3f11d09c3b95ae5a066c240caec9a7b068cf206b3ed350420e84cc379ab1cf8a",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=08d7e84882d373c36a1db161eb9eed1da80ceb5d4373f65abc86f4e87e11a54f",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=9b08c031113955862b3bcd9f969c8ba721f7fe5c42aaa9992935fc4e7dd6e5ed",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=875112f8a4a7c22e349f0230c6bf5fd73331c3c54e542c3eaa896d3c21c868a3",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=05de18ee0111c91b4db21f46b6e99b20769ca0d69ec405ad6b48506dc23bbad6",
+ "gbrain_refuse_revived_withdrawn_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=7a383cc3e5c2742020f138aa962696f0e07d76f981295de0c38294a0c33f94ec",
+ "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4a3444d23904f780bb53285e3abc3ce1b079b27bf3faee2ef60b2915ad672146",
+ "gbrain_refuse_unguarded_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=84360ce2ecf76f1dc9aaa00f5e7518531387e4a4bd53285f9ea617b27172bae5",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702",
@@ -4305,6 +4307,8 @@
"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_preserve_withdrawal_insert": "CREATE TRIGGER facts_preserve_withdrawal_insert BEFORE INSERT ON public.facts FOR EACH ROW WHEN (((new.expired_at IS NULL) AND (COALESCE(current_setting('gbrain.fact_withdrawal_stamp_deferred'::text, true), ''::text) <> 'on'::text))) EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",
"facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged AFTER UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()",
+ "facts.facts_refuse_revived_withdrawal": "CREATE TRIGGER facts_refuse_revived_withdrawal AFTER UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW WHEN ((new.expired_at IS NULL)) EXECUTE FUNCTION gbrain_refuse_revived_withdrawn_fact()",
+ "facts.facts_refuse_unguarded_inserted": "CREATE TRIGGER facts_refuse_unguarded_inserted AFTER INSERT ON public.facts REFERENCING NEW TABLE AS inserted_facts FOR EACH STATEMENT EXECUTE FUNCTION gbrain_refuse_unguarded_inserted_facts()",
"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.json
index 0a534c8c5d..e0bea0aea2 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -555,19 +555,21 @@
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4f2d679df92779f6941e2378b82d5a9d5fb5cb4fe8d571f4d69801e6f646bde6",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",
- "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
- "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=3f11d09c3b95ae5a066c240caec9a7b068cf206b3ed350420e84cc379ab1cf8a",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=08d7e84882d373c36a1db161eb9eed1da80ceb5d4373f65abc86f4e87e11a54f",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=9b08c031113955862b3bcd9f969c8ba721f7fe5c42aaa9992935fc4e7dd6e5ed",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=875112f8a4a7c22e349f0230c6bf5fd73331c3c54e542c3eaa896d3c21c868a3",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=05de18ee0111c91b4db21f46b6e99b20769ca0d69ec405ad6b48506dc23bbad6",
+ "gbrain_refuse_revived_withdrawn_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=7a383cc3e5c2742020f138aa962696f0e07d76f981295de0c38294a0c33f94ec",
+ "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4a3444d23904f780bb53285e3abc3ce1b079b27bf3faee2ef60b2915ad672146",
+ "gbrain_refuse_unguarded_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=84360ce2ecf76f1dc9aaa00f5e7518531387e4a4bd53285f9ea617b27172bae5",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702",
@@ -4301,6 +4303,8 @@
"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_preserve_withdrawal_insert": "CREATE TRIGGER facts_preserve_withdrawal_insert BEFORE INSERT ON public.facts FOR EACH ROW WHEN (((new.expired_at IS NULL) AND (COALESCE(current_setting('gbrain.fact_withdrawal_stamp_deferred'::text, true), ''::text) <> 'on'::text))) EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",
"facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged AFTER UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()",
+ "facts.facts_refuse_revived_withdrawal": "CREATE TRIGGER facts_refuse_revived_withdrawal AFTER UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW WHEN ((new.expired_at IS NULL)) EXECUTE FUNCTION gbrain_refuse_revived_withdrawn_fact()",
+ "facts.facts_refuse_unguarded_inserted": "CREATE TRIGGER facts_refuse_unguarded_inserted AFTER INSERT ON public.facts REFERENCING NEW TABLE AS inserted_facts FOR EACH STATEMENT EXECUTE FUNCTION gbrain_refuse_unguarded_inserted_facts()",
"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/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 3fdbc2e4e6..fb7b53459d 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -8,7 +8,6 @@
100
],
"helpers": {
- "AFTER_ROW_PURGE_TRIGGERS": "d662c13baa69343f298168a7b23ab32622a04c23061abb6321c8dc0f74e3f39f",
"ALIAS_TABLES": "cddd37c636af42d862c08ca7754a57dfe9d12576b769fa8f74a5f02c803f67a0",
"BELIEF_FACTS_STREAM_INDEX": "9e4491eb9e0b94924a58deea3feff1b315ec0efd25a77a4e6515b362beffbc92",
"BOUNDED_TIMELINE_CHECKPOINT": "385c4da3e28732343148795d6e9a86670813a7a7cfa1e52f8a5bb494680a3c0d",
@@ -16,8 +15,12 @@
"CONTENT_CHUNKS_GENERATION_INDEX": "c434b3a4acdad499cf3b9f170d9f9967b8e3e8218c829db99f3ecba3b53c8b5d",
"CONTENT_CHUNKS_OCCURRENCE_GENERATION_INDEX": "b4f73db97ad878ef7256128ddef83fd11e2e08fd215e389d9e921a0daf04853d",
"CONTENT_CHUNKS_OCCURRENCE_INDEX": "7b692ba777b30399ab5a3b100eb40b3b9d1b3fb2322dc4dc808ba8a4d667912c",
- "DEFINER_GUARDS": "5f44654b4ac1202d60368f05ed7736bedcec5267673d42ee4b6b9fff8cff2106",
- "DERIVATION_STORED_GUARD_SQL": "df2f7a46d7c8a364c4e5ae208f4d8830b976b3f2aeca6f21667517bc9810b66d",
+ "DEFINER_FUNCTION_SQL": "ca03804c9a449a42b1d95474e29a43b31f0804b8c7b329bf4a163c7b7f71a39c",
+ "DEFINER_GUARDS": "03b33d9e251774efabb14c9f324264959587b8657e75ee65fd30432241918ce3",
+ "DEFINER_TRIGGERS": "d0408baa4ec464b104ed133b5916a39dfd22880bc5fcd0a324e3cd739c5fc668",
+ "DERIVATION_SCOPE_ENTRY_FUNCTION_SQL": "1477f86e1c50cd947716b84f6339f1d2899eeee86330957fc9b2fa581bd2d21e",
+ "DERIVATION_STORED_GUARD_FUNCTION_SQL": "62257732f75bf48f37268217a81e371441db5410779a392d665801c36040809a",
+ "DERIVATION_STORED_GUARD_TRIGGER_SQL": "ff55e347bb9cf69dbd540500909cf59a497ad0e6d3fcc40bb9c0e0e3fe8b3860",
"EXEMPT_RE": "e8b623114f4f77fc3abcfc479abec1442dbf41bc607e046d124b44572d59953c",
"FACTS_SUPERSEDED_BY_INDEX": "555c2b267989359a078de0f82cea830584bc0a268be6796bf526c0a9bed45905",
"FACT_PURGES_ALL_SUBJECTS_INDEX": "99e2eb6c24134b539cb4cfd6e5ff66a724463525d09e9ba1fdde3c13f5787b6c",
@@ -27,6 +30,8 @@
"FTS_CJK_BOUNDARY_REGEX": "e8605bc0f2c6f3ecd2b451cbc8a4fe27ae0974d048f0bea655533cf37e0ff88d",
"FTS_INPUT_FUNCTION_SQL": "d2f44fc1ef338ff7563c07659d938b743fedb20230948792c71068c022ec54c3",
"FUNCTION_SEARCH_PATH_HARDENING_SQL": "25ac6f1fedd5cf69582c79eceeaae58e5a7cf779e5cedbbfc4985b3702e37526",
+ "GUARD_FUNCTION_SQL": "f25f1638357f309c3c50524dc86f3564aa836d28efc86a3dd4d72eec1302ecc6",
+ "GUARD_TRIGGERS": "ec81fc215a2ab1864b95045a48266cdd8148cade94c169b52b0f464c587111fe",
"INGEST_LOG_MARKED_INDEX": "1099f19af7873878974239a9a6f1a627827221eebd75aea01896246e0809e91c",
"INGEST_LOG_UNMARKED_INDEX": "c94e6b009f830527d2f1d6af1683bee94189474e8e67aa4c60165ab4abbd8726",
"ISSUANCE_CLOCK_SLACK_SECONDS": "8f36c80392df6f9b9c754826289b63969d9d41ca8955213291e4413d614dce35",
@@ -51,7 +56,6 @@
"TABLES": "3fc77a0fccb525f9b791098f9eae27b19adaa3f5dadbabcff2a719137cbc3ef8",
"TOKEN_TTL_MAX_SECONDS": "f4a45bec6ec0bacc859dc57732ceb76cec7eb72f242b5a6c89d47190d0525ab4",
"TOKEN_TTL_MIN_SECONDS": "441d8ce6bd21f753de90abd3013eaa9992a469ea60c590f1005533618199aa25",
- "TRIGGERS": "ce913384dc4209f35654ecb53e29d5a7bdefeba8a4a824e0ad49ce9dae7c6ef4",
"analyzeAfterIndexBuild": "8d627df6b496e1c197a244f8519aeaf3aebcd23e3f7cf514576d453a4270e33a",
"analyzeDeferred": "e627ca5e77ce0b79cf5eae7c749a0c9275f04bc186704e3f3a6e05121bb78442",
"analyzeYieldingToVacuum": "edba1beff1547ea5c2e9f902efe44ab24e8d7016b2253603dcbba92d4137ca9a",
@@ -62,13 +66,12 @@
"checkpointKey": "337ef776b18f428542093e27c4d570249d6a5856e5a17e4499d26a22877af34b",
"chunkSearchVectorTriggerFnSql": "93ed4e29aa058949621b4198fe1ec317218f4b9ec0db0626ec6dc7001032047d",
"clampOAuthTokenTtls": "b1e94ea8f5b3c3870a56b0f6d00d0a274c2e9dcad912b828848aec250732645f",
- "definerGuardSql": "157ff36d1f4ca06c91d642b92b2bba89e2cebc8a6ba19235545d25ed34920668",
"dropInvalidConcurrentIndex": "6864d844b7dfb2fbecdd0fb9c73e06248473376feb794b3fe58f036c70d2d44c",
"enableRlsSql": "b7901b3d5231fcfacd3260ce0f59d4701d8c0bee902808ff48b1d8affbd444b6",
"ensureFactsFtsIndex": "95e723314ac30cea2db48e0e167c554ef1fa06df80cae765faa2a080a3a655c2",
"getFtsLanguage": "0d790b4c4af1f67a2a1bbd59470beb13f434917b381931baf8404a41c5d903db",
"grantFromRow": "2d0603bb0f964d7e45e04aa76bac54cd4f6f63c91a8d9f028b60b4792bc1695e",
- "hardenGuards": "40fecc92694e291f65a78492e33e6647c49d1a9222167739c7d8e27a1c7adfde",
+ "hardenGuards": "80ee96125eb9075a4145e62ef2bea49f9b95c6e9a47a081918c4acc28ad9d9ba",
"hnswMaxDimsForType": "a187cdcc520f813b7c39da97ce53da58509232ed9f851627ef41abfe1b68bd26",
"inShortTransaction": "366c67944d8aeb6b71450da05259a0fa5005fa8f6ec6091671f3c78a682db216",
"isLockTimeoutError": "52a3720e1ffb74ce381cc3269f78130c38a89c807e308283ec3d557bae2b89b1",
@@ -4407,8 +4410,8 @@
"idempotent": true,
"name": "segment_derivations",
"sql": {
- "length": 9373,
- "sha256": "cae7c94cd835c6cc15c027d7f85ac41b0f9b01c143d8e7d273f2229b0db10aa6"
+ "length": 9439,
+ "sha256": "1213f5e694ad49ea2847bcfef9e540cc6874d880b9d3507aff94a8667d9d354a"
},
"sqlFor": "absent",
"transaction": false,
@@ -4459,13 +4462,16 @@
"handler": {
"form": "arrow",
"helpers": [
- "AFTER_ROW_PURGE_TRIGGERS",
+ "DEFINER_FUNCTION_SQL",
"DEFINER_GUARDS",
- "DERIVATION_STORED_GUARD_SQL",
+ "DEFINER_TRIGGERS",
+ "DERIVATION_SCOPE_ENTRY_FUNCTION_SQL",
+ "DERIVATION_STORED_GUARD_FUNCTION_SQL",
+ "DERIVATION_STORED_GUARD_TRIGGER_SQL",
"FUNCTION_SEARCH_PATH_HARDENING_SQL",
+ "GUARD_FUNCTION_SQL",
+ "GUARD_TRIGGERS",
"LEGACY_SEARCH_PATH_SETTINGS",
- "TRIGGERS",
- "definerGuardSql",
"hardenGuards",
"inShortTransaction",
"isLockTimeoutError",
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 407e113253..52123d3c82 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -552,19 +552,21 @@
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b794bdc82a9818e1b53738ee7476788cfc05929dd7fcde8b3d07d9a3e221fe59",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4f2d679df92779f6941e2378b82d5a9d5fb5cb4fe8d571f4d69801e6f646bde6",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",
- "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
- "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, public, pg_temp] body_sha256=3f11d09c3b95ae5a066c240caec9a7b068cf206b3ed350420e84cc379ab1cf8a",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=08d7e84882d373c36a1db161eb9eed1da80ceb5d4373f65abc86f4e87e11a54f",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=9b08c031113955862b3bcd9f969c8ba721f7fe5c42aaa9992935fc4e7dd6e5ed",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=875112f8a4a7c22e349f0230c6bf5fd73331c3c54e542c3eaa896d3c21c868a3",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=05de18ee0111c91b4db21f46b6e99b20769ca0d69ec405ad6b48506dc23bbad6",
+ "gbrain_refuse_revived_withdrawn_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=7a383cc3e5c2742020f138aa962696f0e07d76f981295de0c38294a0c33f94ec",
+ "gbrain_refuse_stored_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=4a3444d23904f780bb53285e3abc3ce1b079b27bf3faee2ef60b2915ad672146",
+ "gbrain_refuse_unguarded_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=true config=[search_path=pg_catalog, pg_temp] body_sha256=84360ce2ecf76f1dc9aaa00f5e7518531387e4a4bd53285f9ea617b27172bae5",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702",
@@ -4313,6 +4315,8 @@
"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_preserve_withdrawal_insert": "CREATE TRIGGER facts_preserve_withdrawal_insert BEFORE INSERT ON public.facts FOR EACH ROW WHEN (((new.expired_at IS NULL) AND (COALESCE(current_setting('gbrain.fact_withdrawal_stamp_deferred'::text, true), ''::text) <> 'on'::text))) EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",
"facts.facts_refuse_purged": "CREATE TRIGGER facts_refuse_purged AFTER UPDATE OF fact, source_id, visibility, entity_slug ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()",
+ "facts.facts_refuse_revived_withdrawal": "CREATE TRIGGER facts_refuse_revived_withdrawal AFTER UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW WHEN ((new.expired_at IS NULL)) EXECUTE FUNCTION gbrain_refuse_revived_withdrawn_fact()",
+ "facts.facts_refuse_unguarded_inserted": "CREATE TRIGGER facts_refuse_unguarded_inserted AFTER INSERT ON public.facts REFERENCING NEW TABLE AS inserted_facts FOR EACH STATEMENT EXECUTE FUNCTION gbrain_refuse_unguarded_inserted_facts()",
"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()",