Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge origin/master bf6057714 (0.60.466.0) into capy/gbra95-guard-definer
garrytane07a16d5cbcd
diff --cc CHANGELOG.mdindex f21b933140,52b4651a2e..30c9c5fb70--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -10,40 -10,37 +10,71 @@@ credits are retained; no result has beeidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).- ## [0.60.466.0] - 2026-10-26++## [Unreleased]++**A temporary table can no longer slip purged or forgotten content past gbrain's guards. Before, any database session, including gbrain's own role, could create an empty table named like a purge list and have a purged claim, page or take stored again, or a forgotten fact saved active.**++gbrain keeps lists of what you purged (`gbrain forget --purge`) and what you forgot (`gbrain forget`), and database guards check every write against them. Those guards looked tables up in a way that let a session's own temporary tables come first. So a session could create an empty temporary table with the same name as a purge list, and the guard read that empty table instead and let the write through. Every gbrain function now looks at temporary tables last. Nothing else about the guards changed.++### How to get it++Upgrade and let the migration run (`gbrain upgrade`, or `gbrain apply-migrations --yes`). Then check:++```bash+gbrain doctor --json # function_search_path: ok+```++### What changed++| Situation | Before | Now |+|---|---|---|+| A session creates a temporary table or view named like a purge or withdrawal list, then saves purged content | the purged claim, page, take or derivation was stored again, and a forgotten fact was saved active, for the owner and any other writer | refused (or dropped, or stamped forgotten), exactly as without the temporary table |- | The migrating role does not own some gbrain functions | — | migration v276 updates the ones it owns, names the rest on stderr and carries on; `gbrain doctor` (`function_search_path`) prints the `ALTER FUNCTION` to run as each owner |++| The migrating role does not own some gbrain functions | — | migration v277 updates the ones it owns, names the rest on stderr and carries on; `gbrain doctor` (`function_search_path`) prints the `ALTER FUNCTION` to run as each owner |++### What to watch for after you upgrade++- **Still open:** on Postgres, a write role with no row-level-security policy on a purge or withdrawal list reads it as empty, so its purged or forgotten writes still go through. Until gbrain#7659 lands, give such a role a `SELECT` policy on those lists for the sources it writes.+- An older gbrain that runs `gbrain init` or `gbrain upgrade` against the brain undoes this for the functions it re-creates. Doctor flags them; `gbrain init` or `gbrain upgrade` with this release, or the printed `ALTER FUNCTION`, puts it back.+- Procedures in `public` are left alone.++### Itemized changes+- - `src/core/function-search-path.ts`: `FUNCTION_SEARCH_PATH_HARDENING_SQL` appends `pg_temp` to every function in `public` (`prokind = 'f'`) the current role owns that pins `pg_catalog, public` or `pg_catalog`. ALTER only, no body changes. It is the last statement of the schema blob, runs in migration v276 (`function_search_path_pg_temp`) and after `gbrain reindex-search-vector` re-creates the search-vector trigger functions.++- `src/core/function-search-path.ts`: `FUNCTION_SEARCH_PATH_HARDENING_SQL` appends `pg_temp` to every function in `public` (`prokind = 'f'`) the current role owns that pins `pg_catalog, public` or `pg_catalog`. ALTER only, no body changes. It is the last statement of the schema blob, runs in migration v277 (`function_search_path_pg_temp`) and after `gbrain reindex-search-vector` re-creates the search-vector trigger functions.+- `src/commands/doctor/checks/function-search-path.ts`: new `function_search_path` check (fail) naming each function still without `pg_temp`, with the `ALTER FUNCTION ... SET search_path` to run as its owner. It never suggests an owner change.+- The purge and withdrawal guards are unchanged: `SECURITY INVOKER`, same bodies, same `BEFORE ROW` timing.+- Tests: `test/e2e/function-search-path-postgres.test.ts` (temporary table and view shadows for the owner and a non-owner writer, the migration from the previous version, a migrating role that owns all but one function, schema replay, lock timeout), `test/function-search-path-pglite.test.ts`, `test/doctor-function-search-path.test.ts`.++ ## [0.60.466.0] - 2026-10-26++ **A brain whose database is at schema v265 now upgrades instead of stopping with `column "pending" does not exist`, and on a brain with a large write journal each write claim is a quick index lookup again instead of a scan of the whole journal after every restart.**++ Two upgrade problems are fixed. First, a brain at schema v265 could not reach any later release: the upgrade replays the current schema before running migrations, and one index in it filters on a column that only the next migration adds, so the replay failed before any migration ran and every retry failed the same way. Second, after a restart the write queue checked "has a foreground write committed on this worktree since I last looked?" with no index to answer it, so on a brain with hundreds of thousands of past write receipts each claim walked every receipt. Claims could overrun their claim phase, the queue grew, and sync looked stuck.++ ### What changed++ | Situation | Before | Now |+ |---|---|---|+ | Upgrading a brain at schema v265 (Postgres or PGLite) | every upgrade attempt failed with `column "pending" does not exist` | the upgrade adds the missing column first (exactly as migration v266 defines it, no data changes), then migrates to the latest schema |+ | A write claim right after a restart, on a large journal | each claim scanned the journal (about 175 ms per claim on a test brain with ~590k receipts) | migration v276 adds the partial index `persistence_requests_foreground_committed`; the same claim takes under 1 ms |+ | The new index is missing or INVALID on a brain already at the latest schema | — | `gbrain doctor` (`persistence_request_indexes`) names it and says write claims can time out; `gbrain repair request-indexes` previews the fix and `--apply` rebuilds it |++ ### What to watch for after you upgrade++ - On Postgres, migration v276 builds the index with `CREATE INDEX CONCURRENTLY`, so writes keep flowing; on a very large journal the build can take a while. If it is interrupted, `gbrain doctor` reports the INVALID index and `gbrain repair request-indexes --apply` rebuilds it. PGLite builds it inline.+ - The index also covers compacted receipts of every kind, so on a long-lived brain it holds most committed receipts.+ - Nothing rewrites your data. The v265 fix only adds a column with its default.++ ### Itemized changes++ - `src/core/engine-sql/bootstrap.ts`: the forward-reference bootstrap probes `derived_generation_items` and its `pending` column and adds the column on a v265 brain before the schema replay (#7645).+ - `src/core/persistence/schema.ts`, `src/core/schema-migrations/v276-persistence-foreground-committed-index.ts`: `persistence_requests_foreground_committed` on `(worktree_id, sequence)`, with the write claims' committed-foreground predicate written the way the claim probe writes it; built online by v276 (transaction-free, `CONCURRENTLY` on Postgres, an INVALID leftover rebuilt) and listed among the request-table online indexes (#7649).+ - `src/core/repair/request-indexes.ts`, `src/commands/doctor/checks/persistence-requests.ts`: repair and doctor cover the new index; the doctor message names write claims.+ - `test/fixtures/schema-history/`, `scripts/capture-schema-history-fixture.ts`: a fresh brain as each release from schema v260 to v275 created it, for both engines, captured from that release's own code with a round-trip fidelity check. `test/schema-history-upgrade.slow.test.ts` (PGLite) and `test/e2e/schema-history-upgrade.test.ts` (Postgres) upgrade every fixture to the latest schema and compare the result with a fresh install, so the next missing forward reference fails a test instead of a user's upgrade.+ - `test/schema-bootstrap-coverage.test.ts`: the bootstrap coverage check now reads columns in partial-index `WHERE` predicates and `INCLUDE` lists.+ - Tests for the index: `test/migration-persistence-foreground-committed-index.test.ts`, `test/e2e/persistence-claim-committed-probe-7649-postgres.test.ts` (both claim paths use the index on a 160k-receipt Postgres journal).++ Reported by @glen-carlson (#7645) and @andreineacsu (#7649). Contributed by @Masashi-Ono0611.+## [0.60.465.0] - 2026-10-26**On a managed brain, releasing a held fact (`gbrain trust release h<id>`) now writes it into its entity page's `## Facts` table through the page-write door, so the released fact lives in Git and a re-import keeps it, instead of a database-only row the file never had.**diff --cc docs/ENGINES.mdindex 6bc5b837da,afb0465bd0..9cc7cfba24--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@@ -390,19 -390,6 +390,19 @@@ segmented chunk (`test/e2e/segmented-swpolicies above it creates segmented pages and sees only its sources' rows(`test/e2e/segmented-rls-scope.test.ts`).+**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- `pg_temp` (migration v276, #7632), so a session's temp table or view named like a ledger++`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). Where the migrating role- does not own a function, v276 names it on stderr and leaves it; `gbrain doctor`++does not own a function, v277 names it on stderr and leaves it; `gbrain doctor`+(`function_search_path`) prints the `ALTER FUNCTION` to run as its owner+(`test/e2e/function-search-path-postgres.test.ts`).+**In engine-sql.** A read in a migrated domain takes a `ScopedRead` when itruns through this helper and a `LegacyUnscopedRead` when it runs on the pool(`src/core/engine-sql/brands.ts`); the engine obtains the branded executor, sodiff --cc docs/guides/rls-and-you.mdindex d467208591,7b78af865f..7b93bf3546--- a/docs/guides/rls-and-you.md+++ b/docs/guides/rls-and-you.md@@@ -260,18 -260,9 +260,18 @@@ both with the trigger inert, so a tabl## Function search_path-Every plpgsql function gbrain installs pins `search_path = pg_catalog, public`,+Every plpgsql function gbrain installs pins `search_path = pg_catalog, public, pg_temp`,so a same-named object in another schema can never change what the function-reads or writes. The three fact-fingerprint functions+reads or writes. `pg_temp` is named last because PostgreSQL otherwise searches the+caller's temporary schema first for tables and views: a session, the owner included,+could shadow a purge or withdrawal ledger a guard reads with an empty temporary one of- the same name and store purged content again. On an older brain, migration v276 appends++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(`gbrain_fact_fingerprint`, `gbrain_fact_fingerprint_v1`,`gbrain_fact_normalize`) are SQL functions that an index expression uses, sothey call `pg_catalog.`-qualified built-ins instead of pinning a setting (adiff --cc llms-full.txtindex 880fb54c75,41badaee49..f18580835d--- a/llms-full.txt+++ b/llms-full.txt@@@ -5836,19 -5836,6 +5836,19 @@@ segmented chunk (`test/e2e/segmented-swpolicies above it creates segmented pages and sees only its sources' rows(`test/e2e/segmented-rls-scope.test.ts`).+**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- `pg_temp` (migration v276, #7632), so a session's temp table or view named like a ledger++`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). Where the migrating role- does not own a function, v276 names it on stderr and leaves it; `gbrain doctor`++does not own a function, v277 names it on stderr and leaves it; `gbrain doctor`+(`function_search_path`) prints the `ALTER FUNCTION` to run as its owner+(`test/e2e/function-search-path-postgres.test.ts`).+**In engine-sql.** A read in a migrated domain takes a `ScopedRead` when itruns through this helper and a `LegacyUnscopedRead` when it runs on the pool(`src/core/engine-sql/brands.ts`); the engine obtains the branded executor, sodiff --cc src/commands/doctor/checks/function-search-path.tsindex b74004cfad,0000000000..fac672a367mode 100644,000000..100644--- a/src/commands/doctor/checks/function-search-path.ts+++ b/src/commands/doctor/checks/function-search-path.ts@@@ -1,52 -1,0 +1,52 @@@+/**+ * function_search_path doctor check (#7632): every gbrain function that pins a search_path ends it with pg_temp.+ *+ * Without it, a session's temp table or view named like a ledger (fact_purges, page_purges, take_purges,+ * fact_withdrawals) hides that ledger from the guard that reads it, and a purged or withdrawn write goes through.- * Migration v276 appends pg_temp to every function the migrating role owns and names the rest on stderr; this check++ * Migration v277 appends pg_temp to every function the migrating role owns and names the rest on stderr; this check+ * names each function still without it and the ALTER FUNCTION to run as its owner. ALTER FUNCTION ... SET changes+ * neither the owner nor the body, so the next boot's CREATE OR REPLACE still succeeds. Read-only.+ */++import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { checkError } from '../check-fix.ts';+import { LEGACY_SEARCH_PATH_SETTINGS } from '../../../core/function-search-path.ts';++/** The gbrain functions whose pinned search_path lacks a trailing pg_temp, and the ALTER that fixes each. */+export async function functionSearchPathProblems(engine: BrainEngine): Promise<{ functions: string[]; fix: string[] }> {+ const rows = await engine.executeRaw<{ sig: string; path: string }>(+ `SELECT p.oid::regprocedure::text AS sig, substr(c.setting, 13) AS path+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace CROSS JOIN LATERAL unnest(p.proconfig) AS c(setting)+ WHERE n.nspname = 'public' AND p.prokind = 'f' AND c.setting = ANY($1::text[]) ORDER BY 1`,+ [[...LEGACY_SEARCH_PATH_SETTINGS]]);+ return {+ functions: rows.map(r => r.sig),+ fix: rows.map(r => `ALTER FUNCTION ${r.sig} SET search_path = ${r.path}, pg_temp;`),+ };+}++async function runFunctionSearchPath(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ ctx.progress.heartbeat('function_search_path');+ try {+ const { functions, fix } = await functionSearchPathProblems(engine);+ if (functions.length === 0) {+ checks.push({ name: 'function_search_path', status: 'ok', message: 'Every gbrain function that pins a search_path ends it with pg_temp' });+ } else {+ checks.push({+ name: 'function_search_path',+ status: 'fail',+ message: `${functions.length} function(s) pin search_path without pg_temp last (${functions.join(', ')}), so a temp table or view named like a purge or withdrawal ledger hides it from the guard that reads it. `- + `Fix (as the role that owns each function; migration v276 did the ones the migrating role owned): ${fix.join(' ')}`,++ + `Fix (as the role that owns each function; migration v277 did the ones the migrating role owned): ${fix.join(' ')}`,+ });+ }+ } catch (e) {+ checks.push(checkError('function_search_path', 'check function search paths', e));+ }+ return checks;+}++export const functionSearchPathEntry: DoctorEntry = { name: 'function_search_path', emits: ['function_search_path'], run: runFunctionSearchPath };diff --cc src/core/behavior-change-notice.tsindex 41a4c2573c,df9e1b5142..ffc5101eb0--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -1308,8 -1308,6 +1308,8 @@@ export const BEHAVIOR_CHANGES: Readonly{ since: '0.60.464.0', text: 'Security: `gbrain serve --access=read-only` (the `=` form) now sets the read-only ceiling. It passed flag validation before but started the serve with full write access, because only `--access read-only` was read. A config that used the `=` form now gets the read-only tool set and refused mutations it asked for; a repeated `--access` never widens a read-only value, and an invalid value in either form refuses. `--surface=<v>` likewise now sets the serve surface (it was ignored, leaving the full surface), and a repeated `--surface` takes the narrowest value.' },{ since: '0.60.464.0', text: 'A managed sync pass whose process was killed or crashed now reads `resumable` / `pass_interrupted` in `gbrain sync status` (with an `interrupted` block naming the pass and the dead holder) instead of `pass_unfinished`, and a second killed pass reads `blocked` / `pass_abandoned` at once. `gbrain doctor` `managed_sync_blocked` lists both (warn, fail after an hour). A live pass still committing is no longer counted abandoned because its row is old.' },{ since: '0.60.465.0', text: 'On a managed brain, `gbrain trust release h<id>` of a held fact whose entity page exists now writes the fact into that page\'s `## Facts` fence through the page-write door (a `trust_release` page write) and flips the hold in the same publication, so the released fact lives in the page\'s file and a re-import keeps it. Before, the release inserted a database-only row the file never held; a fence-guard hold that names an existing fence row created a database-only twin of it, and now indexes that row and leaves the file unchanged. The row is stamped `user_confirmed` with origin `trust_release` and the page keeps its trust tier. A hold decided after the release was accepted fails `preview_changed` and writes nothing; a remote request, or a deleted or private entity page, refuses and the fact stays held. A hold with no entity page, and unmanaged brains, release database-only as before.' },+ // #7632 function search_path. `since` is stamped at the merge slot.- { since: '0.60.466.0', id: 'function_search_path_pg_temp', text: 'Every gbrain function that pins a search_path now ends it with `pg_temp` (`ALTER FUNCTION ... SET search_path`, no body changes). Before, the purge and withdrawal guards pinned `pg_catalog, public`, which leaves the session\'s temporary schema first for tables and views: any session, the owner included, could create an empty temp table or view named like a ledger (`fact_purges`, `page_purges`, `take_purges`, `fact_withdrawals`, `page_segment_derivation_purges`) and store a purged claim, page, take or derivation again, or save a withdrawn fact active. The guards are otherwise unchanged (SECURITY INVOKER, same bodies, same timing). Still open, not fixed here: on Postgres, a write role with no RLS policy on a ledger reads it empty, so its purged or withdrawn writes still go through (gbrain#7659). Where the migrating role does not own a function, the migration leaves it, names it on stderr and carries on, and `gbrain doctor` (`function_search_path`) prints the `ALTER FUNCTION` to run as its owner; that changes no owner, so later boots still succeed. An older gbrain binary that replays its schema against the brain (`gbrain init` or `gbrain upgrade` from it; an ordinary boot replays nothing) drops `pg_temp` from the functions it re-creates; doctor flags them, and `gbrain init` or `gbrain upgrade` with this release, or the printed `ALTER FUNCTION`, puts it back. An ordinary boot of this release does not.' },++ { since: 'TBD', id: 'function_search_path_pg_temp', text: 'Every gbrain function that pins a search_path now ends it with `pg_temp` (`ALTER FUNCTION ... SET search_path`, no body changes). Before, the purge and withdrawal guards pinned `pg_catalog, public`, which leaves the session\'s temporary schema first for tables and views: any session, the owner included, could create an empty temp table or view named like a ledger (`fact_purges`, `page_purges`, `take_purges`, `fact_withdrawals`, `page_segment_derivation_purges`) and store a purged claim, page, take or derivation again, or save a withdrawn fact active. The guards are otherwise unchanged (SECURITY INVOKER, same bodies, same timing). Still open, not fixed here: on Postgres, a write role with no RLS policy on a ledger reads it empty, so its purged or withdrawn writes still go through (gbrain#7659). Where the migrating role does not own a function, the migration leaves it, names it on stderr and carries on, and `gbrain doctor` (`function_search_path`) prints the `ALTER FUNCTION` to run as its owner; that changes no owner, so later boots still succeed. An older gbrain binary that replays its schema against the brain (`gbrain init` or `gbrain upgrade` from it; an ordinary boot replays nothing) drops `pg_temp` from the functions it re-creates; doctor flags them, and `gbrain init` or `gbrain upgrade` with this release, or the printed `ALTER FUNCTION`, puts it back. An ordinary boot of this release does not.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --cc src/core/schema-migrations/latest.generated.tsindex 4059749ed5,4059749ed5..6b1b446066--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@@ -4,4 -4,4 +4,4 @@@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.--export const LATEST_SCHEMA_VERSION = 276;++export const LATEST_SCHEMA_VERSION = 277;diff --cc src/core/schema-migrations/registry.generated.tsindex 192a9c4f1b,f09d46ac19..73a365f90e--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@@ -276,7 -276,7 +276,8 @@@ import { v272 } from './v272-git-canoniimport { v273 } from './v273-segment-derivations.ts';import { v274 } from './v274-pages-withheld-source-path.ts';import { v275 } from './v275-rls-backfill-unguarded-tables.ts';- import { v276 } from './v276-function-search-path-pg-temp.ts';+ import { v276 } from './v276-persistence-foreground-committed-index.ts';++import { v277 } from './v277-function-search-path-pg-temp.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@@ -552,4 -552,4 +553,5 @@@ export const MIGRATIONS: Migration[] =v274,v275,v276,++ v277,];diff --cc src/core/schema-migrations/v277-function-search-path-pg-temp.tsindex d2c81c7adc,0000000000..2a67e5ca57mode 100644,000000..100644--- a/src/core/schema-migrations/v277-function-search-path-pg-temp.ts+++ b/src/core/schema-migrations/v277-function-search-path-pg-temp.ts@@@ -1,49 -1,0 +1,49 @@@+import type { Migration } from './types.ts';+import type { BrainEngine } from '../engine.ts';+import { migrationStatementTimeoutMs } from '../migration-timeout.ts';+import { isLockTimeoutError } from '../retry-matcher.ts';+import { resolveSchemaLockTimeoutMs, schemaLockBlockedError } from '../postgres-engine/schema-lock-timeout.ts';+import { FUNCTION_SEARCH_PATH_HARDENING_SQL, LEGACY_SEARCH_PATH_SETTINGS } from '../function-search-path.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: every gbrain function that pins a search_path gets pg_temp appended last (src/core/function-search-path.ts),+// so a temp table or view named like a ledger no longer hides it from a guard. ALTER only, no body changes. ALTER+// FUNCTION needs the owner: a function the migrating role does not own is left as it was and named on stderr, and+// doctor's function_search_path check keeps failing with the SQL to run as its owner. One short transaction with the+// migration's statement and lock timeouts.++/** Appends pg_temp where the role may, then names on stderr and returns every function still without it. */+export async function hardenFunctionSearchPaths(engine: BrainEngine, label: string): Promise<string[]> {+ const lockTimeoutMs = resolveSchemaLockTimeoutMs();+ try {+ await engine.transaction(async tx => {+ if (engine.kind === 'postgres') {+ await tx.executeRaw(`SET LOCAL statement_timeout = '${migrationStatementTimeoutMs()}'`);+ await tx.executeRaw(`SET LOCAL lock_timeout = '${lockTimeoutMs}ms'`);+ }- await tx.runMigration(276, FUNCTION_SEARCH_PATH_HARDENING_SQL);++ await tx.runMigration(277, FUNCTION_SEARCH_PATH_HARDENING_SQL);+ });+ } catch (error) {+ if (isLockTimeoutError(error)) throw schemaLockBlockedError({ step: `${label} search_path`, timeoutMs: lockTimeoutMs, sessions: null, sampledDuringWait: false });+ throw error;+ }+ const left = (await engine.executeRaw<{ sig: string }>(+ `SELECT p.oid::regprocedure::text AS sig FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace+ WHERE n.nspname = 'public' AND p.prokind = 'f' AND p.proconfig && $1::text[] ORDER BY 1`, [[...LEGACY_SEARCH_PATH_SETTINGS]])).map(r => r.sig);+ if (left.length > 0) {+ process.stderr.write(` ${label}: ${left.length} function(s) left without pg_temp on their search_path (${left.join(', ')}): `+ + 'ALTER FUNCTION needs the owner. Run gbrain doctor for the SQL to run as that role.\n');+ }+ return left;+}+- export const v276: Migration = {- version: 276,++export const v277: Migration = {++ version: 277,+ name: 'function_search_path_pg_temp',+ idempotent: true,+ transaction: false,+ sql: '',- handler: async engine => { await hardenFunctionSearchPaths(engine, 'v276'); },++ handler: async engine => { await hardenFunctionSearchPaths(engine, 'v277'); },+};diff --cc test/e2e/function-search-path-postgres.test.tsindex d292abacd6,0000000000..b161008783mode 100644,000000..100644--- a/test/e2e/function-search-path-postgres.test.ts+++ b/test/e2e/function-search-path-postgres.test.ts@@@ -1,321 -1,0 +1,321 @@@+/**+ * Every gbrain function that pins a search_path ends it with pg_temp, so a temp table or view named like a purge or+ * withdrawal ledger no longer hides it from the guard that reads it (#7632, src/core/function-search-path.ts).+ *+ * Before, the guards pinned `pg_catalog, public`, which leaves the caller's temporary schema first in the relation+ * search: any session could create an empty temp table named fact_purges (or take_purges, page_purges, fact_withdrawals,+ * page_segment_derivation_purges) and store a purged claim, take, page or derivation again, or save a withdrawn fact+ * active, as the owner or as a non-owner writer. The guards themselves are as on master (SECURITY INVOKER, same bodies,+ * same timing); a writer with no policy on a ledger still reads it empty under its own RLS (#7659), which this file does+ * not cover: its writer has policies on every table.+ * Run: DATABASE_URL=... bun test test/e2e/function-search-path-postgres.test.ts+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import postgres from '#postgres';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { LATEST_VERSION, runMigrations } from '../../src/core/migrate.ts';+import { derivationNeedles } from '../../src/core/page-body/segment-derive.ts';- import { v276 } from '../../src/core/schema-migrations/v276-function-search-path-pg-temp.ts';++import { v277 } from '../../src/core/schema-migrations/v277-function-search-path-pg-temp.ts';++const DATABASE_URL = process.env.DATABASE_URL;+const describeE2E = DATABASE_URL ? describe : describe.skip;++type Sql = ReturnType<typeof postgres>;+type Outcome = { rows: Array<Record<string, unknown>> } | { code: string; message: string };++const PURGED_CLAIM = 'alice-example joined acme-example as cto';+const WITHDRAWN_CLAIM = 'alice-example lives in city-a';+const PURGED_TAKE = 'acme-example will double revenue';+const PURGED_HASH = 'deadbeefcafe00000000000000000001';+const SHA = `decode(repeat('ab', 32), 'hex')`;+const SHADOWED = ['fact_purges', 'fact_withdrawals', 'take_purges', 'page_purges', 'page_segment_derivation_purges'];+const GUARD_TRIGGERS = ['facts_guard_inserted', 'facts_preserve_withdrawal', 'facts_refuse_purged', 'page_segment_derivations_refuse_purging',+ 'pages_refuse_purged', 'takes_refuse_purged'];++const suffix = randomUUID().replaceAll('-', '').slice(0, 12);+const WRITER = `gbrain_test_path_writer_${suffix}`;+const scratch: string[] = [];+const createdRoles: string[] = [];+let admin: Sql | null = null;++function urlFor(name: string): string {+ const url = new URL(DATABASE_URL!);+ url.pathname = `/${name}`;+ return url.toString();+}++async function freshBrain(): Promise<{ url: string; conn: Sql }> {+ assertSafeE2eDatabaseUrl(DATABASE_URL!);+ const name = `gbrain_test_path_${randomUUID().replaceAll('-', '')}`;+ await admin!.unsafe(`CREATE DATABASE ${name}`);+ scratch.push(name);+ const url = urlFor(name);+ const conn = postgres(url, { max: 1, prepare: false, onnotice: () => {} });+ const engine = new PostgresEngine();+ await engine.connect({ database_url: url });+ try { await engine.initSchema(); } finally { await engine.disconnect(); }+ return { url, conn };+}++/** Runs `fn` as `role` in one transaction that is rolled back; each `run` is its own savepoint. */+async function as<T>(conn: Sql, role: string, fn: (run: (sql: string, params?: unknown[]) => Promise<Outcome>) => Promise<T>): Promise<T> {+ const session = await conn.reserve();+ try {+ await session.unsafe('BEGIN');+ await session.unsafe(`SET LOCAL ROLE ${role}`);+ return await fn(async (sql, params) => {+ await session.unsafe('SAVEPOINT attempt');+ try {+ const rows = await session.unsafe(sql, params as never[]);+ await session.unsafe('RELEASE SAVEPOINT attempt');+ return { rows: [...rows] as Array<Record<string, unknown>> };+ } catch (error) {+ await session.unsafe('ROLLBACK TO SAVEPOINT attempt');+ const e = error as { code?: string; message?: string };+ return { code: String(e.code), message: String(e.message) };+ }+ });+ } finally {+ await session.unsafe('ROLLBACK').catch(() => {});+ session.release();+ }+}++const rowsOf = (o: Outcome) => ('rows' in o ? o.rows : (() => { throw new Error(`expected rows, got ${o.code}: ${o.message}`); })());+const outcome = (o: Outcome) => ('code' in o ? o.message.split(':')[0] : `stored ${o.rows.length}`);++async function capturingStderr<T>(fn: () => Promise<T>): Promise<{ value: T; stderr: string }> {+ const write = process.stderr.write.bind(process.stderr);+ let stderr = '';+ process.stderr.write = ((chunk: string | Uint8Array) => { stderr += String(chunk); return true; }) as typeof process.stderr.write;+ try { return { value: await fn(), stderr }; } finally { process.stderr.write = write; }+}++/** SECURITY DEFINER functions, guard trigger timing and every pinned search_path in public. */+async function catalog(c: Sql) {+ const definers = await c.unsafe<Array<{ fn: string }>>(+ `SELECT p.oid::regprocedure::text AS fn FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'public' AND p.prosecdef ORDER BY 1`);+ const triggers = await c.unsafe<Array<{ trigger: string; timing: string }>>(+ `SELECT tgname AS trigger, CASE WHEN (tgtype & 2) <> 0 THEN 'BEFORE' ELSE 'AFTER' END AS timing FROM pg_trigger+ WHERE NOT tgisinternal AND tgname = ANY($1::text[]) ORDER BY 1`, [GUARD_TRIGGERS]);+ const paths = await c.unsafe<Array<{ sig: string; setting: string }>>(+ `SELECT p.oid::regprocedure::text AS sig, s.setting FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace+ CROSS JOIN LATERAL unnest(p.proconfig) AS s(setting) WHERE n.nspname = 'public' AND s.setting LIKE 'search_path=%' ORDER BY 1`);+ return {+ definers: definers.map(d => d.fn),+ triggers: triggers.map(t => ({ trigger: t.trigger, timing: t.timing })),+ pinned: paths.length,+ withoutTemp: paths.filter(p => !p.setting.endsWith(', pg_temp')).map(p => p.sig),+ };+}+- /** Puts a brain back in the shape every brain had before #7632 (no pg_temp on any pinned path), at the version before v276. */++/** Puts a brain back in the shape every brain had before #7632 (no pg_temp on any pinned path), at the version before v277. */+async function rewind(c: Sql): Promise<void> {+ await c.unsafe(`DO $$ DECLARE f RECORD; BEGIN+ FOR f IN SELECT p.oid::regprocedure AS sig, substr(s.setting, 13) AS path FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace+ CROSS JOIN LATERAL unnest(p.proconfig) AS s(setting) WHERE n.nspname = 'public' AND s.setting LIKE 'search_path=%, pg_temp' LOOP+ EXECUTE format('ALTER FUNCTION %s SET search_path = %s', f.sig, left(f.path, -9));+ END LOOP; END $$;- UPDATE config SET value = '${v276.version - 1}' WHERE key = 'version';`);++ UPDATE config SET value = '${v277.version - 1}' WHERE key = 'version';`);+}++describeE2E('a temp table or view named like a ledger hides nothing from the guards (#7632)', () => {+ let conn: Sql;+ let url: string;+ let owner = '';+ const ids: Record<string, number> = {};++ beforeAll(async () => {+ assertSafeE2eDatabaseUrl(DATABASE_URL!);+ admin = postgres(DATABASE_URL!, { max: 1, prepare: false, onnotice: () => {} });+ await admin.unsafe(`CREATE ROLE ${WRITER} NOLOGIN NOSUPERUSER NOBYPASSRLS`);+ createdRoles.push(WRITER);+ ({ url, conn } = await freshBrain());+ [{ owner }] = await conn.unsafe<Array<{ owner: string }>>('SELECT current_user AS owner');+ // A non-owner writer with a policy on every RLS table, ledgers included: the guards refuse it exactly as the owner.+ await conn.unsafe(`GRANT USAGE ON SCHEMA public TO ${WRITER};+ GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO ${WRITER};+ GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO ${WRITER};+ DO $$ DECLARE t RECORD; BEGIN+ FOR t IN SELECT c.oid::regclass AS rel FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') AND c.relrowsecurity LOOP+ EXECUTE format('CREATE POLICY gbrain_test_writer ON %s TO ${WRITER} USING (true) WITH CHECK (true)', t.rel);+ END LOOP; END $$`);+ for (const [key, slug] of [['takes', 'people/alice-example'], ['derived', 'notes/derivation-example']]) {+ const [row] = await conn.unsafe<Array<{ id: number }>>(`INSERT INTO pages (slug, type, title, compiled_truth) VALUES ($1, 'note', $1, 'x') RETURNING id`, [slug]);+ ids[key] = row!.id;+ }+ await conn.unsafe(`INSERT INTO fact_purges (source_id, visibility, subject, fact_hash) VALUES ('default', 'private', '*', gbrain_fact_fingerprint($1))`, [PURGED_CLAIM]);+ await conn.unsafe(`INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ('default', 'private', '*', gbrain_fact_fingerprint($1))`, [WITHDRAWN_CLAIM]);+ await conn.unsafe(`INSERT INTO page_purges (source_id, content_hash, slug) VALUES ('default', $1, 'notes/purged-example')`, [PURGED_HASH]);+ await conn.unsafe(`INSERT INTO take_purges (source_id, subject, claim_hash) VALUES ('default', '*', gbrain_fact_fingerprint($1))`, [PURGED_TAKE]);+ const { needles, patterns } = await derivationNeedles({ executeRaw: (sql: string, params?: unknown[]) => conn.unsafe(sql, params as never[]) } as never, [PURGED_CLAIM]);+ await conn.unsafe(`INSERT INTO page_segment_derivation_purges (request_id, source_id, needles, patterns, page_ids) VALUES ($1::uuid, 'default', $2::text[], $3::text[], $4::int[])`,+ [randomUUID(), needles, patterns, [ids.derived]]);+ }, 300_000);++ afterAll(async () => {+ await conn?.end();+ if (admin) {+ for (const name of scratch) await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`);+ for (const role of createdRoles) await admin.unsafe(`DROP ROLE IF EXISTS ${role}`).catch(() => {});+ await admin.end();+ }+ });++ /** Each guarded write the ledgers should stop, and what became of it. */+ async function guardedWrites(run: (sql: string, params?: unknown[]) => Promise<Outcome>) {+ const fact = outcome(await run(`INSERT INTO facts (fact, source) VALUES ($1, 'probe') RETURNING id`, [PURGED_CLAIM]));+ const page = outcome(await run(`INSERT INTO pages (slug, type, title, compiled_truth, content_hash) VALUES ('notes/again-example', 'note', 't', 'x', $1) RETURNING id`, [PURGED_HASH]));+ const take = outcome(await run(`INSERT INTO takes (page_id, row_num, claim, kind, holder) VALUES ($1, 1, $2, 'take', 'alice-example') RETURNING id`, [ids.takes, PURGED_TAKE]));+ const derivation = outcome(await run(`INSERT INTO page_segment_derivations (page_id, pipeline, occurrence_id, pipeline_version, segment_sha256, context_hash, state, output)+ VALUES ($1, 'links', 1, 1, ${SHA}, ${SHA}, 'done', $2::jsonb) RETURNING 1 AS stored`, [ids.derived, JSON.stringify({ text: PURGED_CLAIM })]));+ const [w] = rowsOf(await run(`INSERT INTO facts (fact, source) VALUES ($1, 'probe') RETURNING id`, [WITHDRAWN_CLAIM]));+ const [stamped] = rowsOf(await run('SELECT expired_at IS NOT NULL AS expired FROM facts WHERE id = $1', [w!.id]));+ return { fact, page, take, derivation, withdrawn: stamped!.expired ? 'expired' : 'active' };+ }+ const REFUSED = { fact: 'purged_content', page: 'purged_content', take: 'purged_content', derivation: 'stored 0', withdrawn: 'expired' };++ test('1. without a shadow, the owner and a non-owner writer have a purged fact, page and take refused, a purged derivation dropped and a withdrawn fact stamped', async () => {+ for (const role of [owner, WRITER]) {+ expect({ role, ...(await as(conn, role, guardedWrites)) }).toEqual({ role, ...REFUSED });+ }+ });++ test('2. a temp table or view named like each ledger hides nothing, for the owner and for a non-owner writer', async () => {+ for (const role of [owner, WRITER]) {+ for (const kind of ['TABLE', 'VIEW']) {+ const result = await as(conn, role, async run => {+ for (const ledger of SHADOWED) {+ rowsOf(await run(kind === 'TABLE' ? `CREATE TEMP TABLE ${ledger} (LIKE public.${ledger})` : `CREATE TEMP VIEW ${ledger} AS SELECT * FROM public.${ledger} WHERE false`));+ }+ return guardedWrites(run);+ });+ expect({ role, kind, ...result }).toEqual({ role, kind, ...REFUSED });+ }+ }+ });++ test('3. after a fresh install: no SECURITY DEFINER function, the guard triggers as on master, every pinned search_path ends in pg_temp', async () => {+ const c = await catalog(conn);+ expect(c.definers).toEqual([]);+ expect(c.triggers).toEqual([+ { trigger: 'facts_guard_inserted', timing: 'AFTER' },+ { trigger: 'facts_preserve_withdrawal', timing: 'BEFORE' },+ { trigger: 'facts_refuse_purged', timing: 'BEFORE' },+ { trigger: 'page_segment_derivations_refuse_purging', timing: 'BEFORE' },+ { trigger: 'pages_refuse_purged', timing: 'BEFORE' },+ { trigger: 'takes_refuse_purged', timing: 'BEFORE' },+ ]);+ expect(c.pinned).toBeGreaterThanOrEqual(35);+ expect(c.withoutTemp).toEqual([]);+ });++ test('4. a brain at the version before, migrated (no schema blob replay), ends the same, and doctor passes only after', async () => {+ const { functionSearchPathProblems } = await import('../../src/commands/doctor/checks/function-search-path.ts');+ const brain = await freshBrain();+ const engine = new PostgresEngine();+ try {+ await rewind(brain.conn);+ const before = await catalog(brain.conn);+ expect(before.withoutTemp.length).toBe(before.pinned);+ await engine.connect({ database_url: brain.url });+ expect((await functionSearchPathProblems(engine)).functions.length).toBe(before.pinned);+ const { value, stderr } = await capturingStderr(() => runMigrations(engine));+ expect(value.current).toBe(LATEST_VERSION);+ expect(stderr).not.toContain('left without pg_temp');+ expect(await catalog(brain.conn)).toEqual(await catalog(conn));+ expect(await functionSearchPathProblems(engine)).toEqual({ functions: [], fix: [] });+ } finally {+ await engine.disconnect();+ await brain.conn.end();+ }+ }, 300_000);++ test('5. a migrating role that owns every table and function but one finishes, names that one, and the printed fix (as its owner) clears it; the migrating role then boots', async () => {+ const { functionSearchPathProblems } = await import('../../src/commands/doctor/checks/function-search-path.ts');+ const brain = await freshBrain();+ const migrator = `gbrain_test_path_migrator_${suffix}`;+ const other = `gbrain_test_path_other_${suffix}`;+ await admin!.unsafe(`CREATE ROLE ${migrator} LOGIN PASSWORD 'migrator' NOSUPERUSER BYPASSRLS; CREATE ROLE ${other} NOLOGIN NOSUPERUSER`);+ createdRoles.push(migrator, other);+ const engine = new PostgresEngine();+ try {+ await rewind(brain.conn);+ await brain.conn.unsafe(`GRANT USAGE, CREATE ON SCHEMA public TO ${migrator};+ DO $$ DECLARE r RECORD; BEGIN+ FOR r IN SELECT c.oid::regclass AS rel FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'v', 'm', 'S')+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = c.oid AND d.deptype IN ('e', 'a', 'i')) LOOP+ EXECUTE format('ALTER TABLE %s OWNER TO ${migrator}', r.rel);+ END LOOP;+ FOR r IN SELECT p.oid::regprocedure AS sig FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace+ WHERE n.nspname = 'public' AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e') LOOP+ EXECUTE format('ALTER ROUTINE %s OWNER TO ${migrator}', r.sig);+ END LOOP; END $$;+ ALTER FUNCTION gbrain_refuse_purged_fact() OWNER TO ${other}`);+ const asMigrator = new URL(brain.url);+ asMigrator.username = migrator;+ asMigrator.password = 'migrator';+ await engine.connect({ database_url: asMigrator.toString() });+ const { value, stderr } = await capturingStderr(() => runMigrations(engine));+ expect(value.current).toBe(LATEST_VERSION);+ expect(stderr).toContain('1 function(s) left without pg_temp on their search_path (gbrain_refuse_purged_fact())');+ expect((await catalog(brain.conn)).withoutTemp).toEqual(['gbrain_refuse_purged_fact()']);+ const { functions, fix } = await functionSearchPathProblems(engine);+ expect({ functions, fix }).toEqual({+ functions: ['gbrain_refuse_purged_fact()'],+ fix: ['ALTER FUNCTION gbrain_refuse_purged_fact() SET search_path = pg_catalog, public, pg_temp;'],+ });+ await brain.conn.unsafe(`SET ROLE ${other}; ${fix.join('\n')} RESET ROLE;`);+ expect(await functionSearchPathProblems(engine)).toEqual({ functions: [], fix: [] });+ await engine.initSchema();+ expect(await functionSearchPathProblems(engine)).toEqual({ functions: [], fix: [] });+ expect((await catalog(brain.conn)).withoutTemp).toEqual([]);+ } finally {+ await engine.disconnect().catch(() => {});+ await brain.conn.end();+ }+ }, 300_000);++ test('6. a brain at the latest version that boots again (schema blob replay, no migration) keeps pg_temp on every pinned path', async () => {+ const engine = new PostgresEngine();+ try {+ await engine.connect({ database_url: url });+ const { value } = await capturingStderr(() => runMigrations(engine));+ expect(value.applied).toBe(0);+ const before = await catalog(conn);+ await engine.initSchema();+ expect(await catalog(conn)).toEqual(before);+ } finally {+ await engine.disconnect();+ }+ }, 300_000);+- test('7. v276 refuses with schema_lock_blocked while another session holds a function it alters, and finishes after', async () => {++ test('7. v277 refuses with schema_lock_blocked while another session holds a function it alters, and finishes after', async () => {+ const { withEnv } = await import('../helpers/with-env.ts');+ const engine = new PostgresEngine();+ const holder = postgres(url, { max: 1, prepare: false, onnotice: () => {} });+ try {+ await conn.unsafe('ALTER FUNCTION gbrain_try_jsonb(text) SET search_path = pg_catalog, public');+ await engine.connect({ database_url: url });+ const session = await holder.reserve();+ try {+ await session.unsafe(`BEGIN; ALTER FUNCTION gbrain_try_jsonb(text) SET statement_timeout = '1min'`);- const error = await withEnv({ GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS: '1' }, () => v276.handler!(engine).then(() => null, (e: unknown) => e));- expect(error).toMatchObject({ code: 'schema_lock_blocked', detail: 'v276 search_path' });++ const error = await withEnv({ GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS: '1' }, () => v277.handler!(engine).then(() => null, (e: unknown) => e));++ expect(error).toMatchObject({ code: 'schema_lock_blocked', detail: 'v277 search_path' });+ expect((await catalog(conn)).withoutTemp).toEqual(['gbrain_try_jsonb(text)']);+ } finally {+ await session.unsafe('ROLLBACK');+ session.release();+ }- await withEnv({ GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS: '1' }, () => v276.handler!(engine));++ await withEnv({ GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS: '1' }, () => v277.handler!(engine));+ expect((await catalog(conn)).withoutTemp).toEqual([]);+ } finally {+ await holder.end();+ await engine.disconnect();+ }+ }, 120_000);+});diff --cc test/fixtures/goldens/migrations/records.jsonindex 96cc898647,87a755dc51..d237e339f9--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@@ -1,6 -1,6 +1,6 @@@{"golden": {-- "count": 271,++ "count": 272,"gaps": [17,18,@@@ -63,7 -62,6 +64,7 @@@"ensureFactsFtsIndex": "95e723314ac30cea2db48e0e167c554ef1fa06df80cae765faa2a080a3a655c2","getFtsLanguage": "0d790b4c4af1f67a2a1bbd59470beb13f434917b381931baf8404a41c5d903db","grantFromRow": "2d0603bb0f964d7e45e04aa76bac54cd4f6f63c91a8d9f028b60b4792bc1695e",- "hardenFunctionSearchPaths": "f952470fa48774cfcca953394e397876028b7e2ea2e2f2b85fcaf1224ab0939e",++ "hardenFunctionSearchPaths": "c6bc786acfef568578879e5d8d943d0029e41fcdd9419f72b6e3018cc19a20db","hnswMaxDimsForType": "a187cdcc520f813b7c39da97ce53da58509232ed9f851627ef41abfe1b68bd26","isLockTimeoutError": "52a3720e1ffb74ce381cc3269f78130c38a89c807e308283ec3d557bae2b89b1","lockTableForAnalyze": "b6e4f173cffd877d2cfd85af813aa694a6d2c32907eaea613c6879800d3a7b44",@@@ -90,7 -88,7 +91,7 @@@"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67","withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"},-- "latest": 276,++ "latest": 277,"records": [{"handler": {@@@ -4449,30 -4447,34 +4450,59 @@@"verify": "absent","version": 275},+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "PERSISTENCE_FOREGROUND_COMMITTED_INDEX",+ "PLANNER_REPAIR_TABLES",+ "analyzeAfterIndexBuild",+ "analyzeDeferred",+ "analyzeYieldingToVacuum",+ "buildIndexOnline",+ "dropInvalidConcurrentIndex",+ "lockTableForAnalyze",+ "migrationNotice",+ "quietMigrationNotices",+ "tableRows"+ ],+ "sha256": "6216cb939d9e686a3386b406051d172d78e86f55edb629f7672b9602926d0484"+ },+ "idempotent": true,+ "name": "persistence_foreground_committed_index",+ "sql": {+ "length": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "sqlFor": "absent",+ "transaction": false,+ "verify": "absent",+ "version": 276++ },+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "FUNCTION_SEARCH_PATH_HARDENING_SQL",+ "LEGACY_SEARCH_PATH_SETTINGS",+ "hardenFunctionSearchPaths",+ "isLockTimeoutError",+ "migrationStatementTimeoutMs",+ "resolveSchemaLockTimeoutMs",+ "schemaLockBlockedError"+ ],- "sha256": "60b6bf855bfd2b0e950999a6c183de96e826507e305b1939eefe5c6c8f343975"++ "sha256": "15a27669929ea32760cb218168dc0cc1500d248b640c7a0185f9ee6792c22e8c"+ },+ "idempotent": true,+ "name": "function_search_path_pg_temp",+ "sql": {+ "length": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "sqlFor": "absent",+ "transaction": false,+ "verify": "absent",- "version": 276++ "version": 277}],"versions": [@@@ -4746,7 -4748,7 +4776,8 @@@273,274,275,-- 276++ 276,++ 277]},"normalizer": "migrations-record-v1"diff --cc test/function-search-path-pglite.test.tsindex 19fccfbac7,0000000000..9a2de81427mode 100644,000000..100644--- a/test/function-search-path-pglite.test.ts+++ b/test/function-search-path-pglite.test.ts@@@ -1,69 -1,0 +1,69 @@@+/**+ * #7632 on PGLite: every gbrain function that pins a search_path ends it with pg_temp, so a temp table named like a+ * purge or withdrawal ledger hides nothing from the guard that reads it. PGLite has one role, the owner, and before the+ * change its guards read the empty temp table and stored the purged write. The guards are otherwise as on master.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';++const PURGED_CLAIM = 'alice-example joined acme-example as cto';+const WITHDRAWN_CLAIM = 'alice-example lives in city-a';+const PURGED_TAKE = 'acme-example will double revenue';+const PURGED_HASH = 'deadbeefcafe00000000000000000002';+const SHADOWED = ['fact_purges', 'fact_withdrawals', 'take_purges', 'page_purges'];++describe('function search_path ends in pg_temp on PGLite (#7632)', () => {+ let engine: PGLiteEngine;+ let takesPage = 0;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const [page] = await engine.executeRaw<{ id: number }>(`INSERT INTO pages (slug, type, title, compiled_truth) VALUES ('people/alice-example', 'person', 'a', 'x') RETURNING id`);+ takesPage = page!.id;+ await engine.executeRaw(`INSERT INTO fact_purges (source_id, visibility, subject, fact_hash) VALUES ('default', 'private', '*', gbrain_fact_fingerprint($1))`, [PURGED_CLAIM]);+ await engine.executeRaw(`INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ('default', 'private', '*', gbrain_fact_fingerprint($1))`, [WITHDRAWN_CLAIM]);+ await engine.executeRaw(`INSERT INTO page_purges (source_id, content_hash, slug) VALUES ('default', $1, 'notes/purged-example')`, [PURGED_HASH]);+ await engine.executeRaw(`INSERT INTO take_purges (source_id, subject, claim_hash) VALUES ('default', '*', gbrain_fact_fingerprint($1))`, [PURGED_TAKE]);+ }, 120_000);+ afterAll(async () => { await engine?.disconnect(); });++ test('every function that pins a search_path ends it with pg_temp, and none is SECURITY DEFINER', async () => {+ const rows = await engine.executeRaw<{ sig: string; setting: string; secdef: boolean }>(+ `SELECT p.oid::regprocedure::text AS sig, s.setting, p.prosecdef AS secdef FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace+ CROSS JOIN LATERAL unnest(p.proconfig) AS s(setting) WHERE n.nspname = 'public' AND s.setting LIKE 'search_path=%' ORDER BY 1`);+ expect(rows.length).toBeGreaterThanOrEqual(35);+ expect(rows.filter(r => !r.setting.endsWith(', pg_temp') || r.secdef).map(r => r.sig)).toEqual([]);+ });++ test('temp tables named like the ledgers hide nothing: purged writes are refused and a withdrawn fact is stamped', async () => {+ const attempt = (sql: string, params: unknown[]) => engine.executeRaw(sql, params).then(() => 'stored', (e: Error) => e.message.split(':')[0]);+ try {+ for (const ledger of SHADOWED) await engine.executeRaw(`CREATE TEMP TABLE ${ledger} (LIKE public.${ledger})`);+ const fact = await attempt(`INSERT INTO facts (fact, source) VALUES ($1, 'probe')`, [PURGED_CLAIM]);+ const page = await attempt(`INSERT INTO pages (slug, type, title, compiled_truth, content_hash) VALUES ('notes/again-example', 'note', 't', 'x', $1)`, [PURGED_HASH]);+ const take = await attempt(`INSERT INTO takes (page_id, row_num, claim, kind, holder) VALUES ($1, 1, $2, 'take', 'alice-example')`, [takesPage, PURGED_TAKE]);+ const [w] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts (fact, source) VALUES ($1, 'probe') RETURNING id`, [WITHDRAWN_CLAIM]);+ const [stamped] = await engine.executeRaw<{ expired: boolean }>('SELECT expired_at IS NOT NULL AS expired FROM facts WHERE id = $1', [w!.id]);+ expect({ fact, page, take, withdrawn: stamped!.expired ? 'expired' : 'active' })+ .toEqual({ fact: 'purged_content', page: 'purged_content', take: 'purged_content', withdrawn: 'expired' });+ } finally {+ for (const ledger of SHADOWED) await engine.executeRaw(`DROP TABLE IF EXISTS pg_temp.${ledger}`);+ }+ });++ test('a procedure in public pinning the old search_path is left alone: boots and the migration still succeed, and doctor does not name it', async () => {+ const { functionSearchPathProblems } = await import('../src/commands/doctor/checks/function-search-path.ts');- const { v276 } = await import('../src/core/schema-migrations/v276-function-search-path-pg-temp.ts');++ const { v277 } = await import('../src/core/schema-migrations/v277-function-search-path-pg-temp.ts');+ await engine.executeRaw(`CREATE PROCEDURE public.proc_example() LANGUAGE plpgsql SET search_path = pg_catalog, public AS $p$ BEGIN END $p$`);+ try {+ await engine.initSchema();- await v276.handler!(engine);++ await v277.handler!(engine);+ expect(await functionSearchPathProblems(engine)).toEqual({ functions: [], fix: [] });+ const [proc] = await engine.executeRaw<{ config: string[] }>(`SELECT proconfig AS config FROM pg_proc WHERE proname = 'proc_example'`);+ expect(proc!.config).toEqual(['search_path=pg_catalog, public']);+ } finally {+ await engine.executeRaw('DROP PROCEDURE IF EXISTS public.proc_example()');+ }+ }, 120_000);+});