@ultimat3/db 31.28.0 → 31.30.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/README.md CHANGED
@@ -33,6 +33,7 @@ await withTransaction(async (tx) => {
33
33
  | `client.copyIn(target, rows)` / `canCopyIn(client)` | `As of 2026-11-11`: `COPY … FROM STDIN` on `postgresClient()`, its pins, a `DbTx` on one and the replica router (to the primary) → [Bulk load: `copyIn`](#bulk-load-copyin) |
34
34
  | `db()` / `baseClient()` / `setDbClient()` | the ambient client; `db()` returns the open tx if any |
35
35
  | `dbClientInstalled()` | `As of 30.0`: whether `setDbClient` installed a client that is still in place. Never builds the lazy default. `@ultimat3/entity`'s `testDriver()` asks it on every repository call |
36
+ | `ambientClient()` | `As of 31.30`: the client `db()` would use now — installed, or the lazy default once built — else `undefined`. Never builds. A caller that displaces it with `setDbClient` reads it to restore or close it |
36
37
  | `dbExecutor(client = db)` | the client as `@ultimat3/core`'s `PgExecutor` (`query(text, values)`) — what a jobs, idempotency, notify or MCP confirmation store takes. The client is resolved per statement: the default reaches the boot's client even when declared at module scope, and joins an open `withTransaction`; `() => pool` pins one pool whatever transaction is open |
37
38
  | `DbTx.origin` | `As of 2026-08`: the client the transaction was **opened on** — `options.client` or `baseClient()`, never the reservation it runs statements through. `@ultimat3/entity` compares a pinned repository's client against it, so a pinned repo joins its own shard's transaction instead of being refused |
38
39
  | `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) |
@@ -40,6 +41,7 @@ await withTransaction(async (tx) => {
40
41
  | `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 |
41
42
  | `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 |
42
43
  | `migrate()` / `rollback()` / `readLedger()` | the `x_migrations` ledger |
44
+ | `ledgerAheadOfBuild()` / `ROLLBACK_ALLOW_DESTRUCTIVE_ENV` | `As of 31.30`: the ledger split when it is exactly a rollback onto a newer build's schema (every unknown row newer than the newest shipped, nothing pending), else `undefined` and `auditLedger` refuses it; a destructive row ahead throws `X_MIGRATION_ROLLBACK_DESTRUCTIVE` unless named in the variable. `migrate()`'s own first step, exported so `x db status` judges a ledger as `x db migrate` will |
43
45
  | `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 |
44
46
  | `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 |
45
47
  | `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) |
@@ -222,6 +224,28 @@ too bloated differs per app. `checkDb()` stays the readiness probe `/readyz` rea
222
224
  | `activity` | `queryVisible: false` (and `query: null`) for a session another role owns when this one lacks `pg_read_all_stats` |
223
225
  | Who sees what | whoever runs it sees the SQL text (redacted) of **every session on the app's database role**, and of every role when that role holds `pg_read_all_stats` or is a superuser: other users' requests, background jobs, `psql` sessions. Literals are `?`, statement shape and identifiers are not. Run it with the credentials of someone allowed to see that |
224
226
 
227
+ ## Server health gauges
228
+
229
+ `As of 2026-11`. `startPostgresStatsGauges(executor, intervalMs?)` samples the Postgres server every
230
+ `POSTGRES_STATS_INTERVAL_MS` (15 s) — at once, one round at a time, unref'd — and returns an async stop
231
+ that awaits the round in flight (release it before the pool closes);
232
+ `postgresStatsSampler(executor).sample()` is one round. Run by ONE role (the scheduler): these are server
233
+ facts, and every pod reading them would multiply the load for the same numbers.
234
+
235
+ | Series | What it is |
236
+ |---|---|
237
+ | `db_server_connections` / `db_server_max_connections` | client backends on the whole server, against its `max_connections` |
238
+ | `db_longest_transaction_seconds` | this database's oldest open transaction this role can see (`pg_read_all_stats` widens it), 0 when none |
239
+ | `db_autovacuum_backlog_ratio` | the worst table's dead tuples over its autovacuum trigger (global settings): above 1 it is due |
240
+ | `db_replication_slot_retained_bytes{slot}` | the WAL each of this database's logical slots holds on the primary; a dropped slot reads 0 |
241
+ | `db_stats_sample_ok` | 1 when the last round landed, 0 when it failed and every value above is stale |
242
+
243
+ Two constant catalog statements per round, no user table, no lock. A failed round never rejects
244
+ and logs `db.stats.sample-failed` once per streak; a value the driver did not send as a finite
245
+ number leaves the gauge at its last good value. The gauges are declared on the first sample, so a
246
+ process that samples nothing exposes none. The chart's alert rules read all six; a
247
+ zero autovacuum trigger (threshold 0 over an empty table) is skipped, never a division by zero.
248
+
225
249
  ## Index access methods
226
250
 
227
251
  `btree` is the default and is never written out; `gin` is what makes `@>` / `<@` / `&&` / `?` on a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/db",
3
- "version": "31.28.0",
3
+ "version": "31.30.0",
4
4
  "description": "Postgres access, transactions, migrations and drift detection",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -45,7 +45,7 @@
45
45
  "test": "bun test"
46
46
  },
47
47
  "dependencies": {
48
- "@ultimat3/core": "31.28.0"
48
+ "@ultimat3/core": "31.30.0"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@electric-sql/pglite": ">=0.5.0"
package/src/client.ts CHANGED
@@ -360,6 +360,15 @@ export function dbClientInstalled(): boolean {
360
360
  return installed;
361
361
  }
362
362
 
363
+ /**
364
+ * The client `db()` would use now — installed, or the lazy default once something built it — and
365
+ * `undefined` when neither exists. Never builds: a caller that displaces it with `setDbClient`
366
+ * reads it here to close or restore it, where `baseClient()` would open a pool to answer.
367
+ */
368
+ export function ambientClient(): DbClient | undefined {
369
+ return ambient;
370
+ }
371
+
363
372
  /**
364
373
  * The pool, ignoring any open transaction. `withTransaction` must not re-enter `db()`.
365
374
  *
package/src/index.ts CHANGED
@@ -24,6 +24,7 @@ export type {
24
24
  ReservableClient,
25
25
  } from './client';
26
26
  export {
27
+ ambientClient,
27
28
  baseClient,
28
29
  db,
29
30
  dbClientInstalled,
@@ -177,6 +178,8 @@ export {
177
178
  rollback,
178
179
  runningAppVersion,
179
180
  } from './migrate';
181
+ export type { LedgerAhead, LedgerAheadOptions } from './migrate-rollback';
182
+ export { ledgerAheadOfBuild, ROLLBACK_ALLOW_DESTRUCTIVE_ENV } from './migrate-rollback';
180
183
  export {
181
184
  migrationConcurrentPartitioned,
182
185
  migrationDestructive,
@@ -192,6 +195,12 @@ export {
192
195
  lockHeavyStatements,
193
196
  migrationLockHeavy,
194
197
  } from './migration-lock-lint';
198
+ export type { PostgresStatsSampler } from './pg-stats-gauges';
199
+ export {
200
+ POSTGRES_STATS_INTERVAL_MS,
201
+ postgresStatsSampler,
202
+ startPostgresStatsGauges,
203
+ } from './pg-stats-gauges';
195
204
  export type {
196
205
  PgliteClient,
197
206
  PgliteDriver,
package/src/migrate.ts CHANGED
@@ -358,8 +358,8 @@ export async function rollback(options: RollbackOptions): Promise<readonly strin
358
358
  if (migration === undefined) {
359
359
  throw migrationConflict(
360
360
  `migration "${row.id}" is in the ledger but not in this build, so its down SQL is unknown`,
361
- // Same reason as `auditLedger`'s: `x db status` does not exist. The `down` SQL only
362
- // exists in the build that shipped it, so the fix is the read that names that build.
361
+ // Same reason as `auditLedger`'s: psql works where the CLI is absent. The `down` SQL
362
+ // only exists in the build that shipped it, so the fix reads which build that was.
363
363
  `psql "$DATABASE_URL" -c "select id, app_version from ${renderFixShellArg(LEDGER_TABLE, '<ledger table>')} ` +
364
364
  `order by id desc limit 5" # deploy the build that shipped the migration ` +
365
365
  `whose id is base64 ${Buffer.from(row.id, 'utf8').toString('base64')}, ` +
@@ -128,10 +128,9 @@ export function auditLedger(
128
128
  throw migrationConflict(
129
129
  `the ledger records migration "${first.id}" applied by app version "${first.app_version}" ` +
130
130
  `but this build is "${appVersion}" and does not ship it`,
131
- // `x db status` has never existed — the subcommands are gen, migrate, reset, studio, branch
132
- // and backfill — and this is one of the two errors most likely to fire during a real deploy.
133
- // A `fix:` is copied and run verbatim, so it names the ledger read that works anywhere psql
134
- // does, and the one edit that resolves the disagreement.
131
+ // One of the two errors most likely to fire during a real deploy, often on a box with no
132
+ // CLI. A `fix:` is copied and run verbatim, so it names the ledger read that works anywhere
133
+ // psql does (`x db status --json` reads the same rows), and the one edit that resolves it.
135
134
  conflictFix(first),
136
135
  );
137
136
  }
@@ -0,0 +1,131 @@
1
+ // Single responsibility: the Postgres server's own health as gauges — connections against
2
+ // `max_connections`, the longest open transaction, the autovacuum backlog and the WAL each logical
3
+ // slot retains — sampled on an interval by ONE role (the scheduler), because a scrape reads gauges
4
+ // synchronously and these are server facts every pod would otherwise read the same of.
5
+
6
+ import type { Gauge, PgExecutor } from '@ultimat3/core';
7
+ import { gauge, logger, renderThrowable } from '@ultimat3/core';
8
+ import { PG_SERVER_STATS_SQL, PG_SLOT_STATS_SQL } from './pg-stats-sql';
9
+
10
+ /** A scrape reads every ~15s; sampling faster costs the server reads nobody sees. */
11
+ export const POSTGRES_STATS_INTERVAL_MS = 15_000;
12
+
13
+ interface Gauges {
14
+ readonly connections: Gauge;
15
+ readonly maxConnections: Gauge;
16
+ readonly longestTransaction: Gauge;
17
+ readonly autovacuumBacklog: Gauge;
18
+ readonly slotRetained: Gauge;
19
+ readonly sampleOk: Gauge;
20
+ }
21
+
22
+ let declared: Gauges | undefined;
23
+
24
+ /** On the first sample, never at import: a process that samples nothing declares no series. */
25
+ function gauges(): Gauges {
26
+ declared ??= {
27
+ connections: gauge('db_server_connections', {
28
+ unit: '{connection}',
29
+ description: 'Client connections open on the Postgres server, every database counted',
30
+ }),
31
+ maxConnections: gauge('db_server_max_connections', {
32
+ unit: '{connection}',
33
+ description: "The Postgres server's max_connections",
34
+ }),
35
+ longestTransaction: gauge('db_longest_transaction_seconds', {
36
+ unit: 's',
37
+ description: "Age of this database's oldest open transaction this role can see — 0 when none",
38
+ }),
39
+ autovacuumBacklog: gauge('db_autovacuum_backlog_ratio', {
40
+ unit: '1',
41
+ description: "The worst table's dead tuples over the count that triggers its autovacuum",
42
+ }),
43
+ slotRetained: gauge('db_replication_slot_retained_bytes', {
44
+ unit: 'By',
45
+ description: "WAL the primary keeps for one of this database's logical replication slots",
46
+ }),
47
+ // A failed round leaves every value above at its last good number — a long transaction that
48
+ // began after the sampler died would read as none. This is what says the numbers are stale.
49
+ sampleOk: gauge('db_stats_sample_ok', {
50
+ unit: '1',
51
+ description:
52
+ 'Whether the last Postgres stats round landed: 1, or 0 when the values are stale',
53
+ }),
54
+ };
55
+ return declared;
56
+ }
57
+
58
+ const finite = (row: Readonly<Record<string, unknown>> | undefined, key: string) => {
59
+ const value = row?.[key];
60
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
61
+ };
62
+
63
+ /** A value the driver did not send as a finite number writes nothing: the last good one stands. */
64
+ const recordIf = (target: Gauge, value: number | undefined, attributes = {}): void => {
65
+ if (value !== undefined) target.record(value, attributes);
66
+ };
67
+
68
+ export interface PostgresStatsSampler {
69
+ /** One round. Never rejects: a database that cannot be measured is logged, once per streak. */
70
+ sample(): Promise<void>;
71
+ }
72
+
73
+ export function postgresStatsSampler(executor: PgExecutor): PostgresStatsSampler {
74
+ // The slots the last round published: a dropped slot reads 0, never its last size forever.
75
+ let published: ReadonlySet<string> = new Set();
76
+ let failing = false;
77
+ return {
78
+ async sample(): Promise<void> {
79
+ try {
80
+ const [server] = await executor.query<Record<string, unknown>>(PG_SERVER_STATS_SQL, []);
81
+ const slots = await executor.query<Record<string, unknown>>(PG_SLOT_STATS_SQL, []);
82
+ const g = gauges();
83
+ recordIf(g.connections, finite(server, 'connections'));
84
+ recordIf(g.maxConnections, finite(server, 'max_connections'));
85
+ recordIf(g.longestTransaction, finite(server, 'longest_transaction_seconds'));
86
+ recordIf(g.autovacuumBacklog, finite(server, 'autovacuum_backlog_ratio'));
87
+ const seen = new Set<string>();
88
+ for (const row of slots) {
89
+ if (typeof row['slot'] !== 'string') continue;
90
+ seen.add(row['slot']);
91
+ recordIf(g.slotRetained, finite(row, 'retained_bytes'), { slot: row['slot'] });
92
+ }
93
+ for (const slot of published) if (!seen.has(slot)) g.slotRetained.record(0, { slot });
94
+ published = seen;
95
+ g.sampleOk.record(1);
96
+ failing = false;
97
+ } catch (error) {
98
+ gauges().sampleOk.record(0);
99
+ if (failing) return;
100
+ failing = true;
101
+ logger.warn('db.stats.sample-failed', { error: renderThrowable(error) });
102
+ }
103
+ },
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Samples now and every `intervalMs`, one round at a time; returns the stop. Unref'd. The stop is
109
+ * async and awaits the round in flight: release it BEFORE the pool closes, or that round's query
110
+ * meets a closing pool and logs `db.stats.sample-failed` on every shutdown.
111
+ */
112
+ export function startPostgresStatsGauges(
113
+ executor: PgExecutor,
114
+ intervalMs: number = POSTGRES_STATS_INTERVAL_MS,
115
+ ): () => Promise<void> {
116
+ const sampler = postgresStatsSampler(executor);
117
+ let inFlight: Promise<void> | undefined;
118
+ const tick = (): void => {
119
+ if (inFlight !== undefined) return;
120
+ inFlight = sampler.sample().finally(() => {
121
+ inFlight = undefined;
122
+ });
123
+ };
124
+ tick();
125
+ const timer = setInterval(tick, intervalMs);
126
+ timer.unref();
127
+ return async () => {
128
+ clearInterval(timer);
129
+ await inFlight;
130
+ };
131
+ }
@@ -0,0 +1,31 @@
1
+ // Single responsibility: the two constant catalog reads behind the Postgres stats gauges. Statistics
2
+ // views and settings only — no statement here reads a user table, and none takes a lock.
3
+
4
+ /**
5
+ * One row. `connections` counts every client backend on the SERVER, because `max_connections` is
6
+ * the server's: another database's sessions spend the same budget. The longest transaction is this
7
+ * database's own; without `pg_read_all_stats` another role's `xact_start` reads null, so it is the
8
+ * longest this role can see. The autovacuum backlog is the worst table's dead tuples over the count
9
+ * that triggers its autovacuum (global settings; a per-table override is not read): above 1 the
10
+ * table is due, and staying above it means autovacuum is not keeping up. A trigger of 0 (threshold
11
+ * 0 over an empty table) is skipped by `nullif`: float8 `0 / 0` raises and took the round with it.
12
+ */
13
+ export const PG_SERVER_STATS_SQL = `select
14
+ (select count(*) from pg_stat_activity where backend_type = 'client backend')::int as connections,
15
+ current_setting('max_connections')::int as max_connections,
16
+ coalesce((select extract(epoch from max(now() - xact_start)) from pg_stat_activity
17
+ where datname = current_database() and backend_type = 'client backend'
18
+ and xact_start is not null and pid <> pg_backend_pid()), 0)::float8 as longest_transaction_seconds,
19
+ coalesce((select max(s.n_dead_tup / nullif(current_setting('autovacuum_vacuum_threshold')::float8
20
+ + current_setting('autovacuum_vacuum_scale_factor')::float8 * greatest(c.reltuples, 0), 0))
21
+ from pg_stat_user_tables s join pg_class c on c.oid = s.relid), 0)::float8 as autovacuum_backlog_ratio`;
22
+
23
+ /**
24
+ * The WAL each of this database's logical slots holds back on the primary: what an inactive or
25
+ * lagging replicator costs in disk. Bounded by `max_replication_slots`. A standby answers no rows —
26
+ * `pg_current_wal_lsn()` is refused during recovery, and a standby retains nothing for a slot.
27
+ */
28
+ export const PG_SLOT_STATS_SQL = `select slot_name as slot,
29
+ pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)::float8 as retained_bytes
30
+ from pg_replication_slots
31
+ where database = current_database() and restart_lsn is not null and not pg_is_in_recovery()`;