Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Purge and withdrawal guards refuse a write role that can't read their ledgers (#7632) (#9517)

Garry Tan5eafe8f355db
diff --git a/behavior-changes.d/guard_ledgers_fail_closed_7632.md b/behavior-changes.d/guard_ledgers_fail_closed_7632.md
new file mode 100644
index 0000000000..8c757012f1
--- /dev/null
+++ b/behavior-changes.d/guard_ledgers_fail_closed_7632.md
@@ -0,0 +1,4 @@
+---
+kind: fix
+---
+On Postgres, a database write role that neither owns gbrain's purge and withdrawal ledgers (`fact_purges`, `fact_withdrawals`, `take_purges`, `page_purges`, `page_segment_derivation_purges`, `page_segment_derivation_purge_pages`) nor bypasses row-level security, and holds no policy that lets it read one, now gets a refusal on the writes that ledger's guard checks, where before the guard read the ledger as empty and let the write through: a purged claim, take, page or derivation could be stored again and a withdrawn fact saved active. The refusal is `writer_coordinator_required: writer state is unreadable to this database role` (P0001, `unreadable_state`); its hint names the table and the policy to add, and docs/ENGINES.md ("Purge and withdrawal guards") lists the policies a scoped write role needs. The guards stay SECURITY INVOKER: no trigger runs with different rights. The owner, a role that bypasses RLS, a ledger without row-level security and PGLite are unaffected. Where the role running migrations does not own a guard function, the upgrade leaves that function, names it on stderr and finishes; the next migration run by a role that owns it fixes it (#7632, #7659).
diff --git a/changelog.d/fix-guard-ledgers-fail-closed-7632.md b/changelog.d/fix-guard-ledgers-fail-closed-7632.md
new file mode 100644
index 0000000000..85efa046cd
--- /dev/null
+++ b/changelog.d/fix-guard-ledgers-fail-closed-7632.md
@@ -0,0 +1,10 @@
+---
+important: security
+---
+**A restricted Postgres write role can no longer save purged or withdrawn content again by lacking a read policy on the purge and withdrawal ledgers: the guard now refuses the write with a message naming the policy to add.**
+
+<!-- behavior-change: guard_ledgers_fail_closed_7632 -->
+
+### Fixed
+- The seven purge and withdrawal guard triggers (facts, takes, pages, segment derivations and the derivation sweep's scope note) read their ledgers as the writing role. A role with write policies on the guarded table but no policy on the ledger read it as empty, so a purged claim, take, page or derivation could be stored again while the purge reported done, and a withdrawn fact could be saved or set active again. Each guard now refuses such a role with `writer_coordinator_required` (`unreadable_state`), the same refusal the writer fences and derived-state maintainers use, and its hint names the table and the docs/ENGINES.md recipe. The guards keep running with the writer's own rights (no SECURITY DEFINER). Migration v318 applies it to existing brains. Owners, roles that bypass row-level security and PGLite see no change. (#7632, #7659)
+- After upgrading on Postgres, check the guards. v318 can only replace a guard function the migrating role owns. One owned by another role stays fail-open, and v318 names it in a single stderr line starting `guards:`. docs/ENGINES.md ("Purge and withdrawal guards") has a query that lists the seven guards and whether each now fails closed. For any that doesn't, its owner runs `ALTER FUNCTION public.<name>() OWNER TO <the role gbrain migrates as>`, then `gbrain apply-migrations --yes` (or the next gbrain start) replaces it.
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 6ec181d5e4..d9885e9b6b 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -438,15 +438,77 @@ 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`).
+<a id="purge-and-withdrawal-guards"></a>
**Purge and withdrawal guards.** The guards that refuse purged content and keep withdrawn
facts withdrawn run as the writing role (`SECURITY INVOKER`) and read their ledgers
(`fact_purges`, `fact_withdrawals`, `take_purges`, `page_purges` and the derivation purge
-tables) under that role's RLS. Every gbrain function that pins a search_path ends it with
+tables) under that role's RLS. Since migration v318 (#7632, #7659) they fail closed: when
+RLS applies to the writing role on a ledger and no permissive policy of the role covers it,
+the guard refuses the write with `writer_coordinator_required: writer state is unreadable to
+this database role` (P0001, relationship `unreadable_state`), whose `HINT` names the table
+and the policy to add, instead of reading the ledger as empty and letting a purged claim,
+take, page or derivation, or a withdrawn fact, through. The refused writes are fact inserts
+and claim updates, fact re-activations, take writes, page content writes, segment derivation
+writes, and page soft-deletes or segment retirements while the derivation purge tables are
+unreadable. The owner (without `FORCE ROW LEVEL SECURITY`), a role that bypasses RLS, a
+ledger without RLS and PGLite are not affected. A scoped write role needs these policies, on
+top of the maintainer recipe below for `pages` and `sources`; they let it read only the
+ledger rows of the sources it writes and change none:
+
+<!-- gbrain:ledger-rls-recipe:begin (applied verbatim by test/guard-ledgers-fail-closed-7632.test.ts) -->
+```sql
+-- The ledgers of the writer's own sources, with the pages_scope_filter predicate.
+CREATE POLICY fact_purges_writer_scope ON fact_purges FOR SELECT TO <writer-role>
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+CREATE POLICY fact_withdrawals_writer_scope ON fact_withdrawals FOR SELECT TO <writer-role>
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+CREATE POLICY take_purges_writer_scope ON take_purges FOR SELECT TO <writer-role>
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+CREATE POLICY page_purges_writer_scope ON page_purges FOR SELECT TO <writer-role>
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+CREATE POLICY page_segment_derivation_purges_writer_scope ON page_segment_derivation_purges FOR SELECT TO <writer-role>
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+-- The note a page leaving a running derivation sweep's scope leaves for that sweep.
+CREATE POLICY page_segment_derivation_purge_pages_writer_note ON page_segment_derivation_purge_pages FOR INSERT TO <writer-role>
+ WITH CHECK (EXISTS (SELECT 1 FROM page_segment_derivation_purges r
+ WHERE r.request_id = page_segment_derivation_purge_pages.request_id));
+```
+<!-- gbrain:ledger-rls-recipe:end -->
+
+**Check that the upgrade replaced every guard.** Migration v318 can only replace a guard function
+the role running it owns. A guard owned by another role is left as it was, so it still lets a
+scoped writer without ledger policies through, and v318 only names it in one stderr line
+(`guards: N purge or withdrawal guard(s) still read their ledgers as empty ...`). After upgrading,
+run this as any role that can read the catalog. Every one of the seven rows must show
+`fails_closed = t`:
+
+```sql
+SELECT p.proname, pg_get_userbyid(p.proowner) AS owner,
+ strpos(p.prosrc, 'row_security_active(') > 0 AS fails_closed
+FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
+WHERE n.nspname = 'public' AND p.proname IN ('gbrain_guard_inserted_facts',
+ 'gbrain_preserve_fact_withdrawal', 'gbrain_refuse_purged_fact', 'gbrain_refuse_purged_take',
+ 'gbrain_refuse_purged_page', 'gbrain_refuse_purging_derivation', 'gbrain_mark_derivation_scope_entry')
+ORDER BY 1;
+```
+
+For a row with `fails_closed = f`, connect as the role in its `owner` column and run
+`ALTER FUNCTION public.<proname>() OWNER TO <the role gbrain migrates as>;`. Then run
+`gbrain apply-migrations --yes`, or start gbrain: every migration run re-creates a guard that
+is missing its check, provided the migrating role owns it. You can also run gbrain once as the
+owning role instead. Run the query again to confirm.
+
+The segmented storage recipe above already covers the two derivation purge tables for a
+role it applies to. A policy that filters out ledger rows of a source the role writes hides
+them from the guard, as before. Every gbrain function that pins a search_path ends it with
`pg_temp` (migration v277, #7632), so a session's temp table or view named like a ledger
cannot hide it from a guard; before, any session, the owner included, could store purged
-content that way. A write role with no policy on a ledger still reads it empty, so its
-purged or withdrawn writes still go through: give a scoped write role a `SELECT` policy on
-the ledgers of the sources it writes (gbrain#7659 tracks the fix). Each definition outside
+content that way. Each definition outside
`src/core/schema-migrations/` pins `pg_catalog, public, pg_temp` itself (`bun run check:search-path`
fails one that does not, or a pinned function missing from `PINNED_FUNCTION_NAMES`), so a schema
replay keeps it; historical migration bodies still pin the old path, so every migration run ends by
diff --git a/docs/guides/rls-and-you.md b/docs/guides/rls-and-you.md
index 3a546f87d1..dc4fbb766c 100644
--- a/docs/guides/rls-and-you.md
+++ b/docs/guides/rls-and-you.md
@@ -269,10 +269,11 @@ could shadow a purge or withdrawal ledger a guard reads with an empty temporary
the same name and store purged content again. On an older brain, migration v277 appends
`pg_temp` to every gbrain function it owns with `ALTER FUNCTION` (no body changes), and
`gbrain doctor` (`function_search_path`) names any function it could not change, with the
-`ALTER FUNCTION` to run as its owner. This does not close the scoped-writer gap: on
-Postgres, a write role with no RLS policy on a ledger still reads it empty, so its purged
-or withdrawn writes still go through (gbrain#7659 tracks the fix; [docs/ENGINES.md](../ENGINES.md)
-("Purge and withdrawal guards") has the policy to add meanwhile). The three fact-fingerprint functions
+`ALTER FUNCTION` to run as its owner. Since migration v318 (gbrain#7632, gbrain#7659) a
+write role that RLS keeps from reading a ledger is refused with `writer_coordinator_required`
+(`unreadable_state`) on the writes that guard checks, instead of reading the ledger as empty
+and letting purged or withdrawn content through; [docs/ENGINES.md](../ENGINES.md#purge-and-withdrawal-guards)
+has the policies a scoped write role needs. The three fact-fingerprint functions
(`gbrain_fact_fingerprint`, `gbrain_fact_fingerprint_v1`,
`gbrain_fact_normalize`) are SQL functions that an index expression uses, so
they call `pg_catalog.`-qualified built-ins instead of pinning a setting (a
diff --git a/llms-full.txt b/llms-full.txt
index 26309a23c4..1f50816f92 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5395,15 +5395,77 @@ 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`).
+<a id="purge-and-withdrawal-guards"></a>
**Purge and withdrawal guards.** The guards that refuse purged content and keep withdrawn
facts withdrawn run as the writing role (`SECURITY INVOKER`) and read their ledgers
(`fact_purges`, `fact_withdrawals`, `take_purges`, `page_purges` and the derivation purge
-tables) under that role's RLS. Every gbrain function that pins a search_path ends it with
+tables) under that role's RLS. Since migration v318 (#7632, #7659) they fail closed: when
+RLS applies to the writing role on a ledger and no permissive policy of the role covers it,
+the guard refuses the write with `writer_coordinator_required: writer state is unreadable to
+this database role` (P0001, relationship `unreadable_state`), whose `HINT` names the table
+and the policy to add, instead of reading the ledger as empty and letting a purged claim,
+take, page or derivation, or a withdrawn fact, through. The refused writes are fact inserts
+and claim updates, fact re-activations, take writes, page content writes, segment derivation
+writes, and page soft-deletes or segment retirements while the derivation purge tables are
+unreadable. The owner (without `FORCE ROW LEVEL SECURITY`), a role that bypasses RLS, a
+ledger without RLS and PGLite are not affected. A scoped write role needs these policies, on
+top of the maintainer recipe below for `pages` and `sources`; they let it read only the
+ledger rows of the sources it writes and change none:
+
+<!-- gbrain:ledger-rls-recipe:begin (applied verbatim by test/guard-ledgers-fail-closed-7632.test.ts) -->
+```sql
+-- The ledgers of the writer's own sources, with the pages_scope_filter predicate.
+CREATE POLICY fact_purges_writer_scope ON fact_purges FOR SELECT TO <writer-role>
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+CREATE POLICY fact_withdrawals_writer_scope ON fact_withdrawals FOR SELECT TO <writer-role>
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+CREATE POLICY take_purges_writer_scope ON take_purges FOR SELECT TO <writer-role>
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+CREATE POLICY page_purges_writer_scope ON page_purges FOR SELECT TO <writer-role>
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+CREATE POLICY page_segment_derivation_purges_writer_scope ON page_segment_derivation_purges FOR SELECT TO <writer-role>
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+-- The note a page leaving a running derivation sweep's scope leaves for that sweep.
+CREATE POLICY page_segment_derivation_purge_pages_writer_note ON page_segment_derivation_purge_pages FOR INSERT TO <writer-role>
+ WITH CHECK (EXISTS (SELECT 1 FROM page_segment_derivation_purges r
+ WHERE r.request_id = page_segment_derivation_purge_pages.request_id));
+```
+<!-- gbrain:ledger-rls-recipe:end -->
+
+**Check that the upgrade replaced every guard.** Migration v318 can only replace a guard function
+the role running it owns. A guard owned by another role is left as it was, so it still lets a
+scoped writer without ledger policies through, and v318 only names it in one stderr line
+(`guards: N purge or withdrawal guard(s) still read their ledgers as empty ...`). After upgrading,
+run this as any role that can read the catalog. Every one of the seven rows must show
+`fails_closed = t`:
+
+```sql
+SELECT p.proname, pg_get_userbyid(p.proowner) AS owner,
+ strpos(p.prosrc, 'row_security_active(') > 0 AS fails_closed
+FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
+WHERE n.nspname = 'public' AND p.proname IN ('gbrain_guard_inserted_facts',
+ 'gbrain_preserve_fact_withdrawal', 'gbrain_refuse_purged_fact', 'gbrain_refuse_purged_take',
+ 'gbrain_refuse_purged_page', 'gbrain_refuse_purging_derivation', 'gbrain_mark_derivation_scope_entry')
+ORDER BY 1;
+```
+
+For a row with `fails_closed = f`, connect as the role in its `owner` column and run
+`ALTER FUNCTION public.<proname>() OWNER TO <the role gbrain migrates as>;`. Then run
+`gbrain apply-migrations --yes`, or start gbrain: every migration run re-creates a guard that
+is missing its check, provided the migrating role owns it. You can also run gbrain once as the
+owning role instead. Run the query again to confirm.
+
+The segmented storage recipe above already covers the two derivation purge tables for a
+role it applies to. A policy that filters out ledger rows of a source the role writes hides
+them from the guard, as before. Every gbrain function that pins a search_path ends it with
`pg_temp` (migration v277, #7632), so a session's temp table or view named like a ledger
cannot hide it from a guard; before, any session, the owner included, could store purged
-content that way. A write role with no policy on a ledger still reads it empty, so its
-purged or withdrawn writes still go through: give a scoped write role a `SELECT` policy on
-the ledgers of the sources it writes (gbrain#7659 tracks the fix). Each definition outside
+content that way. Each definition outside
`src/core/schema-migrations/` pins `pg_catalog, public, pg_temp` itself (`bun run check:search-path`
fails one that does not, or a pinned function missing from `PINNED_FUNCTION_NAMES`), so a schema
replay keeps it; historical migration bodies still pin the old path, so every migration run ends by
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index f4884d2882..0cd5deb7dc 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -209,6 +209,7 @@ test/get-page-federated-scope.test.ts #2555 get_chunks federated scope 5 source-
test/get-page-federated-scope.test.ts #4275 alias hop scope: archived sources, include_deleted, fuzzy precedence, grant precedence 5 source-surface-helper
test/git-env-guard.test.ts (file-level) 5 readFileSync
test/grant-execution-prerequisites.test.ts execution prerequisite table 1 readFileSync
+test/guard-ledgers-fail-closed-7632.test.ts owner behaviour is unchanged 10 readFileSync
test/guest-derived-registry.test.ts guest derived-producer registry 2 readFileSync
test/guest-derived-registry.test.ts guest pages feed no derived rows (pglite, repo-less) 4 readFileSync
test/harness-onboarding.test.ts harness identity and private handoff 6 readFileSync
diff --git a/src/core/derived-state-maintainers.ts b/src/core/derived-state-maintainers.ts
index 475828ae0f..e159eefbf7 100644
--- a/src/core/derived-state-maintainers.ts
+++ b/src/core/derived-state-maintainers.ts
@@ -18,8 +18,11 @@
export type PolicyCommand = 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE';
const POLICY_COMMAND: Record<PolicyCommand, string> = { SELECT: 'r', INSERT: 'a', UPDATE: 'w', DELETE: 'd' };
-/** PL/pgSQL for a trigger body: refuse unless the caller may run every one of `commands` on `table`. `pad` indents lines after the first. */
-export function requireMaintainerPoliciesSql(table: string, commands: readonly PolicyCommand[], pad = ' '): string {
+/**
+ * PL/pgSQL for a trigger body: refuse unless the caller may run every one of `commands` on `table`. `pad` indents lines after
+ * the first; `hint`, a constant without quotes, becomes the refusal's HINT.
+ */
+export function requireMaintainerPoliciesSql(table: string, commands: readonly PolicyCommand[], pad = ' ', hint?: string): string {
return [
`IF pg_catalog.row_security_active('${table}') THEN`,
` IF EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY[${commands.map(c => `'${POLICY_COMMAND[c]}'`).join(',')}]) AS needed(cmd) WHERE NOT EXISTS (`,
@@ -27,12 +30,22 @@ export function requireMaintainerPoliciesSql(table: string, commands: readonly P
` AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END))) THEN`,
` RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: writer state is unreadable to this database role',`,
` TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:unreadable_state',`,
- ` DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','${table}')::text;`,
+ ` DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','${table}')::text${hint ? `,\n${pad} HINT='${hint}'` : ''};`,
' END IF;',
'END IF;',
].join(`\n${pad}`);
}
+/**
+ * #7632/#7659: the purge and withdrawal guards read their ledgers as the writing role, which read a ledger it holds no
+ * policy on as empty and let a purged claim, take, page or derivation, or a withdrawn fact, through. Each guard checks
+ * first, as the maintainers do; the refusal's HINT names the table, the policy the role needs and the recipe.
+ */
+export function requireLedgerPoliciesSql(table: string, commands: readonly PolicyCommand[], pad = ' '): string {
+ return requireMaintainerPoliciesSql(table, commands, pad, `Give this database role a policy on ${table} allowing ${commands.join(' and ')}`
+ + ' on the rows of the sources it writes (docs/ENGINES.md#purge-and-withdrawal-guards), or connect as the table owner.');
+}
+
/**
* page_retrievals has no foreign key (v224): this statement trigger removes the rows of hard-deleted pages. A schema
* blob fragment, so every boot's replay keeps this body.
diff --git a/src/core/facts/insert-guard-schema.ts b/src/core/facts/insert-guard-schema.ts
index 41160d827d..03a6bd953a 100644
--- a/src/core/facts/insert-guard-schema.ts
+++ b/src/core/facts/insert-guard-schema.ts
@@ -41,7 +41,12 @@
* only the insert half moves here. A statement trigger sees only the rows the
* statement wrote: a row ON CONFLICT DO NOTHING skipped is not checked (it is
* not saved either). Installed by migration v264.
+ *
+ * #7632/#7659: a writing role that RLS keeps from reading a ledger, or from updating the rows it inserted when a
+ * withdrawal matches, is refused (derived-state-maintainers.ts requireLedgerPoliciesSql) instead of reading the ledger as
+ * empty.
*/
+import { requireLedgerPoliciesSql } from '../derived-state-maintainers.ts';
import { FACT_WITHDRAWAL_STAMP_SETTING } from '../persistence/attribution-schema.ts';
export const FACT_INSERT_GUARD_TRIGGER = 'facts_guard_inserted';
@@ -55,6 +60,18 @@ export const FACT_INSERT_GUARD_FUNCTION = 'gbrain_guard_inserted_facts';
*/
export const GUARD_OUTCOME_MARKER_SQL = "(i.source IN ('cli:extract-conversation-facts:terminal:v2','cli:extract-conversation-facts:non-extractable:v2','cli:extract-conversation-facts:terminal') AND i.fact IN ('EXTRACTION_COMPLETE','EXTRACTION_NOT_APPLICABLE'))";
+/** The WITH clause naming, as m, the active inserted facts a withdrawal matches and its earliest withdrawn_at. */
+const WITHDRAWN_INSERTS_SQL = `WITH n AS MATERIALIZED (
+ SELECT i.id, i.source_id, i.visibility, i.entity_slug, i.source_markdown_slug,
+ gbrain_fact_fingerprint(i.fact) AS fact_hash, gbrain_fact_fingerprint_v1(i.fact) AS fact_hash_v1
+ FROM inserted_facts i WHERE i.expired_at IS NULL),
+ m AS (
+ SELECT n.id, min(w.withdrawn_at) AS withdrawn_at FROM n JOIN fact_withdrawals w
+ ON w.source_id = n.source_id AND w.visibility = n.visibility
+ AND w.subject = ANY(CASE WHEN starts_with(COALESCE(n.source_markdown_slug, ''), 'memory/members/') THEN ARRAY[n.source_markdown_slug]
+ ELSE ARRAY['*', n.entity_slug] END) AND w.fact_hash IN (n.fact_hash, n.fact_hash_v1)
+ GROUP BY n.id)`;
+
/**
* The guard function alone (#7778 re-creates it without touching the triggers). The purge refusal skips an extraction
* outcome row (facts/audit-sources.ts `isOutcomeMarker`): that bookkeeping marker is not a claim, and a subject-'*'
@@ -65,6 +82,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_inserted_facts() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
DECLARE purged TEXT; stamp_setting TEXT;
BEGIN
+ ${requireLedgerPoliciesSql('fact_purges', ['SELECT'], ' ')}
PERFORM s.id FROM sources s WHERE s.id IN (SELECT i.source_id FROM inserted_facts i) ORDER BY s.id FOR SHARE OF s;
IF EXISTS (SELECT 1 FROM fact_purges p WHERE p.source_id IN (SELECT i.source_id FROM inserted_facts i)) THEN
WITH n AS MATERIALIZED (
@@ -80,19 +98,16 @@ CREATE OR REPLACE FUNCTION gbrain_guard_inserted_facts() RETURNS trigger
DETAIL = json_build_object('table', 'facts', 'hash8', left(purged, 8))::text;
END IF;
END IF;
+ IF EXISTS (SELECT 1 FROM inserted_facts i WHERE i.expired_at IS NULL) THEN
+ ${requireLedgerPoliciesSql('fact_withdrawals', ['SELECT'], ' ')}
+ END IF;
IF EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id IN (SELECT i.source_id FROM inserted_facts i WHERE i.expired_at IS NULL)) THEN
+ IF EXISTS (${WITHDRAWN_INSERTS_SQL} SELECT 1 FROM m) THEN
+ ${requireLedgerPoliciesSql('facts', ['SELECT', 'UPDATE'], ' ')}
+ END IF;
stamp_setting := current_setting('${FACT_WITHDRAWAL_STAMP_SETTING}', true);
PERFORM set_config('${FACT_WITHDRAWAL_STAMP_SETTING}', 'on', true);
- WITH n AS MATERIALIZED (
- SELECT i.id, i.source_id, i.visibility, i.entity_slug, i.source_markdown_slug,
- gbrain_fact_fingerprint(i.fact) AS fact_hash, gbrain_fact_fingerprint_v1(i.fact) AS fact_hash_v1
- FROM inserted_facts i WHERE i.expired_at IS NULL),
- m AS (
- SELECT n.id, min(w.withdrawn_at) AS withdrawn_at FROM n JOIN fact_withdrawals w
- ON w.source_id = n.source_id AND w.visibility = n.visibility
- AND w.subject = ANY(CASE WHEN starts_with(COALESCE(n.source_markdown_slug, ''), 'memory/members/') THEN ARRAY[n.source_markdown_slug]
- ELSE ARRAY['*', n.entity_slug] END) AND w.fact_hash IN (n.fact_hash, n.fact_hash_v1)
- GROUP BY n.id)
+ ${WITHDRAWN_INSERTS_SQL}
UPDATE facts f SET expired_at = m.withdrawn_at, valid_until = LEAST(COALESCE(f.valid_until, m.withdrawn_at), m.withdrawn_at)
FROM m WHERE f.id = m.id;
PERFORM set_config('${FACT_WITHDRAWAL_STAMP_SETTING}', COALESCE(stamp_setting, ''), true);
diff --git a/src/core/facts/purge-schema.ts b/src/core/facts/purge-schema.ts
index 56b4f7c367..856b386f9a 100644
--- a/src/core/facts/purge-schema.ts
+++ b/src/core/facts/purge-schema.ts
@@ -24,6 +24,8 @@
* purged to someone who already knows it, never what it said.
*/
+import { requireLedgerPoliciesSql } from '../derived-state-maintainers.ts';
+
const RLS = (table: string) => `DO $rls$ BEGIN
IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;
@@ -113,10 +115,16 @@ ${FACT_PURGES_SUBJECT_INDEX.sql};
${FACT_PURGES_ALL_SUBJECTS_INDEX.sql};
`;
-export const MEMORY_PURGE_GUARD_SQL = `
-CREATE OR REPLACE FUNCTION gbrain_refuse_purged_fact() RETURNS trigger
+/**
+ * The three resurrection guards. Each refuses with writer_coordinator_required (unreadable_state) when row-level
+ * security applies to the writing role on a table it reads and no permissive policy of the role covers it, so an empty
+ * read under RLS never counts as "not purged" (#7632/#7659, derived-state-maintainers.ts). Migration v318 re-creates
+ * the functions alone.
+ */
+export const REFUSE_PURGED_FACT_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_refuse_purged_fact() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
BEGIN
+ ${requireLedgerPoliciesSql('fact_purges', ['SELECT'], ' ')}
PERFORM id FROM sources WHERE id = NEW.source_id FOR SHARE;
IF EXISTS (SELECT 1 FROM fact_purges
WHERE source_id = NEW.source_id AND visibility = NEW.visibility
@@ -128,14 +136,13 @@ CREATE OR REPLACE FUNCTION gbrain_refuse_purged_fact() RETURNS trigger
END IF;
RETURN NEW;
END
- $fn$;
-DROP TRIGGER IF EXISTS facts_refuse_purged ON facts;
-CREATE TRIGGER facts_refuse_purged BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug ON facts
- FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact();
-CREATE OR REPLACE FUNCTION gbrain_refuse_purged_take() RETURNS trigger
+ $fn$`;
+export const REFUSE_PURGED_TAKE_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_refuse_purged_take() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
DECLARE src TEXT; subj TEXT;
BEGIN
+ ${requireLedgerPoliciesSql('pages', ['SELECT'], ' ')}
+ ${requireLedgerPoliciesSql('take_purges', ['SELECT'], ' ')}
SELECT p.source_id, p.slug INTO src, subj FROM pages p WHERE p.id = NEW.page_id;
IF src IS NOT NULL AND EXISTS (SELECT 1 FROM take_purges
WHERE source_id = src AND (subject = '*' OR subject = subj)
@@ -146,24 +153,34 @@ CREATE OR REPLACE FUNCTION gbrain_refuse_purged_take() RETURNS trigger
END IF;
RETURN NEW;
END
- $fn$;
-DROP TRIGGER IF EXISTS 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();
-CREATE OR REPLACE FUNCTION gbrain_refuse_purged_page() RETURNS trigger
+ $fn$`;
+export const REFUSE_PURGED_PAGE_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_refuse_purged_page() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp 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 page_purges WHERE source_id = NEW.source_id AND 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', 'pages', 'hash8', left(NEW.content_hash, 8))::text;
+ AND (TG_OP = 'INSERT' OR NEW.content_hash IS DISTINCT FROM OLD.content_hash OR NEW.source_id IS DISTINCT FROM OLD.source_id) THEN
+ ${requireLedgerPoliciesSql('page_purges', ['SELECT'], ' ')}
+ IF EXISTS (SELECT 1 FROM page_purges WHERE source_id = NEW.source_id AND 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', 'pages', 'hash8', left(NEW.content_hash, 8))::text;
+ END IF;
END IF;
RETURN NEW;
END
- $fn$;
+ $fn$`;
+
+export const MEMORY_PURGE_GUARD_SQL = `
+${REFUSE_PURGED_FACT_FUNCTION_SQL};
+DROP TRIGGER IF EXISTS facts_refuse_purged ON facts;
+CREATE TRIGGER facts_refuse_purged BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug ON facts
+ FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact();
+${REFUSE_PURGED_TAKE_FUNCTION_SQL};
+DROP TRIGGER IF EXISTS 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();
+${REFUSE_PURGED_PAGE_FUNCTION_SQL};
DROP TRIGGER IF EXISTS 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();
diff --git a/src/core/facts/withdrawal-schema.ts b/src/core/facts/withdrawal-schema.ts
index 164f4669fe..5baaf04552 100644
--- a/src/core/facts/withdrawal-schema.ts
+++ b/src/core/facts/withdrawal-schema.ts
@@ -1,3 +1,5 @@
+import { requireLedgerPoliciesSql } from '../derived-state-maintainers.ts';
+
/**
* Characters folded to a space before hashing, so punctuation variants of one
* claim share a fingerprint. Explicit (not [[:punct:]]) so the SQL and the JS
@@ -51,13 +53,16 @@ export const FACT_FINGERPRINT_FUNCTION_STATEMENTS = [
* The insert and update guard that stamps a row matching a withdrawal as withdrawn. GST-2346: a row on a member page
* (memory/members/<id>) matches only that page's own withdrawals: it is its member's own, a withdrawal made later still expires it, and the member's
* save checks the withdrawals of claims that member reads (facts/single-prepare.ts), so a claim it never read cannot
- * expire the row it saves. Re-created alone by the member_page_withdrawal_scope migration.
+ * expire the row it saves. #7632/#7659: a writing role that RLS keeps from reading fact_withdrawals is refused
+ * (derived-state-maintainers.ts requireLedgerPoliciesSql) instead of saving the row active. Re-created alone by the
+ * member_page_withdrawal_scope and guard_ledgers_fail_closed migrations.
*/
export const FACT_WITHDRAWAL_PRESERVE_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_preserve_fact_withdrawal() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
DECLARE withdrawn TIMESTAMPTZ;
BEGIN
IF NEW.expired_at IS NULL THEN
+ ${requireLedgerPoliciesSql('fact_withdrawals', ['SELECT'], ' ')}
-- Serializes insertion with source-locked withdrawal, including a
-- concurrent reimport. Ordinary row locks work on both engines.
PERFORM id FROM sources WHERE id = NEW.source_id FOR SHARE;
diff --git a/src/core/function-search-path.ts b/src/core/function-search-path.ts
index d988804cc9..b11855bcac 100644
--- a/src/core/function-search-path.ts
+++ b/src/core/function-search-path.ts
@@ -12,10 +12,11 @@
* it so), so a schema replay keeps pg_temp. Historical migration bodies still pin the legacy settings, and so does a
* brain created before the change, which is what the hardening below completes: ALTER FUNCTION only, no body rewritten,
* so every guard keeps master's body, SECURITY INVOKER and BEFORE ROW timing.
- * A write role with no policy on a ledger still reads it empty under its own RLS; that fail-open stays open (#7659).
+ * A write role that RLS keeps from a ledger is refused by the guard itself since v318 (#7659, requireLedgerPoliciesSql).
*/
import type { BrainEngine } from './engine.ts';
+import { failClosedLedgerGuards } from './guard-ledger-checks.ts';
import { migrationStatementTimeoutMs } from './migration-timeout.ts';
import { isLockTimeoutError } from './retry-matcher.ts';
import { resolveSchemaLockTimeoutMs, schemaLockBlockedError } from './postgres-engine/schema-lock-timeout.ts';
@@ -93,8 +94,11 @@ function isConcurrentCatalogUpdate(error: unknown): boolean {
* listing what it left failed. A pg_proc row lock it cannot take
* becomes `schema_lock_blocked`; a concurrent update of the same pg_proc row (`apply-migrations --force-schema` beside
* another process's boot) is retried, since the step is idempotent. Prints nothing: the caller decides who is told.
+ * It first re-creates any purge or withdrawal guard left without its ledger check that the role owns (guard-ledger-checks.ts,
+ * #7659), best-effort and silent: v318 names the ones another role owns, and every later migration run retries them.
*/
export async function hardenFunctionSearchPaths(engine: BrainEngine, attempt = 1): Promise<string[] | null> {
+ if (attempt === 1) await failClosedLedgerGuards(engine).catch(() => undefined);
if ((await legacySearchPathFunctions(engine)).length === 0) return [];
const lockTimeoutMs = resolveSchemaLockTimeoutMs();
try {
diff --git a/src/core/guard-ledger-checks.ts b/src/core/guard-ledger-checks.ts
new file mode 100644
index 0000000000..e18fcac25c
--- /dev/null
+++ b/src/core/guard-ledger-checks.ts
@@ -0,0 +1,44 @@
+/**
+ * #7632/#7659: the purge and withdrawal guards refuse a writing role that row-level security keeps from their ledgers
+ * (derived-state-maintainers.ts requireLedgerPoliciesSql). Migration v318 installs those bodies and every migration run
+ * re-checks them, so a guard the migrating role could not re-create (another role owns it: CREATE OR REPLACE needs the
+ * owner, #7659 question 8) never aborts the upgrade, is named, and is re-created by the first migration run of a role
+ * that owns it (hardenFunctionSearchPaths, which every run calls). An older gbrain that replays its schema blob over the
+ * derivation guards is put right the same way. Each guard stays
+ * SECURITY INVOKER; nothing but the seven function bodies changes.
+ */
+
+import type { BrainEngine } from './engine.ts';
+import { FACT_INSERT_GUARD_FUNCTION_SQL } from './facts/insert-guard-schema.ts';
+import { REFUSE_PURGED_FACT_FUNCTION_SQL, REFUSE_PURGED_PAGE_FUNCTION_SQL, REFUSE_PURGED_TAKE_FUNCTION_SQL } from './facts/purge-schema.ts';
+import { FACT_WITHDRAWAL_PRESERVE_FUNCTION_SQL } from './facts/withdrawal-schema.ts';
+import { DERIVATION_SCOPE_ENTRY_FUNCTION_SQL, REFUSE_PURGING_DERIVATION_FUNCTION_SQL } from './page-body/schema.ts';
+
+/** Each guard, the ledger whose check marks its current body, and that body. */
+const LEDGER_GUARDS: ReadonlyArray<{ name: string; ledger: string; sql: string }> = [
+ { name: 'gbrain_refuse_purged_fact', ledger: 'fact_purges', sql: REFUSE_PURGED_FACT_FUNCTION_SQL },
+ { name: 'gbrain_refuse_purged_take', ledger: 'take_purges', sql: REFUSE_PURGED_TAKE_FUNCTION_SQL },
+ { name: 'gbrain_refuse_purged_page', ledger: 'page_purges', sql: REFUSE_PURGED_PAGE_FUNCTION_SQL },
+ { name: 'gbrain_preserve_fact_withdrawal', ledger: 'fact_withdrawals', sql: FACT_WITHDRAWAL_PRESERVE_FUNCTION_SQL },
+ { name: 'gbrain_guard_inserted_facts', ledger: 'fact_withdrawals', sql: FACT_INSERT_GUARD_FUNCTION_SQL },
+ { name: 'gbrain_mark_derivation_scope_entry', ledger: 'page_segment_derivation_purges', sql: DERIVATION_SCOPE_ENTRY_FUNCTION_SQL },
+ { name: 'gbrain_refuse_purging_derivation', ledger: 'page_segment_derivation_purges', sql: REFUSE_PURGING_DERIVATION_FUNCTION_SQL },
+];
+
+/**
+ * Re-creates every installed guard whose body lacks its ledger check and that the current role may replace, and returns
+ * the ones another role owns (regprocedure text) with the current role, for the message naming them.
+ */
+export async function failClosedLedgerGuards(engine: Pick<BrainEngine, 'executeRaw'>): Promise<{ left: string[]; role: string }> {
+ const rows = await engine.executeRaw<{ name: string; sig: string; owned: boolean; role: string }>(
+ `SELECT p.proname AS name, p.oid::regprocedure::text AS sig, pg_has_role(current_user, p.proowner, 'USAGE') AS owned, current_user::text AS role
+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace JOIN unnest($1::text[], $2::text[]) AS g(name, ledger) ON g.name = p.proname
+ WHERE n.nspname = 'public' AND p.prokind = 'f' AND strpos(p.prosrc, 'row_security_active(''' || g.ledger || ''')') = 0 ORDER BY 1`,
+ [LEDGER_GUARDS.map(g => g.name), LEDGER_GUARDS.map(g => g.ledger)]);
+ const left: string[] = [];
+ for (const row of rows) {
+ if (!row.owned) { left.push(row.sig); continue; }
+ await engine.executeRaw(LEDGER_GUARDS.find(g => g.name === row.name)!.sql);
+ }
+ return { left, role: rows[0]?.role ?? '' };
+}
diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.ts
index 395f277dba..c49609ea33 100644
--- a/src/core/page-body/schema.ts
+++ b/src/core/page-body/schema.ts
@@ -1,3 +1,5 @@
+import { requireLedgerPoliciesSql } from '../derived-state-maintainers.ts';
+
/**
* Segmented page storage (Wave B) DDL shared by migration v248 and both schema
* blobs (src/schema.sql regions; `bun run build:schema`).
@@ -254,6 +256,45 @@ export function derivationScopeLockSql(sourceId: string): string {
return `hashtextextended('gbrain:derivation-scope:' || ${sourceId}, 0)`;
}
+/**
+ * The derivation purge triggers (see PAGE_SEGMENT_DERIVATIONS_SQL below) read page_segment_derivation_purges, and the
+ * scope-entry note writes page_segment_derivation_purge_pages, as the writing role. #7632/#7659: a role that RLS keeps
+ * from them is refused (derived-state-maintainers.ts requireLedgerPoliciesSql) instead of reading no sweep, which let a
+ * purged claim be stored again and a page leave a sweep's scope unnoted. Migration v318 re-creates the functions alone.
+ */
+export const DERIVATION_SCOPE_ENTRY_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS $func$
+DECLARE
+ src TEXT;
+ page INTEGER;
+BEGIN
+ ${requireLedgerPoliciesSql('page_segment_derivation_purges', ['SELECT'])}
+ ${requireLedgerPoliciesSql('page_segment_derivation_purge_pages', ['INSERT'])}
+ 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`;
+export const REFUSE_PURGING_DERIVATION_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS $func$
+BEGIN
+ ${requireLedgerPoliciesSql('page_segment_derivation_purges', ['SELECT'])}
+ ${requireLedgerPoliciesSql('pages', ['SELECT'])}
+ 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 ${derivationSweepScopeSql('NEW', 'p', 'x.page_ids')}
+ AND ${derivationHoldsClaimSql('NEW', 'x.needles', 'x.patterns')}) THEN
+ RETURN NULL;
+ END IF;
+ RETURN NEW;
+END
+$func$ LANGUAGE plpgsql`;
+
/**
* 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
@@ -328,24 +369,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 SET search_path = pg_catalog, public, pg_temp 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;
+${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();
@@ -355,16 +379,7 @@ CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON page_b
DROP TRIGGER IF EXISTS pages_derivation_scope_delete ON pages;
CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON pages
FOR EACH ROW WHEN (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
-CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public, 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 ${derivationSweepScopeSql('NEW', 'p', 'x.page_ids')}
- AND ${derivationHoldsClaimSql('NEW', 'x.needles', 'x.patterns')}) THEN
- RETURN NULL;
- END IF;
- RETURN NEW;
-END
-$func$ LANGUAGE plpgsql;
+${REFUSE_PURGING_DERIVATION_FUNCTION_SQL};
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();`;
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index bf555ddfdb..02cc5f38c2 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -135,8 +135,12 @@ const RELATIONSHIP_TEXT: Record<string, string> = {
topology_outside_administration: 'a source topology change outside writer administration',
unreadable_state: 'writer state this database role cannot fully read (row-level security hides it or applies to the role, or a singleton row is missing)',
};
-/** #7780: the tables an unreadable_state raise names in its DETAIL `state` (writer-guard-schema.ts, git-canonical-schema.ts). */
-const UNREADABLE_STATES: ReadonlySet<unknown> = new Set(['persistence_brain', 'git_canonical_brain', 'sources', 'pages', 'guest_sources']);
+/**
+ * #7780: the tables an unreadable_state raise names in its DETAIL `state` (writer-guard-schema.ts, git-canonical-schema.ts),
+ * and since #7632 the ledgers the purge and withdrawal guards read (derived-state-maintainers.ts requireLedgerPoliciesSql).
+ */
+const UNREADABLE_STATES: ReadonlySet<unknown> = new Set(['persistence_brain', 'git_canonical_brain', 'sources', 'pages', 'guest_sources',
+ 'facts', 'fact_purges', 'fact_withdrawals', 'take_purges', 'page_purges', 'page_segment_derivation_purges', 'page_segment_derivation_purge_pages']);
/**
* #7777: the persistence protocol guards (shared-skills/persistence-schema.ts) raise SQLSTATE 42501, which is also
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index a0172f15eb..942503053b 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1555,6 +1555,26 @@ DECLARE
src TEXT;
page INTEGER;
BEGIN
+ IF pg_catalog.row_security_active('page_segment_derivation_purges') THEN
+ IF EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY['r']) AS needed(cmd) WHERE NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = 'page_segment_derivation_purges'::regclass::oid AND p.polpermissive AND p.polcmd::text IN ('*', needed.cmd)
+ AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END))) THEN
+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: writer state is unreadable to this database role',
+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:unreadable_state',
+ DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','page_segment_derivation_purges')::text,
+ HINT='Give this database role a policy on page_segment_derivation_purges allowing SELECT on the rows of the sources it writes (docs/ENGINES.md#purge-and-withdrawal-guards), or connect as the table owner.';
+ END IF;
+ END IF;
+ IF pg_catalog.row_security_active('page_segment_derivation_purge_pages') THEN
+ IF EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY['a']) AS needed(cmd) WHERE NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = 'page_segment_derivation_purge_pages'::regclass::oid AND p.polpermissive AND p.polcmd::text IN ('*', needed.cmd)
+ AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END))) THEN
+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: writer state is unreadable to this database role',
+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:unreadable_state',
+ DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','page_segment_derivation_purge_pages')::text,
+ HINT='Give this database role a policy on page_segment_derivation_purge_pages allowing INSERT on the rows of the sources it writes (docs/ENGINES.md#purge-and-withdrawal-guards), or connect as the table owner.';
+ END IF;
+ END IF;
IF TG_TABLE_NAME = 'pages' THEN
src := NEW.source_id;
page := NEW.id;
@@ -1579,6 +1599,26 @@ CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON pages
FOR EACH ROW WHEN (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS \$func\$
BEGIN
+ IF pg_catalog.row_security_active('page_segment_derivation_purges') THEN
+ IF EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY['r']) AS needed(cmd) WHERE NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = 'page_segment_derivation_purges'::regclass::oid AND p.polpermissive AND p.polcmd::text IN ('*', needed.cmd)
+ AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END))) THEN
+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: writer state is unreadable to this database role',
+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:unreadable_state',
+ DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','page_segment_derivation_purges')::text,
+ HINT='Give this database role a policy on page_segment_derivation_purges allowing SELECT on the rows of the sources it writes (docs/ENGINES.md#purge-and-withdrawal-guards), or connect as the table owner.';
+ END IF;
+ END IF;
+ IF pg_catalog.row_security_active('pages') THEN
+ IF EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY['r']) AS needed(cmd) WHERE NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = 'pages'::regclass::oid AND p.polpermissive AND p.polcmd::text IN ('*', needed.cmd)
+ AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END))) THEN
+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: writer state is unreadable to this database role',
+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:unreadable_state',
+ DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','pages')::text,
+ HINT='Give this database role a policy on pages allowing SELECT on the rows of the sources it writes (docs/ENGINES.md#purge-and-withdrawal-guards), or connect as the table owner.';
+ END IF;
+ END IF;
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 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))
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 1f1ca88c7f..48f0f2c4f8 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -2304,6 +2304,26 @@ DECLARE
src TEXT;
page INTEGER;
BEGIN
+ IF pg_catalog.row_security_active('page_segment_derivation_purges') THEN
+ IF EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY['r']) AS needed(cmd) WHERE NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = 'page_segment_derivation_purges'::regclass::oid AND p.polpermissive AND p.polcmd::text IN ('*', needed.cmd)
+ AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END))) THEN
+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: writer state is unreadable to this database role',
+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:unreadable_state',
+ DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','page_segment_derivation_purges')::text,
+ HINT='Give this database role a policy on page_segment_derivation_purges allowing SELECT on the rows of the sources it writes (docs/ENGINES.md#purge-and-withdrawal-guards), or connect as the table owner.';
+ END IF;
+ END IF;
+ IF pg_catalog.row_security_active('page_segment_derivation_purge_pages') THEN
+ IF EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY['a']) AS needed(cmd) WHERE NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = 'page_segment_derivation_purge_pages'::regclass::oid AND p.polpermissive AND p.polcmd::text IN ('*', needed.cmd)
+ AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END))) THEN
+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: writer state is unreadable to this database role',
+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:unreadable_state',
+ DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','page_segment_derivation_purge_pages')::text,
+ HINT='Give this database role a policy on page_segment_derivation_purge_pages allowing INSERT on the rows of the sources it writes (docs/ENGINES.md#purge-and-withdrawal-guards), or connect as the table owner.';
+ END IF;
+ END IF;
IF TG_TABLE_NAME = 'pages' THEN
src := NEW.source_id;
page := NEW.id;
@@ -2328,6 +2348,26 @@ CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON pages
FOR EACH ROW WHEN (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS \$func\$
BEGIN
+ IF pg_catalog.row_security_active('page_segment_derivation_purges') THEN
+ IF EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY['r']) AS needed(cmd) WHERE NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = 'page_segment_derivation_purges'::regclass::oid AND p.polpermissive AND p.polcmd::text IN ('*', needed.cmd)
+ AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END))) THEN
+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: writer state is unreadable to this database role',
+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:unreadable_state',
+ DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','page_segment_derivation_purges')::text,
+ HINT='Give this database role a policy on page_segment_derivation_purges allowing SELECT on the rows of the sources it writes (docs/ENGINES.md#purge-and-withdrawal-guards), or connect as the table owner.';
+ END IF;
+ END IF;
+ IF pg_catalog.row_security_active('pages') THEN
+ IF EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY['r']) AS needed(cmd) WHERE NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = 'pages'::regclass::oid AND p.polpermissive AND p.polcmd::text IN ('*', needed.cmd)
+ AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END))) THEN
+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: writer state is unreadable to this database role',
+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:unreadable_state',
+ DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','pages')::text,
+ HINT='Give this database role a policy on pages allowing SELECT on the rows of the sources it writes (docs/ENGINES.md#purge-and-withdrawal-guards), or connect as the table owner.';
+ END IF;
+ END IF;
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 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))
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 8c86b99565..86d2aebb51 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 317;
+export const LATEST_SCHEMA_VERSION = 318;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index ed8ba44003..0af151dad4 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -318,6 +318,7 @@ import { v314 } from './v314-guest-notes-fail-closed.ts';
import { v315 } from './v315-facts-context-head-index.ts';
import { v316 } from './v316-pages-source-type-index.ts';
import { v317 } from './v317-pages-projection-waiting-index.ts';
+import { v318 } from './v318-guard-ledgers-fail-closed.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -634,4 +635,5 @@ export const MIGRATIONS: Migration[] = [
v315,
v316,
v317,
+ v318,
];
diff --git a/src/core/schema-migrations/v318-guard-ledgers-fail-closed.ts b/src/core/schema-migrations/v318-guard-ledgers-fail-closed.ts
new file mode 100644
index 0000000000..67c4eb0600
--- /dev/null
+++ b/src/core/schema-migrations/v318-guard-ledgers-fail-closed.ts
@@ -0,0 +1,35 @@
+import type { Migration } from './types.ts';
+import { failClosedLedgerGuards } from '../guard-ledger-checks.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/#7659: the purge and withdrawal guards read their ledgers (fact_purges,
+// fact_withdrawals, take_purges, page_purges, the derivation purge tables) as
+// the writing role. A role that neither owns them nor bypasses RLS, with write
+// policies on a guarded table but none on its ledger, read the ledger empty, so
+// a purged claim, take, page or derivation could be stored again and a
+// withdrawn fact saved active. Each guard now refuses with
+// writer_coordinator_required (unreadable_state, as v281 does) when RLS
+// applies to the caller on a table it reads and no permissive policy of the
+// caller covers it; the HINT names the table and the docs/ENGINES.md recipe.
+// The owner, a role that bypasses RLS, a table without RLS and PGLite behave as
+// before. Every guard stays SECURITY INVOKER with its timing: no SECURITY
+// DEFINER (#7659), no privilege change, no row read or written. Replaces only
+// the seven functions: their triggers already call them, and re-creating the
+// triggers would take ACCESS EXCLUSIVE locks on facts, pages and takes. A
+// function another role owns is left and named on stderr, never an abort;
+// every later migration run re-creates it once a role that owns it runs
+// (hardenFunctionSearchPaths, guard-ledger-checks.ts).
+export const v318: Migration = {
+ version: 318,
+ name: 'guard_ledgers_fail_closed',
+ idempotent: true,
+ sql: '',
+ handler: async engine => {
+ const { left, role } = await failClosedLedgerGuards(engine);
+ if (left.length === 0) return;
+ process.stderr.write(` guards: ${left.length} purge or withdrawal guard(s) still read their ledgers as empty for a write role without ledger policies (${left.join(', ')}): `
+ + `CREATE OR REPLACE FUNCTION needs the owner. As that role run ALTER FUNCTION public.<name>() OWNER TO ${role}, or connect gbrain as it; the next migration run re-creates them (docs/ENGINES.md#purge-and-withdrawal-guards).\n`);
+ },
+};
diff --git a/src/schema.sql b/src/schema.sql
index c7b8a52438..fbca6302e8 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -2300,6 +2300,26 @@ DECLARE
src TEXT;
page INTEGER;
BEGIN
+ IF pg_catalog.row_security_active('page_segment_derivation_purges') THEN
+ IF EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY['r']) AS needed(cmd) WHERE NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = 'page_segment_derivation_purges'::regclass::oid AND p.polpermissive AND p.polcmd::text IN ('*', needed.cmd)
+ AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END))) THEN
+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: writer state is unreadable to this database role',
+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:unreadable_state',
+ DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','page_segment_derivation_purges')::text,
+ HINT='Give this database role a policy on page_segment_derivation_purges allowing SELECT on the rows of the sources it writes (docs/ENGINES.md#purge-and-withdrawal-guards), or connect as the table owner.';
+ END IF;
+ END IF;
+ IF pg_catalog.row_security_active('page_segment_derivation_purge_pages') THEN
+ IF EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY['a']) AS needed(cmd) WHERE NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = 'page_segment_derivation_purge_pages'::regclass::oid AND p.polpermissive AND p.polcmd::text IN ('*', needed.cmd)
+ AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END))) THEN
+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: writer state is unreadable to this database role',
+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:unreadable_state',
+ DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','page_segment_derivation_purge_pages')::text,
+ HINT='Give this database role a policy on page_segment_derivation_purge_pages allowing INSERT on the rows of the sources it writes (docs/ENGINES.md#purge-and-withdrawal-guards), or connect as the table owner.';
+ END IF;
+ END IF;
IF TG_TABLE_NAME = 'pages' THEN
src := NEW.source_id;
page := NEW.id;
@@ -2324,6 +2344,26 @@ CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON pages
FOR EACH ROW WHEN (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS $func$
BEGIN
+ IF pg_catalog.row_security_active('page_segment_derivation_purges') THEN
+ IF EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY['r']) AS needed(cmd) WHERE NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = 'page_segment_derivation_purges'::regclass::oid AND p.polpermissive AND p.polcmd::text IN ('*', needed.cmd)
+ AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END))) THEN
+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: writer state is unreadable to this database role',
+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:unreadable_state',
+ DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','page_segment_derivation_purges')::text,
+ HINT='Give this database role a policy on page_segment_derivation_purges allowing SELECT on the rows of the sources it writes (docs/ENGINES.md#purge-and-withdrawal-guards), or connect as the table owner.';
+ END IF;
+ END IF;
+ IF pg_catalog.row_security_active('pages') THEN
+ IF EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY['r']) AS needed(cmd) WHERE NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = 'pages'::regclass::oid AND p.polpermissive AND p.polcmd::text IN ('*', needed.cmd)
+ AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END))) THEN
+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: writer state is unreadable to this database role',
+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:unreadable_state',
+ DETAIL=pg_catalog.jsonb_build_object('op',TG_OP,'relationship','unreadable_state','state','pages')::text,
+ HINT='Give this database role a policy on pages allowing SELECT on the rows of the sources it writes (docs/ENGINES.md#purge-and-withdrawal-guards), or connect as the table owner.';
+ END IF;
+ END IF;
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 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))
diff --git a/test/e2e/guard-ledgers-fail-closed-7632-postgres.test.ts b/test/e2e/guard-ledgers-fail-closed-7632-postgres.test.ts
new file mode 100644
index 0000000000..3c3709e5c7
--- /dev/null
+++ b/test/e2e/guard-ledgers-fail-closed-7632-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../guard-ledgers-fail-closed-7632.test.ts'));
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index aefbd11828..21fe995d38 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -649,18 +649,18 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"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=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6677571f69ebfb82f183514caf6b94ccaaa0fda3a4326cf7601d21f155936c15",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false 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_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
"gbrain_release_refresh_barrier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0474782d352e51a92be5486f0d1eb0245cd6dc70ab6d7320acc685330690db4b",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"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",
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 c740019d4c..09fcc914cf 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -649,18 +649,18 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"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=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6677571f69ebfb82f183514caf6b94ccaaa0fda3a4326cf7601d21f155936c15",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false 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_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
"gbrain_release_refresh_barrier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0474782d352e51a92be5486f0d1eb0245cd6dc70ab6d7320acc685330690db4b",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"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",
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 fe21554b09..8ee24805f6 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -649,18 +649,18 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"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=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6677571f69ebfb82f183514caf6b94ccaaa0fda3a4326cf7601d21f155936c15",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false 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_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
"gbrain_release_refresh_barrier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0474782d352e51a92be5486f0d1eb0245cd6dc70ab6d7320acc685330690db4b",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"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",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index dfd94f1bc9..0fac98492d 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -421,9 +421,9 @@
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"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=false 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=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "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_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"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 1dcccf0ed2..91c0a54848 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -421,9 +421,9 @@
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"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=false 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=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "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_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"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 4693b8b6aa..7f8a79ca8e 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -421,9 +421,9 @@
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"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=false 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=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "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_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"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 22e8fb57e2..889aee2ca0 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -430,9 +430,9 @@
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"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=false 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=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "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_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"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 471cf0a697..08336e78ad 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -652,18 +652,18 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"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=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6677571f69ebfb82f183514caf6b94ccaaa0fda3a4326cf7601d21f155936c15",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false 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_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
"gbrain_release_refresh_barrier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0474782d352e51a92be5486f0d1eb0245cd6dc70ab6d7320acc685330690db4b",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"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",
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 db15a1783e..0c0f0b2f9b 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -652,18 +652,18 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"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=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6677571f69ebfb82f183514caf6b94ccaaa0fda3a4326cf7601d21f155936c15",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false 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_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
"gbrain_release_refresh_barrier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0474782d352e51a92be5486f0d1eb0245cd6dc70ab6d7320acc685330690db4b",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"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",
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 f4879910fc..4b1cec5459 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -652,18 +652,18 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"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=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6677571f69ebfb82f183514caf6b94ccaaa0fda3a4326cf7601d21f155936c15",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false 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_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
"gbrain_release_refresh_barrier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0474782d352e51a92be5486f0d1eb0245cd6dc70ab6d7320acc685330690db4b",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"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",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index e99d61f5ec..51a96d0dc5 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 312,
+ "count": 313,
"gaps": [
17,
18,
@@ -70,9 +70,10 @@
"dropInvalidConcurrentIndex": "6864d844b7dfb2fbecdd0fb9c73e06248473376feb794b3fe58f036c70d2d44c",
"enableRlsSql": "b7901b3d5231fcfacd3260ce0f59d4701d8c0bee902808ff48b1d8affbd444b6",
"ensureFactsFtsIndex": "95e723314ac30cea2db48e0e167c554ef1fa06df80cae765faa2a080a3a655c2",
+ "failClosedLedgerGuards": "dadd3ceb13286ca7ab969a911a310c87be313de6ec2c2c8e14d3f95b72901481",
"getFtsLanguage": "0d790b4c4af1f67a2a1bbd59470beb13f434917b381931baf8404a41c5d903db",
"grantFromRow": "e31bd308b413c11f2879ac4393fbc0362a1a974f937196f11029481e4dc64f69",
- "hardenFunctionSearchPaths": "10c9c70c8d10002c30de6b0d0a15b13118732a7ac54dbf7e835db0f7325f2629",
+ "hardenFunctionSearchPaths": "fd4dbb5e6f42931b80b3b041dde4b22100d08a449bd2d8b9c4a6e555e8959dfa",
"hnswMaxDimsForType": "a187cdcc520f813b7c39da97ce53da58509232ed9f851627ef41abfe1b68bd26",
"identityIndexHasSource": "ab7e4cad64ebf233f3a884816c114b0c582f4f2166c3bcf19ed8d92bcfcf3807",
"isLockTimeoutError": "52a3720e1ffb74ce381cc3269f78130c38a89c807e308283ec3d557bae2b89b1",
@@ -104,7 +105,7 @@
"widenIdentityIndex": "86a6176bd7637d964dbc1d3cd3b1bdfa3ca0161e1ee248c37d7380a1471282e6",
"withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"
},
- "latest": 317,
+ "latest": 318,
"records": [
{
"handler": {
@@ -2259,8 +2260,8 @@
"idempotent": true,
"name": "durable_fact_withdrawals",
"sql": {
- "length": 3374,
- "sha256": "92ad77a5b9dc3469a1b9b9e7ad8a84c880ef11b196cdfb984ab2c7c14285232a"
+ "length": 4502,
+ "sha256": "9843f1619915b1e6f507560317c83ea41b6a3f1fe412d3a99bc34d0e37671630"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -2572,8 +2573,8 @@
"idempotent": true,
"name": "fact_withdrawal_subject",
"sql": {
- "length": 3346,
- "sha256": "6d14a03d43407f42c2b879a45d5bdc2dc0a7fe3d9e8c940cd1ad4016f2134bba"
+ "length": 4474,
+ "sha256": "e519d7a2cfd55833e8a2578d4a86c7104a6614042dc80523c5d5ec35b1fe60c6"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -2656,8 +2657,8 @@
"idempotent": true,
"name": "fact_withdrawal_normalized_fingerprint",
"sql": {
- "length": 4090,
- "sha256": "0c476c2882988329fe96e9047069dc9c3f0965a4aa7354e5172db9b12da07977"
+ "length": 5218,
+ "sha256": "be030a0bbd1afec71a3055bcdb67d190b26e582e72a6cc256ea9bfbf2a0ca687"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -3496,8 +3497,8 @@
"idempotent": true,
"name": "memory_purge",
"sql": {
- "length": 5854,
- "sha256": "0a546100c3fb35a18855764ae62f4beec16b5bd45409f836b93c732d74e0c0c2"
+ "length": 10146,
+ "sha256": "8e68069899bf4a92a09dd896b3901ee0c72ade2478d721420a9fe0e61fd45c26"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -4237,8 +4238,8 @@
"idempotent": true,
"name": "set_based_fact_insert_guards",
"sql": {
- "length": 8761,
- "sha256": "e18eb98a4c7d4a9ef22447e3b866734b5b9ccc2405dea1f3373acc2a3d687231"
+ "length": 12894,
+ "sha256": "80072441dbeb3a3989bb4471ab7ac624b1aa21c4e9dd9d4e59975700e50abaa3"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -4426,8 +4427,8 @@
"idempotent": true,
"name": "segment_derivations",
"sql": {
- "length": 6545,
- "sha256": "569a377e019da9cc9c75ee982698e07b4a9d508af2404e3c2a95895a843649eb"
+ "length": 10961,
+ "sha256": "c35e78d10772e3d7f36e15f3dc39030a617d000bf25f87a3d9e82731149b755f"
},
"sqlFor": "absent",
"transaction": false,
@@ -4540,8 +4541,8 @@
"idempotent": true,
"name": "outcome_markers_skip_purge_guard",
"sql": {
- "length": 2737,
- "sha256": "337ac78ceff3b9a1cc108c3eef54972935f0892e3daef9330678a894bc21e9e3"
+ "length": 6870,
+ "sha256": "30e88e73d6c7c7a7fab54c5884535eb5c2ffa294ade9485801a654afbd1c834d"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -4987,8 +4988,8 @@
"idempotent": true,
"name": "member_page_withdrawal_scope",
"sql": {
- "length": 3868,
- "sha256": "c395452c23bbd0043302678d8d43a0504c041eceaf368d715a2c351402fa8107"
+ "length": 9129,
+ "sha256": "97119f853f23194ed6ac926a0a18e2cb6f3e6289a436f1c2c1bf4d61526d1483"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -5183,6 +5184,25 @@
"transaction": "absent",
"verify": "absent",
"version": 317
+ },
+ {
+ "handler": {
+ "form": "arrow",
+ "helpers": [
+ "failClosedLedgerGuards"
+ ],
+ "sha256": "91dfb9029c2d14bbed0f3325ea2fe2c364d9aae52c788e86d9b218d18b8cc729"
+ },
+ "idempotent": true,
+ "name": "guard_ledgers_fail_closed",
+ "sql": {
+ "length": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 318
}
],
"versions": [
@@ -5497,7 +5517,8 @@
314,
315,
316,
- 317
+ 317,
+ 318
]
},
"normalizer": "migrations-record-v1"
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 bb3e06f9e4..02547b3de2 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -649,18 +649,18 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"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=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=72ac0027fd37ecc4c72ad2e294ae3a98564736339b9ac917ea5d4112ec3cd35f",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=6677571f69ebfb82f183514caf6b94ccaaa0fda3a4326cf7601d21f155936c15",
+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",
- "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
- "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false 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_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
+ "gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
+ "gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
"gbrain_release_refresh_barrier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0474782d352e51a92be5486f0d1eb0245cd6dc70ab6d7320acc685330690db4b",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"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",
diff --git a/test/guard-ledgers-fail-closed-7632.test.ts b/test/guard-ledgers-fail-closed-7632.test.ts
new file mode 100644
index 0000000000..742bef34b8
--- /dev/null
+++ b/test/guard-ledgers-fail-closed-7632.test.ts
@@ -0,0 +1,345 @@
+/**
+ * #7632/#7659: the purge and withdrawal guards run SECURITY INVOKER and read their ledgers (fact_purges, fact_withdrawals,
+ * take_purges, page_purges, the derivation purge tables) as the writing role. A role that neither owns the ledgers nor
+ * bypasses RLS, with write policies on the guarded table but none on the ledger, read it empty: a purged claim, take,
+ * page or derivation was stored again and a withdrawn fact saved (or set) active, while the owner was refused.
+ *
+ * Contract (migration v318): each guard refuses with writer_coordinator_required (unreadable_state, the v278/v281
+ * refusal, its HINT naming the table and the docs/ENGINES.md recipe) when RLS applies to the caller on its ledger and no
+ * permissive policy of the caller covers it. The owner, a role that bypasses RLS, a ledger without RLS and a role
+ * holding the docs/ENGINES.md policies (applied verbatim) keep exactly the guard they had. The owner arm runs on PGLite
+ * and Postgres (PGLite has no roles); the role arms and the upgrade arm run on Postgres through
+ * test/e2e/guard-ledgers-fail-closed-7632-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { LATEST_VERSION, MIGRATIONS, runMigrations } from '../src/core/migrate.ts';
+import { FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING } from '../src/core/facts/insert-guard-schema.ts';
+import { failClosedLedgerGuards } from '../src/core/guard-ledger-checks.ts';
+import { recordDerivationPurge } from '../src/core/page-body/segment-derive.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { databaseRefusal } from '../src/core/persistence/publication-failure.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: Array<{ name: string; engine: BrainEngine }> = [];
+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-7632-db-'));
+let closePostgres: (() => Promise<void>) | undefined;
+const suffix = randomUUID().replaceAll('-', '').slice(0, 12);
+const SCOPED = `gbrain_ledger_7632_${suffix}`;
+const BYPASS = `gbrain_ledger_bypass_7632_${suffix}`;
+const UNREADABLE = /writer_coordinator_required: writer state is unreadable to this database role/;
+const PURGED = /purged_content: /;
+const ROLLBACK = 'guard-probe-rollback';
+const LEDGERS = ['fact_purges', 'fact_withdrawals', 'take_purges', 'page_purges', 'page_segment_derivation_purges', 'page_segment_derivation_purge_pages'];
+/** The guards v318 re-creates. */
+const GUARD_FUNCTIONS = ['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_purging_derivation'];
+const migration = MIGRATIONS.find(m => m.name === 'guard_ledgers_fail_closed')!;
+
+beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push({ name: 'pglite', engine });
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push({ name: 'postgres', engine: pg.engine }); closePostgres = pg.close;
+ }
+}, 180_000);
+afterAll(async () => {
+ for (const { engine } of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });
+});
+
+type Exec = Pick<BrainEngine, 'executeRaw'>;
+interface Seed { pageId: number; claim: string; hash: string }
+/** A page in 'default', written as the owner and committed; each case gets its own claim. */
+async function seedPage(engine: BrainEngine): Promise<Seed> {
+ const id = randomUUID().slice(0, 8);
+ const [page] = await engine.executeRaw<{ id: number }>(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,content_hash)
+ VALUES('default',$1,'note','Seed','body',repeat('a',64)) RETURNING id`, [`notes/guard-${id}`]);
+ return { pageId: page!.id, claim: `Zebra ${id} migrates north every spring`, hash: `${id}${'b'.repeat(56)}` };
+}
+const insertFact = (s: Seed): [string, unknown[]] => [`INSERT INTO facts(source_id,entity_slug,fact,kind,source,visibility)
+ VALUES('default','people/alice-example',$1,'fact','probe','world')`, [s.claim]];
+const activeFacts = (s: Seed): [string, unknown[]] => ['SELECT count(*)::int AS active FROM facts WHERE fact=$1 AND expired_at IS NULL', [s.claim]];
+const withdraw = (tx: Exec, s: Seed) => tx.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash)
+ VALUES('default','world','*',gbrain_fact_fingerprint($1))`, [s.claim]);
+const purgeFact = (tx: Exec, s: Seed) => tx.executeRaw(`INSERT INTO fact_purges(source_id,visibility,subject,fact_hash)
+ VALUES('default','world','*',gbrain_fact_fingerprint($1))`, [s.claim]);
+
+interface Guard {
+ name: string;
+ /** The function whose refusal the hidden-ledger case expects. */
+ raiser: string;
+ /** Each table, hidden from the scoped role on its own, makes this guard refuse. */
+ hidden: string[];
+ /** Owner writes inside the probe transaction, before the write under test. */
+ seed: (tx: Exec, s: Seed) => Promise<unknown>;
+ op: (s: Seed) => [string, unknown[]];
+ settings?: Record<string, string>;
+ /** Read as the owner after the write. */
+ probe: (s: Seed) => [string, unknown[]];
+ /** What the guard does: refuse the write, or keep the probed state. */
+ guarded: { result: string | RegExp; derived?: Record<string, unknown> };
+}
+
+const GUARDS: Guard[] = [
+ { name: 'a purged claim inserted as a fact', raiser: 'gbrain_guard_inserted_facts', hidden: ['fact_purges'],
+ seed: purgeFact, op: insertFact, probe: activeFacts, guarded: { result: PURGED } },
+ { name: 'a fact updated to a purged claim', raiser: 'gbrain_refuse_purged_fact', hidden: ['fact_purges'],
+ seed: async (tx, s) => { await tx.executeRaw(insertFact(s)[0], [`Placeholder ${s.claim}`]); await purgeFact(tx, s); },
+ op: s => ['UPDATE facts SET fact=$1 WHERE fact=$2', [s.claim, `Placeholder ${s.claim}`]], probe: activeFacts, guarded: { result: PURGED } },
+ { name: 'a withdrawn fact saved again as active', raiser: 'gbrain_preserve_fact_withdrawal', hidden: ['fact_withdrawals'],
+ seed: withdraw, op: insertFact, probe: activeFacts, guarded: { result: 'ok', derived: { active: 0 } } },
+ { name: 'a withdrawn fact saved again by a deferred bulk insert', raiser: 'gbrain_guard_inserted_facts', hidden: ['fact_withdrawals'],
+ seed: withdraw, op: insertFact, settings: { [FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING]: 'on' }, probe: activeFacts,
+ guarded: { result: 'ok', derived: { active: 0 } } },
+ { name: 'a withdrawn fact set active again', raiser: 'gbrain_preserve_fact_withdrawal', hidden: ['fact_withdrawals'],
+ seed: async (tx, s) => { await withdraw(tx, s); await tx.executeRaw(insertFact(s)[0], insertFact(s)[1]); },
+ op: s => ['UPDATE facts SET expired_at=NULL, valid_until=NULL WHERE fact=$1', [s.claim]], probe: activeFacts,
+ guarded: { result: 'ok', derived: { active: 0 } } },
+ { name: 'a purged take claim', raiser: 'gbrain_refuse_purged_take', hidden: ['take_purges'],
+ seed: (tx, s) => tx.executeRaw(`INSERT INTO take_purges(source_id,subject,claim_hash) VALUES('default','*',gbrain_fact_fingerprint($1))`, [s.claim]),
+ op: s => [`INSERT INTO takes(page_id,row_num,claim,kind,holder,weight) VALUES($1,1,$2,'take','brain',0.5)`, [s.pageId, s.claim]],
+ probe: s => ['SELECT count(*)::int AS takes FROM takes WHERE page_id=$1', [s.pageId]], guarded: { result: PURGED } },
+ { name: 'purged page content', raiser: 'gbrain_refuse_purged_page', hidden: ['page_purges'],
+ seed: (tx, s) => tx.executeRaw(`INSERT INTO page_purges(source_id,content_hash,slug) VALUES('default',$1,'notes/purged-example')`, [s.hash]),
+ op: s => ['UPDATE pages SET content_hash=$1 WHERE id=$2', [s.hash, s.pageId]],
+ probe: s => ['SELECT count(*)::int AS pages FROM pages WHERE content_hash=$1', [s.hash]], guarded: { result: PURGED } },
+ { name: 'a derivation holding a purged claim', raiser: 'gbrain_refuse_purging_derivation', hidden: ['page_segment_derivation_purges'],
+ seed: (tx, s) => recordDerivationPurge(tx, randomUUID(), 'default', [s.pageId], [s.claim]),
+ op: s => [`INSERT INTO page_segment_derivations(page_id,pipeline,occurrence_id,pipeline_version,segment_sha256,context_hash,state,output)
+ VALUES($1,'links',1,1,sha256('a'::bytea),sha256('b'::bytea),'done',jsonb_build_object('text',$2::text))`, [s.pageId, s.claim]],
+ probe: s => ['SELECT count(*)::int AS derivations FROM page_segment_derivations WHERE page_id=$1', [s.pageId]],
+ guarded: { result: 'ok', derived: { derivations: 0 } } },
+ { name: 'a page leaving a running derivation sweep unnoted', raiser: 'gbrain_mark_derivation_scope_entry',
+ hidden: ['page_segment_derivation_purges', 'page_segment_derivation_purge_pages'],
+ seed: (tx, s) => recordDerivationPurge(tx, randomUUID(), 'default', [], [s.claim]),
+ op: s => ['UPDATE pages SET deleted_at=now() WHERE id=$1', [s.pageId]],
+ probe: s => ['SELECT count(*)::int AS noted FROM page_segment_derivation_purge_pages WHERE page_id=$1', [s.pageId]],
+ guarded: { result: 'ok', derived: { noted: 1 } } },
+];
+
+interface Outcome { result: string; derived?: Record<string, unknown>; error?: unknown }
+/**
+ * Runs `before`, seeds the ledger and runs the guarded write in a transaction that always rolls back: the write as `role`
+ * when given (with the guard's settings and `scopes`), then the probe as the owner. `result` is 'ok' or the error message.
+ */
+async function run(engine: BrainEngine, g: Guard, s: Seed, opts: { role?: string; scopes?: string; before?: string } = {}): Promise<Outcome> {
+ let derived: Record<string, unknown> | undefined;
+ try {
+ await engine.transaction(async tx => {
+ if (opts.before) await tx.executeRaw(opts.before);
+ await g.seed(tx, s);
+ if (opts.role) await tx.executeRaw(`SET LOCAL ROLE ${opts.role}`);
+ if (opts.scopes) await tx.executeRaw(`SELECT set_config('app.scopes',$1,true)`, [opts.scopes]);
+ for (const [key, value] of Object.entries(g.settings ?? {})) await tx.executeRaw('SELECT set_config($1,$2,true)', [key, value]);
+ await tx.executeRaw(...g.op(s));
+ if (opts.role) await tx.executeRaw('RESET ROLE');
+ [derived] = await tx.executeRaw<Record<string, unknown>>(...g.probe(s));
+ throw new Error(ROLLBACK);
+ });
+ return { result: 'unreachable' };
+ } catch (error) {
+ const message = (error as Error).message;
+ return message === ROLLBACK ? { result: 'ok', derived } : { result: message, error };
+ }
+}
+
+function expectGuarded(outcome: Outcome, g: Guard, label: string) {
+ expect({ result: outcome.result, derived: outcome.derived }, label)
+ .toEqual({ result: typeof g.guarded.result === 'string' ? g.guarded.result : expect.stringMatching(g.guarded.result), derived: g.guarded.derived });
+}
+
+describe('owner behaviour is unchanged', () => {
+ for (const g of GUARDS) {
+ test(`${g.raiser}: the owner is guarded against ${g.name}`, async () => {
+ for (const { name, engine } of engines) expectGuarded(await run(engine, g, await seedPage(engine)), g, `${name} ${g.name}`);
+ });
+ }
+});
+
+/** The SQL between `marker` recipe comments in docs/ENGINES.md, for `role`. */
+function docsRecipe(marker: string, role: string): string {
+ // test-reads-source-ok[structural]: the operator recipes are applied verbatim, so the documented policies are the tested ones.
+ const doc = readFileSync(new URL('../docs/ENGINES.md', import.meta.url), 'utf8');
+ const block = new RegExp(`<!-- gbrain:${marker}:begin[^>]*-->\\s*\`\`\`sql\\n([\\s\\S]*?)\`\`\`\\s*<!-- gbrain:${marker}:end -->`).exec(doc);
+ if (!block) throw new Error(`docs/ENGINES.md has no ${marker} block`);
+ return block[1]!.replaceAll('<writer-role>', role);
+}
+
+(backends.includes('postgres') ? describe : describe.skip)('a scoped writer without policies on a guard ledger (Postgres)', () => {
+ let engine: BrainEngine;
+ let tables: string[] = [];
+ const as = { role: SCOPED };
+ /** Open policies for the scoped role on every table except `hidden`. */
+ async function policies(hidden: string[]) {
+ for (const table of tables) {
+ await engine.executeRaw(`DROP POLICY IF EXISTS ${SCOPED}_open ON ${table}`);
+ if (hidden.includes(table)) continue;
+ await engine.executeRaw(`CREATE POLICY ${SCOPED}_open ON ${table} FOR ALL TO ${SCOPED} USING (true) WITH CHECK (true)`);
+ }
+ }
+
+ beforeAll(async () => {
+ engine = engines.find(e => e.name === 'postgres')!.engine;
+ for (const role of [SCOPED, BYPASS]) {
+ await engine.executeRaw(`CREATE ROLE ${role} NOLOGIN NOSUPERUSER ${role === BYPASS ? 'BYPASSRLS' : 'NOBYPASSRLS'}`);
+ await engine.executeRaw(`GRANT USAGE ON SCHEMA public TO ${role}`);
+ await engine.executeRaw(`GRANT ALL ON ALL TABLES IN SCHEMA public TO ${role}`);
+ await engine.executeRaw(`GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO ${role}`);
+ }
+ for (const table of [...LEDGERS, 'facts', 'takes', 'pages', 'sources', 'page_segment_derivations']) {
+ await engine.executeRaw(`ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY`);
+ }
+ tables = (await engine.executeRaw<{ t: string }>(`SELECT tablename AS t FROM pg_tables WHERE schemaname = 'public' ORDER BY 1`)).map(r => r.t);
+ const [effective] = await engine.transaction(async tx => {
+ await tx.executeRaw(`SET LOCAL ROLE ${SCOPED}`);
+ return tx.executeRaw<{ rolsuper: boolean; rolbypassrls: boolean; owns: boolean }>(`SELECT rolsuper, rolbypassrls,
+ pg_has_role(current_user, (SELECT relowner FROM pg_class WHERE oid = 'public.fact_withdrawals'::regclass), 'USAGE') AS owns
+ FROM pg_roles WHERE rolname = current_user`);
+ });
+ expect(effective).toEqual({ rolsuper: false, rolbypassrls: false, owns: false });
+ }, 60_000);
+ afterAll(async () => {
+ if (!engine) return;
+ for (const role of [SCOPED, BYPASS]) {
+ await engine.executeRaw(`DROP OWNED BY ${role}`).catch(() => undefined);
+ await engine.executeRaw(`DROP ROLE IF EXISTS ${role}`);
+ }
+ });
+
+ test('with a policy on every table the scoped role is guarded like the owner', async () => {
+ await policies([]);
+ for (const g of GUARDS) expectGuarded(await run(engine, g, await seedPage(engine), as), g, g.name);
+ });
+
+ for (const g of GUARDS) {
+ for (const hidden of g.hidden) {
+ test(`${g.raiser}: no policy on ${hidden} refuses ${g.name} instead of passing it`, async () => {
+ await policies([hidden]);
+ const outcome = await run(engine, g, await seedPage(engine), as);
+ expect({ result: outcome.result, derived: outcome.derived }).toEqual({ result: expect.stringMatching(UNREADABLE), derived: undefined });
+ expect(databaseRefusal(outcome.error)).toMatchObject({ code: 'writer_coordinator_required',
+ detail: { origin: 'database_guard', sqlstate: 'P0001', raiser: g.raiser, relationship: 'unreadable_state', state: hidden } });
+ const hint = (outcome.error as { hint?: string }).hint ?? '';
+ expect(hint).toContain(`a policy on ${hidden} allowing`);
+ expect(hint).toContain('docs/ENGINES.md#purge-and-withdrawal-guards');
+ });
+ }
+ }
+
+ test('a policy for another role does not count as the caller\'s', async () => {
+ const g = GUARDS[2]!;
+ await policies(['fact_withdrawals']);
+ await engine.executeRaw(`CREATE POLICY ${SCOPED}_other ON fact_withdrawals FOR SELECT TO ${BYPASS} USING (true)`);
+ try {
+ expect((await run(engine, g, await seedPage(engine), as)).result).toMatch(UNREADABLE);
+ } finally {
+ await engine.executeRaw(`DROP POLICY ${SCOPED}_other ON fact_withdrawals`);
+ }
+ });
+
+ test('a writer that may only insert facts is refused only when a withdrawal matches a fact it inserts', async () => {
+ await policies(['facts']);
+ await engine.executeRaw(`CREATE POLICY ${SCOPED}_read ON facts FOR SELECT TO ${SCOPED} USING (true)`);
+ await engine.executeRaw(`CREATE POLICY ${SCOPED}_insert ON facts FOR INSERT TO ${SCOPED} WITH CHECK (true)`);
+ const unrelated = (g: Guard): Guard => ({ ...g, seed: (tx, s) => withdraw(tx, { ...s, claim: `Other ${s.claim}` }) });
+ try {
+ for (const g of [GUARDS[2]!, GUARDS[3]!]) {
+ expect(await run(engine, unrelated(g), await seedPage(engine), as), g.name).toEqual({ result: 'ok', derived: { active: 1 } });
+ }
+ expect((await run(engine, GUARDS[3]!, await seedPage(engine), as)).result).toMatch(UNREADABLE);
+ } finally {
+ for (const name of ['read', 'insert']) await engine.executeRaw(`DROP POLICY ${SCOPED}_${name} ON facts`);
+ }
+ });
+
+ test('a ledger without row-level security guards the scoped role with no policy on it', async () => {
+ for (const g of GUARDS) {
+ await policies(g.hidden);
+ const off = g.hidden.map(t => `ALTER TABLE ${t} DISABLE ROW LEVEL SECURITY`).join('; ');
+ expectGuarded(await run(engine, g, await seedPage(engine), { ...as, before: off }), g, g.name);
+ }
+ });
+
+ test('a role that bypasses RLS is guarded with no policies at all', async () => {
+ for (const table of tables) await engine.executeRaw(`DROP POLICY IF EXISTS ${SCOPED}_open ON ${table}`);
+ for (const g of GUARDS) expectGuarded(await run(engine, g, await seedPage(engine), { role: BYPASS }), g, g.name);
+ });
+
+ test('the docs/ENGINES.md maintainer and ledger recipes, applied verbatim, guard a scoped writer like the owner', async () => {
+ const recipe = [docsRecipe('maintainer-rls-recipe', SCOPED), docsRecipe('ledger-rls-recipe', SCOPED)].join('\n');
+ const created = [...recipe.matchAll(/CREATE POLICY (\w+) ON (\w+)/g)].map(match => ({ name: match[1]!, table: match[2]! }));
+ expect(created.filter(p => LEDGERS.includes(p.table)).map(p => p.table).sort()).toEqual([...LEDGERS].sort());
+ await policies([...new Set(created.map(p => p.table))]);
+ await engine.executeRaw(recipe);
+ try {
+ for (const g of GUARDS) expectGuarded(await run(engine, g, await seedPage(engine), { ...as, scopes: 'default' }), g, g.name);
+ } finally {
+ for (const p of created) await engine.executeRaw(`DROP POLICY IF EXISTS ${p.name} ON ${p.table}`);
+ }
+ });
+
+ // From before v277 (whose search_path hardening now re-creates guards missing their check), from v283 and from v317.
+ for (const from of [276, 283, migration.version - 1]) test(`an upgraded brain at v${from} ends with every guard failing closed`, async () => {
+ for (const fn of GUARD_FUNCTIONS) {
+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION ${fn}() RETURNS trigger LANGUAGE plpgsql
+ SET search_path = pg_catalog, public, pg_temp AS $fn$ BEGIN RETURN ${fn === 'gbrain_guard_inserted_facts' || fn === 'gbrain_mark_derivation_scope_entry' ? 'NULL' : 'NEW'}; END $fn$`);
+ }
+ await engine.setConfig('version', String(from));
+ await runMigrations(engine);
+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));
+ const rows = await engine.executeRaw<{ proname: string; definer: boolean; path: string[]; checks: string[] }>(`SELECT p.proname, p.prosecdef AS definer,
+ p.proconfig AS path, ARRAY(SELECT DISTINCT m[1] FROM regexp_matches(p.prosrc, 'row_security_active\\(''(\\w+)''\\)', 'g') AS m ORDER BY 1) AS checks
+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'public' AND p.proname = ANY($1::text[]) ORDER BY 1`, [GUARD_FUNCTIONS]);
+ const path = ['search_path=pg_catalog, public, pg_temp'];
+ expect(rows).toEqual([
+ { proname: 'gbrain_guard_inserted_facts', definer: false, path, checks: ['fact_purges', 'fact_withdrawals', 'facts'] },
+ { proname: 'gbrain_mark_derivation_scope_entry', definer: false, path, checks: ['page_segment_derivation_purge_pages', 'page_segment_derivation_purges'] },
+ { proname: 'gbrain_preserve_fact_withdrawal', definer: false, path, checks: ['fact_withdrawals'] },
+ { proname: 'gbrain_refuse_purged_fact', definer: false, path, checks: ['fact_purges'] },
+ { proname: 'gbrain_refuse_purged_page', definer: false, path, checks: ['page_purges'] },
+ { proname: 'gbrain_refuse_purged_take', definer: false, path, checks: ['pages', 'take_purges'] },
+ { proname: 'gbrain_refuse_purging_derivation', definer: false, path, checks: ['page_segment_derivation_purges', 'pages'] },
+ ]);
+ for (const g of GUARDS) {
+ await policies([g.hidden[0]!]);
+ expect((await run(engine, g, await seedPage(engine), as)).result, g.name).toMatch(UNREADABLE);
+ }
+ }, 120_000);
+
+ test('a guard another role owns is left and named, and the next migration run of a role that owns it fails it closed', async () => {
+ const closed = async (tx: Exec) => (await tx.executeRaw<{ closed: boolean }>(
+ "SELECT strpos(prosrc, 'row_security_active(''fact_purges'')') > 0 AS closed FROM pg_proc WHERE proname = 'gbrain_refuse_purged_fact'"))[0]!.closed;
+ try {
+ await engine.transaction(async tx => {
+ await tx.executeRaw(`CREATE OR REPLACE FUNCTION gbrain_refuse_purged_fact() RETURNS trigger LANGUAGE plpgsql
+ SET search_path = pg_catalog, public, pg_temp AS $fn$ BEGIN RETURN NEW; END $fn$`);
+ await tx.executeRaw(`SET LOCAL ROLE ${SCOPED}`);
+ expect(await failClosedLedgerGuards(tx)).toEqual({ left: ['gbrain_refuse_purged_fact()'], role: SCOPED });
+ expect(await closed(tx)).toBe(false);
+ await tx.executeRaw('RESET ROLE');
+ expect((await failClosedLedgerGuards(tx)).left).toEqual([]);
+ expect(await closed(tx)).toBe(true);
+ throw new Error(ROLLBACK);
+ });
+ } catch (error) {
+ if ((error as Error).message !== ROLLBACK) throw error;
+ }
+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION gbrain_refuse_purged_fact() RETURNS trigger LANGUAGE plpgsql
+ SET search_path = pg_catalog, public, pg_temp AS $fn$ BEGIN RETURN NEW; END $fn$`);
+ expect((await runMigrations(engine)).applied).toBe(0);
+ expect(await closed(engine)).toBe(true);
+ });
+});