import type { SessionAttachmentReadAccess } from "./session-file-attachments"; import { AsyncLocalStorage } from "node:async_hooks"; import { eq, sql, type SQL } from "drizzle-orm"; import type { PgDatabase, PgTransactionConfig } from "drizzle-orm/pg-core"; import { drizzle } from "drizzle-orm/postgres-js"; import type { Settings } from "@opengeni/config"; import postgres from "postgres"; import { databaseBootConnectOptions } from "./boot-connect"; import { databaseUrlUser, logDatabaseCredentialEvent, rotatingDatabasePasswordFor, type RotatingDatabasePassword, type DatabaseCredentialEventListener, type DatabasePasswordFiles, withDatabaseAuthenticationRetry, } from "./database-credentials"; import { DatabaseTransactionError, isDatabaseConnectionLoss, isDatabasePersistenceFailure, isRetryableDatabaseTransportFailure, nestedPostgresSqlState, runIdempotentPersistenceTransaction, type IdempotentPersistenceTransactionOptions, } from "./persistence-errors"; import { LOSSLESS_CONTENT_WRITER_APPLICATION_NAME } from "./lossless-json"; import * as schema from "./schema"; import { startDatabaseTiming } from "./database-timing"; import { traceQuery, traceTransaction } from "./database-spans"; import { createSessionListChangeSource, type SessionListChangeSource, } from "./session-list-notifications"; // Structural cross-driver query port. Opengeni passes explicit tables to its // builders; it never uses Drizzle's schema-registered relational `query` API. // Omit that API at both root and transaction scope without rejecting a host's // richer schema-configured handle. The query-result HKT remains deliberately // driver-independent; standalone raw row arrays retain their existing shape. export type Database = Omit, "query" | "transaction"> & { transaction( run: (tx: DatabaseTransaction) => Promise, config?: PgTransactionConfig, ): Promise; }; type DatabaseTransaction = Database & { rollback(): never }; declare const sessionActivityDatabaseBrand: unique symbol; /** * A workspace-scoped session writer transaction. The BEFORE row trigger stamps * activity in the same write; the brand retains the writer/tenancy boundary. */ export type SessionActivityDatabase = Database & { readonly [sessionActivityDatabaseBrand]: true; }; export type DbClient = { db: Database; close: () => Promise; }; export type RlsContext = { accountId: string; workspaceId?: string | null; }; /** The requested tenant no longer exists. Other scope/setup failures stay errors. */ export class WorkspaceNotFoundError extends Error { constructor(readonly workspaceId: string) { super(`Workspace not found: ${workspaceId}`); } } export type SessionRlsActorContext = { /** Server-authorized session attachment scope; never taken from request JSON. */ sessionAttachmentReadAccess?: SessionAttachmentReadAccess; subjectId: string; /** Host-verified personal file ownership, never a request-supplied subject. */ privateFileOwnerSubjectId?: string | null; initiatingHumanSubjectId?: string | null; /** Root reconstructed from a verified live agent attempt, never page input. */ agentRootSessionId?: string | null; }; /** Request-local proof from the signed published-Site gateway and live viewer cookie. */ export type SiteViewerRlsContext = Readonly<{ siteId: string; principal: string }>; const siteViewerRlsContext = new AsyncLocalStorage(); export function currentSiteViewerRlsContext(): SiteViewerRlsContext | undefined { return siteViewerRlsContext.getStore(); } export function withSiteViewerRlsContext(context: SiteViewerRlsContext, run: () => T): T { return siteViewerRlsContext.run(Object.freeze({ ...context }), run); } const sessionRlsActorContext = new AsyncLocalStorage(); export function currentSessionAttachmentReadAccess(): SessionAttachmentReadAccess | undefined { return sessionRlsActorContext.getStore()?.sessionAttachmentReadAccess; } /** * The ambient session RLS actor established by the caller, if any. Read-only: * helpers use it to decide whether the caller already owns session access and * must never mutate it. */ export function currentSessionRlsActorContext(): Readonly | undefined { return sessionRlsActorContext.getStore(); } /** * Runs `fn` with no session RLS actor, so its reads see the tenant as the * system does (private chats included). Only for narrow reads whose result is * never disclosed to the request, or whose disclosure a durable binding * already authorizes (a chat's own agent, read for its system prompt); not * re-exported from the package. */ export async function withoutSessionRlsActor(fn: () => Promise): Promise { return await sessionRlsActorContext.exit(() => siteViewerRlsContext.exit(fn)); } /** * Stable identity of the ambient session RLS actor: every field that * `setRlsContext` turns into database-visible GUCs or that scoped reads * consult. Two callers with equal keys see exactly the same rows, so the key * is safe for sharing a read result between them; `null` means no actor, in * which case the subject GUC stays empty for every such caller. */ export function currentSessionRlsActorIdentityKey(): string | null { const actor = sessionRlsActorContext.getStore(); if (!actor) return null; return JSON.stringify([ actor.subjectId, actor.initiatingHumanSubjectId ?? null, actor.privateFileOwnerSubjectId ?? null, actor.sessionAttachmentReadAccess ?? null, actor.agentRootSessionId ?? null, siteViewerRlsContext.getStore() ?? null, ]); } /** * The ambient session RLS actor's frozen initiating human: `undefined` when * there is no actor, `null` when the actor has no human. Reads that must act * for the turn's human take it from here, never from a caller argument. */ export function currentSessionRlsActorInitiatingHumanSubjectId(): string | null | undefined { const actor = sessionRlsActorContext.getStore(); if (!actor) return undefined; return actor.initiatingHumanSubjectId ?? null; } export async function withSessionRlsActorContext( actor: SessionRlsActorContext, fn: () => Promise, ): Promise { if (!actor.subjectId.trim()) { throw new Error("withSessionRlsActorContext: a non-empty subjectId is required"); } if ( actor.initiatingHumanSubjectId !== undefined && actor.initiatingHumanSubjectId !== null && !actor.initiatingHumanSubjectId.trim() ) { throw new Error( "withSessionRlsActorContext: initiatingHumanSubjectId must be null or non-empty", ); } if ( actor.privateFileOwnerSubjectId !== undefined && actor.privateFileOwnerSubjectId !== null && !actor.privateFileOwnerSubjectId.trim() ) { throw new Error( "withSessionRlsActorContext: privateFileOwnerSubjectId must be null or non-empty", ); } return await sessionRlsActorContext.run(actor, fn); } type RlsContextSettings = { accountId: string; workspaceId: string; subjectId: string; privateFileOwnerSubjectId: string; initiatingHumanSubjectId: string; personalResourceHumanSubjectId: string; personalResourceActorSubjectId: string; agentRootSessionId: string; siteId: string; siteViewerPrincipal: string; }; /** * RLS posture for the connection Opengeni's query layer runs over (Step I, §7.7). * * - `"force"` (DEFAULT — today's standalone behavior, byte-for-byte): Opengeni * connects as a NON-OWNER role (`opengeni_app`) and every table carries * `FORCE ROW LEVEL SECURITY`, so the workspace/account GUCs set by * `setRlsContext` are the ONLY thing that admits rows — even the table owner * is subject to RLS. This is the Fork-A isolation guarantee. * - `"scoped"` (embedded Fork-B opt-in): the host runs Opengeni's queries over a * role that OWNS the dedicated schema (RLS need not be forced for that role), * relying on the host's own tenant boundary. Opengeni STILL emits the * `set_config('opengeni.account_id'/'workspace_id', …)` GUCs defensively on * every scoped query, so the application query path is byte-identical between * the two strategies and the app code is RLS-mode-agnostic. The strategy is a * declared posture (consumed by `provisionRoles` and as a documented * invariant), NOT a query-path branch — there is deliberately no `if * (strategy === …)` anywhere in the helpers below. Picking `"scoped"` does not * relax any GUC; it only changes which DB role the host provisions/connects as * and asserts that the host accepts owning the isolation boundary. */ export type RlsStrategy = "force" | "scoped"; /** * Resolve a host-IdP/Better-Auth user *identifier* by email. Injected via * `createDb({ userLookup })` (Step I). UNSET → today's raw parameterized select * against Better Auth's `auth_users` table (see `getManagedUserByEmail`), which * relies on the postgres-js array-shaped `db.execute` result. An embedded host * whose identity lives elsewhere (a different IdP table, a different driver, or * a non-`auth_users` user store) injects this closure so Opengeni never touches * `auth_users` directly. Returns the user id, or null when no such user exists. */ export type UserLookup = (db: Database, email: string) => Promise; export type ManagedUserProfile = { id: string; name: string | null; email: string; /** * The host has verified that this person controls `email`. Only verified * addresses are bound for Site SQL's `:viewer_email`; omitted means unknown. */ emailVerified?: boolean; }; /** Host identity projection used by organization administration rosters. */ export type UserProfileLookup = ( db: Database, userIds: readonly string[], ) => Promise; export type CreateDbOptions = { /** Direct or session-pooled PostgreSQL URL for API list invalidations. Lazy; never a transaction pooler. */ notificationDatabaseUrl?: string; /** * The Postgres `search_path` for this connection (Step I, §7.8 runtime half). * UNSET → today's behavior: NO `search_path` startup parameter is sent, so the * server default applies (`public` for standalone, where every table + the * `vector` extension + `gen_random_uuid()` live). For an embedded dedicated * schema, pass e.g. `"opengeni,opengeni_private,public"` — postgres-js sends * it as a per-session startup parameter (the supported, query-param-free way; * URL `?search_path=` is IGNORED by postgres-js). Keep `public` LAST so the * `vector` type and `gen_random_uuid()` (which live in `public` on the * pgvector image) still resolve — the schema-isolation contract live footgun. */ searchPath?: string; /** RLS posture; defaults to `"force"` (today's standalone). */ rlsStrategy?: RlsStrategy; /** Host-provided user-by-email resolver; unset → today's raw `auth_users` query. */ userLookup?: UserLookup; /** Host-provided user profile projection; unset → standalone `auth_users`. */ userProfileLookup?: UserProfileLookup; /** postgres-js pool size; defaults to today's `10`. */ max?: number; /** * How long a refused first connection is retried while the client has never * reached the server; defaults to the boot grace. 0 fails immediately. */ bootConnectGraceMs?: number; /** * Use named prepared statements. Unset → {@link defaultDatabasePreparedStatements}: * on for a direct connection, off behind PgBouncer's port. Pass `false` for any * other transaction-pooling proxy. */ preparedStatements?: boolean; /** * Seconds an idle pooled connection stays open before it closes. Unset → * {@link DEFAULT_DATABASE_POOL_IDLE_TIMEOUT_SECONDS}; 0 keeps idle connections * open until their lifetime ends. */ idleTimeoutSeconds?: number; /** * Upper bound, in seconds, on a pooled connection's age. Each connection slot * draws its own lifetime between 75% and 100% of this, so connections opened * together do not all reconnect together. Unset → * {@link DEFAULT_DATABASE_POOL_MAX_LIFETIME_SECONDS}; 0 never recycles. */ maxLifetimeSeconds?: number; /** * Connection-local default transaction isolation sent in the postgres-js * startup parameters. This is intentionally not a role/database default: * tests and embedded callers can exercise a different ambient isolation * without mutating a shared PostgreSQL role or affecting other connections. */ isolationLevel?: postgres.ConnectionParameters["default_transaction_isolation"]; /** * Read the login's password from mounted files on every connection attempt * instead of from the URL, so it can be rotated while the process runs (see * `RotatingDatabasePassword`). Unset (or no file configured) → today's * behavior: the URL password, no password function, no added retry. Also * applies to the session-list LISTEN connection when * `notificationDatabaseUrl` logs in as the same user. */ passwordFiles?: DatabasePasswordFiles; /** * Content-free credential events (switches, reloads) of the pool and of its * LISTEN connection; defaults to a console line. */ onCredentialEvent?: DatabaseCredentialEventListener; }; /** * The active RLS strategy + userLookup for an injected `Database`, recorded in a * side WeakMap so helpers (and `getManagedUserByEmail`) can consult the host's * binding without changing every call signature. A handle with no recorded * config (e.g. one built outside `createDb`, or in a test) falls back to the * standalone defaults: `rlsStrategy: "force"`, raw `auth_users` lookup. */ type DbBinding = { rlsStrategy: RlsStrategy; userLookup?: UserLookup; userProfileLookup?: UserProfileLookup; sessionListChanges?: SessionListChangeSource; cancellableTransactions?: boolean; }; const dbBindings = new WeakMap(); /** Absent for externally constructed handles or transaction-only connections. */ export function sessionListChangesFor(db: Database): SessionListChangeSource | undefined { return dbBindings.get(db as object)?.sessionListChanges; } /** The strategy bound to a handle (or the `"force"` default). */ export function rlsStrategyFor(db: Database): RlsStrategy { return dbBindings.get(db as unknown as object)?.rlsStrategy ?? "force"; } /** * Run a raw SQL query and read its rows as a typed array. * * Why this exists: the Step I driver widening (`Database = PgDatabase`) * deliberately sets the query-result HKT to `any` so `db.execute(…)` is callable * across drivers whose raw-result shapes differ (postgres-js → row array; * node-postgres → `{ rows }`). A side effect is that `db.execute(…)` now * resolves to `any`, erasing the per-row element type at the call site. Opengeni's * OWN internal raw queries usually run over the postgres-js handle `createDb` * builds (array result), while an embedded host may inject a node-postgres style * driver (`{ rows }`). Normalize those two standard shapes in one place; reject * an unknown driver result rather than silently treating it as an empty query. */ export async function rawRows>( executor: Pick, query: SQL, ): Promise { const result = await executor.execute(query); if (Array.isArray(result)) { return result as unknown as T[]; } const rows = (result as unknown as { rows?: unknown }).rows; if (Array.isArray(rows)) { return rows as T[]; } throw new Error("Unsupported database execute() result shape"); } export type SandboxProviderReadLockIdentity = { workspaceId: string; sandboxGroupId: string; leaseEpoch: number; instanceId: string; }; export class SandboxProviderReadLockUnavailableError extends Error { constructor() { super("Sandbox provider reads are temporarily busy. Retry the request."); this.name = "SandboxProviderReadLockUnavailableError"; } } const SANDBOX_PROVIDER_READ_LOCK_WAIT_MS = 15_000; const SANDBOX_PROVIDER_READ_LOCK_POLL_MAX_MS = 200; function sandboxProviderReadLockKey(identity: SandboxProviderReadLockIdentity): string { return [ "sandbox-provider-read", identity.workspaceId, identity.sandboxGroupId, identity.leaseEpoch, identity.instanceId, ].join(":"); } async function waitForSandboxProviderReadLockPoll( delayMs: number, signal?: AbortSignal | undefined, ): Promise { if (signal?.aborted) { throw signal.reason ?? new DOMException("The operation was aborted", "AbortError"); } await new Promise((resolve, reject) => { let settled = false; let timer: ReturnType; const cleanup = () => signal?.removeEventListener("abort", abort); const finish = () => { if (settled) return; settled = true; cleanup(); resolve(); }; const abort = () => { if (settled) return; settled = true; clearTimeout(timer); cleanup(); reject(signal?.reason ?? new DOMException("The operation was aborted", "AbortError")); }; timer = setTimeout(finish, delayMs); signal?.addEventListener("abort", abort, { once: true }); if (signal?.aborted) abort(); }); } /** * Cross-process exclusive boundary for one exact live provider instance's * API-direct read request. Modal accepts concurrent commands from one attached * handle, but independent API replicas reconstruct different handles; issuing * overlapping command groups through those handles can make an otherwise valid * read fail transiently. Keep concurrency inside one batched request while * serializing only separate requests that target the same lease identity. * * The callback intentionally runs while one transaction-pinned DB connection * holds the advisory lock. The direct lease holder separately prevents drain, * and the abort-aware bounded poll prevents a disconnected HTTP request from * occupying the connection indefinitely. */ export async function withSandboxProviderReadLock( db: Database, identity: SandboxProviderReadLockIdentity, signal: AbortSignal | undefined, fn: () => Promise, ): Promise { const key = sandboxProviderReadLockKey(identity); const deadline = Date.now() + SANDBOX_PROVIDER_READ_LOCK_WAIT_MS; return await db.transaction(async (lockedDb) => { let pollMs = 20; while (true) { if (signal?.aborted) { throw signal.reason ?? new DOMException("The operation was aborted", "AbortError"); } const [row] = await rawRows<{ acquired: boolean }>( lockedDb, sql`select pg_try_advisory_xact_lock(hashtextextended(${key}, 0)) as acquired`, ); if (row?.acquired === true) return await fn(); const remainingMs = deadline - Date.now(); if (remainingMs <= 0) throw new SandboxProviderReadLockUnavailableError(); await waitForSandboxProviderReadLockPoll(Math.min(pollMs, remainingMs), signal); pollMs = Math.min(pollMs * 2, SANDBOX_PROVIDER_READ_LOCK_POLL_MAX_MS); } }); } /** Jittered reconnect delay in seconds after `retries` consecutive connection failures. */ export function databaseReconnectBackoffSeconds(retries: number): number { return (0.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 2); } /** PgBouncer's port, which Azure Flexible Server's built-in pooler always uses. */ const PGBOUNCER_PORT = "6432"; /** * Whether a pool should use named prepared statements when the operator has not * said. A direct Postgres connection should: postgres-js otherwise sends every * parameterized statement unnamed and must wait for a Describe reply before it * can Bind, so each such statement costs two round trips instead of one, and the * server re-parses and re-plans it every time. A transaction-pooling PgBouncer * must not: named statements live on one backend, the pooler hands the next * transaction a different one, and execution intermittently fails with * `prepared statement "s_N" does not exist`. Port 6432 is the only signal the URL * carries; other poolers need `preparedStatements: false` explicitly. */ export function defaultDatabasePreparedStatements(databaseUrl: string): boolean { const authority = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/?#]*@)?([^/?#]*)/i.exec(databaseUrl)?.[1] ?? ""; return !authority.split(",").some((host) => host.endsWith(`:${PGBOUNCER_PORT}`)); } /** * Each PostgreSQL backend keeps its catalog cache, and the plans of every * statement it has prepared, until the connection closes. Measured on the * migrated schema as the FORCE-RLS runtime role, a backend that has run the * app's statements holds about 45 MB unprepared and 125-220 MB prepared, and an * idle one keeps all of it. Close idle connections after 30 seconds: reopening * costs the next query a connection handshake (tens of milliseconds) and about * 0.25 ms of cache warmup per statement it runs again. */ export const DEFAULT_DATABASE_POOL_IDLE_TIMEOUT_SECONDS = 30; /** * The pool reuses the most recently idle connection first, so a busy * connection never reaches the idle timeout. Its memory keeps growing with * every new statement text, every generic plan, and every IN-list or multi-row * VALUES arity it prepares. Recycling at most every ten minutes bounds that * growth; a new backend pays its warmup again (well under a second for every * statement the app runs), about 0.05% of the lifetime. */ export const DEFAULT_DATABASE_POOL_MAX_LIFETIME_SECONDS = 600; /** * The longest timer the runtime can arm (2^31 - 1 ms). A longer delay does not * wait longer: Node and Bun fire it after 1 ms, which would close every * connection right after it opens or goes idle. Use 0 to turn a timer off. */ export const MAX_DATABASE_POOL_TIMER_SECONDS = 2_147_483; function poolSeconds(name: string, value: number): number { if (!Number.isFinite(value) || value < 0 || value > MAX_DATABASE_POOL_TIMER_SECONDS) { throw new TypeError( `createDb: ${name} must be between 0 and ${MAX_DATABASE_POOL_TIMER_SECONDS} seconds (0 turns it off)`, ); } return value; } /** * postgres.js evaluates a function `max_lifetime` once per connection slot, * which is how its own default (30-60 minutes) is jittered. Draw from the top * quarter below the configured bound so the bound holds. */ export function jitteredDatabaseMaxLifetime(maxSeconds: number): () => number { const bound = poolSeconds("maxLifetimeSeconds", maxSeconds); return () => bound * (0.75 + Math.random() / 4); } /** Pool options taken from deployment settings; unset fields keep the pool defaults. */ export function databasePoolOptions( settings: Pick< Settings, | "databasePreparedStatements" | "databasePoolIdleTimeoutSeconds" | "databasePoolMaxLifetimeSeconds" >, ): Pick { return { ...(settings.databasePreparedStatements === undefined ? {} : { preparedStatements: settings.databasePreparedStatements }), ...(settings.databasePoolIdleTimeoutSeconds === undefined ? {} : { idleTimeoutSeconds: settings.databasePoolIdleTimeoutSeconds }), ...(settings.databasePoolMaxLifetimeSeconds === undefined ? {} : { maxLifetimeSeconds: settings.databasePoolMaxLifetimeSeconds }), }; } type PostgresSql = postgres.Sql | postgres.TransactionSql; const databaseQuerySignal = new AsyncLocalStorage(); /** * Run a pool query again after its connection was refused with 28P01, on the * password candidate the pool then selects (see * `withDatabaseAuthenticationRetry`): only while the pool selects another * password than the refused login used, under a small hard cap; a single * password fails fast. * * Repeating is safe: PostgreSQL raises 28P01 only while authenticating a NEW * connection, before the server has run any statement on it. postgres.js * rejects only the operation that started that connection attempt (its * "initial" query or BEGIN); the queries queued behind it go to the next * attempt, which asks for the password again. So nothing the rejected * operation asked for has run, and running it again cannot apply anything * twice. The last 28P01 surfaces unchanged. */ function hasDriverQueryMode(query: unknown): boolean { const state = query as { onlyDescribe?: unknown; cursorFn?: unknown; cursorRows?: unknown; forEachFn?: unknown; streaming?: unknown; }; return Boolean( state.onlyDescribe || state.cursorFn || state.cursorRows || state.forEachFn || state.streaming, ); } function retryingAuthentication( first: postgres.PendingQuery, again: () => postgres.PendingQuery, credential: RotatingDatabasePassword, ): postgres.PendingQuery { const observe = first.then.bind(first); let result: Promise | undefined; Object.defineProperty(first, "then", { configurable: true, writable: true, value: (...args: Parameters["then"]>) => { let attempts = 0; // postgres.js queries are lazy: `then` sends them, so each attempt reads // the selected candidate right as it starts. result ??= withDatabaseAuthenticationRetry( credential, () => { attempts += 1; let settle = observe as unknown as ( resolve: (value: unknown) => void, reject: (reason: unknown) => void, ) => unknown; if (attempts > 1) { const next = again(); // Keep the caller's result mode (`.values()` / `.raw()`) and protocol // (parameterless queries default to the simple protocol; `.simple()`). const original = first as unknown as { isRaw?: unknown; options?: { simple?: unknown }; }; const retry = next as unknown as { isRaw?: unknown; options?: { simple?: unknown } }; if (original.isRaw !== undefined) retry.isRaw = original.isRaw; if (original.options && retry.options) retry.options.simple = original.options.simple; settle = next.then.bind(next) as never; } return new Promise((resolve, reject) => settle(resolve, reject)); }, // A retry re-sends the same text and parameters in the same result // mode and protocol; streaming, cursor, forEach and describe queries // keep the driver's own behavior (none goes through the pool today). () => !hasDriverQueryMode(first), ); return result.then(...args); }, }); return first; } /** Only used on a reserved transaction connection. Join the protocol cancel * before allowing rollback/release, so it cannot reach a later pool borrower. * The postgres patch exposes the driver's existing cancellation completion. */ function abortableQuery( query: postgres.PendingQuery, signal: AbortSignal, ): postgres.PendingQuery { const observe = query.then.bind(query); let result: Promise | undefined; Object.defineProperty(query, "then", { value: (...args: Parameters["then"]>) => { result ??= (async () => { signal.throwIfAborted(); let cancellation: Promise | undefined; const abort = () => { cancellation = query.cancel(); // Observe a failed cancel immediately; the query still must settle. void cancellation.catch(() => {}); }; signal.addEventListener("abort", abort, { once: true }); try { return await new Promise((resolve, reject) => observe(resolve, reject)); } finally { signal.removeEventListener("abort", abort); if (cancellation) await cancellation; signal.throwIfAborted(); } })(); return result.then(...args); }, }); return query; } /** * Postgres refuses to reuse a prepared statement whose result columns changed * since it was prepared: SQLSTATE 0A000, "cached plan must not change result * type", raised from `RevalidateCachedQuery` before the statement runs. A * rolling migration that adds a column causes it for every statement that * expands the table's row (`select *`, `table.*`, `returning *`, a CTE or * function over that row) on connections the running release prepared earlier. * Found directly or through a wrapping error's `cause` (Drizzle wraps query * failures). Other 0A000 errors are unrelated features and do not match. */ export function isStalePreparedResultError(error: unknown): boolean { let current = error; for (let depth = 0; depth < 5 && current && typeof current === "object"; depth += 1) { const candidate = current as { code?: unknown; routine?: unknown; message?: unknown }; if ( candidate.code === "0A000" && (candidate.routine === "RevalidateCachedQuery" || (typeof candidate.message === "string" && candidate.message.includes("cached plan must not change result type"))) ) { return true; } current = (current as { cause?: unknown }).cause; } return false; } /** Whether a statement in one transaction attempt was refused as stale. */ type StaleResultRefusals = { refused: boolean }; /** * Note a transaction's stale-result refusal even when the caller never sees it: * with statements in flight together (`Promise.all`), a sibling's "current * transaction is aborted" (25P02) can reject first and become the callback's * error, while the refusal that aborted the transaction settles later. */ function observingStaleRefusal( query: postgres.PendingQuery, refusals: StaleResultRefusals, ): postgres.PendingQuery { const observe = query.then.bind(query); Object.defineProperty(query, "then", { configurable: true, writable: true, value: (...[onFulfilled, onRejected]: Parameters["then"]>) => observe(onFulfilled as never, (error: unknown) => { if (isStalePreparedResultError(error)) refusals.refused = true; if (onRejected) return onRejected(error); throw error; }), }); return query; } /** * Run a pool transaction again when it failed only because a statement in it * was prepared against an older row type (see {@link isStalePreparedResultError}). * * Outside a transaction postgres.js re-prepares and repeats such a statement * (our patch keeps that working with other statements in flight). Inside one * the refusal aborts the transaction, so only the whole transaction can be * repeated. That is safe for its database work: the refused statement never * ran and the transaction rolled back, so nothing it wrote remains. As with any * repeated attempt (an activity retry, a client retry), work the callback does * outside the database runs again. * * The attempt is repeated when its error is the refusal, or when any statement * in it was refused (see {@link observingStaleRefusal}): the transaction was * aborted by then, so every later error in it follows from the refusal. * * Our postgres.js patch makes a connection forget every statement it prepared * on its first such refusal, not just the refused one, so each connection * refuses at most once per schema change. One attempt per pool connection * plus one is therefore enough for any transaction to reach a refreshed * connection; another schema change in the meantime can only add a refusal, * which surfaces unchanged once the attempts are spent. */ async function retryingStalePreparedResults( attempts: number, run: (refusals: StaleResultRefusals) => Promise, ): Promise { for (let attempt = 1; ; attempt += 1) { const refusals: StaleResultRefusals = { refused: false }; try { return await run(refusals); } catch (error) { if (attempt >= attempts || !(refusals.refused || isStalePreparedResultError(error))) { throw error; } // A maintenance stop that arrived meanwhile ends the retries. databaseQuerySignal.getStore()?.throwIfAborted(); } } } /** * Drizzle sends every query through `sql.unsafe(text, params)`, and postgres-js * never prepares `unsafe` queries unless asked per call, whatever the pool's * `prepare` option says. Ask on every call, including inside transactions and * savepoints, which hand Drizzle a fresh transaction-scoped `sql`. Queries without * parameters keep postgres-js's one-message simple protocol. * * Some statements vary their SQL text by list length (`in ($1, $2, ...)` from * `inArray`, multi-row inserts), and each length becomes another named * statement on every connection that runs it: 0.13-0.56 MB each as the RLS role. * Staging's 908 distinct statements held 24 such families with 107 texts; * preparing only the first text of each saved 7% of a warm backend's memory. * That is too little to justify a per-query family check here, so every text is * still prepared and the connection lifetime bounds the accumulation. Pass a * list as one array parameter with `anyOf` (`./sql-arrays`) where it is hot. */ function preparingUnsafe( target: T, prepare = true, reserved = false, credential?: RotatingDatabasePassword, staleResultAttempts = 1, staleRefusals?: StaleResultRefusals, ): T { const wrapScoped = (args: unknown[], refusals: StaleResultRefusals | undefined) => args.map((arg) => typeof arg === "function" ? async (scoped: postgres.TransactionSql) => { databaseQuerySignal.getStore()?.throwIfAborted(); const result = await (arg as (scoped: postgres.TransactionSql) => unknown)( preparingUnsafe(scoped, prepare, true, undefined, 1, refusals), ); databaseQuerySignal.getStore()?.throwIfAborted(); return result; } : arg, ); return new Proxy(target, { get(base, property) { if (property === "unsafe") { return (query: string, parameters?: unknown[], options?: postgres.UnsafeQueryOptions) => { const signal = reserved ? databaseQuerySignal.getStore() : undefined; signal?.throwIfAborted(); const send = () => traceQuery(base.unsafe(query, parameters as never, { prepare, ...options }), query); const pending = credential && !reserved ? retryingAuthentication(send(), send, credential) : send(); const observed = staleRefusals ? observingStaleRefusal(pending, staleRefusals) : pending; return signal ? abortableQuery(observed, signal) : observed; }; } if (property === "begin" || property === "savepoint") { const method = Reflect.get(base, property) as unknown; if (typeof method !== "function") return method; // Only the pool's own BEGIN repeats a transaction; a savepoint's // failure belongs to its enclosing transaction, which it reports to. const repeatable = (run: (refusals: StaleResultRefusals | undefined) => Promise) => property === "begin" && !reserved && staleResultAttempts > 1 ? retryingStalePreparedResults(staleResultAttempts, run) : run(staleRefusals); if (property === "begin" && credential && !reserved) { return (...args: unknown[]) => repeatable((refusals) => traceTransaction("transaction", async () => { let entered = false; const tracked = args.map((arg) => typeof arg === "function" ? (scoped: unknown) => { entered = true; return (arg as (scoped: unknown) => unknown)(scoped); } : arg, ); // Only BEGIN's own connection attempt can be repeated for // authentication: once the callback ran, its work is the // caller's to judge. let attempts = 0; return withDatabaseAuthenticationRetry( credential, () => { // A maintenance stop that arrived meanwhile ends the retries. if (attempts++ > 0) databaseQuerySignal.getStore()?.throwIfAborted(); return method.apply(base, wrapScoped(tracked, refusals)) as Promise; }, () => !entered, ); }), ); } return (...args: unknown[]) => repeatable((refusals) => traceTransaction(property === "begin" ? "transaction" : "savepoint", () => method.apply(base, wrapScoped(args, refusals)), ), ); } return Reflect.get(base, property); }, }); } export function createDb(databaseUrl: string, options: CreateDbOptions = {}): DbClient { const preparedStatements = options.preparedStatements ?? defaultDatabasePreparedStatements(databaseUrl); // idle_timeout + max_lifetime recycle connections so a pooler-recycled backend // is never reused indefinitely, and bound the memory each backend holds. // An idle connection is not just a backend slot: the backend keeps its // catalog cache and every prepared plan (tens to hundreds of megabytes on // this schema), so idle connections close after 30 s by default. A five-minute // idle timeout (#5215) let staging's backends average about 65 MB and run a // 32 GiB server out of memory at about 340 connections. See the defaults' // docs above and docs/deployment.md for sizing. const idleTimeoutSeconds = poolSeconds( "idleTimeoutSeconds", options.idleTimeoutSeconds ?? DEFAULT_DATABASE_POOL_IDLE_TIMEOUT_SECONDS, ); const maxLifetime = jitteredDatabaseMaxLifetime( options.maxLifetimeSeconds ?? DEFAULT_DATABASE_POOL_MAX_LIFETIME_SECONDS, ); // No password files: undefined, so the pool uses the URL password exactly // as before, without a password function or any added retry. const onCredentialEvent = options.onCredentialEvent ?? logDatabaseCredentialEvent("database"); const credential = rotatingDatabasePasswordFor(databaseUrl, options.passwordFiles, (event) => onCredentialEvent(event, "pool"), ); const client = postgres(databaseUrl, { max: options.max ?? 10, prepare: preparedStatements, idle_timeout: idleTimeoutSeconds, // postgres.js accepts a function here (its own default is one) but types // the option as a number. max_lifetime: maxLifetime as unknown as number, // Asked on every login attempt: re-reads the files, then returns the // pool's selected candidate and records it for that login (our postgres.js // patch passes the login's identity and tags its 28P01 with it). ...(credential ? { pass: (login: object) => credential.password(login) } : {}), // postgres.js grows one pool-wide reconnect delay after every refused or // reset connection (3^n / 100 s, up to 20 s) and queues queries behind it. // After a restart or failover that left the server refusing connections // for a while, requests then hung for up to 20 s after it was back. Keep // the same jittered growth but cap it at 2 s. backoff: databaseReconnectBackoffSeconds, // A fresh pod can be refused for a moment while its network policy and DNS // settle; retry that first connection briefly instead of failing boot. ...databaseBootConnectOptions(databaseUrl, options.bootConnectGraceMs), // `connection` carries per-session Postgres STARTUP parameters. The exact // `application_name` is also the PgBouncer-compatible current-image receipt // for migration 0352's restrictive sessions policy; arbitrary custom startup // parameters are not portable through transaction poolers. `search_path` // (embedded only) is the supported, query-param-free way to scope a connection // to a dedicated schema — postgres-js IGNORES a URL `?search_path=`. Unset // searchPath → omit it so the server default (`public`) is unchanged for // standalone. connection: { application_name: LOSSLESS_CONTENT_WRITER_APPLICATION_NAME, ...(options.searchPath ? { search_path: options.searchPath } : {}), ...(options.isolationLevel ? { default_transaction_isolation: options.isolationLevel } : {}), // plan_cache_mode stays at the server default (auto). Planning a statement // under row-level security expands every policy on every table it reads, // which often costs ten times its execution; auto lets a prepared statement, // and every statement inside a PL/pgSQL routine or trigger, reuse a generic // plan once Postgres finds it no costlier than planning per execution, and // keeps custom plans where bound values matter (a partial index on a bound // value makes the custom plan cheaper, so auto keeps choosing it). Routines // whose plans must always see their arguments pin force_custom_plan in // their own SET clause. }, }); // Registering the full schema eagerly allocates one relational query builder // per table on every transaction/savepoint, even for a single raw SQL query. // One attempt per pool connection plus one: see retryingStalePreparedResults. const db = drizzle( preparingUnsafe(client, preparedStatements, false, credential, (options.max ?? 10) + 1), ); const notificationDatabaseUrl = options.notificationDatabaseUrl; // The LISTEN connection is its own pool with its own sticky candidate. The // files hold one login's password, so they apply only to that same login. const notificationCredential = notificationDatabaseUrl && credential && databaseUrlUser(notificationDatabaseUrl) === databaseUrlUser(databaseUrl) ? rotatingDatabasePasswordFor(notificationDatabaseUrl, options.passwordFiles, (event) => onCredentialEvent(event, "notifications"), ) : undefined; const sessionListChanges = notificationDatabaseUrl ? createSessionListChangeSource(notificationDatabaseUrl, { ...(options.searchPath ? { searchPath: options.searchPath } : {}), ...(notificationCredential ? { credential: notificationCredential } : {}), }) : undefined; dbBindings.set(db as unknown as object, { rlsStrategy: options.rlsStrategy ?? "force", cancellableTransactions: true, ...(options.userLookup ? { userLookup: options.userLookup } : {}), ...(options.userProfileLookup ? { userProfileLookup: options.userProfileLookup } : {}), ...(sessionListChanges ? { sessionListChanges } : {}), }); return { db, close: async () => { await sessionListChanges?.close(); await client.end(); }, }; } /** Run maintenance within its caller's existing deadline, not a new timeout. * Keep any shorter configured statement timeout. A disconnected caller is * detected during execution, including an abrupt process exit. A network * partition remains subject to TCP failure detection and the server deadline. * Unsupported injected drivers are explicit rather than silently detached. */ export async function withDatabaseMaintenanceLifetime( db: Database, lifetime: { signal: AbortSignal; deadlineAtMs?: number }, run: (scoped: Database) => Promise, ): Promise { lifetime.signal.throwIfAborted(); if (!dbBindingFor(db)?.cancellableTransactions) throw new Error("The database driver does not support joined maintenance cancellation"); return databaseQuerySignal.run(lifetime.signal, () => db.transaction(async (tx) => { lifetime.signal.throwIfAborted(); const remaining = lifetime.deadlineAtMs === undefined ? null : Math.floor(lifetime.deadlineAtMs - Date.now()); if (remaining !== null && remaining <= 0) throw new Error("The maintenance run deadline passed"); await tx.execute(sql`select set_config('statement_timeout', coalesce(least(nullif(extract(epoch from current_setting('statement_timeout')::interval)*1000,0),${remaining}::numeric),0)::text || 'ms',true), set_config('client_connection_check_interval',least(nullif(extract(epoch from current_setting('client_connection_check_interval')::interval)*1000,0),100)::text || 'ms',true)`); return run(tx); }), ); } /** * Cancel the server-side statements of `run` when `signal` aborts, for * example when the HTTP client that asked for a read has gone away. Each * statement on a transaction connection that is still executing gets a * protocol cancel, so PostgreSQL stops working for nobody and the transaction * rolls back. Queries outside a transaction are not cancelled. A surrounding * cancellation scope still applies: either signal cancels. * * Use it for reads, or for writes that may safely roll back when the caller * leaves. Injected drivers without joined cancellation run `run` unchanged. */ export async function withDatabaseQueryCancellation( db: Database, signal: AbortSignal | undefined, run: () => Promise, ): Promise { if (!signal || !dbBindingFor(db)?.cancellableTransactions) return await run(); signal.throwIfAborted(); const outer = databaseQuerySignal.getStore(); return await databaseQuerySignal.run(outer ? AbortSignal.any([outer, signal]) : signal, run); } /** * Register a host's `rlsStrategy`/`userLookup` against an externally-constructed * `Database` handle (e.g. one the embedded host built from its own driver and * injected, rather than via `createDb`). Lets the same WeakMap-backed lookups * work for injected handles. Standalone never calls this (it uses `createDb`). */ export function registerDbBinding( db: Database, binding: { rlsStrategy?: RlsStrategy; userLookup?: UserLookup; userProfileLookup?: UserProfileLookup; }, ): void { dbBindings.set(db as unknown as object, { rlsStrategy: binding.rlsStrategy ?? "force", ...(binding.userLookup ? { userLookup: binding.userLookup } : {}), ...(binding.userProfileLookup ? { userProfileLookup: binding.userProfileLookup } : {}), }); } export async function setRlsContext(db: Database, context: RlsContext): Promise { // Fail loud on an empty/blank account id: a "" account would set an RLS GUC // that matches no tenant row, silently returning zero rows from every scoped // read (a phantom "not found" / "no active subscription"). An RLS context with // no account is always a bug at the call site, never a valid query scope. if (typeof context.accountId !== "string" || context.accountId.trim() === "") { throw new Error("setRlsContext: a non-empty accountId is required to establish an RLS context"); } await applyRlsScope(db, { accountId: context.accountId, workspaceId: context.workspaceId ?? null, locks: [], readParent: false, }); } /** An advisory transaction lock taken while a scope is established. `key` is * either a literal key or a prefix completed with the scope's account id. */ export type RlsScopeLock = { key: string | { accountPrefix: string }; mode: "shared" | "exclusive"; hash: "extended" | "text"; }; export type RlsScopeInput = { /** The tenant account, or null to resolve it from `workspaceId` within the * same statement. */ accountId: string | null; workspaceId: string | null; /** Authenticated subject for actor-private rows; overrides the ambient * session actor's subject. */ subjectId?: string; /** Locks taken in this order, after the context is set. */ locks: readonly RlsScopeLock[]; /** Return the enclosing scope's settings so a nested scope can restore them. */ readParent: boolean; }; type AppliedRlsScope = { context: { accountId: string; workspaceId: string | null }; parent: RlsContextSettings | null; }; function sessionTenancyLock(workspaceId: string): RlsScopeLock { return { key: `session-tenancy:${workspaceId}`, mode: "shared", hash: "extended" }; } function rlsScopeLockCall(lock: RlsScopeLock, keyValue: unknown): SQL { const key = typeof lock.key === "string" ? sql`${keyValue}::text` : sql`(${keyValue}::text || resolved.account_id)`; const hashed = lock.hash === "extended" ? sql`hashtextextended(${key}, 0)` : sql`hashtext(${key})`; return lock.mode === "shared" ? sql`pg_advisory_xact_lock_shared(${hashed})` : sql`pg_advisory_xact_lock(${hashed})`; } /** Every value an RLS scope statement binds; the rest of its text is its shape. */ export type RlsScopeValues = { accountId: string | null; workspaceId: string | null; settingsWorkspaceId: string; agentRootSessionId: string; siteId: string; siteViewerPrincipal: string; /** Defined exactly when the subject GUC is set. */ subjectId: string | undefined; /** Defined exactly when a session actor is in scope. */ privateFileOwner: string | undefined; initiatingHumanSubjectId: string | undefined; /** Each lock's literal key or account prefix, in lock order. */ lockKeys: string[]; }; type RlsScopeSlots = { [K in Exclude]: unknown } & { lockKeys: unknown[]; }; /** @internal The reference builder; exported for statement equivalence tests. */ export function buildRlsScopeStatement(input: RlsScopeInput, values: RlsScopeSlots): SQL { const account = input.accountId !== null ? sql`${values.accountId}::text` : sql`(select ${schema.workspaces.accountId}::text from ${schema.workspaces} where ${schema.workspaces.id} = ${values.workspaceId}::uuid)`; const settings: SQL[] = [ sql`set_config('opengeni.account_id', resolved.account_id, true)`, sql`set_config('opengeni.workspace_id', ${values.settingsWorkspaceId}::text, true)`, sql`set_config('opengeni.lossless_content_writer', '1', true)`, sql`set_config('opengeni.sandbox_recovery_protocol_v2', '1', true)`, sql`set_config('opengeni.pending_tool_event_output_v1', '1', true)`, sql`set_config('opengeni.session_variable_set_attachments_v1', '1', true)`, sql`set_config('opengeni.shared_personal_choice_v1', '1', true)`, sql`set_config('opengeni.site_session_audience_v1', '1', true)`, sql`set_config('jit', 'off', true)`, sql`set_config('opengeni.agent_root_session_id', ${values.agentRootSessionId}::text, true)`, sql`set_config('opengeni.site_id', ${values.siteId}::text, true)`, sql`set_config('opengeni.site_viewer_principal', ${values.siteViewerPrincipal}::text, true)`, ]; if (values.subjectId !== undefined) { settings.push(sql`set_config('opengeni.subject_id', ${values.subjectId}::text, true)`); } if (values.privateFileOwner !== undefined) { settings.push( sql`set_config('opengeni.private_file_owner', ${values.privateFileOwner}::text, true)`, sql`set_config('opengeni.initiating_human_subject_id', ${values.initiatingHumanSubjectId}::text, true)`, ); } const steps: SQL[] = [ sql`parent as materialized (select current_setting('opengeni.account_id', true) as account_id, current_setting('opengeni.workspace_id', true) as workspace_id, current_setting('opengeni.subject_id', true) as subject_id, current_setting('opengeni.private_file_owner', true) as private_file_owner, current_setting('opengeni.initiating_human_subject_id', true) as initiating_human_subject_id, current_setting('opengeni.personal_resource_human_subject_id', true) as personal_resource_human_subject_id, current_setting('opengeni.personal_resource_actor_subject_id', true) as personal_resource_actor_subject_id, current_setting('opengeni.agent_root_session_id', true) as agent_root_session_id, current_setting('opengeni.site_id', true) as site_id, current_setting('opengeni.site_viewer_principal', true) as site_viewer_principal)`, sql`resolved as materialized (select ${account} as account_id from parent)`, sql`scope as materialized (select ${sql.join( settings.map((setting, index) => sql`${setting} as ${sql.raw(`s${index}`)}`), sql`, `, )} from resolved where resolved.account_id is not null and resolved.account_id <> '')`, ]; let last = "scope"; input.locks.forEach((lock, index) => { const name = `lock_${index}`; steps.push( sql`${sql.raw(name)} as materialized (select ${rlsScopeLockCall(lock, values.lockKeys[index])} as locked from ${sql.raw(last)}, resolved)`, ); last = name; }); return sql`with ${sql.join(steps, sql`, `)} select resolved.account_id as resolved_account_id, current_setting('opengeni.account_id', true) as account_id, current_setting('opengeni.workspace_id', true) as workspace_id, current_setting('opengeni.subject_id', true) as subject_id, parent.account_id as parent_account_id, parent.workspace_id as parent_workspace_id, parent.subject_id as parent_subject_id, parent.private_file_owner as parent_private_file_owner, parent.initiating_human_subject_id as parent_initiating_human_subject_id, parent.personal_resource_human_subject_id as parent_personal_resource_human_subject_id, parent.personal_resource_actor_subject_id as parent_personal_resource_actor_subject_id, parent.agent_root_session_id as parent_agent_root_session_id, parent.site_id as parent_site_id, parent.site_viewer_principal as parent_site_viewer_principal from ${sql.raw(last)}, resolved, parent`; } type RlsScopeTemplate = { text: string[]; slots: Array<(values: RlsScopeValues) => unknown> }; /** * Compiled RLS scope statements per database dialect and shape. This * statement runs at the start of nearly every transaction, and building and * rendering its few hundred SQL chunks dominated its cost. Its text depends * only on its shape (account given or resolved, subject, actor, lock kinds); * every value is a bound parameter. A shape is rendered once with a marker in * every value position, so the template records exactly which value each * parameter is; later scopes of that shape bind their values into the * rendered text, producing the identical statement and parameters. */ const rlsScopeTemplates = new WeakMap>(); function rlsScopeShape(input: RlsScopeInput, values: RlsScopeValues): string { return [ input.accountId === null ? "resolve" : "account", values.subjectId === undefined ? "-" : "subject", values.privateFileOwner === undefined ? "-" : "actor", ...input.locks.map( (lock) => `${typeof lock.key === "string" ? "key" : "prefix"}:${lock.hash}:${lock.mode}`, ), ].join("|"); } /** @internal The statement `applyRlsScope` runs; exported for equivalence tests. */ export function rlsScopeStatement(db: Database, input: RlsScopeInput, values: RlsScopeValues): SQL { const dialect = (db as unknown as { dialect?: { sqlToQuery?: unknown } }).dialect; if (!dialect || typeof dialect.sqlToQuery !== "function") { return buildRlsScopeStatement(input, values); } let templates = rlsScopeTemplates.get(dialect); if (!templates) { templates = new Map(); rlsScopeTemplates.set(dialect, templates); } const shape = rlsScopeShape(input, values); let template = templates.get(shape); if (template === undefined) { template = compileRlsScopeTemplate( input, values, dialect as { sqlToQuery(query: SQL): { sql: string; params: unknown[] } }, ); templates.set(shape, template); } if (!template) return buildRlsScopeStatement(input, values); return sql( template.text as unknown as TemplateStringsArray, ...template.slots.map((slot) => slot(values)), ); } function compileRlsScopeTemplate( input: RlsScopeInput, values: RlsScopeValues, dialect: { sqlToQuery(query: SQL): { sql: string; params: unknown[] } }, ): RlsScopeTemplate | null { const readers = new Map unknown>(); const marker = (name: string, read: (values: RlsScopeValues) => unknown) => { const value = `\u0000opengeni-rls-scope-slot:${name}\u0000`; readers.set(value, read); return value; }; const query = dialect.sqlToQuery( buildRlsScopeStatement(input, { accountId: marker("accountId", (v) => v.accountId), workspaceId: marker("workspaceId", (v) => v.workspaceId), settingsWorkspaceId: marker("settingsWorkspaceId", (v) => v.settingsWorkspaceId), agentRootSessionId: marker("agentRootSessionId", (v) => v.agentRootSessionId), siteId: marker("siteId", (v) => v.siteId), siteViewerPrincipal: marker("siteViewerPrincipal", (v) => v.siteViewerPrincipal), subjectId: values.subjectId === undefined ? undefined : marker("subjectId", (v) => v.subjectId), privateFileOwner: values.privateFileOwner === undefined ? undefined : marker("privateFileOwner", (v) => v.privateFileOwner), initiatingHumanSubjectId: values.privateFileOwner === undefined ? undefined : marker("initiatingHumanSubjectId", (v) => v.initiatingHumanSubjectId), lockKeys: input.locks.map((_lock, index) => marker(`lock${index}`, (v) => v.lockKeys[index])), }), ); // The rendered text numbers each bound parameter in order. Anything else // (an unexpected placeholder, a value that is not one of the markers) keeps // this shape on the ordinary builder. const text = query.sql.split(/\$\d+/); const placeholders = query.sql.match(/\$\d+/g) ?? []; if ( placeholders.length !== query.params.length || placeholders.some((placeholder, index) => placeholder !== `$${index + 1}`) ) { return null; } const slots: RlsScopeTemplate["slots"] = []; for (const param of query.params) { const read = readers.get(param); if (!read) return null; slots.push(read); } return { text, slots }; } /** * Establish a transaction's whole RLS scope in ONE statement, on the backend * that runs the rest of the transaction: read the enclosing scope (nested * only), resolve the tenant account from the workspace when it is not known, * set the tenant, writer-capability, subject and session-actor GUCs, take the * scope's advisory locks in order, and read the applied tenant and subject * back. Each step is a MATERIALIZED CTE that selects from the previous one, so * PostgreSQL evaluates them in exactly that order. A missing workspace yields * no row and fails loud. * * Transaction-local writer identity covers supported injected/embedded * database handles whose connection-level application_name is host-owned. * Standalone createDb connections also carry version receipts in their exact * application_name, while old Opengeni binaries set neither current receipt. * * JIT is off for these short request transactions: row-level security * functions inflate planner cost estimates past jit_above_cost, so PostgreSQL * spent seconds compiling queries that execute in milliseconds (the session * list's tree-stats query: 0.4 s of work behind 3.8 s of JIT). Transaction-local, * so it is safe behind transaction poolers and never leaks to other work. */ async function applyRlsScope(db: Database, input: RlsScopeInput): Promise { if (input.accountId !== null && input.accountId.trim() === "") { throw new Error("setRlsContext: a non-empty accountId is required to establish an RLS context"); } if (input.accountId === null && !input.workspaceId) { throw new Error("an RLS scope needs an accountId or a workspaceId to resolve it from"); } if (input.subjectId !== undefined && !input.subjectId.trim()) { throw new Error("setSubjectRlsContext: a non-empty subjectId is required"); } const actor = sessionRlsActorContext.getStore(); const siteViewer = siteViewerRlsContext.getStore(); const subjectId = input.subjectId ?? actor?.subjectId; const [row] = await rawRows<{ resolved_account_id: string; account_id: string | null; workspace_id: string | null; subject_id: string | null; parent_account_id: string | null; parent_workspace_id: string | null; parent_subject_id: string | null; parent_private_file_owner: string | null; parent_initiating_human_subject_id: string | null; parent_personal_resource_human_subject_id: string | null; parent_personal_resource_actor_subject_id: string | null; parent_agent_root_session_id: string | null; parent_site_id: string | null; parent_site_viewer_principal: string | null; }>( db, rlsScopeStatement(db, input, { accountId: input.accountId, workspaceId: input.workspaceId, settingsWorkspaceId: input.workspaceId ?? "", agentRootSessionId: actor?.agentRootSessionId ?? "", siteId: siteViewer?.siteId ?? "", siteViewerPrincipal: siteViewer?.principal ?? "", subjectId, privateFileOwner: actor ? (actor.privateFileOwnerSubjectId ?? "") : undefined, initiatingHumanSubjectId: actor ? (actor.initiatingHumanSubjectId ?? "") : undefined, lockKeys: input.locks.map((lock) => typeof lock.key === "string" ? lock.key : lock.key.accountPrefix, ), }), ); if (!row) { if (input.accountId === null) throw new WorkspaceNotFoundError(input.workspaceId!); throw new Error("RLS context could not be applied on the active backend"); } const expectedWorkspaceId = input.workspaceId ?? ""; // A caller-supplied account is the expectation; otherwise the account the // same statement resolved from the workspace. const expectedAccountId = input.accountId ?? row.resolved_account_id; // Defense-in-depth: the applied values are read back by the same statement // on the backend that keeps them for the rest of the transaction. A // mismatch means the context was genuinely lost, so fail loud instead of // running scoped reads that would see zero rows (a phantom "not found"). if (!expectedAccountId || (row.account_id ?? "") !== expectedAccountId) { throw new Error( `RLS context not applied on the active backend: expected account ${expectedAccountId}, got "${row.account_id ?? ""}"`, ); } if ((row.workspace_id ?? "") !== expectedWorkspaceId) { throw new Error( `RLS context not applied on the active backend: expected workspace "${expectedWorkspaceId}", got "${row.workspace_id ?? ""}"`, ); } if (subjectId !== undefined && (row.subject_id ?? "") !== subjectId) { throw new Error("Authenticated subject RLS context was not applied on the active backend"); } return { context: { accountId: expectedAccountId, workspaceId: input.workspaceId }, parent: input.readParent ? { accountId: row.parent_account_id ?? "", workspaceId: row.parent_workspace_id ?? "", subjectId: row.parent_subject_id ?? "", privateFileOwnerSubjectId: row.parent_private_file_owner ?? "", initiatingHumanSubjectId: row.parent_initiating_human_subject_id ?? "", personalResourceHumanSubjectId: row.parent_personal_resource_human_subject_id ?? "", personalResourceActorSubjectId: row.parent_personal_resource_actor_subject_id ?? "", agentRootSessionId: row.parent_agent_root_session_id ?? "", siteId: row.parent_site_id ?? "", siteViewerPrincipal: row.parent_site_viewer_principal ?? "", } : null, }; } async function readRlsContextSettings(db: Database): Promise { const [settings] = await rawRows<{ account_id: string | null; workspace_id: string | null; subject_id: string | null; private_file_owner: string | null; initiating_human_subject_id: string | null; personal_resource_human_subject_id: string | null; personal_resource_actor_subject_id: string | null; agent_root_session_id: string | null; site_id: string | null; site_viewer_principal: string | null; }>( db, sql`select current_setting('opengeni.account_id', true) as account_id, current_setting('opengeni.workspace_id', true) as workspace_id, current_setting('opengeni.subject_id', true) as subject_id, current_setting('opengeni.private_file_owner', true) as private_file_owner, current_setting('opengeni.initiating_human_subject_id', true) as initiating_human_subject_id, current_setting('opengeni.personal_resource_human_subject_id', true) as personal_resource_human_subject_id, current_setting('opengeni.personal_resource_actor_subject_id', true) as personal_resource_actor_subject_id, current_setting('opengeni.agent_root_session_id', true) as agent_root_session_id, current_setting('opengeni.site_id', true) as site_id, current_setting('opengeni.site_viewer_principal', true) as site_viewer_principal`, ); return { accountId: settings?.account_id ?? "", workspaceId: settings?.workspace_id ?? "", subjectId: settings?.subject_id ?? "", privateFileOwnerSubjectId: settings?.private_file_owner ?? "", initiatingHumanSubjectId: settings?.initiating_human_subject_id ?? "", personalResourceHumanSubjectId: settings?.personal_resource_human_subject_id ?? "", personalResourceActorSubjectId: settings?.personal_resource_actor_subject_id ?? "", agentRootSessionId: settings?.agent_root_session_id ?? "", siteId: settings?.site_id ?? "", siteViewerPrincipal: settings?.site_viewer_principal ?? "", }; } async function assertRlsContextApplied(db: Database, context: RlsContext): Promise { const applied = await readRlsContextSettings(db); const expectedWorkspaceId = context.workspaceId ?? ""; if (applied.accountId !== context.accountId) { throw new Error( `RLS context not applied on the active backend: expected account ${context.accountId}, got "${applied.accountId}"`, ); } if (applied.workspaceId !== expectedWorkspaceId) { throw new Error( `RLS context not applied on the active backend: expected workspace "${expectedWorkspaceId}", got "${applied.workspaceId}"`, ); } } async function restoreRlsContextSettings( db: Database, settings: RlsContextSettings, ): Promise { const [restored] = await rawRows<{ account_id: string; workspace_id: string; subject_id: string; private_file_owner: string; initiating_human_subject_id: string; personal_resource_human_subject_id: string; personal_resource_actor_subject_id: string; agent_root_session_id: string; site_id: string; site_viewer_principal: string; }>( db, sql`select set_config('opengeni.account_id', ${settings.accountId}, true) as account_id, set_config('opengeni.workspace_id', ${settings.workspaceId}, true) as workspace_id, set_config('opengeni.subject_id', ${settings.subjectId}, true) as subject_id, set_config('opengeni.private_file_owner', ${settings.privateFileOwnerSubjectId}, true) as private_file_owner, set_config('opengeni.initiating_human_subject_id', ${settings.initiatingHumanSubjectId}, true) as initiating_human_subject_id, set_config('opengeni.personal_resource_human_subject_id', ${settings.personalResourceHumanSubjectId}, true) as personal_resource_human_subject_id, set_config('opengeni.personal_resource_actor_subject_id', ${settings.personalResourceActorSubjectId}, true) as personal_resource_actor_subject_id, set_config('opengeni.agent_root_session_id', ${settings.agentRootSessionId}, true) as agent_root_session_id, set_config('opengeni.site_id', ${settings.siteId}, true) as site_id, set_config('opengeni.site_viewer_principal', ${settings.siteViewerPrincipal}, true) as site_viewer_principal`, ); if ( restored?.account_id !== settings.accountId || restored.workspace_id !== settings.workspaceId || restored.subject_id !== settings.subjectId || restored.private_file_owner !== settings.privateFileOwnerSubjectId || restored.initiating_human_subject_id !== settings.initiatingHumanSubjectId || restored.personal_resource_human_subject_id !== settings.personalResourceHumanSubjectId || restored.personal_resource_actor_subject_id !== settings.personalResourceActorSubjectId || restored.agent_root_session_id !== settings.agentRootSessionId || restored.site_id !== settings.siteId || restored.site_viewer_principal !== settings.siteViewerPrincipal ) { throw new Error("RLS context could not be restored after a nested scope"); } } /** Attribute only failures outside the application callback to our transaction * driver. BEGIN/COMMIT/ROLLBACK can throw raw postgres.js errors, unlike ORM * queries. Only unentered pool admission can retry; entered callbacks cannot. */ async function withDatabaseTransactionProvenance( db: Database, fn: (db: Database) => Promise, transactionConfig?: PgTransactionConfig, ): Promise { // Only admission on a pool can be retried here. Once the driver entered the // callback, COMMIT may have succeeded and external effects may have run. // A savepoint cannot repair its parent's lost connection either. const maxAttempts = isTransactionHandle(db) ? 1 : 8; for (let attempt = 1; ; attempt += 1) { let entered = false; let callbackFailure: { error: unknown } | undefined; try { return await db.transaction(async (tx) => { entered = true; try { return await fn(tx as unknown as Database); } catch (error) { callbackFailure = { error }; throw error; } }, transactionConfig); } catch (error) { // A provider/tool rejection propagated by a successful rollback is still // the provider/tool's error, even if it has a connection-looking code. if (callbackFailure && callbackFailure.error === error) throw error; if ( !entered && attempt < maxAttempts && (nestedPostgresSqlState(error) === "53300" || isDatabaseConnectionLoss(error) || isRetryableDatabaseTransportFailure(error)) ) { // Equal jitter, 250 ms doubling to 4 s: at most 15.75 s of backoff. // No pooled connection is held while waiting; each try reacquires one. const ceilingMs = Math.min(250 * 2 ** (attempt - 1), 4_000); await new Promise((resolve) => setTimeout(resolve, ceilingMs * (0.5 + Math.random() / 2))); continue; } if (!isDatabasePersistenceFailure(error)) throw error; throw new DatabaseTransactionError( entered ? "settlement" : "admission", error, callbackFailure?.error, ); } } } export async function withRlsContext( db: Database, context: RlsContext, fn: (db: Database) => Promise, transactionConfig?: PgTransactionConfig, sessionTenancyFence: "shared" | "none" = "shared", ): Promise { if (typeof context.accountId !== "string" || context.accountId.trim() === "") { throw new Error("setRlsContext: a non-empty accountId is required to establish an RLS context"); } const workspaceId = context.workspaceId || null; return await withRlsScope( db, { accountId: context.accountId, workspaceId: context.workspaceId ?? null, locks: workspaceId && sessionTenancyFence === "shared" ? [sessionTenancyLock(workspaceId)] : [], }, (scoped) => fn(scoped), transactionConfig, ); } /** * Run `fn` in one transaction (or savepoint, when nested) whose RLS scope is * established by a single statement (see applyRlsScope). The callback gets the * resolved tenant context. A nested scope restores its parent's tenant and * actor settings when it returns. */ async function withRlsScope( db: Database, scope: Omit, fn: (db: Database, context: AppliedRlsScope["context"]) => Promise, transactionConfig?: PgTransactionConfig, ): Promise { const restoreParentScope = isTransactionHandle(db); // Callback entry includes connection admission AND BEGIN/SAVEPOINT round-trip. // This is deliberately not advertised as pure pool wait. const admission = startDatabaseTiming( restoreParentScope ? "savepoint_admission" : "transaction_admission", ); try { return await withDatabaseTransactionProvenance( db, async (tx) => { admission("completed"); const setup = startDatabaseTiming("rls_setup"); const scoped = tx as unknown as Database; let applied: AppliedRlsScope; try { // One statement sets the scope, takes its locks and reads the applied // tenant back on this transaction's backend (see applyRlsScope). applied = await applyRlsScope(scoped, { ...scope, readParent: restoreParentScope }); setup("completed"); } catch (error) { setup("failed"); throw error; } const callback = startDatabaseTiming("scoped_callback"); let value: T; try { value = await fn(scoped, applied.context); callback("completed"); } catch (error) { callback("failed"); throw error; } // A nested transaction is a savepoint, and SET LOCAL survives successful // savepoint release. Restore the parent tenant and actor proof together; // writer/protocol capabilities intentionally remain transaction-wide. if (applied.parent) await restoreRlsContextSettings(scoped, applied.parent); return value; }, transactionConfig, ); } catch (error) { // No-op after callback entry; only admission failures are counted here. admission("failed"); throw error; } } /** * Run one bounded database operation on a transaction-pinned backend. * * Callers that also have an application deadline should check their abort * signal before returning from `fn`; throwing there rolls the transaction back * even when the application deadline won a surrounding Promise race. */ export async function withDatabaseStatementTimeout( db: Database, timeoutMs: number, fn: (db: Database) => Promise, ): Promise { if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) { throw new Error("withDatabaseStatementTimeout requires a positive timeout"); } const boundedTimeoutMs = Math.max(1, Math.floor(timeoutMs)); return await db.transaction(async (tx) => { const scoped = tx as unknown as Database; await scoped.execute( sql`select set_config('statement_timeout', ${`${boundedTimeoutMs}ms`}, true)`, ); return await fn(scoped); }); } export async function rlsContextForWorkspace( db: Database, workspaceId: string, ): Promise { const [row] = await db .select({ accountId: schema.workspaces.accountId }) .from(schema.workspaces) .where(eq(schema.workspaces.id, workspaceId)) .limit(1); if (!row) { throw new WorkspaceNotFoundError(workspaceId); } return { accountId: row.accountId, workspaceId }; } export async function withWorkspaceRls( db: Database, workspaceId: string, fn: (db: Database) => Promise, transactionConfig?: PgTransactionConfig, ): Promise { // The tenant account is resolved inside the scope's setup statement. return await withRlsScope( db, { accountId: null, workspaceId, locks: [sessionTenancyLock(workspaceId)] }, (scoped) => fn(scoped), transactionConfig, ); } /** True for an open transaction (or savepoint) handle rather than a pool handle. */ export function isTransactionHandle(db: Database): boolean { return typeof (db as Database & { rollback?: unknown }).rollback === "function"; } /** Session activity is stamped by the row trigger; retain the scoped writer API. */ export async function withSessionActivityRlsContext( db: Database, context: RlsContext & { workspaceId: string }, fn: (db: SessionActivityDatabase) => Promise, transactionConfig?: PgTransactionConfig, fenceMode: "shared" | "none" = "shared", organizationMembershipFence = false, ): Promise { if (typeof context.accountId !== "string" || context.accountId.trim() === "") { throw new Error("setRlsContext: a non-empty accountId is required to establish an RLS context"); } return await withSessionActivityRlsScope( db, { accountId: context.accountId, workspaceId: context.workspaceId }, fn, transactionConfig, fenceMode, organizationMembershipFence, ); } async function withSessionActivityRlsScope( db: Database, scope: { accountId: string | null; workspaceId: string; subjectId?: string }, fn: (db: SessionActivityDatabase) => Promise, transactionConfig: PgTransactionConfig | undefined, fenceMode: "shared" | "none", organizationMembershipFence: boolean, ): Promise { // Only callers that reauthorize or mutate under the membership lifecycle // lock take it, always exclusively, and before even a shared tenancy fence: // an exclusive tenancy/control waiter can otherwise complete the same lock // cycle. The turn claim deliberately takes no membership fence at all. The // scope's setup statement takes both in this order. const locks: RlsScopeLock[] = [ ...(organizationMembershipFence ? [ { key: { accountPrefix: "organization-membership:" }, mode: "exclusive", hash: "extended", } satisfies RlsScopeLock, ] : []), ...(fenceMode === "shared" ? [sessionTenancyLock(scope.workspaceId)] : []), ]; return await withRlsScope( db, { accountId: scope.accountId, workspaceId: scope.workspaceId, ...(scope.subjectId !== undefined ? { subjectId: scope.subjectId } : {}), locks, }, async (scopedDb, context) => { const value = await fn(scopedDb as SessionActivityDatabase); // Keep the tenant proof; removing the activity gate must not weaken RLS. await assertRlsContextApplied(scopedDb, context); return value; }, transactionConfig, ); } /** * `organizationMembershipFence` is required when the callback takes the * organization-membership lifecycle lock (for example external-actor * reauthorization): that lock precedes the session-tenancy fence and the * canonical control/workspace/session prefix, never follows it. */ export async function withWorkspaceSessionActivityRls( db: Database, workspaceId: string, fn: (db: SessionActivityDatabase) => Promise, transactionConfig?: PgTransactionConfig, organizationMembershipFence = false, ): Promise { // The tenant account is resolved inside the scope's setup statement. return await withSessionActivityRlsScope( db, { accountId: null, workspaceId }, fn, transactionConfig, "shared", organizationMembershipFence, ); } /** * Run one of several ordered workspace activity scopes inside a caller-owned * transaction. Tenant and actor settings are restored before the next scope. */ export async function withRestoredSessionActivityRlsContext( db: Database, context: RlsContext & { workspaceId: string }, fn: (db: SessionActivityDatabase) => Promise, ): Promise { if (!isTransactionHandle(db)) { throw new Error("Sequential workspace activity scopes require a caller-owned transaction"); } return await withRlsContext(db, context, async (scopedDb) => { const value = await fn(scopedDb as SessionActivityDatabase); await assertRlsContextApplied(scopedDb, context); return value; }); } /** * Open one nested savepoint without losing the scoped writer brand. */ export async function withSessionActivitySavepoint( db: SessionActivityDatabase, fn: (db: SessionActivityDatabase) => Promise, ): Promise { return await db.transaction(async (tx) => await fn(tx as unknown as SessionActivityDatabase)); } export async function retrySessionActivityRls( db: Database, workspaceId: string, options: IdempotentPersistenceTransactionOptions, fn: (db: SessionActivityDatabase) => Promise, ): Promise { return await runIdempotentPersistenceTransaction(options, async () => { return await withWorkspaceSessionActivityRls(db, workspaceId, fn); }); } export async function retryWorkspacePersistence( db: Database, workspaceId: string, options: IdempotentPersistenceTransactionOptions, fn: (db: Database) => Promise, ): Promise { return await runIdempotentPersistenceTransaction(options, async () => { return await withWorkspaceRls(db, workspaceId, fn); }); } export async function retryRlsPersistence( db: Database, context: RlsContext, options: IdempotentPersistenceTransactionOptions, fn: (db: Database) => Promise, ): Promise { return await runIdempotentPersistenceTransaction(options, async () => { return await withRlsContext(db, context, fn); }); } /** * Personal workspace data needs both tenant and authenticated-principal GUCs. * `session_pins` uses this helper so FORCE RLS rejects another member's rows * even if a future query accidentally omits its explicit subject predicate. */ export async function withWorkspaceSubjectRls( db: Database, workspaceId: string, subjectId: string, fn: (db: Database) => Promise, transactionConfig?: PgTransactionConfig, sessionTenancyFence: "shared" | "none" = "shared", ): Promise { if (!subjectId.trim()) { throw new Error("withWorkspaceSubjectRls: a non-empty subjectId is required"); } return await withRlsScope( db, { accountId: null, workspaceId, subjectId, locks: sessionTenancyFence === "shared" ? [sessionTenancyLock(workspaceId)] : [], }, (scoped) => fn(scoped), transactionConfig, ); } export async function withWorkspaceSubjectSessionActivityRls( db: Database, workspaceId: string, subjectId: string, fn: (db: SessionActivityDatabase) => Promise, transactionConfig?: PgTransactionConfig, fenceMode: "shared" | "none" = "shared", organizationMembershipFence = false, ): Promise { if (!subjectId.trim()) { throw new Error("withWorkspaceSubjectSessionActivityRls: a non-empty subjectId is required"); } return await withSessionActivityRlsScope( db, { accountId: null, workspaceId, subjectId }, fn, transactionConfig, fenceMode, organizationMembershipFence, ); } /** Apply and verify actor-private RLS on an already transaction-pinned handle, * in one statement that sets the subject and reads it back. */ export async function setSubjectRlsContext(db: Database, subjectId: string): Promise { if (!subjectId.trim()) { throw new Error("setSubjectRlsContext: a non-empty subjectId is required"); } const [applied] = await rawRows<{ subject_id: string | null }>( db, sql`with applied as materialized ( select set_config('opengeni.subject_id', ${subjectId}::text, true) as subject_id ) select current_setting('opengeni.subject_id', true) as subject_id from applied`, ); if ((applied?.subject_id ?? "") !== subjectId) { throw new Error("Authenticated subject RLS context was not applied on the active backend"); } } export async function withWorkspaceUsageLock( db: Database, workspaceId: string, fn: (db: Database) => Promise, ): Promise { return await withRlsScope( db, { accountId: null, workspaceId, locks: [ sessionTenancyLock(workspaceId), { key: `usage:${workspaceId}`, mode: "exclusive", hash: "text" }, ], }, (scoped) => fn(scoped), ); } export async function withAccountRls( db: Database, accountId: string, fn: (db: Database) => Promise, ): Promise { return await withRlsContext(db, { accountId, workspaceId: null }, fn); } /** Internal lookup for the host binding attached to a database handle. */ export function dbBindingFor(db: Database): DbBinding | undefined { return dbBindings.get(db as unknown as object); }