@ultimat3/db 30.9.0 → 31.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -60,6 +60,7 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
60
60
  `pool-profile.ts`, `connection-url.ts`, `bun-sql.ts`, `pool-reserve.ts`, `db-health.ts` (`checkDb`),
61
61
  `statement-funnel.ts` (`sendOn`/`runOn`), `pool-gate.ts`, `pool-sweep.ts`, `pool-retire.ts`,
62
62
  `pool-listeners.ts` and `pool-timer.ts` hold the rest.
63
+ - **`statement-cancel.ts` cancels a POOLED `select` in flight when the ambient `ctx.signal` aborts** (`57014` on the server; `X_ABORTED`, or the coded reason itself). Never a write, never a pin, never a statement sent after the abort. README.
63
64
  - **`pool-gate.ts` is the one count of `max`** (`takeSlot`/`freeSlot`), per pool; a wait past `acquireTimeoutMs` is `X_DB_POOL_EXHAUSTED`. Full rule: `docs/history/db.md`.
64
65
  - **`pool-sweep.ts`: an unanswered statement retires the pool** (`statementTimeoutMs + UNANSWERED_GRACE_MS`), pooled or pinned; age is ticks that fired, never a clock. Full rule: `docs/history/db.md`.
65
66
  - **`pool-pins.ts`: a pin is swept against ITS bound** (a `statement_timeout` it set; the role's after `COMMIT`/`ROLLBACK`); after a miss it sends nothing. `reserve()` passes `reserveWithin` what the gate left of one budget. **`pool-listeners.ts` holds `client.listen`** and re-dials every session on a retirement, with backoff.
@@ -76,19 +77,25 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
76
77
 
77
78
  ## Observation
78
79
 
79
- - **`observe.ts`: one process-wide `StatementObserver`** (`setStatementObserver()`). Guard at the
80
- call site; one observer, not a list; the seam swallows nothing; `onStatement` is synchronous and
81
- must not issue SQL. Only `runOn` (`statement-funnel.ts`) and `statement()` (`pglite.ts`) invoke
82
- it; both observe success and failure, and notify outside the statement's own `try`.
80
+ - **No observer slot** (v31): every statement is a `db.statement` event on core's bus
81
+ (`instrument()`), emitted by `traceStatement` (`statement-span.ts`) — the ONE shell both funnels,
82
+ `runOn` (`statement-funnel.ts`) and `statement()` (`pglite.ts`), call. Guarded by
83
+ `subscribed('db.statement')`; emitted on success and failure, outside the statement's own `try`;
84
+ a subscriber's throw is contained by the bus, never the caller's. A subscriber must not issue SQL.
85
+ `bun run scripts/instrument-slots.ts` (`X_INSTRUMENT_SLOT_FORBIDDEN`) refuses a `set*Observer`.
86
+ Each funnel reads core's `callerStack()` at its ENTRY (before the pool/turn-queue `await`) and
87
+ hands it to `traceStatement` as `DbStatementEvent.callerStack` — `undefined`, nothing built,
88
+ unless `captureStatementStacks()` is held (the `statements` fixture; never production).
83
89
  - **`attribution.ts`**: `withStatementAttribution(entity, op, fn)` — guard first (two strings, no
84
- allocation), a scope not a parameter, innermost pair wins; the funnels stamp it on both settle paths.
90
+ allocation; the guard is `subscribed('db.statement')`), a scope not a parameter, innermost pair wins; the funnels stamp it on both settle paths.
85
91
  `@ultimat3/entity`'s `postgresRepo` is the one producer.
86
92
  - **`statement-shape.ts`**: `statementFingerprint(event)` (`entity.op` when attributed, else collapsed
87
93
  text) and `statementKind(text)` off `statementVerb(text)`. Read by `x dev`'s ledger and
88
94
  `@ultimat3/testing`'s `statements` fixture. It counts nothing.
89
- - **`statement-span.ts`**: `withStatementSpan` wraps the send alone — `db.<verb>`, attribute
90
- `STATEMENT_ATTRIBUTE` (`@ultimat3/cli`'s `dev-traces.ts` imports it), OTel kind `client`, opened
91
- only when an observer is installed.
95
+ - **`statement-span.ts`**: `withStatementSpan` wraps the send alone — `db.<verb>`, OTel kind
96
+ `client`, attributes from core's `SEMCONV` only (`db.system.name`, `db.query.text`,
97
+ `db.operation.name`; never the old `db.statement`). **Opened for every statement**, production
98
+ included, subscriber or not.
92
99
  - **`expected-loop.ts` is the ONLY suppression**: `expectedQueryLoop(reason, fn)`, innermost reason,
93
100
  blank is `X_INVARIANT`; the funnel stamps `expected`; it suppresses a verdict, never a statement.
94
101
  The framework's own loops declare themselves (`migrate()`, `rollback()`, admin's `search.ts`).
@@ -96,7 +103,7 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
96
103
  - **`failure-store-pg.ts` writes `x_failures` through `outsideTransaction`** — the 5xx rolled the
97
104
  request's transaction back. Table applied by the boot (`FRAMEWORK_SCHEMA`) whether capture is on
98
105
  or not; bundles only (counts are `x_error_groups`'). `failurePurgeTarget` has no default window.
99
- - `@ultimat3/jobs` never imports this package; its statements pass the observer through
106
+ - `@ultimat3/jobs` never imports this package; its statements reach the bus through
100
107
  `dbExecutor` (`db-executor.ts`, the ONE `PgExecutor` builder; the CLI binds it), unattributed.
101
108
 
102
109
  ## Migrations
@@ -161,6 +168,7 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
161
168
  `drift-triggers.ts` (`X_LIFECYCLE_TRIGGER_MISSING`; `retain` on a partitioned table is
162
169
  `X_ENTITY_RETAIN_INVALID`).
163
170
  - **Views**: `generate-view.ts`.
171
+ - **`partitionBy`** (`generate-partition.ts`): one plpgsql `ultimate_partitions` named/bounded for migration and `partitionMaintenance` alike; `X_MIGRATION_PARTITION_CHANGE`. README.
164
172
  - **`retired.ts`: a retired column**. Full rule: `docs/history/db.md`.
165
173
  - **`entity-shape.ts` holds the `*Like` interfaces** (every later field optional).
166
174
  - **`snapshot-json.ts` writes a fixed point of Biome** (an array collapses when it fits at `<= 100`
package/README.md CHANGED
@@ -37,24 +37,24 @@ await withTransaction(async (tx) => {
37
37
  | `withTransaction()` / `currentTx()` | transaction scope; `currentTx()` is the outbox seam. `{ retry: n }` (`As of 2026-08`) re-runs `fn` from the top on a `40001`/`40P01` and on nothing else — default 0, so `fn` must be idempotent before you ask for it. Each re-run **waits first**, `As of 2026-08-23`: exponential from 10ms, capped at 500ms, full jitter (`@ultimat3/core`'s `backoffDelay`). A budget of 0 waits not at all. **A transaction the server aborted is reported as one**, `As of 2026-10-02` → [Transactions that end badly](#transactions-that-end-badly) |
38
38
  | `completeTransaction()` / `refuseAbandoned()` | `As of 2026-11-02`: the mark that takes the open root's statements and COMMIT past an abandoned scope (a keyed action's), and the check for a write that goes through no `DbTx` (`@ultimat3/entity`'s `writing()`, the enqueue facade) → [Transactions that end badly](#transactions-that-end-badly) |
39
39
  | `liveTxConnection()` | the connection of the transaction still **open** on this async context, or `undefined`. `currentTx()` keeps answering a finished scope's handle to a promise chain the body forgot to await; this is the one that says whether a statement sent now is really inside a transaction. `@ultimat3/action` reads it before binding an idempotency settlement to a commit |
40
- | `sqlState()` / `sqlStateCode()` / `isRetryableState()` / `SQLSTATE` | `As of 2026-08`: the SQLSTATE a driver error carries, and the closed table from it to a code. `Bun.SQL` puts it on `errno`; PGlite puts it on `code`; **one** reader answers for both |
40
+ | `sqlState()` / `isRetryableState()` / `SQLSTATE` | `As of 2026-08`: the SQLSTATE a driver error carries, and the closed table from it to a code. `Bun.SQL` puts it on `errno`; PGlite puts it on `code`; **one** reader answers for both |
41
41
  | `migrate()` / `rollback()` / `readLedger()` | the `x_migrations` ledger |
42
42
  | `statementsOf()` | `As of 2026-08`: a SQL script → the statements a driver sends one at a time. One send is one statement, so `migrate()` splits with this — a `;` inside a literal, an identifier, a dollar-quoted body or a comment is data |
43
- | `withReplicaReads()` / `replicaScope()` | `As of 2026-08-24`: the scope inside which a plain read may be served by a replica — until it writes, after which every read in it is the primary's. No scope open, nothing routes |
43
+ | `withReplicaReads()` | `As of 2026-08-24`: the scope inside which a plain read may be served by a replica — until it writes, after which every read in it is the primary's. No scope open, nothing routes |
44
44
  | `poolerFromEnv()` / `POOLER_ENV` / `PoolerMode` / `POOLER_WAIT_MS` / `statementBound()` / `lostStatementBound()` / `StatementBound` / `poolerSessionRequired()` | `As of 2026-11-03`: a connection pooler in the path (`pooler.ts`), and the two bounds as the session reads them. [Pool sizing by role](#pool-sizing-by-role) |
45
45
  | `replicatedClient()` / `ReplicaStats` / `REPLICA_URL_ENV` | `As of 2026-08-24`: one `DbClient` over a primary and a standby. `baseClient()` builds one when `DATABASE_REPLICA_URL` is set and the single-pool client when it is not |
46
- | `INDEX_METHODS` / `IndexMethod` / `indexMethodOf()` / `indexMethodSql()` / `declaredMethod()` / `isIndexMethod()` | `As of 2026-08-24`: an index's access method — `btree` or `gin`, closed. Absent is `btree`, the live side is read open (whatever `pg_am` said), and the DDL literal is re-derived from the set rather than spliced from the input |
46
+ | `INDEX_METHODS` / `IndexMethod` / `indexMethodOf()` / `indexMethodSql()` / `declaredMethod()` | `As of 2026-08-24`: an index's access method — `btree` or `gin`, closed. Absent is `btree`, the live side is read open (whatever `pg_am` said), and the DDL literal is re-derived from the set rather than spliced from the input |
47
47
  | `isPlainRead()` | `As of 2026-08-24`: whether a statement may leave the primary. An allow-list — everything it cannot vouch for is the primary's |
48
48
  | `checkDrift()` / `diffSchema()` / `assertNoSchemaDrift()` | drift, with a `--json` report. `checkDrift()` is the **post-migrate verification** — the live database against the ledger: columns, declared indexes (access method `As of 2026-08-24`, columns, uniqueness, direction, and whether a predicate is there at all — never its text), declared CHECK constraints by NAME (`missing-check`, `As of 2026-08-25` — never a predicate, which the catalog answers rewritten) and declared foreign keys, matched on where the key points and not on its constraint name, with the `on delete` rule compared through one normalisation `As of 2026-08-19` |
49
49
  | `declaredSchema()` / `expectedSchema()` | `As of 2026-08`: the schema the migrations write down, or `undefined` when the newest one carries no snapshot — never an older snapshot standing in for it |
50
50
  | `parseSnapshot()` | `As of 2026-08`: a `<id>.snapshot.json` sidecar validated to the last nested field, or `undefined`. `{"tables":[null]}` is valid JSON and is not a schema |
51
51
  | `snapshotJson()` | `As of 2026-08`: the sidecar's **bytes** — the JSON Biome would have printed, trailing newline included. The one writer of a `<id>.snapshot.json`, because `JSON.stringify(…, null, 2)` is not formatter-clean and an app's `lint` step rejected the file `x db gen` had just written |
52
52
  | `isLedgerMissing()` | `As of 2026-08`: whether an error is Postgres' `undefined_table` for `x_migrations` — the one condition a caller may read as "nothing applied" |
53
- | `appTables()` / `FRAMEWORK_TABLE_PREFIX` | `As of 2026-08`: the live schema minus the `x_` namespace — no migration declares the ledger, the queue, the outbox or an auth table, so none of them is drift |
53
+ | `appTables()` | `As of 2026-08`: the live schema minus the `x_` namespace — no migration declares the ledger, the queue, the outbox or an auth table, so none of them is drift |
54
54
  | `sameTenantKeyName()` | the name of a same-tenant composite key, `<table>_<column>_tenant_fkey`, within 63 bytes. `ColumnDescriptionLike.sameTenant` is what makes a key composite; `@ultimat3/entity`'s memory driver reads this so its refusal names the constraint Postgres would |
55
55
  | `generateMigration()` | `x db gen "<name>"` — reversible up/down SQL, and `destructive` for the marker the file must carry. `As of 2026-08` a foreign key is its own `alter table … add constraint`, emitted after every table statement: inline, a `references()` had to point at a table entity registration order happened to create first, and `down` had to drop them in an order it did not control. `As of 2026-08-19` a **removed** `references()` emits its `drop constraint` (it emitted nothing, and the snapshot then denied a constraint the database still held), a changed `onDelete` is a drop-and-add rebuild, and a declared `on delete` rule reaches the clause at all. `As of 2026-08-25` a **retype** drops the partial indexes and CHECK constraints written against that column first and restores them in `down`: Postgres compiles both predicates against the old type and cannot recompile either, so `alter column … type text using …::text` was `42883 operator does not exist: text = post_status` and the migration aborted mid-run. A plain btree over the column is left alone — measured, Postgres rebuilds that one itself. `As of 2026-08-26` `replicaIdentityFull` names the tables a live query subscribes to and emits one `alter table … replica identity full` each, last in `up`, recorded on the snapshot so the next generation emits none — a parameter and never an entity field, because the live-query set is a tier-3 fact (`replica-identity.ts`) |
56
56
  | `declaredIndexes()` / `invariantChecks()` / `constraintNameFor()` | `As of 2026-08-25`: the DDL an entity **invariant** becomes — a `check` as a named `CONSTRAINT`, a `unique` as a partial-capable unique INDEX, an `assert` as nothing. `EntityDescriptionLike` had no `invariants` field for three majors, so a regenerated migration silently held **none** of them, including the composite UNIQUE `upsertAll`'s `on conflict` is inferred against |
57
- | `declaredChecks()` / `checkClauses()` / `checkPlan()` / `columnChecks()` / `columnCheckName()` / `columnNamesConstraint()` | `As of 2026-08-25`: **every** CHECK a table declares — a column's own (`enumerated()`'s value set, `tz()`'s IANA whitelist, `locale()`'s tags, money's currency pattern and scale bound) and an invariant's — on ONE list, so `createTable`, `diffTable` and `snapshotOf` agree about what exists. A column's check reached `create table` **inline and anonymous** and nothing else: the snapshot recorded none and the diff had no arm, so a value added to `enumerated()` generated no migration and a regenerated ENUM column came back as bare `text`. The name is `<table>_<column>_check` because that is the name **Postgres itself mints** for the old anonymous form — measured — so the repair lands on the constraint an already-generated database is holding; `checkPlan` emits `drop constraint if exists` before the `add` for exactly that column, because a bare add is `42710` there and a no-op everywhere else |
57
+ | `declaredChecks()` / `checkPlan()` / `columnChecks()` | `As of 2026-08-25`: **every** CHECK a table declares — a column's own (`enumerated()`'s value set, `tz()`'s IANA whitelist, `locale()`'s tags, money's currency pattern and scale bound) and an invariant's — on ONE list, so `createTable`, `diffTable` and `snapshotOf` agree about what exists. A column's check reached `create table` **inline and anonymous** and nothing else: the snapshot recorded none and the diff had no arm, so a value added to `enumerated()` generated no migration and a regenerated ENUM column came back as bare `text`. The name is `<table>_<column>_check` because that is the name **Postgres itself mints** for the old anonymous form — measured — so the repair lands on the constraint an already-generated database is holding; `checkPlan` emits `drop constraint if exists` before the `add` for exactly that column, because a bare add is `42710` there and a no-op everywhere else |
58
58
  | `defaultExpression()` / `ColumnDefaultLike` | `As of 2026-08-25`: a column's `default` as SQL. A DECLARED default (`{ kind: 'value', value }`) wins; `gen_random_uuid()` and `now()` stay as the inference for a description that carries only `hasDefault` |
59
59
  | `unrenderedOf()` / `unrenderedComment()` / `UnrenderedDeclaration` | `As of 2026-08-25`: what the generator could **not** write, on `GeneratedMigration.unrendered` and as a `-- UNRENDERED` block at the top of a non-empty `up`. A generator that emits less than the declaration in silence is the defect the whole file exists against, and `x verify`'s `drift` step reads a source hash — it never reads the SQL, so the loss was green. **`unrenderedOf(entities, current)` takes the recorded schema**, required and nullable: a rule declared as an `assert` reaches no SQL by design and is no loss on its own, but one whose CHECK a previous migration RECORDED is dropped by this run and reported by nothing — five in `examples/dummy`, and `@ultimat3/cli`'s `repairFix` then offered `x db gen "drop <name>"` as the repair for the loss that command performs |
60
60
  | `isNonTransactional()` / `NO_TRANSACTION_MARKER` / `isConcurrentIndexStatement()` / `concurrentIndexTarget()` | `As of 2026-10-31`: the `-- transaction: false` marker a migration carries to run outside a transaction, and the concurrent index statements that need it → [Indexes built concurrently](#indexes-built-concurrently-and-every-index-drop) |
@@ -72,17 +72,31 @@ await withTransaction(async (tx) => {
72
72
  | `PgliteOptions.snapshotDir` | `As of 2026-10`: a directory for the post-`initdb` snapshot, so an in-memory boot is a restore (~0.4 s against ~2.7 s). Keyed on the PGlite version alone — `initdb` never sees a linked extension, so one snapshot serves every set; checksummed, never trusted, written by temp-name-then-rename. Ignored for a data directory on disk |
73
73
  | `createBranch()` / `dropBranch()` / `reapBranches()` | copy-on-write branch databases. `As of 2026-08-19` the marker comment records the **base** as well as the instant (`ultimate:branch:<base>:<iso>`, on `BranchInfo.base`), and `reapBranches()` sweeps only branches of the database it is connected to — one Postgres hosting two Ultimate apps used to mean one app's nightly reap dropped the other's branches. A pre-3.x marker records no base and is skipped, never dropped |
74
74
  | `pgliteClient()` / `branchPglite()` | the embedded database — Postgres in this process |
75
- | `ensureReadOnlyRole()` / `grantReadOnlySql()` / `READONLY_ROLE` | a `NOLOGIN`, SELECT-only Postgres role — layer 1 of `db.query`'s defence |
76
- | `readOnlyQuery()` / `READONLY_TIMEOUT_MS` | one statement inside `BEGIN READ ONLY` with a statement timeout — layer 2 |
75
+ | `ensureReadOnlyRole()` / `READONLY_ROLE` | a `NOLOGIN`, SELECT-only Postgres role — layer 1 of `db.query`'s defence |
76
+ | `readOnlyQuery()` | one statement inside `BEGIN READ ONLY` with a statement timeout — layer 2 |
77
77
  | `dbDiagnostics()` / `DIAGNOSTICS_LIMIT` / `DIAGNOSTICS_TIMEOUT_MS` (from `@ultimat3/db/diagnostics`) | `As of 2026-11`: what the database is doing now, as seven sections (`blockers`, `activity`, `slowQueries`, `unusedIndexes`, `invalidIndexes`, `notValidConstraints`, `deadTuples`), each `{ available: true, rows }` or `{ available: false, code, reason, fix }` → [Diagnostics](#diagnostics). `x db diagnostics` prints it |
78
- | `setStatementObserver()` / `statementObserver()` | `As of 2026-08`: one event **and one `db.<verb>` span** per settled statement, both drivers; uninstalled is one branch |
78
+ | `DbStatementEvent` / `StatementAttribution` (types, core's) | `As of 2026-11` (v31): every settled statement, both drivers, is one `db.<verb>` client span — **always, production included** — carrying `db.system.name=postgresql`, `db.query.text` (parameterised) and `db.operation.name`; and one `db.statement` event on core's bus while anything subscribes: `subscribe('db.statement', (e) => …)`. No subscriber is one map read |
79
79
  | `expectedSeqScan()` / `expectedSeqScanReason()` | `As of 2026-11`: the one way a hand-written statement says it reads its table whole — `x exercise`'s plan sweep lists it exempt with the reason instead of `X_QUERY_UNINDEXED`. Same shape as `expectedQueryLoop()`: required, non-blank, innermost wins. A small table says it once on the entity: `scan: '<why>'` |
80
- | `expectedQueryLoop()` / `expectedQueryLoopReason()` | `As of 2026-08`: the one way to declare a loop of queries deliberate — the reason rides on every statement it issues as `StatementEvent.expected` |
81
- | `withStatementAttribution()` / `statementAttribution()` | `As of 2026-08`: the `{ entity, op }` pair on `StatementEvent.attribution`, scoped exactly like `expectedQueryLoop()` — `@ultimat3/entity`'s `postgresRepo` is the one producer |
82
- | `STATEMENT_ATTRIBUTE` | `As of 2026-08`: `db.statement`, the OTel attribute each span carries its text under — declared here, read by `x dev`'s timeline |
80
+ | `expectedQueryLoop()` / `expectedQueryLoopReason()` | `As of 2026-08`: the one way to declare a loop of queries deliberate — the reason rides on every statement it issues as `DbStatementEvent.expected` |
81
+ | `withStatementAttribution()` / `statementAttribution()` | `As of 2026-08`: the `{ entity, op }` pair on `DbStatementEvent.attribution`, scoped exactly like `expectedQueryLoop()` — `@ultimat3/entity`'s `postgresRepo` is the one producer |
83
82
  | `statementFingerprint()` / `statementKind()` / `statementVerb()` | `As of 2026-08`: what shape a statement is — `entity.op` when attributed else its own collapsed text, read or write from the leading verb. One rule, so two detectors group identically |
84
83
  | `recordingClient()` | in-memory `DbClient` that records SQL, for tests |
85
84
 
85
+ ### `@ultimat3/db/adapter`
86
+
87
+ `As of v31`: what a host or driver wires, never what an app calls. The `.` barrel is the app API;
88
+ the types below stay on it too wherever a `.` signature names them.
89
+
90
+ | Export | |
91
+ |---|---|
92
+ | `defaultClient()` | the boot's client, built from `DATABASE_URL` (and `DATABASE_REPLICA_URL`) |
93
+ | `loadPgliteDriver()` | the optional `@electric-sql/pglite` peer, imported by variable specifier |
94
+ | `PostgresClientOptions` / `ReplicatedClientOptions` | the pool options `postgresClient()` / `replicatedClient()` take |
95
+ | `ReservableClient` / `ListeningClient` | a client that pins one session; one that holds a `LISTEN` |
96
+
97
+ `PostgresFailureStore`, the `x_failures` store's shape, is on `.` only: no `runtime.ts` field takes
98
+ one, so it is no port.
99
+
86
100
  ## `sql` is parameters-only
87
101
 
88
102
  String interpolation is how every SQL injection ships, and an agent writing SQL cannot be
@@ -97,6 +111,8 @@ trusted to remember the difference between a value and a fragment. So:
97
111
  `sql`/`raw` did not produce;
98
112
  - `raw(trusted)` is the one audited escape hatch, `identifier(name)` the safe way to interpolate
99
113
  a table or column, `literal(text)` for utility statements that reject bound parameters.
114
+ `As of 2026-11-09` `identifier()` also refuses a NUL and a name over 63 **bytes**
115
+ (`sql.ts`'s `MAX_IDENTIFIER_BYTES`), which Postgres would truncate without an error (`X_SQL_UNSAFE`).
100
116
 
101
117
  ## Failure bundles: `x_failures`
102
118
 
@@ -120,6 +136,7 @@ fragments to splice and `page(rows)`, which answers core's `Page`.
120
136
  | A null key | `X_KEYSET_NULL_KEY`, on any row of a page, whatever its size |
121
137
  | The cursor | core's signed codec; scoped to `scope` plus every key's column, kind and direction. Another read's is `X_CURSOR_INVALID` |
122
138
  | `limit` | a whole number ≥ 1 (`finiteCount`), read as `limit + 1` |
139
+ | `direction`, `kind` | `As of 2026-11-09`: `'asc'`/`'desc'` and the five kinds, exactly — anything else is `X_INVARIANT` at `keyset()`. The `order by` splice is re-derived from the closed set, never the caller's text. Map a request's sort onto the two literals yourself |
123
140
 
124
141
  Proven on both engines: `keyset.live.test.ts` (Postgres) and `keyset-embedded.test.ts` (PGlite)
125
142
  walk four rows inside one millisecond across page boundaries, and assert the plan holds no sort.
@@ -184,12 +201,13 @@ layer 1 covers only what existed at grant time.
184
201
 
185
202
  ## Diagnostics
186
203
 
187
- `As of 2026-11`. `dbDiagnostics({ client?, limit? })` answers facts, never a verdict: how bloated is
204
+ `As of 2026-11`. `dbDiagnostics({ client?, limit?, deadlineMs? })` answers facts, never a verdict: how bloated is
188
205
  too bloated differs per app. `checkDb()` stays the readiness probe `/readyz` reads.
189
206
 
190
207
  | Rule | |
191
208
  |---|---|
192
209
  | Read-only, bounded | every section is one catalog statement through `readOnlyQuery()`: `BEGIN READ ONLY`, `DIAGNOSTICS_TIMEOUT_MS` (2 s), a cursor capped at `limit` (default 20). Sequential, so one connection |
210
+ | `deadlineMs` | `As of 2026-11-09`: the whole command's budget, the `select 1` probe included. Default: the probe waits 3 s, the command 15 s. On a cold embedded database the probe IS the boot, so `x db diagnostics` passes 30 s there |
193
211
  | One failure stays one | a section that throws is `{ available: false, code, reason, fix }`; the other six answer. The single throw is a probe (`select 1`) that cannot connect |
194
212
  | No row values | no statement reads a user table. Session SQL (`activity`, `blockers`, `slowQueries`) has every literal replaced by `?` before it leaves (`db-diagnostics-redact.ts`, over the package's one lexer); a `scheme://user:pass@` in a reason is masked |
195
213
  | `slowQueries` | reads `pg_stat_statements`; absent (always on PGlite) is `available: false` with the operator's `create extension` + `shared_preload_libraries` fix. The framework never creates an extension |
@@ -248,7 +266,7 @@ commit what it writes, ship. The drop is its own non-transactional migration.
248
266
 
249
267
  | API | |
250
268
  |---|---|
251
- | `setLocal(tx, settings)` / `readLocal(tx, names)` | the framework's ONE `set_config` caller: `select set_config($1, $2, true)`, parameter-bound and transaction-local, so a value ends with its transaction and a pooled connection hands nothing on (`read-transaction.test.ts` greps the tree for a second one) |
269
+ | `setLocal(tx, settings)` | the framework's ONE `set_config` caller: `select set_config($1, $2, true)`, parameter-bound and transaction-local, so a value ends with its transaction and a pooled connection hands nothing on (`read-transaction.test.ts` greps the tree for a second one) |
252
270
  | `withReadTransaction(fn, { settings, client })` | `withTransaction(fn, { readOnly: true, client })`, then `setLocal`. Inside an open transaction it joins it, applies the settings, runs `fn` and puts the prior values back |
253
271
  | `withStatementTimeout(ms, fn, { client })` | one read's own `statement_timeout`, transaction-local. Refused above the bound already in force, and non-positive (`X_DB_STATEMENT_BOUND_INVALID`); firing is `X_DB_STATEMENT_TIMEOUT`. A transaction is the primary's, so a bounded read never reaches a replica |
254
272
  | `setTransactionSettings(provider)` | the settings every ROOT transaction sets right after `BEGIN` — row security's tenant. One provider; unset costs one comparison |
@@ -257,11 +275,10 @@ commit what it writes, ship. The drop is its own non-transactional migration.
257
275
 
258
276
  | API | |
259
277
  |---|---|
260
- | `enableRowSecuritySql(table, column, type)` / `dropRowSecuritySql(table)` | `enable` + `force` + one `ultimate_tenant` policy: `using` and `with check` both `column = nullif(current_setting('x.tenant', true), '')::type or current_setting('x.cross', true) = 'on'`. Unset matches nothing |
261
- | `rowSecurityPlan(plan, input)` / `rowSecurityAfter(input)` | what `x db gen` emits per tenant table when the flag flips, both directions, grants to the app role |
278
+ | `enableRowSecuritySql(table, column, type)` | `enable` + `force` + one `ultimate_tenant` policy: `using` and `with check` both `column = nullif(current_setting('x.tenant', true), '')::type or current_setting('x.cross', true) = 'on'`. Unset matches nothing |
262
279
  | `rowSecureClient(client)` | a statement sent outside a transaction while the provider has a tenant is wrapped: `BEGIN [READ ONLY]`, `set_config`, the statement, `COMMIT` |
263
- | `assertRowSecurityBinds(client)` / `rowSecurityRole(client)` | `X_DB_ROW_SECURITY_BYPASSED` for a superuser, a `bypassrls` role, or the owner of an unforced table — Postgres exempts all three |
264
- | `ensureRowSecurityRoles(client)` / `assumeRole(client, role)` | `x_app` (`nosuperuser nobypassrls`) and `x_migrator` (`bypassrls`, owns tables), with default privileges from one to the other. `rowSecurityRolesSql()` is the same list as text |
280
+ | `assertRowSecurityBinds(client)` | `X_DB_ROW_SECURITY_BYPASSED` for a superuser, a `bypassrls` role, or the owner of an unforced table — Postgres exempts all three |
281
+ | `rowSecurityRolesSql()` | `x_app` (`nosuperuser nobypassrls`) and `x_migrator` (`bypassrls`, owns tables), with default privileges from one to the other, as text |
265
282
  | `serveAsAppRole(client)` | PGlite's superuser session: the roles, DML on every existing table and sequence to `x_app`, then `set role x_app` |
266
283
  | `generateMigration({ rowSecurity: { enabled, tenants } })` | `x db gen`: the policy per tenant table, typed off the column, recorded `rowSecurity: true` on the snapshot; off drops it |
267
284
  | `rowSecurityDifferences(entities, snapshot, option)` / `rowSecurityDrift(d)` | the flag against the migrations, `X_DB_ROW_SECURITY_DRIFT`. `checkDrift` raises the same code from `policyNames` (catalog: an enabled AND forced table's policies) |
@@ -409,6 +426,23 @@ create trigger "ultimate_append_only" before update or delete on "ledger" for ea
409
426
  | Engines | Postgres and PGlite alike (`generate-append-only.live.test.ts`, `generate-append-only-embedded.test.ts`) |
410
427
  | Drift | `introspectSchema()` writes `triggerNames` (enabled, non-internal) on every table — the catalog half; `appendOnly` is the snapshot half, never read from the catalog |
411
428
 
429
+ ## Partitioned tables (`entity({ partitionBy })`)
430
+
431
+ `As of 2026-11-09`. `EntityDescriptionLike.partition` (`PartitionDescriptionLike`: physical `column`, `interval` from `PARTITION_INTERVALS`, `ahead`, `retain?: { after, afterMs }`) is what `generate-partition.ts` reads.
432
+
433
+ | Part | What |
434
+ |---|---|
435
+ | `x db gen`, new table | `create table … partition by range ("<column>")`, its indexes, then `create or replace function ultimate_partitions(…)` and one call: the current partition plus `ahead`, judged at APPLY time (`now()`) — never a retention sweep |
436
+ | `partitionMaintenance(description, now, { from? })` | the function call, every value bound: creates ahead (and back to `from`'s partition, sweeping nothing then); NAMES expired partitions with their state (`attached`/`pending`/`detached`), never drops one; `null` on a plain table |
437
+ | `maintainPartitions(client, description, now, { from?, lockTimeoutMs? })` | what `@ultimat3/jobs`' `partitions()` runs: the call in a transaction with `set local lock_timeout` (`PARTITION_LOCK_TIMEOUT_MS`, 5 s; a wait past it is `X_DB_LOCK_TIMEOUT`, retryable), then per expired partition: `comment` (`RETIRING_COMMENT`), `detach … concurrently` outside any transaction, `drop`. A `pending` detach is finalized, a marked `detached` one dropped. Answers `{ created, dropped }`. Never inside a caller's transaction |
438
+ | Names and bounds | `<table>_pYYYYMMDD` (lower bound), UTC; `week` is ISO; `to_char`, so `DateStyle`/`TimeZone` never move a bound. Hand-made children are never touched |
439
+ | Snapshot | the parent records `partitioned: true` and `partitionInterval` (snapshot only, never read off the catalog) |
440
+ | Refusals | `X_MIGRATION_PARTITION_CHANGE`: from `x db gen` when a recorded partitioned table loses `partitionBy` (`partitionDropped`), from the function at migrate time when it meets a plain table (adoption on a table the hand recipe already partitioned passes) |
441
+ | Interval change | refused by `x db gen` with `X_MIGRATION_PARTITION_CHANGE` (`partitionRewidened`): the snapshot records `partitionInterval` (parsed back by `parseSnapshot`), and partitions of another width would overlap |
442
+ | No default partition | by decision: a default partition forbids `detach … concurrently`, and creating a month it holds rows for scans and moves them under ACCESS EXCLUSIVE. A row past every partition is `23514`; `ahead` is the scheduler-outage budget |
443
+
444
+ Proof: `generate-partition-fixture.ts`, on PGlite (`generate-partition-embedded.test.ts`) and Postgres (`generate-partition.live.test.ts`); a reader holding the parent: `generate-partition-lock.live.test.ts`; the sidecar round trip: `generate-partition-sidecar.test.ts`.
445
+
412
446
  ## The schema dump
413
447
 
414
448
  **Imported from `@ultimat3/db/schema-dump`, never from the barrel** (23.0.0): `introspectCatalog`,
@@ -501,6 +535,21 @@ The last row is the one divergence a second connection would remove and PGlite c
501
535
  issued *inside* an open transaction's scope runs immediately rather than waiting for a turn that
502
536
  scope is already holding, because waiting would be a deadlock with no error to explain it.
503
537
 
538
+ ## A pooled read stops when its caller does
539
+
540
+ `As of 2026-11-09`. A `select` sent on the pool, in flight when the ambient `ctx.signal` aborts, is
541
+ cancelled on the SERVER (`Bun.SQL`'s `cancel()`, `57014`) and its connection goes back at once —
542
+ before, a hung-up caller held it until `statement_timeout`, so firing requests and disconnecting
543
+ emptied the pool past any rate limit. `statement-cancel.ts`; `statement-cancel.live.test.ts`.
544
+
545
+ | Case | |
546
+ |---|---|
547
+ | a pooled `select`, abort while it runs | cancelled. A client hang-up throws `X_ABORTED`; a coded reason (`X_TIMEOUT`, a job's) is thrown as itself |
548
+ | a write (`insert`/`update`/…, or a `with` that may hide one) | never cancelled: a click followed by a navigation must keep landing |
549
+ | any statement on a pin (`withTransaction`, `readOnlyQuery`) | never cancelled here: aborting the statement aborts the transaction, which `transaction-guard.ts` decides |
550
+ | a statement sent after the abort | sent as before: a job's settle and a fenced write go out past it on purpose |
551
+ | no context, or PGlite | nothing to cancel: in-process, one session |
552
+
504
553
  ## Pool sizing by role
505
554
 
506
555
  `ROLE` picks the profile — a `worker` draining a queue must not size like a `web` process.
@@ -656,9 +705,9 @@ reader cannot tell a considered loop from a silenced one.
656
705
  | | |
657
706
  |---|---|
658
707
  | Scope | core's `asyncContext<string>('the expected-loop reason')`, never a `new AsyncLocalStorage` here: it survives every `await` at any depth, and two loops running at once never read each other. Nesting keeps the innermost reason |
659
- | What it carries | `StatementEvent.expected`, stamped by both funnels at settle time — a diagnostic judging a whole request runs after every scope in it closed |
708
+ | What it carries | `DbStatementEvent.expected`, stamped by both funnels at settle time — a diagnostic judging a whole request runs after every scope in it closed |
660
709
  | What it suppresses | a **verdict**, never a statement. The SQL is still sent, still observed, still a span: only the thing that warns is told the author already answered |
661
- | What it costs | nothing without a diagnostic — the reason is read inside the branch that already checks for an installed observer |
710
+ | What it costs | nothing without a diagnostic — the reason is read only while `db.statement` has a subscriber |
662
711
 
663
712
  The framework's own deliberate loops declare themselves at source: `migrate()` and `rollback()`
664
713
  (one transaction per migration, so a failure leaves an exact ledger) and `@ultimat3/admin`'s
@@ -684,7 +733,7 @@ tree in the gate's `unit` step.
684
733
 
685
734
  ## A statement knows who compiled it
686
735
 
687
- `As of 2026-08`: `StatementEvent.attribution` is no longer always `undefined`.
736
+ `As of 2026-08`: `DbStatementEvent.attribution` is no longer always `undefined`.
688
737
 
689
738
  ```ts
690
739
  return withStatementAttribution('members', 'findById', () =>
@@ -695,9 +744,9 @@ return withStatementAttribution('members', 'findById', () =>
695
744
  | | |
696
745
  |---|---|
697
746
  | Scope | core's `asyncContext<StatementAttribution>()`, `expectedQueryLoop()`'s own shape: it survives every `await` at any depth, and nesting keeps the innermost pair |
698
- | What it carries | `StatementEvent.attribution`, stamped by both funnels at settle time, next to `expected` |
747
+ | What it carries | `DbStatementEvent.attribution`, stamped by both funnels at settle time, next to `expected` |
699
748
  | Producer | `@ultimat3/entity`'s `postgresRepo` — the last caller that still knows the entity and the operation once the SQL exists |
700
- | What it costs | nothing uninstalled — `statementObserver()` is read first, and with nothing installed `fn` runs directly; no scope entered, no object allocated |
749
+ | What it costs | nothing unsubscribed — `subscribed('db.statement')` is read first, and with no subscriber `fn` runs directly; no scope entered, no object allocated |
701
750
 
702
751
  Hand-written SQL, a migration, a health probe, `x db` commands and `@ultimat3/jobs`' own queue
703
752
  statements still carry no `attribution` — nothing above them knows an entity to name, so the field
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/db",
3
- "version": "30.9.0",
3
+ "version": "31.0.0",
4
4
  "description": "Postgres access, transactions, migrations and drift detection",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -25,6 +25,7 @@
25
25
  },
26
26
  "exports": {
27
27
  ".": "./src/index.ts",
28
+ "./adapter": "./src/adapter.ts",
28
29
  "./diagnostics": "./src/diagnostics-entry.ts",
29
30
  "./schema-dump": "./src/schema-dump-entry.ts"
30
31
  },
@@ -44,7 +45,7 @@
44
45
  "test": "bun test"
45
46
  },
46
47
  "dependencies": {
47
- "@ultimat3/core": "30.9.0"
48
+ "@ultimat3/core": "31.0.0"
48
49
  },
49
50
  "peerDependencies": {
50
51
  "@electric-sql/pglite": ">=0.5.0"
package/src/adapter.ts ADDED
@@ -0,0 +1,9 @@
1
+ // `@ultimat3/db/adapter` — the seam a driver or host wires, never the app API: the connection
2
+ // options and client shapes a Postgres/PGlite driver implements, the boot's default client and the
3
+ // PGlite loader. App code reads `db()` from `.`; this entry is for whoever installs the client.
4
+
5
+ export type { PostgresClientOptions, ReservableClient } from './client';
6
+ export { defaultClient } from './default-client';
7
+ export type { ListeningClient } from './listen';
8
+ export { loadPgliteDriver } from './pglite';
9
+ export type { ReplicatedClientOptions } from './replica-client';
@@ -8,8 +8,7 @@
8
8
  // context. It opens through core's seam for the same reason `expected-loop.ts` does: constructing
9
9
  // an `AsyncLocalStorage` here threw at module EVALUATION in a browser bundle, where
10
10
  // `node:async_hooks` is stubbed to `{}`, taking every importer of `@ultimat3/db` down with it.
11
- import { asyncContext } from '@ultimat3/core';
12
- import { type StatementAttribution, statementObserver } from './observe';
11
+ import { asyncContext, type StatementAttribution, subscribed } from '@ultimat3/core';
13
12
 
14
13
  const storage = asyncContext<StatementAttribution>('the statement attribution');
15
14
 
@@ -24,22 +23,22 @@ const storage = asyncContext<StatementAttribution>('the statement attribution');
24
23
  * relation preloaded during `findMany` reads through the *related* repository, and that read is
25
24
  * what its own statement is.
26
25
  *
27
- * **With no observer installed this enters no scope at all** — one property read, one branch, no
26
+ * **With no `db.statement` subscriber this enters no scope at all** — one map read, one branch, no
28
27
  * object allocated (axiom 6). Which is also why the pair arrives as two strings rather than as a
29
28
  * `StatementAttribution`: a literal at the call site would be allocated before the branch could
30
- * decline it, on the path every statement in the process takes. An observer installed *during*
31
- * `fn` therefore sees the statements that follow unattributed; installation happens once, at boot,
32
- * and paying for the scope on every production statement to close that window is the wrong trade.
29
+ * decline it, on the path every statement in the process takes. A subscriber added *during* `fn`
30
+ * therefore sees the statements that follow unattributed; subscribing happens once, at boot, and
31
+ * paying for the scope on every production statement to close that window is the wrong trade.
33
32
  */
34
33
  export function withStatementAttribution<T>(entity: string, op: string, fn: () => T): T {
35
- if (statementObserver() === undefined) return fn();
34
+ if (!subscribed('db.statement')) return fn();
36
35
  return storage.run({ entity, op }, fn);
37
36
  }
38
37
 
39
38
  /**
40
39
  * The innermost enclosing pair, or `undefined` outside every scope — hand-written SQL, a migration,
41
- * a health probe, the job queue's own statements. Read by the two funnels when an observer is
42
- * installed, and by nothing else: a diagnostic reads `StatementEvent.attribution`, which is this
40
+ * a health probe, the job queue's own statements. Read by `traceStatement` while `db.statement`
41
+ * has a subscriber, and by nothing else: a subscriber reads `DbStatementEvent.attribution`, which is this
43
42
  * same answer captured at the moment the statement settled.
44
43
  */
45
44
  export function statementAttribution(): StatementAttribution | undefined {
@@ -0,0 +1,24 @@
1
+ // Single responsibility: the two refusals `x db branch` raises — a branch that exists, and a name
2
+ // that is not one. Split from `errors.ts` at its line ceiling; `index.ts` re-exports both.
3
+
4
+ import { DbError } from './errors';
5
+
6
+ export const branchExists = (branch: string): DbError =>
7
+ new DbError({
8
+ code: 'X_BRANCH_EXISTS',
9
+ cause: `database "${branch}" already exists`,
10
+ fix: `x db branch delete ${branch} # then re-create, or pick another name`,
11
+ meta: { branch },
12
+ });
13
+
14
+ /**
15
+ * An unvalidated branch name is spliced into `CREATE DATABASE "<name>"`, so a bad name is an
16
+ * injection vector, not a typo — hence `X_SQL_UNSAFE` rather than a validation code.
17
+ */
18
+ export const branchNameInvalid = (branch: string): DbError =>
19
+ new DbError({
20
+ code: 'X_SQL_UNSAFE',
21
+ cause: `branch name "${branch}" is not [a-z0-9_-]+`,
22
+ fix: 'x db branch create <name> # lowercase letters, digits, underscore and dash only',
23
+ meta: { branch },
24
+ });
package/src/branch.ts CHANGED
@@ -4,8 +4,9 @@
4
4
  // Branches are cheap and forgettable, so `reapBranches()` is part of the design, not an add-on.
5
5
 
6
6
  import { finiteCount, systemClock } from '@ultimat3/core';
7
+ import { branchExists, branchNameInvalid } from './branch-errors';
7
8
  import { baseClient, type DbClient } from './client';
8
- import { branchExists, branchNameInvalid, DbError } from './errors';
9
+ import { DbError } from './errors';
9
10
  import { identifier, literal, sql } from './sql';
10
11
 
11
12
  const BRANCH_NAME = /^[a-z0-9_-]+$/;
package/src/check-ddl.ts CHANGED
@@ -14,9 +14,9 @@ import { assert } from '@ultimat3/core';
14
14
  import { type ConcurrentPlan, deferValidate } from './concurrent-plan';
15
15
  import type { ColumnDescriptionLike, EntityDescriptionLike } from './entity-shape';
16
16
  import type { CheckDescription, TableDescription } from './introspect';
17
- import { invariantChecks, isIdentifier, MAX_IDENTIFIER_BYTES } from './invariant-ddl';
17
+ import { invariantChecks, isIdentifier } from './invariant-ddl';
18
18
  import { constraintExpressionUnsafe, constraintNameUnsafe } from './invariant-errors';
19
- import { identifier } from './sql';
19
+ import { identifier, MAX_IDENTIFIER_BYTES } from './sql';
20
20
  import { statementsOf } from './statement-split';
21
21
 
22
22
  /**
package/src/client.ts CHANGED
@@ -28,6 +28,7 @@ import { closeRetiredPool } from './pool-retire';
28
28
  import { poolSweep, UNANSWERED_GRACE_MS } from './pool-sweep';
29
29
  import { type PoolerMode, poolerFromEnv, poolerSessionRequired, poolerWaitFor } from './pooler';
30
30
  import { type SqlFragment, sql } from './sql';
31
+ import { watchAbort } from './statement-cancel';
31
32
  import { affectedBy, rowsOf, runOn } from './statement-funnel';
32
33
  import { currentTx } from './transaction';
33
34
 
@@ -154,10 +155,15 @@ export function postgresClient(options: PostgresClientOptions = {}): PostgresCli
154
155
  async function run(fragment: SqlFragment): Promise<unknown> {
155
156
  const slot = takeSlot(connect, profile.acquireTimeoutMs);
156
157
  const live = slot instanceof Promise ? await slot : slot;
158
+ // Pooled only: a pin's statement belongs to a transaction, and cancelling it is not ours to do.
159
+ const watch = watchAbort(fragment.text);
157
160
  try {
158
- const sending = runOn(live.pool, fragment);
161
+ const sending = runOn(watch === undefined ? live.pool : watch.on(live.pool), fragment);
159
162
  return await (sweep === undefined ? sending : sweep.track(live, fragment.text, sending));
163
+ } catch (error) {
164
+ throw watch === undefined ? error : watch.failure(error);
160
165
  } finally {
166
+ watch?.end();
161
167
  freeSlot(live);
162
168
  }
163
169
  }
@@ -51,6 +51,12 @@ export interface DbDiagnosticsOptions {
51
51
  readonly limit?: number | undefined;
52
52
  /** Arms both client-side deadlines. A seam for tests; default an unref'd `setTimeout`. */
53
53
  readonly schedule?: Scheduler | undefined;
54
+ /**
55
+ * The whole command's budget, the connect probe included — a whole number of ms ≥ 1. Default:
56
+ * the probe waits `DIAGNOSTICS_SECTION_DEADLINE_MS` and the command `DIAGNOSTICS_DEADLINE_MS`.
57
+ * Passed, the probe may spend all of it: on a cold embedded database the probe IS the boot.
58
+ */
59
+ readonly deadlineMs?: number | undefined;
54
60
  }
55
61
 
56
62
  /** A section answered, or why it could not be and what would make it answer. Never a throw. */
@@ -100,24 +106,29 @@ export async function dbDiagnostics(options: DbDiagnosticsOptions = {}): Promise
100
106
  const read = { client: options.client, timeoutMs: DIAGNOSTICS_TIMEOUT_MS } as const;
101
107
  const schedule = options.schedule ?? unrefSchedule;
102
108
  const sectionMs = DIAGNOSTICS_SECTION_DEADLINE_MS;
109
+ const commandMs =
110
+ options.deadlineMs === undefined
111
+ ? DIAGNOSTICS_DEADLINE_MS
112
+ : finiteCount('dbDiagnostics', 'deadlineMs', options.deadlineMs, 1);
113
+ const probeMs = options.deadlineMs === undefined ? sectionMs : commandMs;
103
114
  try {
104
- const probe = await within(readOnlyQuery('select 1', read), sectionMs, schedule);
115
+ const probe = await within(readOnlyQuery('select 1', read), probeMs, schedule);
105
116
  if (probe === EXPIRED) {
106
- throw dbUnavailable(`x db diagnostics had no answer to select 1 within ${sectionMs}ms`);
117
+ throw dbUnavailable(`x db diagnostics had no answer to select 1 within ${probeMs}ms`);
107
118
  }
108
119
  } catch (error) {
109
120
  throw isUltimateError(error)
110
121
  ? error
111
122
  : dbUnavailable('x db diagnostics could not open a connection', error);
112
123
  }
113
- const deadline = commandDeadline(DIAGNOSTICS_DEADLINE_MS, schedule);
124
+ const deadline = commandDeadline(commandMs, schedule);
114
125
  const section = async <Row>(
115
126
  statement: string,
116
127
  toRow: (raw: Readonly<Record<string, unknown>>) => Row,
117
128
  fixFor?: (code: string, reason: string) => string | undefined,
118
129
  ): Promise<DiagnosticSection<Row>> => {
119
130
  if (deadline.passed()) {
120
- const reason = `not sent: x db diagnostics passed its ${DIAGNOSTICS_DEADLINE_MS}ms deadline first`;
131
+ const reason = `not sent: x db diagnostics passed its ${commandMs}ms deadline first`;
121
132
  return { available: false, code: TIMED_OUT, reason, fix: GENERIC_FIX };
122
133
  }
123
134
  try {
@@ -157,6 +157,26 @@ export interface EntityDescriptionLike {
157
157
  readonly counts?: readonly CounterDescriptionLike[] | undefined;
158
158
  /** `entity({ retain })`: rows older than the window are swept by `purge()`. Absent is kept. */
159
159
  readonly retain?: RetainDescriptionLike | undefined;
160
+ /**
161
+ * `entity({ partitionBy })`: a range-partitioned table (`generate-partition.ts`). Absent is a
162
+ * plain table, for the reason `invariants` is optional.
163
+ */
164
+ readonly partition?: PartitionDescriptionLike | undefined;
165
+ }
166
+
167
+ /** The bucket widths. `week` is ISO: it starts on a Monday, as `date_trunc('week', …)` does. */
168
+ export const PARTITION_INTERVALS = ['day', 'week', 'month', 'year'] as const;
169
+ export type PartitionInterval = (typeof PARTITION_INTERVALS)[number];
170
+
171
+ /** Structurally assignment-compatible with `@ultimat3/entity`'s `PartitionDescription`. */
172
+ export interface PartitionDescriptionLike {
173
+ /** The physical partition column, part of the primary key. */
174
+ readonly column: string;
175
+ readonly interval: PartitionInterval;
176
+ /** Partitions kept ready past the current one. */
177
+ readonly ahead: number;
178
+ /** Whole partitions whose upper bound is older than `afterMs` are detached, then dropped. */
179
+ readonly retain?: { readonly after: string; readonly afterMs: number } | undefined;
160
180
  }
161
181
 
162
182
  /** Where a table's row images go, and what its trigger needs to write one. Physical names. */
package/src/errors.ts CHANGED
@@ -58,6 +58,7 @@ export const DB_OWNED_ERROR_CODES = [
58
58
  'X_MIGRATION_ROLLBACK_DESTRUCTIVE',
59
59
  'X_ENTITY_RETAIN_INVALID',
60
60
  'X_LIFECYCLE_TRIGGER_MISSING',
61
+ 'X_MIGRATION_PARTITION_CHANGE',
61
62
  ] as const;
62
63
 
63
64
  /**
@@ -131,6 +132,7 @@ export const DB_ERROR_TITLES: Readonly<Record<DbOwnedErrorCode, string>> = {
131
132
  'entity({ retain }) has no window, sits beside appendOnly, or is on a partitioned table',
132
133
  X_LIFECYCLE_TRIGGER_MISSING:
133
134
  'a history or counter trigger the migrations created is missing from the database',
135
+ X_MIGRATION_PARTITION_CHANGE: 'an existing table gained or lost entity({ partitionBy })',
134
136
  };
135
137
 
136
138
  // Registered unconditionally, in one call, so a second package claiming one of db's codes fails
@@ -422,10 +424,10 @@ export const sqlUnsafe = (received: string, position: number): DbError =>
422
424
  meta: { position, received },
423
425
  });
424
426
 
425
- export const identifierUnsafe = (name: string): DbError =>
427
+ export const identifierUnsafe = (name: string, why?: string): DbError =>
426
428
  new DbError({
427
429
  code: 'X_SQL_UNSAFE',
428
- cause: `${JSON.stringify(name)} is not usable as a Postgres identifier`,
430
+ cause: `${JSON.stringify(name)} is not usable as a Postgres identifier${why === undefined ? '' : `: ${why}`}`,
429
431
  fix: 'pass a plain table/column name — identifiers cannot be bound as parameters',
430
432
  meta: { name },
431
433
  });
@@ -462,26 +464,6 @@ export const indexMethodInvalid = (received: unknown): DbError =>
462
464
  fix: "indexes: [{ on: ['tags'], using: 'gin' }] # or leave it out for the btree default",
463
465
  });
464
466
 
465
- export const branchExists = (branch: string): DbError =>
466
- new DbError({
467
- code: 'X_BRANCH_EXISTS',
468
- cause: `database "${branch}" already exists`,
469
- fix: `x db branch delete ${branch} # then re-create, or pick another name`,
470
- meta: { branch },
471
- });
472
-
473
- /**
474
- * An unvalidated branch name is spliced into `CREATE DATABASE "<name>"`, so a bad name is an
475
- * injection vector, not a typo — hence `X_SQL_UNSAFE` rather than a validation code.
476
- */
477
- export const branchNameInvalid = (branch: string): DbError =>
478
- new DbError({
479
- code: 'X_SQL_UNSAFE',
480
- cause: `branch name "${branch}" is not [a-z0-9_-]+`,
481
- fix: 'x db branch create <name> # lowercase letters, digits, underscore and dash only',
482
- meta: { branch },
483
- });
484
-
485
467
  /**
486
468
  * An isolation level that is not one of the three. `X_SQL_UNSAFE` for the reason
487
469
  * `branchNameInvalid` uses it: `BEGIN` takes no parameters, so the level is SPLICED into the
@@ -14,7 +14,7 @@ const storage = asyncContext<string>('the expected-loop reason');
14
14
 
15
15
  /**
16
16
  * Run `fn` with every statement it issues — at any depth, across every `await` — marked expected
17
- * and carrying `reason`. The reason rides on the `StatementEvent` (`expected`), so a diagnostic
17
+ * and carrying `reason`. The reason rides on the `DbStatementEvent` (`expected`), so a diagnostic
18
18
  * that buffers a request's statements and judges them at the end still holds the argument long
19
19
  * after this scope closed.
20
20
  *
@@ -45,8 +45,8 @@ export function expectedQueryLoop<T>(reason: string, fn: () => T): T {
45
45
 
46
46
  /**
47
47
  * The innermost enclosing reason, or `undefined` outside every scope — which is every statement in
48
- * an app that never calls `expectedQueryLoop`. Read by the two funnels when an observer is
49
- * installed, and by nothing else: a diagnostic reads `StatementEvent.expected`, which is the same
48
+ * an app that never calls `expectedQueryLoop`. Read by `traceStatement` while `db.statement`
49
+ * has a subscriber, and by nothing else: a subscriber reads `DbStatementEvent.expected`, which is the same
50
50
  * answer captured at the moment the statement settled.
51
51
  */
52
52
  export function expectedQueryLoopReason(): string | undefined {