Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search_path): definitions pin pg_temp; quieter, bounded end-of-run hardening; doctor fix contract (#7785, #7688)

garrytan47c6a9109d21
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index e4a25c8d82..c216676906 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -398,18 +398,26 @@ tables) under that role's RLS. Every gbrain function that pins a search_path end
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, 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`).
-
+the ledgers of the sources it writes (gbrain#7659 tracks the fix). 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
+putting `pg_temp` back (`hardenFunctionSearchPaths` in `src/core/function-search-path.ts`), and the
+schema blob's generated hardening region must stay its last statement. Where the migrating role
+does not own a function, the run that applies migrations names it on stderr and leaves it;
+`gbrain doctor` (`function_search_path`) prints the schema-qualified `ALTER FUNCTION` to run as its
+owner, or `gbrain apply-migrations --yes` below v277 ([function search path](guides/troubleshooting.md#function-search-path);
+`test/e2e/function-search-path-postgres.test.ts`).
+
+<a id="writer-protocol-fences"></a>
**Writer-protocol fences.** The managed-writer guard, the persistence protocol floor, protocol
activation and the Git-canonical source counter also run as the writing role and read their state
under its RLS. Since migration v278 (#7636) they fail closed: a role that cannot see the
`persistence_brain` row is refused with `writer_coordinator_required` (relationship
`unreadable_state`) on every guarded write, managed brain or not, instead of being treated as
-unmanaged. On a managed brain the same refusal covers a hidden `git_canonical_brain` row or
-Git-canonical source row (for a writer without the git protocol) and a hidden page row behind a tag,
+unmanaged. On a managed brain the same refusal covers, for a writer without the git protocol, a
+hidden `git_canonical_brain` row and, while the brain has any Git-canonical source, a hidden
+target or old source row whether or not that source is Git-canonical; and a hidden page row behind a tag,
timeline entry or take. Protocol activation (row-level security on `sources`, `persistence_requests`,
`persistence_effects`, `persistence_worktrees` or `persistence_source_bindings`) and a change to
which sources are Git-canonical (row-level security on `sources`) refuse any role it applies to,
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index bc221f067d..74502add22 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -29,7 +29,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)` — cheap cross-source enumeration instead of a `getAllSlugs()→getPage(slug)` N+1 (which would silently default to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. `traversePathsDetailed(slug, opts?)` returns `{ paths: GraphPath[], truncated }` — the final SELECT of the path-enumerating recursive CTE is bounded at `TRAVERSE_PATH_ROW_CAP + 1` rows on both engines (the probe row signals overflow; `ORDER BY depth` means the deepest edges are dropped, so a truncated result is still the complete shallow neighbourhood; the cap counts raw rows before the in-memory edge dedup, so `paths.length` alone cannot reveal truncation) and `traversePaths` is its `.paths` projection. Each `GraphPath` carries `from_source_id`/`to_source_id` and the edge dedup keys on page ids; each `traverseGraph` `GraphNode` carries `source_id` (DISTINCT per page), so the same slug in two sources stays two edges or nodes. `resolveSlugWithAliasDetailed(slug, sourceOrSources)` returns `{ canonical_slug, source_id } | null` — the winning alias row AND its owning source under the same scope/precedence rules (`ORDER BY array_position(scope, source_id), id`; null when nothing matches or the `slug_aliases` table does not exist yet); `resolveSlugWithAlias` is its canonical-slug projection (falls back to the input slug). A consumer that goes on to read the canonical page must scope that read to `source_id`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks`/`getChunks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); `getChunkPage(slug, {fromIndex, limit, ...scope})` is get_chunks' paged read: the same predicate as `getChunks`, one count/max query plus the chunk_index range [fromIndex, fromIndex + limit) (a range, so a slug matching a page in two federated sources never splits an index across calls); `getChunks` falls back to the `'default'` source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (`getChunksWithEmbeddings` stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise<GraphNode[]>` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence and offsetting `row_num` past the canonical page's current MAX(row_num) (all rows incl. expired — the partial `idx_facts_fence_key` only excludes NULL; NULL stays NULL) so overlapping fence rows never collide; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise<string[]>` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. `softDeletePages(slugs, {sourceId}): Promise<string[]>` is the batch soft-delete twin, mirroring `deletePages`' contract exactly (required `sourceId`, `> DELETE_BATCH_SIZE` throws, empty input short-circuits, caller owns chunking + decompose-to-one-element-batches on failure): one `UPDATE … SET deleted_at = now() … AND deleted_at IS NULL … RETURNING slug` round-trip returning only the slugs that actually flipped active→soft-deleted — the `deleted_at IS NULL` predicate is load-bearing so a re-run never refreshes an already-soft-deleted row's 72h purge clock — and NOTHING cascades (chunks/links/timeline stay behind the read-side `deleted_at` filters; the autopilot purge phase hard-deletes after 72h; a re-import within the window revives via `putPage`'s upsert; `deletePage`/`deletePages` remain the purge/teardown primitives). `getStats(opts?)` / `getHealth(opts?)` take an optional `{sourceId?, sourceIds?}` scope (same shape as `sourceScopeOpts` output): omitted = brain-wide; scoped = EVERY counter/coverage/degree confines to the grant, including derived-table counts via their page joins, and link-derived numbers count only edges with BOTH endpoints in scope — so an excluded source's numbers can't be recovered by subtraction. Consumer is the remote-caller ladder in `src/core/ops/admin.ts`; `getHealth` is a one-line delegation to `src/core/engine-sql/health.ts`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number>` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional `findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>` (identity precedence is content_hash OR frontmatter->>'id', both with `deleted_at IS NULL`); (2) `resolveSlugs(partial, opts?)` extended with `{sourceId?, sourceIds?}` so the MCP fuzzy `get_page` path scopes by source (field names match `sourceScopeOpts(ctx)` output so handlers spread directly; no opts gives the unscoped behavior). Plus a stable tiebreaker `ORDER BY score DESC, page_id ASC, chunk_id ASC` in `searchVector` in both engines: on a score tie (basis-vector eval fixtures) older `page_id` wins, so a new index on `pages` cannot flip ranking on tied scores.
- `src/core/migrate-pending.ts` — `hasPendingMigrations` (re-exported by `migrate.ts`): one `version` read against the generated `schema-migrations/latest.generated.ts`, so a connect never loads the migration registry.
-- `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, `buildIndexOnline` with its best-effort `analyzeAfterIndexBuild` (a failed ANALYZE warns with the repair command and never fails the build of a valid index), the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill-schema.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, each update grants only its rows' sources to the managed writer guard (`gbrain.write_sources`, transaction-local), and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. With the schema version current no ordinary command runs a pass, so `gbrain apply-migrations --force-schema` (`REVISION_BACKFILL_RESUME_COMMAND`) resumes it; `readRevisionBackfillStatus` feeds doctor `revision_backfill` (`src/commands/doctor/checks/revision-backfill.ts`: ok when NOT NULL, warn with the pending count, the failed rows by page and the resume command, or the `repair orphan-children` preview when only spent rows remain). The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`).
+- `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, `buildIndexOnline` with its best-effort `analyzeAfterIndexBuild` (a failed ANALYZE warns with the repair command and never fails the build of a valid index), the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill-schema.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, each update grants only its rows' sources to the managed writer guard (`gbrain.write_sources`, transaction-local), and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. With the schema version current no ordinary command runs a pass, so `gbrain apply-migrations --force-schema` (`REVISION_BACKFILL_RESUME_COMMAND`) resumes it; `readRevisionBackfillStatus` feeds doctor `revision_backfill` (`src/commands/doctor/checks/revision-backfill.ts`: ok when NOT NULL, warn with the pending count, the failed rows by page and the resume command, or the `repair orphan-children` preview when only spent rows remain). The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`). Every pass also ends by putting `pg_temp` back on gbrain functions' search_path (`hardenFunctionSearchPaths`, best-effort; skipped after a lock refusal so the run does not wait a second `lock_timeout`; functions another role owns are named only on passes that applied migrations, #7688).
+- `src/core/function-search-path.ts` — #7632 search_path hardening: `PINNED_FUNCTION_NAMES` (every gbrain function with a pinned search_path; `scripts/check-search-path.sh` fails one missing from it or a pinned path not ending in `pg_temp`), `FUNCTION_SEARCH_PATH_HARDENING_SQL` (the schema blob's last statement), and `hardenFunctionSearchPaths` (v277 and the end of every migration run: one transaction under the migration timeouts, a pg_proc row lock it cannot take becomes `schema_lock_blocked`, a concurrent pg_proc update is retried, returns the functions left or null when listing them failed). Doctor check: `src/commands/doctor/checks/function-search-path.ts` (`function_search_path`: names any pinned function whose path does not end in `pg_temp`, a missing path included; the fix is `gbrain apply-migrations --yes` below v277, else a host-admin schema-qualified `ALTER FUNCTION`).
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The runner (ordering, retry, verify, repair-handler hooks and the static helper imports engine-live paths require) has a plain ratchet ceiling; migrations no longer live in this file.
- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the squatted npm name; README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + `vector`/`pg_trgm` extensions via `PGliteOptions` (the tarballs are gunzipped and untarred in memory, and `lazyExtension` writes their files into PGLite's filesystem in the extension's `init`, after the backend starts, so postgres loads each `.so` on first use instead of PGLite preloading both on every open, about 30 ms; `readExtensionFiles` refuses any entry that is not a file or directory), plus `startParams` = PGLite's defaults then `PGLITE_START_PARAM_OVERRIDES` (no parallel maintenance workers, `max_wal_size=8GB`: an HNSW build fits the WASM heap, its WAL under the checkpoint trigger). `withSharedBuffers` appends `-c shared_buffers=<size>` when `EngineConfig.pglite_shared_buffers` is set: `connectEngineForServe` sets `ONE_SHOT_READ_SHARED_BUFFERS` (32MB) for a one-shot read-scope CLI process (shared op path, `gbrain call <read op>`, `search`, `sources list`), because the backend zero-fills the whole pool at start (about 55 ms for the 128MB default) and one read never fills it; serve and writes keep the default. The package itself is a type-only import plus one lazy `await import('@electric-sql/pglite')` inside `build()` after the resolver ran: the module must load without the package, or a missing install dies with the raw "Cannot find module" before the tier-3 sentence (#6512). Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.test.ts` (`bun add -g`-shaped hoisted layout, spawned with `bun --no-install` so script auto-install cannot mask a missing package).
diff --git a/docs/guides/rls-and-you.md b/docs/guides/rls-and-you.md
index 7b93bf3546..3a546f87d1 100644
--- a/docs/guides/rls-and-you.md
+++ b/docs/guides/rls-and-you.md
@@ -113,7 +113,7 @@ psql as a BYPASSRLS role (e.g. `postgres`):
```sql
CREATE OR REPLACE FUNCTION auto_enable_rls()
-RETURNS event_trigger AS $$
+RETURNS event_trigger SET search_path = pg_catalog, public, pg_temp AS $$
DECLARE
obj record;
BEGIN
@@ -133,8 +133,9 @@ CREATE EVENT TRIGGER auto_rls_on_create_table
EXECUTE FUNCTION auto_enable_rls();
```
-(This is the same DDL migration v35 runs — the canonical copy lives in
-`src/core/schema-migrations/v035-auto-rls-event-trigger.ts`, one file per schema migration. There's no CLI shortcut:
+(This is the DDL migration v35 runs, with the `SET search_path` later migrations add: keep that clause when you
+paste it, or doctor's `function_search_path` check fails until you run the `ALTER FUNCTION` it prints. The
+original lives in `src/core/schema-migrations/v035-auto-rls-event-trigger.ts`, one file per schema migration. There's no CLI shortcut:
`gbrain apply-migrations --force-retry` targets the vX.Y.Z orchestrator
registry, not numeric schema migrations like v35.)
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index bbf41baa20..49cf42ae87 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -83,6 +83,7 @@
| Writes fail with `connection_inherited_read_only` (SQLSTATE 25006) | [reset the pooler's server connections, stop session-level `SET`, check role defaults](write-refusals.md#connection_inherited_read_only) | brain host | none | `gbrain doctor --json` |
| [Doctor warns `persistence_session_timeouts` (`session_timeouts_not_applied`)](#session-timeouts-not-applied) | `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` on the database, or accept it: preparation reads carry their own bound | brain host | none (a role default; `destructive` only in that it changes a server setting) | `gbrain doctor --only persistence_session_timeouts --json` |
| `gbrain init` or `gbrain upgrade` stops with `schema_lock_blocked` naming a pid (or, before #5227, sat in `wait_event_type=Lock` with no output) | let the named session finish, or with the user's agreement end it on the database host: `SELECT pg_terminate_backend(<pid>)`; then rerun the same command ([ENGINES.md](../ENGINES.md#schema-lock-blocked)) | brain host, after the user agrees | `destructive` when it ends another session | the rerun completes; `gbrain doctor --json` shows the schema at head |
+| Doctor `function_search_path` fails: a gbrain function's search_path does not end in `pg_temp` | follow the check's `fix`: below schema v277 it is `gbrain apply-migrations --yes`; past it, run the printed `ALTER FUNCTION` statements as the role that owns each function ([function search path](#function-search-path)) | agent below v277; brain host past it | none | `gbrain doctor --only function_search_path --json` |
| [`queue_capacity`, `persistence_capacity` or `persistence_request_growth`](#write-capacity) | run the printed `gbrain config set persistence.limits.<limit> <value>` | brain host | none | `gbrain doctor --only persistence_capacity,persistence_request_growth --json` |
| [`dream_paid_loop`, or dream keeps skipping one transcript](#dream-paid-loop) | fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'` | agent, after the user agrees | `paid` (the key is retried) | `gbrain doctor --only dream_paid_loop --json` |
| [A page exists (`gbrain get <slug>` returns it) but search never finds text from it](memory-boundaries.md#large-pages) | `gbrain reindex --oversized --dry-run --json` lists pages stored before the upgrade with a size-based `embed_skip` marker (without `--dry-run` it keyword-indexes them, free); a page above an operator-lowered `content_sanity.bytes_block` keeps its marker until it is raised; a page the content-quality gate quarantined shows in `gbrain quarantine list` (`gbrain quarantine clear <slug>` re-checks it once the user agrees); a file over the 24 MiB page ceiling was never stored ([`file_too_large`](write-refusals.md#file_too_large)). Its chunks waiting for embedding approval (doctor `partial_embedding`) are a paid step: `gbrain embed --held --dry-run`, then `gbrain embed --held --source <id> --max-usd <N>` as printed | agent for the reindex; the user decides embedding spend, a `bytes_block` change and a quarantine clear | none for the reindex; `paid` for `gbrain embed` | `gbrain reindex --oversized --dry-run --json` lists nothing; `gbrain search "<phrase from deep in the page>"` returns the page |
@@ -895,3 +896,22 @@ decides what to undo: the folder's new `.git` directory and the pages imported
from it are theirs to review before anything is removed.
Verify with `gbrain sources status <id> --json` and
`gbrain doctor --only default_source_local_path --json`.
+
+## Function search path
+
+<a id="function-search-path"></a>
+
+Every gbrain function that pins a `search_path` ends it with `pg_temp`, so a session's temporary table or view named
+like a purge or withdrawal ledger cannot hide that ledger from the guard that reads it (#7632). Migration v277 and the
+end of every migration run append it to each function the migrating role owns; doctor's `function_search_path` check
+names any function still without it, including one re-created by hand without its `SET search_path` clause.
+
+- **Below schema v277**, the check's fix is `gbrain apply-migrations --yes`, which runs v277. Check again afterwards:
+ what is left is owned by another role.
+- **A function another role owns** cannot be altered by the migrating role, so the migration leaves it and names it
+ on stderr during runs that apply migrations. Run the `ALTER FUNCTION public.<function>(<args>) SET search_path = …,
+ pg_temp;` statements the check prints (also in its `details.sql`) on the database host as the role that owns each
+ function, for example with `psql -c "…"` connected as that role. `ALTER FUNCTION … SET` changes neither the owner
+ nor the body, so the next boot's `CREATE OR REPLACE` still succeeds.
+
+Verify with `gbrain doctor --only function_search_path --json`.
diff --git a/llms-full.txt b/llms-full.txt
index b8356e3356..f637feb59f 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5923,18 +5923,26 @@ tables) under that role's RLS. Every gbrain function that pins a search_path end
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, 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`).
-
+the ledgers of the sources it writes (gbrain#7659 tracks the fix). 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
+putting `pg_temp` back (`hardenFunctionSearchPaths` in `src/core/function-search-path.ts`), and the
+schema blob's generated hardening region must stay its last statement. Where the migrating role
+does not own a function, the run that applies migrations names it on stderr and leaves it;
+`gbrain doctor` (`function_search_path`) prints the schema-qualified `ALTER FUNCTION` to run as its
+owner, or `gbrain apply-migrations --yes` below v277 ([function search path](guides/troubleshooting.md#function-search-path);
+`test/e2e/function-search-path-postgres.test.ts`).
+
+<a id="writer-protocol-fences"></a>
**Writer-protocol fences.** The managed-writer guard, the persistence protocol floor, protocol
activation and the Git-canonical source counter also run as the writing role and read their state
under its RLS. Since migration v278 (#7636) they fail closed: a role that cannot see the
`persistence_brain` row is refused with `writer_coordinator_required` (relationship
`unreadable_state`) on every guarded write, managed brain or not, instead of being treated as
-unmanaged. On a managed brain the same refusal covers a hidden `git_canonical_brain` row or
-Git-canonical source row (for a writer without the git protocol) and a hidden page row behind a tag,
+unmanaged. On a managed brain the same refusal covers, for a writer without the git protocol, a
+hidden `git_canonical_brain` row and, while the brain has any Git-canonical source, a hidden
+target or old source row whether or not that source is Git-canonical; and a hidden page row behind a tag,
timeline entry or take. Protocol activation (row-level security on `sources`, `persistence_requests`,
`persistence_effects`, `persistence_worktrees` or `persistence_source_bindings`) and a change to
which sources are Git-canonical (row-level security on `sources`) refuse any role it applies to,
@@ -10099,6 +10107,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
| Writes fail with `connection_inherited_read_only` (SQLSTATE 25006) | [reset the pooler's server connections, stop session-level `SET`, check role defaults](write-refusals.md#connection_inherited_read_only) | brain host | none | `gbrain doctor --json` |
| [Doctor warns `persistence_session_timeouts` (`session_timeouts_not_applied`)](#session-timeouts-not-applied) | `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` on the database, or accept it: preparation reads carry their own bound | brain host | none (a role default; `destructive` only in that it changes a server setting) | `gbrain doctor --only persistence_session_timeouts --json` |
| `gbrain init` or `gbrain upgrade` stops with `schema_lock_blocked` naming a pid (or, before #5227, sat in `wait_event_type=Lock` with no output) | let the named session finish, or with the user's agreement end it on the database host: `SELECT pg_terminate_backend(<pid>)`; then rerun the same command ([ENGINES.md](../ENGINES.md#schema-lock-blocked)) | brain host, after the user agrees | `destructive` when it ends another session | the rerun completes; `gbrain doctor --json` shows the schema at head |
+| Doctor `function_search_path` fails: a gbrain function's search_path does not end in `pg_temp` | follow the check's `fix`: below schema v277 it is `gbrain apply-migrations --yes`; past it, run the printed `ALTER FUNCTION` statements as the role that owns each function ([function search path](#function-search-path)) | agent below v277; brain host past it | none | `gbrain doctor --only function_search_path --json` |
| [`queue_capacity`, `persistence_capacity` or `persistence_request_growth`](#write-capacity) | run the printed `gbrain config set persistence.limits.<limit> <value>` | brain host | none | `gbrain doctor --only persistence_capacity,persistence_request_growth --json` |
| [`dream_paid_loop`, or dream keeps skipping one transcript](#dream-paid-loop) | fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'` | agent, after the user agrees | `paid` (the key is retried) | `gbrain doctor --only dream_paid_loop --json` |
| [A page exists (`gbrain get <slug>` returns it) but search never finds text from it](memory-boundaries.md#large-pages) | `gbrain reindex --oversized --dry-run --json` lists pages stored before the upgrade with a size-based `embed_skip` marker (without `--dry-run` it keyword-indexes them, free); a page above an operator-lowered `content_sanity.bytes_block` keeps its marker until it is raised; a page the content-quality gate quarantined shows in `gbrain quarantine list` (`gbrain quarantine clear <slug>` re-checks it once the user agrees); a file over the 24 MiB page ceiling was never stored ([`file_too_large`](write-refusals.md#file_too_large)). Its chunks waiting for embedding approval (doctor `partial_embedding`) are a paid step: `gbrain embed --held --dry-run`, then `gbrain embed --held --source <id> --max-usd <N>` as printed | agent for the reindex; the user decides embedding spend, a `bytes_block` change and a quarantine clear | none for the reindex; `paid` for `gbrain embed` | `gbrain reindex --oversized --dry-run --json` lists nothing; `gbrain search "<phrase from deep in the page>"` returns the page |
@@ -10912,6 +10921,25 @@ from it are theirs to review before anything is removed.
Verify with `gbrain sources status <id> --json` and
`gbrain doctor --only default_source_local_path --json`.
+## Function search path
+
+<a id="function-search-path"></a>
+
+Every gbrain function that pins a `search_path` ends it with `pg_temp`, so a session's temporary table or view named
+like a purge or withdrawal ledger cannot hide that ledger from the guard that reads it (#7632). Migration v277 and the
+end of every migration run append it to each function the migrating role owns; doctor's `function_search_path` check
+names any function still without it, including one re-created by hand without its `SET search_path` clause.
+
+- **Below schema v277**, the check's fix is `gbrain apply-migrations --yes`, which runs v277. Check again afterwards:
+ what is left is owned by another role.
+- **A function another role owns** cannot be altered by the migrating role, so the migration leaves it and names it
+ on stderr during runs that apply migrations. Run the `ALTER FUNCTION public.<function>(<args>) SET search_path = …,
+ pg_temp;` statements the check prints (also in its `details.sql`) on the database host as the role that owns each
+ function, for example with `psql -c "…"` connected as that role. `ALTER FUNCTION … SET` changes neither the owner
+ nor the body, so the next boot's `CREATE OR REPLACE` still succeeds.
+
+Verify with `gbrain doctor --only function_search_path --json`.
+
---
# Migrations
diff --git a/scripts/check-search-path.sh b/scripts/check-search-path.sh
index a263196a92..5488b6b8c1 100755
--- a/scripts/check-search-path.sh
+++ b/scripts/check-search-path.sh
@@ -49,10 +49,41 @@ if [ -n "$BAD" ]; then
echo "ERROR: plpgsql function(s) missing SET search_path:"
echo "$BAD"
echo
- echo "Add 'SET search_path = pg_catalog, public' to the function header, e.g.:"
- echo " CREATE OR REPLACE FUNCTION foo() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$fn\$"
+ echo "Add 'SET search_path = pg_catalog, public, pg_temp' to the function header, e.g.:"
+ echo " CREATE OR REPLACE FUNCTION foo() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$fn\$"
echo "See #1647 / #171 / #5190."
exit 1
fi
-echo "OK: every plpgsql function definition under src/ pins search_path"
+# #7785 / #7688: a pinned search_path ends in pg_temp (otherwise each replay of the definition drops what v277 and the
+# end-of-run hardening append, and a session's temp table named like a ledger hides it from the guard), and every
+# function that pins one is in PINNED_FUNCTION_NAMES (src/core/function-search-path.ts), which the hardening and the
+# doctor check read. The allowlist half runs only when that file exists (fixture trees have none).
+ALLOWLIST_FILE="src/core/function-search-path.ts"
+ALLOWED=""
+if [ -f "$ALLOWLIST_FILE" ]; then
+ ALLOWED="$(perl -0777 -ne 'print join(" ", /'"'"'(\w+)'"'"'/g) if /PINNED_FUNCTION_NAMES\s*=\s*\[(.*?)\]/s && ($_ = $1)' "$ALLOWLIST_FILE")"
+fi
+PATH_BAD="$(printf '%s\n' "$FILES" | GBRAIN_ALLOWED="$ALLOWED" xargs perl -0777 -ne '
+ BEGIN { %allowed = map { $_ => 1 } split / /, ($ENV{GBRAIN_ALLOWED} // ""); $check = length($ENV{GBRAIN_ALLOWED} // ""); }
+ while (/CREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION\s+([\w."]+)\s*\((.*?)\)\s+RETURNS\s+(.*?)\bAS\s+\$(\w*)\$/gis) {
+ my ($name, $rest, $start) = ($1, $3, $-[0]);
+ next unless $rest =~ /search_path\s*(?:=|TO)\s*((?:[\w"]+\s*,\s*)*[\w"]+)/i;
+ my $path = $1;
+ (my $bare = $name) =~ s/^(?:"?public"?\.)?"?([^"]+)"?$/$1/;
+ my $line = 1 + (substr($_, 0, $start) =~ tr/\n//);
+ print "$ARGV:$line: $bare (search_path = $path does not end in pg_temp)\n" unless $path =~ /(?:^|,)\s*pg_temp$/i;
+ print "$ARGV:$line: $bare (not in PINNED_FUNCTION_NAMES)\n" if $check && !$allowed{$bare};
+ }
+' 2>/dev/null || true)"
+
+if [ -n "$PATH_BAD" ]; then
+ echo "ERROR: pinned search_path problem(s):"
+ echo "$PATH_BAD"
+ echo
+ echo "End every pinned search_path with pg_temp, e.g. 'SET search_path = pg_catalog, public, pg_temp', and add each"
+ echo "function that pins one to PINNED_FUNCTION_NAMES in $ALLOWLIST_FILE. See #7632 / #7785."
+ exit 1
+fi
+
+echo "OK: every plpgsql function definition under src/ pins search_path, ending in pg_temp"
diff --git a/src/commands/doctor/checks/function-search-path.ts b/src/commands/doctor/checks/function-search-path.ts
index d23a5f5943..718afbfa24 100644
--- a/src/commands/doctor/checks/function-search-path.ts
+++ b/src/commands/doctor/checks/function-search-path.ts
@@ -1,52 +1,70 @@
/**
- * function_search_path doctor check (#7632): every gbrain function that pins a search_path ends it with pg_temp.
+ * function_search_path doctor check (#7632): every gbrain function (PINNED_FUNCTION_NAMES) ends its pinned search_path
+ * 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 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.
+ * fact_withdrawals) hides that ledger from the guard that reads it, and a purged or withdrawn write goes through. A
+ * function with no search_path at all (re-created by hand without its SET clause) is named too. Below migration v277
+ * the fix is the migration; at or past it, the fix is one schema-qualified ALTER FUNCTION per function, run as the role
+ * that owns it. 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 { PINNED_FUNCTION_NAMES, LEGACY_SEARCH_PATH_SETTINGS } from '../../../core/function-search-path.ts';
+import { agentFix, checkError, doctorVerify } from '../check-fix.ts';
+import { PINNED_FUNCTION_NAMES, PINNED_PATH_SQL } from '../../../core/function-search-path.ts';
+import { v277 } from '../../../core/schema-migrations/v277-function-search-path-pg-temp.ts';
-/** The gbrain functions whose pinned search_path lacks a trailing pg_temp, and the ALTER that fixes each. */
+const NAME = 'function_search_path';
+const DOCS = 'docs/guides/troubleshooting.md#function-search-path';
+
+/** The gbrain functions whose search_path does not end in pg_temp, and the schema-qualified 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[]) AND p.proname = ANY($2::text[]) ORDER BY 1`,
- [[...LEGACY_SEARCH_PATH_SETTINGS], [...PINNED_FUNCTION_NAMES]]);
+ const rows = await engine.executeRaw<{ sig: string; qualified: string; path: string | null }>(
+ `SELECT p.oid::regprocedure::text AS sig,
+ quote_ident(n.nspname) || '.' || quote_ident(p.proname) || '(' || pg_get_function_identity_arguments(p.oid) || ')' AS qualified,
+ (SELECT ${PINNED_PATH_SQL} FROM unnest(p.proconfig) AS c(setting) WHERE c.setting LIKE 'search_path=%' LIMIT 1) AS path
+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
+ WHERE n.nspname = 'public' AND p.prokind = 'f' AND p.proname = ANY($1::text[]) ORDER BY 1`,
+ [[...PINNED_FUNCTION_NAMES]]);
+ const bad = rows.filter(r => r.path === null || !/(^|,)\s*pg_temp$/i.test(r.path));
return {
- functions: rows.map(r => r.sig),
- fix: rows.map(r => `ALTER FUNCTION ${r.sig} SET search_path = ${r.path}, pg_temp;`),
+ functions: bad.map(r => r.sig),
+ fix: bad.map(r => `ALTER FUNCTION ${r.qualified} SET search_path = ${r.path ?? 'pg_catalog, public'}, pg_temp;`),
};
}
async function runFunctionSearchPath(ctx: DoctorContext): Promise<Check[]> {
const engine = connectedEngine(ctx);
- const checks: Check[] = [];
- ctx.progress.heartbeat('function_search_path');
+ ctx.progress.heartbeat(NAME);
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 v277 did the ones the migrating role owned): ${fix.join(' ')}`,
- });
+ return [{ name: NAME, status: 'ok', message: 'Every gbrain function that pins a search_path ends it with pg_temp' }];
+ }
+ const risk = `${functions.length} function(s) do not end their search_path with pg_temp (${functions.join(', ')}), so a temp table or view named like a purge or withdrawal ledger hides it from the guard that reads it.`;
+ const version = parseInt(await engine.getConfig('version') || '0', 10);
+ if (version < v277.version) {
+ return [{
+ name: NAME, status: 'fail',
+ message: `${risk} This brain is at schema v${version}, below migration v${v277.version}, which appends pg_temp to every one its role owns: run gbrain apply-migrations --yes first, then check again.`,
+ fix: agentFix(['gbrain', 'apply-migrations', '--yes', '--no-autopilot-install'],
+ `Runs the pending schema migrations, v${v277.version} among them, on the brain host; this check then names only the functions another role owns.`, NAME, { requires_exclusive: true, docs: DOCS }),
+ details: { functions, schema_version: version },
+ }];
}
+ return [{
+ name: NAME, status: 'fail',
+ message: `${risk} Fix, as the role that owns each function (migration v${v277.version} and every migration run already did the ones the migrating role owns): ${fix.join(' ')}`,
+ fix: { argv: ['psql', '-c', fix.join(' ')], consent: [], actor: 'host_admin', requires_exclusive: false, docs: DOCS, verify: doctorVerify(NAME),
+ why: 'ALTER FUNCTION needs the role that owns each function, so it runs on the database host as that role; it changes neither the owner nor the body.' },
+ details: { functions, sql: fix },
+ }];
} catch (e) {
- checks.push(checkError('function_search_path', 'check function search paths', e));
+ return [checkError(NAME, 'check function search paths', e)];
}
- return checks;
}
-export const functionSearchPathEntry: DoctorEntry = { name: 'function_search_path', emits: ['function_search_path'], run: runFunctionSearchPath };
+export const functionSearchPathEntry: DoctorEntry = { name: NAME, emits: [NAME], run: runFunctionSearchPath };
diff --git a/src/core/facts/insert-guard-schema.ts b/src/core/facts/insert-guard-schema.ts
index 887d6b9f1f..b4e21b314f 100644
--- a/src/core/facts/insert-guard-schema.ts
+++ b/src/core/facts/insert-guard-schema.ts
@@ -59,7 +59,7 @@ export const GUARD_OUTCOME_MARKER_SQL = "(i.source IN ('cli:extract-conversation
*/
export const FACT_INSERT_GUARD_FUNCTION_SQL = `
CREATE OR REPLACE FUNCTION gbrain_guard_inserted_facts() RETURNS trigger
- LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$
+ LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
DECLARE purged TEXT; stamp_setting TEXT;
BEGIN
PERFORM s.id FROM sources s WHERE s.id IN (SELECT i.source_id FROM inserted_facts i) ORDER BY s.id FOR SHARE OF s;
diff --git a/src/core/facts/purge-schema.ts b/src/core/facts/purge-schema.ts
index d185cd6961..56b4f7c367 100644
--- a/src/core/facts/purge-schema.ts
+++ b/src/core/facts/purge-schema.ts
@@ -115,7 +115,7 @@ ${FACT_PURGES_ALL_SUBJECTS_INDEX.sql};
export const MEMORY_PURGE_GUARD_SQL = `
CREATE OR REPLACE FUNCTION gbrain_refuse_purged_fact() RETURNS trigger
- LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$
+ LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
BEGIN
PERFORM id FROM sources WHERE id = NEW.source_id FOR SHARE;
IF EXISTS (SELECT 1 FROM fact_purges
@@ -133,7 +133,7 @@ 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
- LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$
+ LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
DECLARE src TEXT; subj TEXT;
BEGIN
SELECT p.source_id, p.slug INTO src, subj FROM pages p WHERE p.id = NEW.page_id;
@@ -151,7 +151,7 @@ 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
- LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$
+ 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
diff --git a/src/core/facts/withdrawal-schema.ts b/src/core/facts/withdrawal-schema.ts
index a07bfefeb7..a5a21930d5 100644
--- a/src/core/facts/withdrawal-schema.ts
+++ b/src/core/facts/withdrawal-schema.ts
@@ -58,7 +58,7 @@ export const FACT_WITHDRAWAL_SCHEMA_STATEMENTS = [
)`,
...FACT_FINGERPRINT_FUNCTION_STATEMENTS,
`CREATE OR REPLACE FUNCTION gbrain_preserve_fact_withdrawal() RETURNS trigger
- LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$
+ LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
DECLARE withdrawn TIMESTAMPTZ;
BEGIN
IF NEW.expired_at IS NULL THEN
diff --git a/src/core/fts-language.ts b/src/core/fts-language.ts
index d7c8aa2d50..0cf7a4a05a 100644
--- a/src/core/fts-language.ts
+++ b/src/core/fts-language.ts
@@ -141,7 +141,7 @@ const CJK_CLASS = `[${CJK_SLUG_CHARS}]`;
* applies it.
*/
export const FTS_INPUT_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_fts_input(t text) RETURNS text
- LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog
+ LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog, pg_temp
AS $fn$
SELECT regexp_replace(regexp_replace(t, '(${CJK_CLASS})([A-Za-z0-9])', '\\1 \\2', 'g'), '([A-Za-z0-9])(${CJK_CLASS})', '\\1 \\2', 'g')
$fn$;`;
@@ -223,7 +223,7 @@ $$ LANGUAGE plpgsql;`;
}
export function chunkSearchVectorTriggerFnSql(lang: string): string {
- return `CREATE OR REPLACE FUNCTION update_chunk_search_vector() RETURNS TRIGGER SET search_path = pg_catalog, public AS $fn$
+ return `CREATE OR REPLACE FUNCTION update_chunk_search_vector() RETURNS TRIGGER SET search_path = pg_catalog, public, pg_temp AS $fn$
BEGIN
NEW.search_vector :=
${chunkSearchVectorSql(lang, 'NEW.')};
diff --git a/src/core/function-search-path.ts b/src/core/function-search-path.ts
index c282b22a8a..6d81314e2f 100644
--- a/src/core/function-search-path.ts
+++ b/src/core/function-search-path.ts
@@ -8,17 +8,29 @@
* through: for the owner as much as for any other writer. Named last, pg_temp comes after every other schema for
* relations, and PostgreSQL never searches it for functions or operators.
*
- * ALTER FUNCTION only: no body is rewritten, so every guard keeps master's body, SECURITY INVOKER and BEFORE ROW timing.
+ * Every definition gbrain owns now pins `pg_catalog, public, pg_temp` itself (#7785; scripts/check-search-path.sh keeps
+ * 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).
*/
+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';
+
/** The search_path settings gbrain functions pinned before #7632, which the hardening completes with pg_temp. */
export const LEGACY_SEARCH_PATH_SETTINGS = ['search_path=pg_catalog, public', 'search_path=pg_catalog'] as const;
+/** The pinned path in a pg_proc.proconfig entry `c.setting` (`search_path=<path>`). */
+export const PINNED_PATH_SQL = `substr(c.setting, ${'search_path='.length + 1})`;
+
/**
* Every function gbrain installs in public with a pinned search_path, on either engine. The hardening and the doctor
* check touch only these, so another application's function in a shared database keeps its own search_path. A new
- * pinned function joins this list; the fresh-install tests (test/function-search-path-pglite.test.ts, and case 3 of
+ * pinned function joins this list; scripts/check-search-path.sh (bun run check:search-path) names one that does not,
+ * and the fresh-install tests (test/function-search-path-pglite.test.ts, and case 3 of
* test/e2e/function-search-path-postgres.test.ts) fail until it does.
*/
export const PINNED_FUNCTION_NAMES = [
@@ -41,15 +53,15 @@ export const PINNED_FUNCTION_NAMES = [
/**
* Appends pg_temp to the pinned search_path of every gbrain function (PINNED_FUNCTION_NAMES) in public the current
* role may alter that still pins `pg_catalog, public` or `pg_catalog`. A function the role does not own is
- * left as it was, and so is a procedure (ALTER FUNCTION refuses one, and gbrain installs none). Shared by the schema blob (its last statement, so a replay's CREATE OR REPLACE never leaves a function
- * without it), the migration, the end of every migration run (src/core/migrate.ts: a migration that re-creates a
- * function resets its path, and the run may stop before v277) and `gbrain reindex-search-vector`, which rewrites the
+ * left as it was, and so is a procedure (ALTER FUNCTION refuses one, and gbrain installs none). Shared by the schema blob (its last
+ * statement, so a replay's CREATE OR REPLACE never leaves a function without it), hardenFunctionSearchPaths below
+ * (migration v277 and the end of every migration run) and `gbrain reindex-search-vector`, which rewrites the
* search_vector trigger functions.
*/
export const FUNCTION_SEARCH_PATH_HARDENING_SQL = `DO $harden$
DECLARE f RECORD;
BEGIN
- FOR f IN SELECT p.oid::regprocedure AS sig, substr(c.setting, 13) AS path
+ FOR f IN SELECT p.oid::regprocedure AS sig, ${PINNED_PATH_SQL} 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 IN (${LEGACY_SEARCH_PATH_SETTINGS.map(v => `'${v}'`).join(', ')})
AND p.proname IN (${PINNED_FUNCTION_NAMES.map(name => `'${name}'`).join(', ')})
@@ -60,3 +72,48 @@ BEGIN
END LOOP;
END $harden$;`;
+/** The gbrain functions (regprocedure text) whose pinned search_path is still a legacy setting. */
+export async function legacySearchPathFunctions(engine: BrainEngine): Promise<string[]> {
+ return (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[] AND p.proname = ANY($2::text[]) ORDER BY 1`,
+ [[...LEGACY_SEARCH_PATH_SETTINGS], [...PINNED_FUNCTION_NAMES]])).map(r => r.sig);
+}
+
+/** Attempts of the hardening when another session's ALTER or CREATE OR REPLACE updates the same pg_proc row. */
+const CONCURRENT_UPDATE_ATTEMPTS = 3;
+
+function isConcurrentCatalogUpdate(error: unknown): boolean {
+ return /tuple concurrently updated/i.test(error instanceof Error ? error.message : String(error));
+}
+
+/**
+ * Runs the hardening in one short transaction with the migration statement and lock timeouts and returns the
+ * functions it had to leave (owned by another role), [] when none needed it, or null when the hardening committed but
+ * 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.
+ */
+export async function hardenFunctionSearchPaths(engine: BrainEngine, attempt = 1): Promise<string[] | null> {
+ if ((await legacySearchPathFunctions(engine)).length === 0) return [];
+ 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(277, FUNCTION_SEARCH_PATH_HARDENING_SQL);
+ });
+ } catch (error) {
+ if (isLockTimeoutError(error)) {
+ throw schemaLockBlockedError({ step: 'search_path hardening', timeoutMs: lockTimeoutMs, sessions: null, sampledDuringWait: false, lock: 'a gbrain function row lock (pg_proc)' });
+ }
+ if (isConcurrentCatalogUpdate(error) && attempt < CONCURRENT_UPDATE_ATTEMPTS) {
+ await new Promise(resolve => setTimeout(resolve, 100 * attempt));
+ return hardenFunctionSearchPaths(engine, attempt + 1);
+ }
+ throw error;
+ }
+ return legacySearchPathFunctions(engine).catch(() => null);
+}
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 79d38df3c7..319664b80f 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -14,7 +14,7 @@ import {
isRetryableConnError,
} from './retry-matcher.ts';
import { repairTimelineDedupIndex } from './timeline-dedup-repair.ts';
-import { hardenFunctionSearchPaths } from './schema-migrations/v277-function-search-path-pg-temp.ts';
+import { hardenFunctionSearchPaths } from './function-search-path.ts';
import { resumePageRevisionBackfill } from './page-state/revision-backfill-schema.ts';
import { repairPagesUpsertArbiter } from './pages-upsert-arbiter.ts';
import { repairLinkSourceCheck, LINK_SOURCE_GATE_MIGRATION_VERSION } from './link-source-check-repair.ts';
@@ -434,13 +434,26 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: num
}
const backfill = () => resumePageRevisionBackfill(engine).catch(e => console.error(`[migrate] page revision backfill paused (#5216): ${e instanceof Error ? e.message : String(e)}`));
- // #7632: a migration that re-creates a gbrain function resets its search_path, a failing migration can stop the run
- // before v277, and a failed earlier attempt leaves one behind; put pg_temp back on every run, at head too.
- // Best-effort: doctor's function_search_path names what it left.
- const harden = () => hardenFunctionSearchPaths(engine, 'search_path').catch((e: unknown) => process.stderr.write(
- ` search_path: pg_temp not restored on gbrain functions (${e instanceof Error ? e.message : String(e)}); gbrain doctor (function_search_path) names them\n`));
+ // #7632: a migration that re-creates a gbrain function from a historical body resets its search_path, a failing
+ // migration can stop the run before v277, and a failed earlier attempt leaves one behind; put pg_temp back on every
+ // run. At head (nothing pending) it still runs, for a function a failed earlier run left (e2e case 9), but does not
+ // name functions another role owns: doctor's function_search_path does, so a non-owner role is not told on every
+ // boot (#7688). Best-effort: doctor names whatever is left.
+ const harden = async (nameLeftovers: boolean): Promise<void> => {
+ try {
+ const left = await hardenFunctionSearchPaths(engine);
+ if (left === null) {
+ process.stderr.write(' search_path: pg_temp put back on gbrain functions, but listing any left without it failed; gbrain doctor (function_search_path) names them\n');
+ } else if (nameLeftovers && left.length > 0) {
+ process.stderr.write(` search_path: ${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');
+ }
+ } catch (e) {
+ process.stderr.write(` search_path: pg_temp not restored on gbrain functions (${e instanceof Error ? e.message : String(e)}); gbrain doctor (function_search_path) names them\n`);
+ }
+ };
if (pending.length === 0) {
- await harden();
+ await harden(false);
await backfill();
return { applied: 0, current };
}
@@ -470,6 +483,7 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: num
}
let applied = 0;
+ let lockRefused = false;
try {
// Pre-flight: warn about connections that might block DDL
await checkForBlockingConnections(engine);
@@ -488,6 +502,7 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: num
// #7108: apply-migrations and doctor read this to name the migration and the step that helps.
const timedOut = err instanceof MigrationRetryExhausted ? isStatementTimeoutError(err.lastError) : isStatementTimeoutError(err);
if (timedOut) await recordMigrationTimeout(engine, m, MIGRATION_PRELUDES.has(m.version), err instanceof MigrationRetryExhausted ? err.lastBlockers.map(b => b.pid) : []);
+ lockRefused = (err as { code?: unknown }).code === 'schema_lock_blocked' || isLockTimeoutError(err);
throw err;
}
@@ -498,7 +513,9 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: num
// Never leak the fresh-install quiet flag into a later in-process run —
// covers every exit path from here on (incl. the pre-flight probe).
setQuietMigrationNotices(false);
- await harden();
+ // A run stopped by a lock it could not take would wait a second lock_timeout here before its own error surfaced.
+ if (lockRefused) process.stderr.write(' search_path: not put back on gbrain functions after the lock refusal; the next migration run does it, and gbrain doctor (function_search_path) names what is left\n');
+ else await harden(true);
}
await clearMigrationTimeout(engine);
await backfill();
diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.ts
index 9dc285709f..395f277dba 100644
--- a/src/core/page-body/schema.ts
+++ b/src/core/page-body/schema.ts
@@ -21,7 +21,7 @@
* body identity is `body_generation`: its body columns are NULL on both sides
* of a flip, so the generation moves when body_generation does.
*/
-export const PAGE_GENERATION_BUMP_FN_SQL = `CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public AS $func$
+export const PAGE_GENERATION_BUMP_FN_SQL = `CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS $func$
BEGIN
IF (TG_OP = 'INSERT') THEN
NEW.generation := COALESCE((SELECT MAX(generation) FROM pages), 0) + 1;
@@ -328,7 +328,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 AS $func$
+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;
@@ -355,7 +355,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 AS $func$
+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')}
diff --git a/src/core/persistence/git-canonical-schema.ts b/src/core/persistence/git-canonical-schema.ts
index cf9fa44ac3..dfc97a1cb4 100644
--- a/src/core/persistence/git-canonical-schema.ts
+++ b/src/core/persistence/git-canonical-schema.ts
@@ -1,5 +1,5 @@
/** The counter function alone: replacing it takes no table lock (#7636). */
-export const GIT_CANONICAL_COUNT_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_count_git_canonical_sources() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$
+export const GIT_CANONICAL_COUNT_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_count_git_canonical_sources() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
BEGIN
-- #7636: a count over the rows row-level security lets this role see would undercount and could switch G7a off.
IF row_security_active('sources') THEN
diff --git a/src/core/persistence/graduation-schema.ts b/src/core/persistence/graduation-schema.ts
index f0f99659c1..25b0494c95 100644
--- a/src/core/persistence/graduation-schema.ts
+++ b/src/core/persistence/graduation-schema.ts
@@ -39,7 +39,7 @@ CREATE TABLE IF NOT EXISTS persistence_graduation (
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
-CREATE OR REPLACE FUNCTION gbrain_graduation_fence() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fence$
+CREATE OR REPLACE FUNCTION gbrain_graduation_fence() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fence$
DECLARE fence_run text;
BEGIN
SELECT run_id::text INTO fence_run FROM persistence_graduation WHERE singleton = 1;
diff --git a/src/core/persistence/graduation-target.ts b/src/core/persistence/graduation-target.ts
index ceb9b18490..0b68ea91b6 100644
--- a/src/core/persistence/graduation-target.ts
+++ b/src/core/persistence/graduation-target.ts
@@ -292,7 +292,7 @@ export function targetProbeBlockers(probe: TargetProbe, routes: Pick<TargetRoute
/** What a DBA runs once on a target whose gbrain role is not a superuser (the v35 objects, owned by that role). */
function AUTO_RLS_DBA_SQL(role: string): string {
- return `CREATE OR REPLACE FUNCTION public.auto_enable_rls() RETURNS event_trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $f$ DECLARE obj record; BEGIN FOR obj IN SELECT * FROM pg_event_trigger_ddl_commands() WHERE object_type = 'table' AND schema_name = 'public' LOOP EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY', obj.object_identity); END LOOP; END; $f$; `
+ return `CREATE OR REPLACE FUNCTION public.auto_enable_rls() RETURNS event_trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $f$ DECLARE obj record; BEGIN FOR obj IN SELECT * FROM pg_event_trigger_ddl_commands() WHERE object_type = 'table' AND schema_name = 'public' LOOP EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY', obj.object_identity); END LOOP; END; $f$; `
+ `ALTER FUNCTION public.auto_enable_rls() OWNER TO ${role}; `
+ `CREATE EVENT TRIGGER auto_rls_on_create_table ON ddl_command_end WHEN TAG IN ('CREATE TABLE', 'CREATE TABLE AS', 'SELECT INTO') EXECUTE FUNCTION public.auto_enable_rls();`;
}
diff --git a/src/core/persistence/writer-guard-schema.ts b/src/core/persistence/writer-guard-schema.ts
index 666d5cfcb2..4b49cee326 100644
--- a/src/core/persistence/writer-guard-schema.ts
+++ b/src/core/persistence/writer-guard-schema.ts
@@ -6,7 +6,7 @@ export const GUARDED_TABLES = ['pages', 'tags', 'slug_aliases', 'page_aliases',
const sqlList = (names: string[]) => names.map(name => `'${name}'`).join(',');
/** The guard function alone: replacing it takes no table lock (v197). */
export const MANAGED_WRITER_GUARD_FUNCTION_SQL = `
-CREATE OR REPLACE FUNCTION gbrain_require_managed_writer() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$
+CREATE OR REPLACE FUNCTION gbrain_require_managed_writer() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
DECLARE managed boolean; strict_count integer; seen integer; git boolean; unreadable text; target_source text; old_source text; row_data jsonb; old_data jsonb; allowed jsonb;
BEGIN
-- #7636: init always writes the singleton, so a missing row means this role cannot read it (RLS), never "unmanaged".
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index e1d41ac7fe..0e4ae40607 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -32,7 +32,7 @@ CREATE TABLE IF NOT EXISTS sources (
);
CREATE OR REPLACE FUNCTION gbrain_try_jsonb(input text) RETURNS jsonb
- LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog, public AS \$fn\$
+ LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog, public, pg_temp AS \$fn\$
BEGIN
RETURN input::jsonb;
EXCEPTION WHEN data_exception THEN
@@ -78,7 +78,7 @@ CREATE TABLE IF NOT EXISTS pages (
CONSTRAINT pages_source_slug_key UNIQUE (source_id, slug)
);
-CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$
+CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS \$func\$
BEGIN
IF (TG_OP = 'INSERT') THEN
NEW.generation := COALESCE((SELECT MAX(generation) FROM pages), 0) + 1;
@@ -125,7 +125,7 @@ SELECT setval('page_generation_clock_seq', GREATEST(
COALESCE((SELECT MAX(generation) FROM pages), 0)
));
-CREATE OR REPLACE FUNCTION bump_page_generation_clock_fn() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$
+CREATE OR REPLACE FUNCTION bump_page_generation_clock_fn() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS \$func\$
BEGIN
PERFORM nextval('page_generation_clock_seq');
RETURN NULL;
@@ -214,7 +214,7 @@ CREATE INDEX IF NOT EXISTS content_chunks_stale_idx
-- #6370: indexing and the title query read text through gbrain_fts_input(),
-- which splits CJK/ASCII-alnum boundaries (a no-op on text without CJK).
CREATE OR REPLACE FUNCTION gbrain_fts_input(t text) RETURNS text
- LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog
+ LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog, pg_temp
AS \$fn\$
SELECT regexp_replace(regexp_replace(t, '([一-鿿぀-ゟ゠-ヿ가-힯])([A-Za-z0-9])', '\\1 \\2', 'g'), '([A-Za-z0-9])([一-鿿぀-ゟ゠-ヿ가-힯])', '\\1 \\2', 'g')
\$fn\$;
@@ -1117,7 +1117,7 @@ CREATE INDEX IF NOT EXISTS think_ab_results_recent_idx
ON think_ab_results (source_id, ran_at DESC);
-CREATE OR REPLACE FUNCTION enforce_minion_queue_protocol() RETURNS trigger SET search_path = pg_catalog, public AS \$protocol\$
+CREATE OR REPLACE FUNCTION enforce_minion_queue_protocol() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS \$protocol\$
BEGIN
IF TG_OP = 'INSERT' THEN
IF NEW.submission_authority IS NULL OR NEW.claim_generation <> 0 THEN
@@ -1178,7 +1178,7 @@ CREATE TABLE IF NOT EXISTS page_write_guards (
slug TEXT NOT NULL,
PRIMARY KEY (source_incarnation, slug)
);
-CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$fn\$
+CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$fn\$
DECLARE body_moved boolean := false;
BEGIN
IF OLD.knowledge_revision IS NULL THEN
@@ -1546,7 +1546,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 AS \$func\$
+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;
@@ -1573,7 +1573,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 AS \$func\$
+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 (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
@@ -1735,7 +1735,7 @@ CREATE TABLE IF NOT EXISTS persistence_consumers (
PRIMARY KEY(host_id,pid,nonce)
);
-CREATE OR REPLACE FUNCTION gbrain_require_managed_writer() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$fn\$
+CREATE OR REPLACE FUNCTION gbrain_require_managed_writer() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$fn\$
DECLARE managed boolean; strict_count integer; seen integer; git boolean; unreadable text; target_source text; old_source text; row_data jsonb; old_data jsonb; allowed jsonb;
BEGIN
-- #7636: init always writes the singleton, so a missing row means this role cannot read it (RLS), never "unmanaged".
@@ -1858,7 +1858,7 @@ CREATE TABLE IF NOT EXISTS git_canonical_brain (
singleton INTEGER PRIMARY KEY DEFAULT 1 CHECK (singleton = 1),
strict_sources INTEGER NOT NULL DEFAULT 0 CHECK (strict_sources >= 0)
);
-CREATE OR REPLACE FUNCTION gbrain_count_git_canonical_sources() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$fn\$
+CREATE OR REPLACE FUNCTION gbrain_count_git_canonical_sources() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$fn\$
BEGIN
-- #7636: a count over the rows row-level security lets this role see would undercount and could switch G7a off.
IF row_security_active('sources') THEN
@@ -2152,13 +2152,13 @@ CREATE TABLE IF NOT EXISTS persistence_writer_protocols (
registered_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(worktree_id,host_id)
);
-CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer) RETURNS void LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer) RETURNS void LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$\$
BEGIN
IF required >= 2 AND COALESCE(current_setting('gbrain.persistence_protocol',true),'') <> '2' THEN
RAISE EXCEPTION 'writer_upgrade_required: this mutation requires persistence protocol 2' USING ERRCODE='42501';
END IF;
END \$\$;
-CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$\$
DECLARE target text; version integer; floor integer; active boolean; record jsonb;
BEGIN
IF TG_OP='DELETE' THEN target:=OLD.target_kind; version:=OLD.protocol_version;
@@ -2200,7 +2200,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGU
DROP TRIGGER IF EXISTS gbrain_request_protocol ON persistence_requests;
CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR UPDATE OR DELETE ON persistence_requests
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol();
-CREATE OR REPLACE FUNCTION gbrain_guard_effect_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+CREATE OR REPLACE FUNCTION gbrain_guard_effect_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$\$
DECLARE floor integer;
BEGIN
SELECT writer_protocol_floor INTO floor FROM persistence_brain WHERE singleton=1 FOR SHARE;
@@ -2212,7 +2212,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_effect_protocol() RETURNS trigger LANGUA
DROP TRIGGER IF EXISTS gbrain_effect_protocol ON persistence_effects;
CREATE TRIGGER gbrain_effect_protocol BEFORE INSERT OR UPDATE OR DELETE ON persistence_effects
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_effect_protocol();
-CREATE OR REPLACE FUNCTION gbrain_guard_protocol_activation() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+CREATE OR REPLACE FUNCTION gbrain_guard_protocol_activation() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$\$
BEGIN
IF NEW.writer_protocol_floor<OLD.writer_protocol_floor THEN
RAISE EXCEPTION 'writer_upgrade_required: the protocol floor cannot be lowered' USING ERRCODE='42501';
@@ -2239,7 +2239,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_protocol_activation() RETURNS trigger LA
DROP TRIGGER IF EXISTS gbrain_protocol_activation ON persistence_brain;
CREATE TRIGGER gbrain_protocol_activation BEFORE UPDATE ON persistence_brain
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_protocol_activation();
-CREATE OR REPLACE FUNCTION gbrain_guard_skill_publication() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+CREATE OR REPLACE FUNCTION gbrain_guard_skill_publication() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$\$
DECLARE permitted jsonb;
BEGIN
PERFORM gbrain_require_persistence_protocol(2);
@@ -2265,7 +2265,7 @@ CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR UPDATE OR DELETE ON sha
DROP TRIGGER IF EXISTS gbrain_skill_publication ON shared_skill_revisions;
CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR UPDATE OR DELETE ON shared_skill_revisions
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication();
-CREATE OR REPLACE FUNCTION gbrain_lease_shared_skill_delivery() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+CREATE OR REPLACE FUNCTION gbrain_lease_shared_skill_delivery() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$\$
DECLARE item text; found_revision shared_skill_revisions%ROWTYPE; brain text;
BEGIN
SELECT brain_id::text INTO brain FROM persistence_brain WHERE singleton=1;
diff --git a/src/core/planner-stats-schema.ts b/src/core/planner-stats-schema.ts
index 1422986a16..6a12aafaec 100644
--- a/src/core/planner-stats-schema.ts
+++ b/src/core/planner-stats-schema.ts
@@ -33,7 +33,7 @@ CREATE TABLE IF NOT EXISTS planner_stats_state (
analyzed_at TIMESTAMPTZ,
last_analyze_ms INTEGER
);
-CREATE OR REPLACE FUNCTION gbrain_count_modifications() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
+CREATE OR REPLACE FUNCTION gbrain_count_modifications() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$
DECLARE
modified BIGINT;
BEGIN
diff --git a/src/core/postgres-engine/schema-lock-timeout.ts b/src/core/postgres-engine/schema-lock-timeout.ts
index 31365d2cc5..00237b48dd 100644
--- a/src/core/postgres-engine/schema-lock-timeout.ts
+++ b/src/core/postgres-engine/schema-lock-timeout.ts
@@ -79,14 +79,14 @@ function describe(sessions: BlockingSession[]): string {
/** The typed refusal for SQLSTATE 55P03 under the schema bound. */
// engine-sql-ok: the suggestion text quotes an operator's pg_stat_activity query; nothing here runs SQL
-export function schemaLockBlockedError(input: { step: string; timeoutMs: number; sessions: BlockingSession[] | null; sampledDuringWait: boolean }): OperationError {
+export function schemaLockBlockedError(input: { step: string; timeoutMs: number; sessions: BlockingSession[] | null; sampledDuringWait: boolean; lock?: string }): OperationError {
const { step, timeoutMs, sessions } = input;
const holders = sessions === null ? 'The blocking sessions could not be sampled.'
: sessions.length === 0 ? `No blocking session was found${input.sampledDuringWait ? ' at the sample' : ' after the cancel (it may have finished)'}.`
: `Blocked by ${describe(sessions)}${input.sampledDuringWait ? '' : ' (sampled after the cancel)'}.`;
const pids = sessions?.map(s => s.pid) ?? [];
return opError('schema_lock_blocked',
- `Schema ${step} waited ${Math.round(timeoutMs / 1000)}s for a table lock another session holds, and stopped instead of hanging. ${holders} Query text is not shown.`,
+ `Schema ${step} waited ${Math.round(timeoutMs / 1000)}s for ${input.lock ?? 'a table lock'} another session holds, and stopped instead of hanging. ${holders} Query text is not shown.`,
`Nothing was changed by the cancelled step; the schema is as it was. Find what holds the lock (an open transaction in another client, a stuck job): ${pids.length
? `the blocking pid(s) are ${pids.join(', ')}. Let that session finish or, with the user's agreement, end it with SELECT pg_terminate_backend(<pid>) on the database host.`
: 'run SELECT pid, application_name, state FROM pg_stat_activity WHERE state LIKE \'idle in transaction%\' on the database host and let that session finish or, with the user\'s agreement, end it with SELECT pg_terminate_backend(<pid>).'} Then rerun the same gbrain command; a longer wait is GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS.`,
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index c3b0a2e3ac..3b78f13796 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -66,7 +66,7 @@ CREATE TABLE IF NOT EXISTS sources (
-- IS JSON and pg_input_is_valid() are Postgres 16+. Migration v263 installs it
-- on existing brains.
CREATE OR REPLACE FUNCTION gbrain_try_jsonb(input text) RETURNS jsonb
- LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog, public AS \$fn\$
+ LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog, public, pg_temp AS \$fn\$
BEGIN
RETURN input::jsonb;
EXCEPTION WHEN data_exception THEN
@@ -183,7 +183,7 @@ CREATE TABLE IF NOT EXISTS pages (
);
-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_GENERATION_BUMP_FN_SQL). Edit that file, then run: bun run build:schema
-CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$
+CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS \$func\$
BEGIN
IF (TG_OP = 'INSERT') THEN
NEW.generation := COALESCE((SELECT MAX(generation) FROM pages), 0) + 1;
@@ -268,7 +268,7 @@ SELECT setval('page_generation_clock_seq', GREATEST(
COALESCE((SELECT MAX(generation) FROM pages), 0)
));
-CREATE OR REPLACE FUNCTION bump_page_generation_clock_fn() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$
+CREATE OR REPLACE FUNCTION bump_page_generation_clock_fn() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS \$func\$
BEGIN
PERFORM nextval('page_generation_clock_seq');
RETURN NULL;
@@ -434,7 +434,7 @@ CREATE INDEX IF NOT EXISTS content_chunks_stale_idx
-- which splits CJK/ASCII-alnum boundaries (a no-op on text without CJK).
-- BEGIN GENERATED from src/core/fts-language.ts (FTS_INPUT_FUNCTION_SQL). Edit that file, then run: bun run build:schema
CREATE OR REPLACE FUNCTION gbrain_fts_input(t text) RETURNS text
- LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog
+ LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog, pg_temp
AS \$fn\$
SELECT regexp_replace(regexp_replace(t, '([一-鿿぀-ゟ゠-ヿ가-힯])([A-Za-z0-9])', '\\1 \\2', 'g'), '([A-Za-z0-9])([一-鿿぀-ゟ゠-ヿ가-힯])', '\\1 \\2', 'g')
\$fn\$;
@@ -445,7 +445,7 @@ AS \$fn\$
-- NL queries ("how do we handle errors") rank doc-comment hits above body text.
-- BEFORE INSERT OR UPDATE OF specific columns — only refires when those change,
-- not on every chunk update (e.g., embedding refresh doesn't trigger rebuild).
-CREATE OR REPLACE FUNCTION update_chunk_search_vector() RETURNS TRIGGER SET search_path = pg_catalog, public AS \$fn\$
+CREATE OR REPLACE FUNCTION update_chunk_search_vector() RETURNS TRIGGER SET search_path = pg_catalog, public, pg_temp AS \$fn\$
BEGIN
NEW.search_vector :=
setweight(to_tsvector('english', gbrain_fts_input(COALESCE(NEW.doc_comment, ''))), 'A') ||
@@ -1790,7 +1790,7 @@ CREATE INDEX IF NOT EXISTS think_ab_results_recent_idx
-- Reject pre-upgrade producers/claims; old reapers must still be stopped during cutover.
-CREATE OR REPLACE FUNCTION enforce_minion_queue_protocol() RETURNS trigger SET search_path = pg_catalog, public AS \$protocol\$
+CREATE OR REPLACE FUNCTION enforce_minion_queue_protocol() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS \$protocol\$
BEGIN
IF TG_OP = 'INSERT' THEN
IF NEW.submission_authority IS NULL OR NEW.claim_generation <> 0 THEN
@@ -1814,7 +1814,7 @@ CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobs
FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol();
-- NOTIFY trigger for real-time job events (Postgres only, not PGLite)
-CREATE OR REPLACE FUNCTION notify_minion_job_change() RETURNS trigger SET search_path = pg_catalog, public AS \$\$
+CREATE OR REPLACE FUNCTION notify_minion_job_change() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS \$\$
BEGIN
PERFORM pg_notify('minion_jobs', json_build_object(
'id', NEW.id, 'status', NEW.status, 'name', NEW.name,
@@ -1905,7 +1905,7 @@ CREATE TABLE IF NOT EXISTS page_write_guards (
slug TEXT NOT NULL,
PRIMARY KEY (source_incarnation, slug)
);
-CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$fn\$
+CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$fn\$
DECLARE body_moved boolean := false;
BEGIN
IF OLD.knowledge_revision IS NULL THEN
@@ -2294,7 +2294,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 AS \$func\$
+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;
@@ -2321,7 +2321,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 AS \$func\$
+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 (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
@@ -2478,7 +2478,7 @@ CREATE TABLE IF NOT EXISTS persistence_consumers (
PRIMARY KEY(host_id,pid,nonce)
);
-CREATE OR REPLACE FUNCTION gbrain_require_managed_writer() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$fn\$
+CREATE OR REPLACE FUNCTION gbrain_require_managed_writer() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$fn\$
DECLARE managed boolean; strict_count integer; seen integer; git boolean; unreadable text; target_source text; old_source text; row_data jsonb; old_data jsonb; allowed jsonb;
BEGIN
-- #7636: init always writes the singleton, so a missing row means this role cannot read it (RLS), never "unmanaged".
@@ -2603,7 +2603,7 @@ CREATE TABLE IF NOT EXISTS git_canonical_brain (
singleton INTEGER PRIMARY KEY DEFAULT 1 CHECK (singleton = 1),
strict_sources INTEGER NOT NULL DEFAULT 0 CHECK (strict_sources >= 0)
);
-CREATE OR REPLACE FUNCTION gbrain_count_git_canonical_sources() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$fn\$
+CREATE OR REPLACE FUNCTION gbrain_count_git_canonical_sources() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$fn\$
BEGIN
-- #7636: a count over the rows row-level security lets this role see would undercount and could switch G7a off.
IF row_security_active('sources') THEN
@@ -2907,13 +2907,13 @@ CREATE TABLE IF NOT EXISTS persistence_writer_protocols (
registered_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(worktree_id,host_id)
);
-CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer) RETURNS void LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer) RETURNS void LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$\$
BEGIN
IF required >= 2 AND COALESCE(current_setting('gbrain.persistence_protocol',true),'') <> '2' THEN
RAISE EXCEPTION 'writer_upgrade_required: this mutation requires persistence protocol 2' USING ERRCODE='42501';
END IF;
END \$\$;
-CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$\$
DECLARE target text; version integer; floor integer; active boolean; record jsonb;
BEGIN
IF TG_OP='DELETE' THEN target:=OLD.target_kind; version:=OLD.protocol_version;
@@ -2955,7 +2955,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGU
DROP TRIGGER IF EXISTS gbrain_request_protocol ON persistence_requests;
CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR UPDATE OR DELETE ON persistence_requests
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol();
-CREATE OR REPLACE FUNCTION gbrain_guard_effect_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+CREATE OR REPLACE FUNCTION gbrain_guard_effect_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$\$
DECLARE floor integer;
BEGIN
SELECT writer_protocol_floor INTO floor FROM persistence_brain WHERE singleton=1 FOR SHARE;
@@ -2967,7 +2967,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_effect_protocol() RETURNS trigger LANGUA
DROP TRIGGER IF EXISTS gbrain_effect_protocol ON persistence_effects;
CREATE TRIGGER gbrain_effect_protocol BEFORE INSERT OR UPDATE OR DELETE ON persistence_effects
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_effect_protocol();
-CREATE OR REPLACE FUNCTION gbrain_guard_protocol_activation() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+CREATE OR REPLACE FUNCTION gbrain_guard_protocol_activation() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$\$
BEGIN
IF NEW.writer_protocol_floor<OLD.writer_protocol_floor THEN
RAISE EXCEPTION 'writer_upgrade_required: the protocol floor cannot be lowered' USING ERRCODE='42501';
@@ -2994,7 +2994,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_protocol_activation() RETURNS trigger LA
DROP TRIGGER IF EXISTS gbrain_protocol_activation ON persistence_brain;
CREATE TRIGGER gbrain_protocol_activation BEFORE UPDATE ON persistence_brain
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_protocol_activation();
-CREATE OR REPLACE FUNCTION gbrain_guard_skill_publication() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+CREATE OR REPLACE FUNCTION gbrain_guard_skill_publication() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$\$
DECLARE permitted jsonb;
BEGIN
PERFORM gbrain_require_persistence_protocol(2);
@@ -3020,7 +3020,7 @@ CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR UPDATE OR DELETE ON sha
DROP TRIGGER IF EXISTS gbrain_skill_publication ON shared_skill_revisions;
CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR UPDATE OR DELETE ON shared_skill_revisions
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication();
-CREATE OR REPLACE FUNCTION gbrain_lease_shared_skill_delivery() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+CREATE OR REPLACE FUNCTION gbrain_lease_shared_skill_delivery() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS \$\$
DECLARE item text; found_revision shared_skill_revisions%ROWTYPE; brain text;
BEGIN
SELECT brain_id::text INTO brain FROM persistence_brain WHERE singleton=1;
diff --git a/src/core/schema-migrations/v277-function-search-path-pg-temp.ts b/src/core/schema-migrations/v277-function-search-path-pg-temp.ts
index 49e9327ebf..f2b54fe45f 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,46 +1,14 @@
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, PINNED_FUNCTION_NAMES, LEGACY_SEARCH_PATH_SETTINGS } from '../function-search-path.ts';
+import { hardenFunctionSearchPaths } 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 legacy = async () => (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[] AND p.proname = ANY($2::text[]) ORDER BY 1`,
- [[...LEGACY_SEARCH_PATH_SETTINGS], [...PINNED_FUNCTION_NAMES]])).map(r => r.sig);
- if ((await legacy()).length === 0) return [];
- 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(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 legacy();
- 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;
-}
+// FUNCTION needs the owner: a function the migrating role does not own is left as it was; the end of the migration run
+// names it on stderr (src/core/migrate.ts), 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.
export const v277: Migration = {
version: 277,
@@ -48,5 +16,5 @@ export const v277: Migration = {
idempotent: true,
transaction: false,
sql: '',
- handler: async engine => { await hardenFunctionSearchPaths(engine, 'v277'); },
+ handler: async engine => { await hardenFunctionSearchPaths(engine); },
};
diff --git a/src/core/shared-skills/schema.ts b/src/core/shared-skills/schema.ts
index bb5c8f8a5d..2bdd5f5691 100644
--- a/src/core/shared-skills/schema.ts
+++ b/src/core/shared-skills/schema.ts
@@ -54,7 +54,7 @@ export const SHARED_SKILLS_SCHEMA_STATEMENTS: readonly string[] = [
];
export const SHARED_SKILLS_DELIVERY_LEASE_SCHEMA_STATEMENTS: readonly string[] = [
- `CREATE OR REPLACE FUNCTION gbrain_lease_shared_skill_delivery() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
+ `CREATE OR REPLACE FUNCTION gbrain_lease_shared_skill_delivery() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$
DECLARE item text; found_revision shared_skill_revisions%ROWTYPE; brain text;
BEGIN
SELECT brain_id::text INTO brain FROM persistence_brain WHERE singleton=1;
diff --git a/src/schema.sql b/src/schema.sql
index b7f4166081..acb839271a 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -62,7 +62,7 @@ CREATE TABLE IF NOT EXISTS sources (
-- IS JSON and pg_input_is_valid() are Postgres 16+. Migration v263 installs it
-- on existing brains.
CREATE OR REPLACE FUNCTION gbrain_try_jsonb(input text) RETURNS jsonb
- LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog, public AS $fn$
+ LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog, public, pg_temp AS $fn$
BEGIN
RETURN input::jsonb;
EXCEPTION WHEN data_exception THEN
@@ -179,7 +179,7 @@ CREATE TABLE IF NOT EXISTS pages (
);
-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_GENERATION_BUMP_FN_SQL). Edit that file, then run: bun run build:schema
-CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public AS $func$
+CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS $func$
BEGIN
IF (TG_OP = 'INSERT') THEN
NEW.generation := COALESCE((SELECT MAX(generation) FROM pages), 0) + 1;
@@ -264,7 +264,7 @@ SELECT setval('page_generation_clock_seq', GREATEST(
COALESCE((SELECT MAX(generation) FROM pages), 0)
));
-CREATE OR REPLACE FUNCTION bump_page_generation_clock_fn() RETURNS trigger SET search_path = pg_catalog, public AS $func$
+CREATE OR REPLACE FUNCTION bump_page_generation_clock_fn() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS $func$
BEGIN
PERFORM nextval('page_generation_clock_seq');
RETURN NULL;
@@ -430,7 +430,7 @@ CREATE INDEX IF NOT EXISTS content_chunks_stale_idx
-- which splits CJK/ASCII-alnum boundaries (a no-op on text without CJK).
-- BEGIN GENERATED from src/core/fts-language.ts (FTS_INPUT_FUNCTION_SQL). Edit that file, then run: bun run build:schema
CREATE OR REPLACE FUNCTION gbrain_fts_input(t text) RETURNS text
- LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog
+ LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog, pg_temp
AS $fn$
SELECT regexp_replace(regexp_replace(t, '([一-鿿぀-ゟ゠-ヿ가-힯])([A-Za-z0-9])', '\1 \2', 'g'), '([A-Za-z0-9])([一-鿿぀-ゟ゠-ヿ가-힯])', '\1 \2', 'g')
$fn$;
@@ -441,7 +441,7 @@ $fn$;
-- NL queries ("how do we handle errors") rank doc-comment hits above body text.
-- BEFORE INSERT OR UPDATE OF specific columns — only refires when those change,
-- not on every chunk update (e.g., embedding refresh doesn't trigger rebuild).
-CREATE OR REPLACE FUNCTION update_chunk_search_vector() RETURNS TRIGGER SET search_path = pg_catalog, public AS $fn$
+CREATE OR REPLACE FUNCTION update_chunk_search_vector() RETURNS TRIGGER SET search_path = pg_catalog, public, pg_temp AS $fn$
BEGIN
NEW.search_vector :=
setweight(to_tsvector('english', gbrain_fts_input(COALESCE(NEW.doc_comment, ''))), 'A') ||
@@ -1786,7 +1786,7 @@ CREATE INDEX IF NOT EXISTS think_ab_results_recent_idx
-- Reject pre-upgrade producers/claims; old reapers must still be stopped during cutover.
-CREATE OR REPLACE FUNCTION enforce_minion_queue_protocol() RETURNS trigger SET search_path = pg_catalog, public AS $protocol$
+CREATE OR REPLACE FUNCTION enforce_minion_queue_protocol() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS $protocol$
BEGIN
IF TG_OP = 'INSERT' THEN
IF NEW.submission_authority IS NULL OR NEW.claim_generation <> 0 THEN
@@ -1810,7 +1810,7 @@ CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobs
FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol();
-- NOTIFY trigger for real-time job events (Postgres only, not PGLite)
-CREATE OR REPLACE FUNCTION notify_minion_job_change() RETURNS trigger SET search_path = pg_catalog, public AS $$
+CREATE OR REPLACE FUNCTION notify_minion_job_change() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS $$
BEGIN
PERFORM pg_notify('minion_jobs', json_build_object(
'id', NEW.id, 'status', NEW.status, 'name', NEW.name,
@@ -1901,7 +1901,7 @@ CREATE TABLE IF NOT EXISTS page_write_guards (
slug TEXT NOT NULL,
PRIMARY KEY (source_incarnation, slug)
);
-CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$
+CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
DECLARE body_moved boolean := false;
BEGIN
IF OLD.knowledge_revision IS NULL THEN
@@ -2290,7 +2290,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 AS $func$
+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;
@@ -2317,7 +2317,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 AS $func$
+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 (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
@@ -2474,7 +2474,7 @@ CREATE TABLE IF NOT EXISTS persistence_consumers (
PRIMARY KEY(host_id,pid,nonce)
);
-CREATE OR REPLACE FUNCTION gbrain_require_managed_writer() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$
+CREATE OR REPLACE FUNCTION gbrain_require_managed_writer() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
DECLARE managed boolean; strict_count integer; seen integer; git boolean; unreadable text; target_source text; old_source text; row_data jsonb; old_data jsonb; allowed jsonb;
BEGIN
-- #7636: init always writes the singleton, so a missing row means this role cannot read it (RLS), never "unmanaged".
@@ -2599,7 +2599,7 @@ CREATE TABLE IF NOT EXISTS git_canonical_brain (
singleton INTEGER PRIMARY KEY DEFAULT 1 CHECK (singleton = 1),
strict_sources INTEGER NOT NULL DEFAULT 0 CHECK (strict_sources >= 0)
);
-CREATE OR REPLACE FUNCTION gbrain_count_git_canonical_sources() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$
+CREATE OR REPLACE FUNCTION gbrain_count_git_canonical_sources() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
BEGIN
-- #7636: a count over the rows row-level security lets this role see would undercount and could switch G7a off.
IF row_security_active('sources') THEN
@@ -2903,13 +2903,13 @@ CREATE TABLE IF NOT EXISTS persistence_writer_protocols (
registered_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(worktree_id,host_id)
);
-CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer) RETURNS void LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
+CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer) RETURNS void LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$
BEGIN
IF required >= 2 AND COALESCE(current_setting('gbrain.persistence_protocol',true),'') <> '2' THEN
RAISE EXCEPTION 'writer_upgrade_required: this mutation requires persistence protocol 2' USING ERRCODE='42501';
END IF;
END $$;
-CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
+CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$
DECLARE target text; version integer; floor integer; active boolean; record jsonb;
BEGIN
IF TG_OP='DELETE' THEN target:=OLD.target_kind; version:=OLD.protocol_version;
@@ -2951,7 +2951,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGU
DROP TRIGGER IF EXISTS gbrain_request_protocol ON persistence_requests;
CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR UPDATE OR DELETE ON persistence_requests
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol();
-CREATE OR REPLACE FUNCTION gbrain_guard_effect_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
+CREATE OR REPLACE FUNCTION gbrain_guard_effect_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$
DECLARE floor integer;
BEGIN
SELECT writer_protocol_floor INTO floor FROM persistence_brain WHERE singleton=1 FOR SHARE;
@@ -2963,7 +2963,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_effect_protocol() RETURNS trigger LANGUA
DROP TRIGGER IF EXISTS gbrain_effect_protocol ON persistence_effects;
CREATE TRIGGER gbrain_effect_protocol BEFORE INSERT OR UPDATE OR DELETE ON persistence_effects
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_effect_protocol();
-CREATE OR REPLACE FUNCTION gbrain_guard_protocol_activation() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
+CREATE OR REPLACE FUNCTION gbrain_guard_protocol_activation() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$
BEGIN
IF NEW.writer_protocol_floor<OLD.writer_protocol_floor THEN
RAISE EXCEPTION 'writer_upgrade_required: the protocol floor cannot be lowered' USING ERRCODE='42501';
@@ -2990,7 +2990,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_protocol_activation() RETURNS trigger LA
DROP TRIGGER IF EXISTS gbrain_protocol_activation ON persistence_brain;
CREATE TRIGGER gbrain_protocol_activation BEFORE UPDATE ON persistence_brain
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_protocol_activation();
-CREATE OR REPLACE FUNCTION gbrain_guard_skill_publication() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
+CREATE OR REPLACE FUNCTION gbrain_guard_skill_publication() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$
DECLARE permitted jsonb;
BEGIN
PERFORM gbrain_require_persistence_protocol(2);
@@ -3016,7 +3016,7 @@ CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR UPDATE OR DELETE ON sha
DROP TRIGGER IF EXISTS gbrain_skill_publication ON shared_skill_revisions;
CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR UPDATE OR DELETE ON shared_skill_revisions
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication();
-CREATE OR REPLACE FUNCTION gbrain_lease_shared_skill_delivery() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
+CREATE OR REPLACE FUNCTION gbrain_lease_shared_skill_delivery() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$
DECLARE item text; found_revision shared_skill_revisions%ROWTYPE; brain text;
BEGIN
SELECT brain_id::text INTO brain FROM persistence_brain WHERE singleton=1;
diff --git a/test/doctor-function-search-path.test.ts b/test/doctor-function-search-path.test.ts
index 2316cd44e2..243cbaa4e7 100644
--- a/test/doctor-function-search-path.test.ts
+++ b/test/doctor-function-search-path.test.ts
@@ -1,11 +1,17 @@
/**
- * function_search_path doctor check (#7632): names every gbrain function whose pinned search_path lacks a trailing
- * pg_temp, with the ALTER FUNCTION that fixes it; the fix changes no owner, so the next boot still succeeds. The Postgres
- * non-owner path is in test/e2e/function-search-path-postgres.test.ts (case 5).
+ * function_search_path doctor check (#7632, #7688): names every gbrain function whose search_path does not end in
+ * pg_temp, with a schema-qualified ALTER FUNCTION that fixes it; the fix changes no owner, so the next boot still
+ * succeeds. Below migration v277 it points at the migration instead. The Postgres non-owner path is in
+ * test/e2e/function-search-path-postgres.test.ts (case 5).
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { functionSearchPathProblems } from '../src/commands/doctor/checks/function-search-path.ts';
+import { functionSearchPathEntry, functionSearchPathProblems } from '../src/commands/doctor/checks/function-search-path.ts';
+import type { Check } from '../src/commands/doctor.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+const progress = { heartbeat: () => {} };
+const run = async (engine: BrainEngine) => (await functionSearchPathEntry.run({ engine, progress } as never) as Check[]);
describe('function_search_path doctor check (#7632)', () => {
let engine: PGLiteEngine;
@@ -18,6 +24,7 @@ describe('function_search_path doctor check (#7632)', () => {
test('a fresh install has no problem', async () => {
expect(await functionSearchPathProblems(engine)).toEqual({ functions: [], fix: [] });
+ expect(await run(engine)).toEqual([{ name: 'function_search_path', status: 'ok', message: 'Every gbrain function that pins a search_path ends it with pg_temp' }]);
});
test('each function without pg_temp is named, running the printed fix clears it, and a boot after the fix still succeeds', async () => {
@@ -27,8 +34,8 @@ describe('function_search_path doctor check (#7632)', () => {
expect({ functions, fix }).toEqual({
functions: ['gbrain_fts_input(text)', 'gbrain_refuse_purged_page()'],
fix: [
- 'ALTER FUNCTION gbrain_fts_input(text) SET search_path = pg_catalog, pg_temp;',
- 'ALTER FUNCTION gbrain_refuse_purged_page() SET search_path = pg_catalog, public, pg_temp;',
+ 'ALTER FUNCTION public.gbrain_fts_input(t text) SET search_path = pg_catalog, pg_temp;',
+ 'ALTER FUNCTION public.gbrain_refuse_purged_page() SET search_path = pg_catalog, public, pg_temp;',
],
});
await engine.runMigration(0, fix.join('\n'));
@@ -36,4 +43,64 @@ describe('function_search_path doctor check (#7632)', () => {
await engine.initSchema();
expect(await functionSearchPathProblems(engine)).toEqual({ functions: [], fix: [] });
}, 120_000);
+
+ test('the printed fix is schema-qualified, so it runs from a session whose search_path does not name public (#7688)', async () => {
+ await engine.runMigration(0, `ALTER FUNCTION gbrain_try_jsonb(text) SET search_path = pg_catalog, public`);
+ const { fix } = await functionSearchPathProblems(engine);
+ await engine.transaction(async tx => {
+ await tx.executeRaw(`SET LOCAL search_path = pg_catalog`);
+ await tx.executeRaw(fix.join('\n'));
+ });
+ expect(await functionSearchPathProblems(engine)).toEqual({ functions: [], fix: [] });
+ }, 120_000);
+
+ test('a gbrain function re-created without any search_path is named, with a fix that pins one (#7688)', async () => {
+ await engine.runMigration(0, `ALTER FUNCTION gbrain_try_jsonb(text) RESET search_path`);
+ expect(await functionSearchPathProblems(engine)).toEqual({
+ functions: ['gbrain_try_jsonb(text)'],
+ fix: ['ALTER FUNCTION public.gbrain_try_jsonb(input text) SET search_path = pg_catalog, public, pg_temp;'],
+ });
+ await engine.runMigration(0, (await functionSearchPathProblems(engine)).fix.join('\n'));
+ expect(await functionSearchPathProblems(engine)).toEqual({ functions: [], fix: [] });
+ }, 120_000);
+
+ test('at or past v277 the check fails with the ALTER as a host-admin psql fix and the SQL in details (#7688)', async () => {
+ await engine.runMigration(0, `ALTER FUNCTION gbrain_refuse_purged_take() SET search_path = pg_catalog, public`);
+ const [check] = await run(engine);
+ expect(check).toMatchObject({
+ name: 'function_search_path', status: 'fail',
+ fix: { argv: ['psql', '-c', 'ALTER FUNCTION public.gbrain_refuse_purged_take() SET search_path = pg_catalog, public, pg_temp;'], actor: 'host_admin', consent: [],
+ verify: { argv: ['gbrain', 'doctor', '--only', 'function_search_path', '--json'] }, docs: 'docs/guides/troubleshooting.md#function-search-path' },
+ details: { functions: ['gbrain_refuse_purged_take()'], sql: ['ALTER FUNCTION public.gbrain_refuse_purged_take() SET search_path = pg_catalog, public, pg_temp;'] },
+ });
+ expect(check!.message).toContain('as the role that owns each function');
+ await engine.runMigration(0, `ALTER FUNCTION gbrain_refuse_purged_take() SET search_path = pg_catalog, public, pg_temp`);
+ }, 120_000);
+
+ test('below v277 the check points at gbrain apply-migrations --yes instead of hand-written ALTERs (#7688)', async () => {
+ await engine.runMigration(0, `ALTER FUNCTION gbrain_refuse_purged_take() SET search_path = pg_catalog, public`);
+ const latest = await engine.getConfig('version');
+ await engine.setConfig('version', '276');
+ try {
+ const [check] = await run(engine);
+ expect(check).toMatchObject({
+ name: 'function_search_path', status: 'fail',
+ fix: { argv: ['gbrain', 'apply-migrations', '--yes', '--no-autopilot-install'], actor: 'agent', requires_exclusive: true },
+ details: { functions: ['gbrain_refuse_purged_take()'], schema_version: 276 },
+ });
+ expect(check!.message).toContain('below migration v277');
+ expect(check!.message).not.toContain('ALTER FUNCTION');
+ } finally {
+ await engine.setConfig('version', latest!);
+ await engine.runMigration(0, `ALTER FUNCTION gbrain_refuse_purged_take() SET search_path = pg_catalog, public, pg_temp`);
+ }
+ }, 120_000);
+
+ test('a failing probe is reported as a check error, not a pass', async () => {
+ const broken = { executeRaw: async () => { throw new Error('connection reset'); } } as unknown as BrainEngine;
+ const [check] = await run(broken);
+ expect(check).toMatchObject({ name: 'function_search_path', fix_unavailable_reason: 'check_errored' });
+ expect(check!.status).not.toBe('ok');
+ expect(check!.message).toContain('connection reset');
+ });
});
diff --git a/test/e2e/function-search-path-postgres.test.ts b/test/e2e/function-search-path-postgres.test.ts
index 119024896c..f3ae834bad 100644
--- a/test/e2e/function-search-path-postgres.test.ts
+++ b/test/e2e/function-search-path-postgres.test.ts
@@ -265,13 +265,15 @@ describeE2E('a temp table or view named like a ledger hides nothing from the gua
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(stderr.split('1 function(s) left without pg_temp on their search_path (gbrain_refuse_purged_fact())').length - 1).toBe(1);
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;'],
+ fix: ['ALTER FUNCTION public.gbrain_refuse_purged_fact() SET search_path = pg_catalog, public, pg_temp;'],
});
+ const atHead = await capturingStderr(() => runMigrations(engine));
+ expect(atHead.stderr).not.toContain('left without pg_temp');
await brain.conn.unsafe(`SET ROLE ${other}; ${fix.join('\n')} RESET ROLE;`);
expect(await functionSearchPathProblems(engine)).toEqual({ functions: [], fix: [] });
await engine.initSchema();
@@ -308,7 +310,8 @@ describeE2E('a temp table or view named like a ledger hides nothing from the gua
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' }, () => v277.handler!(engine).then(() => null, (e: unknown) => e));
- expect(error).toMatchObject({ code: 'schema_lock_blocked', detail: 'v277 search_path' });
+ expect(error).toMatchObject({ code: 'schema_lock_blocked', detail: 'search_path hardening' });
+ expect((error as Error).message).toContain('for a gbrain function row lock (pg_proc) another session holds');
expect((await catalog(conn)).withoutTemp).toEqual(['gbrain_try_jsonb(text)']);
} finally {
await session.unsafe('ROLLBACK');
diff --git a/test/fixtures/guards/check-search-path.sh/good/src/core/pglite-schema.generated.ts b/test/fixtures/guards/check-search-path.sh/good/src/core/pglite-schema.generated.ts
index 498a16f7f7..ccf06e6c12 100644
--- a/test/fixtures/guards/check-search-path.sh/good/src/core/pglite-schema.generated.ts
+++ b/test/fixtures/guards/check-search-path.sh/good/src/core/pglite-schema.generated.ts
@@ -1,4 +1,4 @@
// Guard self-test fixture (known-GOOD): hardened trigger in the generated template.
export const PGLITE_SCHEMA_TEMPLATE = `
-CREATE OR REPLACE FUNCTION touch_updated_at() RETURNS trigger SET search_path = pg_catalog, public AS $$ BEGIN RETURN NEW; END $$ LANGUAGE plpgsql;
+CREATE OR REPLACE FUNCTION touch_updated_at() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS $$ BEGIN RETURN NEW; END $$ LANGUAGE plpgsql;
`;
diff --git a/test/fixtures/guards/check-search-path.sh/good/src/schema.sql b/test/fixtures/guards/check-search-path.sh/good/src/schema.sql
index e7d6a35516..ffd340e0eb 100644
--- a/test/fixtures/guards/check-search-path.sh/good/src/schema.sql
+++ b/test/fixtures/guards/check-search-path.sh/good/src/schema.sql
@@ -1,2 +1,2 @@
-- Guard self-test fixture (known-GOOD): hardened trigger function.
-CREATE OR REPLACE FUNCTION touch_updated_at() RETURNS trigger SET search_path = pg_catalog, public AS $$ BEGIN RETURN NEW; END $$ LANGUAGE plpgsql;
+CREATE OR REPLACE FUNCTION touch_updated_at() RETURNS trigger SET search_path = pg_catalog, public, pg_temp AS $$ BEGIN RETURN NEW; END $$ LANGUAGE plpgsql;
diff --git a/test/function-search-path-harden.test.ts b/test/function-search-path-harden.test.ts
new file mode 100644
index 0000000000..affb7197f3
--- /dev/null
+++ b/test/function-search-path-harden.test.ts
@@ -0,0 +1,46 @@
+/**
+ * hardenFunctionSearchPaths (#7688): a concurrent update of the same pg_proc row ("tuple concurrently updated", e.g.
+ * `apply-migrations --force-schema` beside another process's boot) is retried, since the step is idempotent; and a
+ * hardening that committed but could not list what it left returns null instead of reading as "not restored".
+ */
+import { describe, expect, test } from 'bun:test';
+import { hardenFunctionSearchPaths } from '../src/core/function-search-path.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+function stubEngine(opts: { failTransactions: number; listFailsAfterCommit?: boolean }) {
+ const state = { transactions: 0, committed: false };
+ const engine = {
+ kind: 'pglite',
+ executeRaw: async () => {
+ if (!state.committed) return [{ sig: 'gbrain_try_jsonb(text)' }];
+ if (opts.listFailsAfterCommit) throw new Error('connection reset');
+ return [];
+ },
+ transaction: async (fn: (tx: unknown) => Promise<void>) => {
+ state.transactions++;
+ if (state.transactions <= opts.failTransactions) throw new Error('tuple concurrently updated');
+ await fn({ executeRaw: async () => [], runMigration: async () => {} });
+ state.committed = true;
+ },
+ } as unknown as BrainEngine;
+ return { engine, state };
+}
+
+describe('hardenFunctionSearchPaths (#7688)', () => {
+ test('a concurrent pg_proc update is retried and the hardening completes', async () => {
+ const { engine, state } = stubEngine({ failTransactions: 1 });
+ expect(await hardenFunctionSearchPaths(engine)).toEqual([]);
+ expect(state.transactions).toBe(2);
+ });
+
+ test('a concurrent update that keeps recurring still surfaces after the bounded attempts', async () => {
+ const { engine, state } = stubEngine({ failTransactions: 99 });
+ await expect(hardenFunctionSearchPaths(engine)).rejects.toThrow('tuple concurrently updated');
+ expect(state.transactions).toBe(3);
+ });
+
+ test('a committed hardening whose follow-up listing fails returns null, not an error', async () => {
+ const { engine } = stubEngine({ failTransactions: 0, listFailsAfterCommit: true });
+ expect(await hardenFunctionSearchPaths(engine)).toBeNull();
+ });
+});
diff --git a/test/function-search-path-pglite.test.ts b/test/function-search-path-pglite.test.ts
index 5a5e4fc0e3..87e95a5799 100644
--- a/test/function-search-path-pglite.test.ts
+++ b/test/function-search-path-pglite.test.ts
@@ -5,7 +5,8 @@
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { PINNED_FUNCTION_NAMES } from '../src/core/function-search-path.ts';
+import { FUNCTION_SEARCH_PATH_HARDENING_SQL, PINNED_FUNCTION_NAMES, legacySearchPathFunctions } from '../src/core/function-search-path.ts';
+import { getPGLiteSchema } from '../src/core/pglite-schema.generated.ts';
const PURGED_CLAIM = 'alice-example joined acme-example as cto';
const WITHDRAWN_CLAIM = 'alice-example lives in city-a';
@@ -83,4 +84,10 @@ describe('function search_path ends in pg_temp on PGLite (#7632)', () => {
await engine.executeRaw('DROP PROCEDURE IF EXISTS public.proc_example()');
}
}, 120_000);
+ test('a schema replay keeps pg_temp by itself: each definition pins it, not only the hardening statement after it (#7785)', async () => {
+ const schema = getPGLiteSchema();
+ expect(schema).toContain(FUNCTION_SEARCH_PATH_HARDENING_SQL);
+ await engine.runMigration(0, schema.replace(FUNCTION_SEARCH_PATH_HARDENING_SQL, ''));
+ expect(await legacySearchPathFunctions(engine)).toEqual([]);
+ }, 120_000);
});
diff --git a/test/migrate-search-path-best-effort.serial.test.ts b/test/migrate-search-path-best-effort.serial.test.ts
index 7dc9f0ad6e..1343be5a03 100644
--- a/test/migrate-search-path-best-effort.serial.test.ts
+++ b/test/migrate-search-path-best-effort.serial.test.ts
@@ -6,16 +6,30 @@
*/
import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';
-const V277 = '../src/core/schema-migrations/v277-function-search-path-pg-temp.ts';
-const actual = await import(V277);
+const HARDENING = '../src/core/function-search-path.ts';
+const actual = await import(HARDENING);
const harden = actual.hardenFunctionSearchPaths;
-mock.module(V277, () => ({ ...actual, hardenFunctionSearchPaths: async (engine: unknown, label: string) => {
- if (label === 'v277') return harden(engine as never, label);
- throw new Error('canceling statement due to lock timeout');
+const state: { calls: number; failFrom: number; error: () => Error } = { calls: 0, failFrom: Infinity, error: () => new Error('canceling statement due to lock timeout') };
+mock.module(HARDENING, () => ({ ...actual, hardenFunctionSearchPaths: async (engine: unknown) => {
+ state.calls++;
+ if (state.calls < state.failFrom) return harden(engine as never);
+ throw state.error();
} }));
+const { v277 } = await import('../src/core/schema-migrations/v277-function-search-path-pg-temp.ts');
const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');
const { LATEST_VERSION, runMigrations } = await import('../src/core/migrate.ts');
+async function captureStderr<T>(run: () => Promise<T>): Promise<{ result: T | Error; 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 { result: await run().catch((e: Error) => e), stderr };
+ } finally {
+ process.stderr.write = write;
+ }
+}
+
describe('the search_path step after a migration run is best-effort (#7632)', () => {
let engine: InstanceType<typeof PGLiteEngine>;
beforeAll(async () => {
@@ -24,22 +38,43 @@ describe('the search_path step after a migration run is best-effort (#7632)', ()
await engine.initSchema();
}, 120_000);
afterAll(async () => { await engine?.disconnect(); });
+ const searchPath = async (name: string) => (await engine.executeRaw<{ setting: string }>(
+ `SELECT s.setting FROM pg_proc p CROSS JOIN LATERAL unnest(p.proconfig) AS s(setting) WHERE p.proname = '${name}' AND s.setting LIKE 'search_path=%'`))[0]?.setting;
test('the migration run finishes the upgrade and names the failed step when it throws', async () => {
await engine.executeRaw(`ALTER FUNCTION gbrain_try_jsonb(text) SET search_path = pg_catalog, public`);
- await engine.executeRaw(`UPDATE config SET value = '${actual.v277.version - 1}' WHERE key = 'version'`);
- 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 {
- expect((await runMigrations(engine)).applied).toBe(LATEST_VERSION - actual.v277.version + 1);
- } finally {
- process.stderr.write = write;
- }
+ await engine.executeRaw(`UPDATE config SET value = '${v277.version - 1}' WHERE key = 'version'`);
+ Object.assign(state, { calls: 0, failFrom: 2 });
+ const { result, stderr } = await captureStderr(() => runMigrations(engine));
+ expect(result).toEqual({ applied: LATEST_VERSION - v277.version + 1, current: LATEST_VERSION });
expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));
expect(stderr).toContain('search_path: pg_temp not restored on gbrain functions (canceling statement due to lock timeout)');
- const [row] = await engine.executeRaw<{ setting: string }>(
- `SELECT s.setting FROM pg_proc p CROSS JOIN LATERAL unnest(p.proconfig) AS s(setting) WHERE p.proname = 'gbrain_try_jsonb' AND s.setting LIKE 'search_path=%'`);
- expect(row!.setting).toBe('search_path=pg_catalog, public, pg_temp');
+ expect(await searchPath('gbrain_try_jsonb')).toBe('search_path=pg_catalog, public, pg_temp');
+ }, 120_000);
+
+ test('at the latest version (nothing pending) a failing search_path step still lets the run finish and names it (#7688)', async () => {
+ await engine.executeRaw(`ALTER FUNCTION gbrain_try_jsonb(text) SET search_path = pg_catalog, public`);
+ Object.assign(state, { calls: 0, failFrom: 1 });
+ const { result, stderr } = await captureStderr(() => runMigrations(engine));
+ expect(result).toEqual({ applied: 0, current: LATEST_VERSION });
+ expect(state.calls).toBe(1);
+ expect(stderr).toContain('search_path: pg_temp not restored on gbrain functions (canceling statement due to lock timeout)');
+ Object.assign(state, { calls: 0, failFrom: Infinity });
+ expect(await captureStderr(() => runMigrations(engine))).toEqual({ result: { applied: 0, current: LATEST_VERSION }, stderr: '' });
+ expect(await searchPath('gbrain_try_jsonb')).toBe('search_path=pg_catalog, public, pg_temp');
+ }, 120_000);
+
+ test('a run a migration stopped on a lock it could not take skips the search_path step instead of waiting a second lock_timeout (#7688)', async () => {
+ await engine.executeRaw(`UPDATE config SET value = '${v277.version - 1}' WHERE key = 'version'`);
+ const lockError = () => Object.assign(new Error('canceling statement due to lock timeout'), { code: '55P03' });
+ Object.assign(state, { calls: 0, failFrom: 1, error: lockError });
+ const { result, stderr } = await captureStderr(() => runMigrations(engine));
+ expect(result).toBeInstanceOf(Error);
+ expect(state.calls).toBe(1);
+ expect(stderr).toContain('search_path: not put back on gbrain functions after the lock refusal');
+ expect(stderr).not.toContain('pg_temp not restored');
+ expect(await engine.getConfig('version')).toBe(String(v277.version - 1));
+ Object.assign(state, { calls: 0, failFrom: Infinity });
+ expect((await captureStderr(() => runMigrations(engine))).result).toEqual({ applied: LATEST_VERSION - v277.version + 1, current: LATEST_VERSION });
}, 120_000);
});
diff --git a/test/scripts/check-search-path.test.ts b/test/scripts/check-search-path.test.ts
index 05852c70a5..82b1ab3fe4 100644
--- a/test/scripts/check-search-path.test.ts
+++ b/test/scripts/check-search-path.test.ts
@@ -55,13 +55,32 @@ describe('check-search-path.sh', () => {
it('flags the legacy RETURNS trigger AS form and accepts a pinned header spread over lines', () => {
write('src/a.sql', 'CREATE OR REPLACE FUNCTION legacy_fn() RETURNS trigger AS $$ BEGIN RETURN NEW; END $$;\n');
- write('src/b.ts', 'const s = `CREATE OR REPLACE FUNCTION pinned_fn() RETURNS trigger\n LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$ BEGIN RETURN NEW; END $fn$`;\n');
+ write('src/b.ts', 'const s = `CREATE OR REPLACE FUNCTION pinned_fn() RETURNS trigger\n LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$ BEGIN RETURN NEW; END $fn$`;\n');
const run = guard();
expect(run.code).toBe(1);
expect(run.out).toContain('src/a.sql:1: legacy_fn');
expect(run.out).not.toContain('pinned_fn');
});
+ it('flags a pinned search_path that does not end in pg_temp, LANGUAGE sql included (#7785)', () => {
+ write('src/a.sql', 'CREATE OR REPLACE FUNCTION legacy_path() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$ BEGIN RETURN NEW; END $fn$;\n');
+ write('src/b.ts', 'const s = `CREATE OR REPLACE FUNCTION sql_path(t text) RETURNS text\n LANGUAGE sql IMMUTABLE SET search_path = pg_catalog\nAS $fn$ SELECT t $fn$`;\n');
+ const run = guard();
+ expect(run.code).toBe(1);
+ expect(run.out).toContain('src/a.sql:1: legacy_path (search_path = pg_catalog, public does not end in pg_temp)');
+ expect(run.out).toContain('src/b.ts:1: sql_path (search_path = pg_catalog does not end in pg_temp)');
+ });
+
+ it('flags a pinned function missing from PINNED_FUNCTION_NAMES when the allowlist file exists (#7688)', () => {
+ write('src/core/function-search-path.ts', "export const PINNED_FUNCTION_NAMES = [\n 'listed_fn',\n] as const;\n");
+ write('src/schema.sql', 'CREATE OR REPLACE FUNCTION listed_fn() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$ BEGIN RETURN NEW; END $fn$;\n'
+ + 'CREATE OR REPLACE FUNCTION public.unlisted_fn() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$ BEGIN RETURN NEW; END $fn$;\n');
+ const run = guard();
+ expect(run.code).toBe(1);
+ expect(run.out).toContain('src/schema.sql:2: unlisted_fn (not in PINNED_FUNCTION_NAMES)');
+ expect(run.out).not.toContain('src/schema.sql:1:');
+ });
+
it('exempts LANGUAGE sql functions and historical migration bodies', () => {
write('src/core/facts/fn.ts', 'const s = `CREATE OR REPLACE FUNCTION inlinable(claim TEXT) RETURNS TEXT\n LANGUAGE SQL IMMUTABLE STRICT AS $fn$ SELECT pg_catalog.lower(claim) $fn$`;\n');
write('src/core/schema-migrations/v001-old.ts', 'const s = `CREATE OR REPLACE FUNCTION old_fn() RETURNS trigger AS $$ BEGIN RETURN NEW; END $$`;\n');