ADR 0002 — Bun.SQL and isolation through row-level security

Status: accepted. Date: 2026-12-03.

Context

Multi-tenant isolation cannot depend on the discipline of whoever writes the query, whether a person or an agent.

Decision

  • Minimal interface over Bun.SQL: sql (parameterized template), transaction, dbHealth, closeDb. No ORM.
  • Execution context (identity, tenant, transaction) in AsyncLocalStorage. sql joins the active transaction at any depth.
  • When there is a tenant in the context, every query runs in a transaction that executes set_config('app.tenant_id', $1, true). The value is local to the transaction, so it does not leak between pool connections.
  • Tables with tenant_id have RLS enabled and forced and a policy on app.tenant_id. Without a tenant context, no rows are visible.
  • Generated services also filter by tenant_id explicitly (defense in depth).

Consequences

  • A query outside a transaction with a tenant costs an extra BEGIN/COMMIT. Cost not yet measured.
  • The application role cannot be SUPERUSER or BYPASSRLS: fellow doctor fails in that case.
  • Legitimate cross-tenant operations have no API yet; they will require an explicit, audited mechanism.

Evidence

packages/core/tests/db.test.ts: a read without WHERE sees only its own tenant; a write to another tenant is rejected by the database; rollback; 20 concurrent executions without leaks.

Conditions for reassessment

Benchmarks show a relevant cost for the per-query transaction, or a pooler in transaction mode (PgBouncer) is adopted, which requires validating local set_config.