@ultimat3/db 31.23.0 → 31.24.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
@@ -14,9 +14,10 @@ Tier 1 — it imports `@ultimat3/core` and nothing else. That placement is load-
14
14
  | SQLSTATE | one reader, `sqlState()` (`sqlstate.ts`). Never read `error.code` for a SQLSTATE |
15
15
  | Reading a caught value | `renderThrowable()` from core (`checkDb` backs `/readyz`) |
16
16
  | Errors | subclass `DbError`; never `throw new Error` in source. A test simulating a database failure throws `dbUnavailable()`; one simulating the caller's body failing throws a bare `Error` on purpose |
17
- | New code | `bun run new-error-code <CODE> --package db --title '…' --fix '…'` writes `DB_OWNED_ERROR_CODES`, `DB_ERROR_TITLES` and the wiki row together; then add it to `errors.test.ts`'s pinned list. The constructor lives where its imports allow (`migration-errors.ts`, `invariant-errors.ts`, `drift-errors.ts`, `dump-drift.ts`); `src/index.ts` re-exports all |
17
+ | New code | `bun run new-error-code <CODE> --package db --title '…' --fix '…'` writes `DB_OWNED_ERROR_CODES`, `DB_ERROR_TITLES` and the wiki row; then pin it in `errors.test.ts`. Constructors live where imports allow (`migration-errors.ts`, `invariant-errors.ts`, `drift-errors.ts`, `dump-drift.ts`); `src/index.ts` re-exports all |
18
18
  | A value ambient across an `await` | `asyncContext<T>(subject)` from core — never `new AsyncLocalStorage`. Three scopes: `transaction.ts`, `attribution.ts`, `expected-loop.ts` |
19
19
  | Exports | explicit in `src/index.ts`; no `export *` |
20
+ | Keyset | `keyset.ts`; SQL `keyset-seek.ts`; null tags `keyset-position.ts` (entity's) |
20
21
  | Files | < 200 LOC (the `packages/db/src/**/*.ts` path instruction), one responsibility, `kebab-case.ts`, test beside source |
21
22
 
22
23
  Pinned public seam — `@ultimat3/auth`, `@ultimat3/entity` and `@ultimat3/jobs` are written against
@@ -262,4 +263,4 @@ Gotchas:
262
263
  the roles in `creators` (default: the connected user).
263
264
  - `Bun.SQL` is reached lazily inside `connect()` — importing `client.ts` must not open a socket.
264
265
 
265
- Why each rule above is shaped the way it is: [`docs/history/db.md`](../../docs/history/db.md).
266
+ Why: [`docs/history/db.md`](../../docs/history/db.md).
package/README.md CHANGED
@@ -138,13 +138,15 @@ fragments to splice and `page(rows)`, which answers core's `Page`.
138
138
  | Precision | selected as `col::text` under `_keyset_<n>`, bound back as `$n::<kind>`: a microsecond survives, a `Date` would floor it and drop rows |
139
139
  | The seek | uniform direction: one row comparison, Index Only Scan on a matching index. Mixed: the or-chain |
140
140
  | `order by` | the bare columns. `date_trunc('milliseconds', …)` there is a Parallel Seq Scan and a sort (100 ms against 0.2 ms, 300,000 rows); the scaffolded `repo-raw-sql` guard reports it |
141
- | A null key | `X_KEYSET_NULL_KEY`, on any row of a page, whatever its size |
142
- | The cursor | core's signed codec; scoped to `scope` plus every key's column, kind and direction. Another read's is `X_CURSOR_INVALID` |
141
+ | A nullable key | `As of 2026-11-14`: `nullable: true`, NULL placed by `nulls: 'first' \| 'last'` (default `asc nulls last`, `desc nulls first`, as the entity driver). Written into `order by`, carried in the cursor as present/absent, seeked by the or-chain. Never the last key |
142
+ | A null key | on an undeclared key, `X_KEYSET_NULL_KEY` on any row of a page, whatever its size; a nullable last key is the same code at `keyset()` |
143
+ | The cursor | core's signed codec; scoped to `scope` plus every key's column, kind and direction (and a nullable key's NULL placement). Another read's is `X_CURSOR_INVALID` |
143
144
  | `limit` | a whole number ≥ 1 (`finiteCount`), read as `limit + 1` |
144
145
  | `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 |
145
146
 
146
147
  Proven on both engines: `keyset.live.test.ts` (Postgres) and `keyset-embedded.test.ts` (PGlite)
147
- walk four rows inside one millisecond across page boundaries, and assert the plan holds no sort.
148
+ walk four rows inside one millisecond across page boundaries, and assert the plan holds no sort;
149
+ the same suites walk a nullable key under all four direction × placement orders, every row once.
148
150
 
149
151
  ## Transactions that end badly
150
152
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/db",
3
- "version": "31.23.0",
3
+ "version": "31.24.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.23.0"
48
+ "@ultimat3/core": "31.24.0"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@electric-sql/pglite": ">=0.5.0"
@@ -233,6 +233,18 @@ export interface CounterDescriptionLike {
233
233
  readonly references: string;
234
234
  /** The child's soft-delete column: a stamped row is not counted. `null` when it has none. */
235
235
  readonly softDelete: string | null;
236
+ /** `countedIn: { where }`: only a child row this predicate holds over is counted. Absent: all. */
237
+ readonly where?: CounterWhereLike | undefined;
238
+ }
239
+
240
+ /**
241
+ * A counter's predicate, compiled once by `@ultimat3/entity`. `sql` names the child's columns
242
+ * qualified by the alias `c` (`c."kind" = 'up'`), which the trigger and the recount both give the
243
+ * child row; `columns` are the physical columns it reads, so a change to one fires the trigger.
244
+ */
245
+ export interface CounterWhereLike {
246
+ readonly sql: string;
247
+ readonly columns: readonly string[];
236
248
  }
237
249
 
238
250
  /** `retain: { after, on }`, with `on` physical. */
@@ -5,7 +5,8 @@
5
5
  import type { CounterDescriptionLike } from './entity-shape';
6
6
  import { triggerInstall } from './generate-history';
7
7
  import type { TriggerRecord } from './introspect';
8
- import { identifier } from './sql';
8
+ import { CROSS_TENANT_SETTING } from './row-security';
9
+ import { identifier, raw, type SqlFragment, sql } from './sql';
9
10
 
10
11
  /**
11
12
  * `ultimate_count_<crc32 of parent.column>`: per counter, because each body names its own tables,
@@ -17,12 +18,19 @@ export function counterTriggerName(parent: string, counter: CounterDescriptionLi
17
18
  return `ultimate_count_${hash}`;
18
19
  }
19
20
 
20
- /** Whether a row image (`old`/`new`) is counted: it names a parent and is not soft-deleted. */
21
+ /**
22
+ * Whether a row image (`old`/`new`) is counted: it names a parent, is not soft-deleted, and — with a
23
+ * `where` — the predicate holds over it. The predicate names the child as `c`, so the image is
24
+ * given that alias in a one-row subquery: one compiled text serves the trigger and the recount.
25
+ */
21
26
  const counted = (image: 'old' | 'new', counter: CounterDescriptionLike): string =>
22
27
  `${image}.${identifier(counter.references).text} is not null` +
23
28
  (counter.softDelete === null
24
29
  ? ''
25
- : ` and ${image}.${identifier(counter.softDelete).text} is null`);
30
+ : ` and ${image}.${identifier(counter.softDelete).text} is null`) +
31
+ (counter.where === undefined
32
+ ? ''
33
+ : ` and exists (select from (select ${image}.*) c where ${counter.where.sql})`);
26
34
 
27
35
  const bump = (parent: string, counter: CounterDescriptionLike, image: string, sign: string) =>
28
36
  `update ${identifier(parent).text} set ${identifier(counter.column).text} = ` +
@@ -33,7 +41,8 @@ const bump = (parent: string, counter: CounterDescriptionLike, image: string, si
33
41
  * Old image out, new image in: an insert adds one, a delete takes one, a re-parent or a soft delete
34
42
  * moves it. Lock order is the PARENT row, so a hot parent serializes its writers — `countBy` plus a
35
43
  * cache is the alternative where that matters. `after … for each row`, so a refused write moves
36
- * nothing, and `update of` the two columns that can change the answer, so no other update pays.
44
+ * nothing, and `update of` the columns that can change the answer — key, stamp, the predicate's —
45
+ * so no other update pays.
37
46
  */
38
47
  export function counterTrigger(parent: string, counter: CounterDescriptionLike): TriggerRecord {
39
48
  const name = counterTriggerName(parent, counter);
@@ -43,16 +52,28 @@ export function counterTrigger(parent: string, counter: CounterDescriptionLike):
43
52
  `${bump(parent, counter, 'old', '-')} end if; if tg_op <> 'DELETE' and ` +
44
53
  `${counted('new', counter)} then ${bump(parent, counter, 'new', '+')} end if; ` +
45
54
  'return null; end; $counter$;';
46
- const watched = [counter.references, ...(counter.softDelete === null ? [] : [counter.softDelete])]
55
+ const watched = [
56
+ ...new Set([
57
+ counter.references,
58
+ ...(counter.softDelete === null ? [] : [counter.softDelete]),
59
+ ...(counter.where?.columns ?? []),
60
+ ]),
61
+ ]
47
62
  .map((column) => identifier(column).text)
48
63
  .join(', ');
49
- return triggerInstall(
64
+ const install = triggerInstall(
50
65
  name,
51
66
  { name, sql: fn },
52
67
  `after insert or delete or update of ${watched}`,
53
68
  counter.table,
54
69
  '',
55
70
  );
71
+ // Cross-tenant for the one statement: under forced row security an unset tenant matches no row.
72
+ const recount = [
73
+ `select set_config('${CROSS_TENANT_SETTING}', 'on', true);`,
74
+ recountSql(parent, counter),
75
+ ];
76
+ return { ...install, recount };
56
77
  }
57
78
 
58
79
  /** The true count of one parent row, as a correlated subquery over `parent` aliased `p`. */
@@ -60,11 +81,14 @@ const truth = (counter: CounterDescriptionLike): string =>
60
81
  `(select count(*)::integer from ${identifier(counter.table).text} c where ` +
61
82
  `c.${identifier(counter.references).text} = p.${identifier(counter.key).text}` +
62
83
  (counter.softDelete === null ? '' : ` and c.${identifier(counter.softDelete).text} is null`) +
84
+ (counter.where === undefined ? '' : ` and (${counter.where.sql})`) +
63
85
  ')';
64
86
 
65
87
  /**
66
88
  * Sets every drifted counter to the truth. A migration adding a counter runs it once, so a table
67
- * that already holds rows starts true; `x db recount --write` runs it again, by key range.
89
+ * that already holds rows starts true. Migration-only: it locks nothing first, so it is not safe
90
+ * beside live writers — `x db recount --write` repairs by key range instead (`recountLockSql`,
91
+ * then `recountBatchSql`), one transaction per window.
68
92
  */
69
93
  export function recountSql(parent: string, counter: CounterDescriptionLike): string {
70
94
  return (
@@ -83,3 +107,90 @@ export function recountDriftSql(parent: string, counter: CounterDescriptionLike)
83
107
  `order by p.${identifier(counter.key).text}`
84
108
  );
85
109
  }
110
+
111
+ /** `p.key > $after and p.key <= $last`, the half-open window one batch covers; no lower bound first. */
112
+ const windowOf = (
113
+ counter: CounterDescriptionLike,
114
+ after: string | null,
115
+ last: string,
116
+ ): SqlFragment => {
117
+ const key = raw(`p.${identifier(counter.key).text}`);
118
+ return after === null ? sql`${key} <= ${last}` : sql`${key} > ${after} and ${key} <= ${last}`;
119
+ };
120
+
121
+ /**
122
+ * The last key of the next window: up to `size` parent keys past `after`, in key order. `null` when
123
+ * none is left. Keys travel as text so any single-column key type bounds the next window.
124
+ */
125
+ export function recountWindowSql(
126
+ parent: string,
127
+ counter: CounterDescriptionLike,
128
+ after: string | null,
129
+ size: number,
130
+ ): SqlFragment {
131
+ const key = raw(`p.${identifier(counter.key).text}`);
132
+ const table = identifier(parent);
133
+ const from = raw(`select ${key.text}::text as "key" from ${table.text} p`);
134
+ const keys =
135
+ after === null
136
+ ? sql`${from} order by ${key} limit ${size}`
137
+ : sql`${from} where ${key} > ${after} order by ${key} limit ${size}`;
138
+ return sql`select max(w."key") as "last" from (${keys}) w`;
139
+ }
140
+
141
+ /**
142
+ * Locks one window's parent rows, in key order, as a counter's trigger locks a parent (`for no key
143
+ * update`, `pg-lock.ts`'s mode). Sent FIRST in the window's transaction: a writer whose trigger
144
+ * already holds a row commits before this returns, and the drift read and repair that follow, each
145
+ * its own statement under READ COMMITTED, take a snapshot that counts it; a writer arriving later
146
+ * waits in its trigger and moves the repaired count by one. An UPDATE alone re-checks a row it
147
+ * waited on but keeps its statement's snapshot for `count(*)` — and writes a stale count.
148
+ */
149
+ export function recountLockSql(
150
+ parent: string,
151
+ counter: CounterDescriptionLike,
152
+ after: string | null,
153
+ last: string,
154
+ ): SqlFragment {
155
+ const from = raw(`select 1 from ${identifier(parent).text} p where `);
156
+ const order = raw(` order by p.${identifier(counter.key).text} for no key update`);
157
+ return sql`${from}${windowOf(counter, after, last)}${order}`;
158
+ }
159
+
160
+ /** The drifted rows of one window, for the report: key, stored and true count. */
161
+ export function recountDriftBatchSql(
162
+ parent: string,
163
+ counter: CounterDescriptionLike,
164
+ after: string | null,
165
+ last: string,
166
+ ): SqlFragment {
167
+ const select = raw(
168
+ `select p.${identifier(counter.key).text}::text as "key", ` +
169
+ `p.${identifier(counter.column).text} as "stored", ${truth(counter)} as "actual" ` +
170
+ `from ${identifier(parent).text} p where `,
171
+ );
172
+ const drifted = raw(
173
+ ` and p.${identifier(counter.column).text} is distinct from ${truth(counter)} ` +
174
+ `order by p.${identifier(counter.key).text}`,
175
+ );
176
+ return sql`${select}${windowOf(counter, after, last)}${drifted}`;
177
+ }
178
+
179
+ /**
180
+ * Sets every drifted counter of one window to the truth: one statement, one batch — only after
181
+ * `recountLockSql` in the same transaction, or a concurrent writer's count is lost.
182
+ */
183
+ export function recountBatchSql(
184
+ parent: string,
185
+ counter: CounterDescriptionLike,
186
+ after: string | null,
187
+ last: string,
188
+ ): SqlFragment {
189
+ const update = raw(
190
+ `update ${identifier(parent).text} p set ${identifier(counter.column).text} = ${truth(counter)} where `,
191
+ );
192
+ const drifted = raw(
193
+ ` and p.${identifier(counter.column).text} is distinct from ${truth(counter)}`,
194
+ );
195
+ return sql`${update}${windowOf(counter, after, last)}${drifted}`;
196
+ }
@@ -4,11 +4,10 @@
4
4
 
5
5
  import type { EntityDescriptionLike } from './entity-shape';
6
6
  import type { Plan } from './foreign-key-plan';
7
- import { counterTrigger, recountSql } from './generate-counter';
7
+ import { counterTrigger } from './generate-counter';
8
8
  import { historyTriggers } from './generate-history';
9
9
  import type { SchemaDescription, TableDescription, TriggerRecord } from './introspect';
10
10
  import { findTable } from './introspect';
11
- import { CROSS_TENANT_SETTING } from './row-security';
12
11
  import { identifier } from './sql';
13
12
 
14
13
  /** Every declared lifecycle trigger, by the table it sits on, in declaration order. */
@@ -45,21 +44,28 @@ const same = (left: TriggerRecord, right: TriggerRecord): boolean =>
45
44
  * row, and the recount would update nothing in silence.
46
45
  */
47
46
  function recounts(
48
- entities: readonly EntityDescriptionLike[],
47
+ declared: ReadonlyMap<string, readonly TriggerRecord[]>,
49
48
  added: ReadonlySet<string>,
50
49
  ): string[] {
51
50
  const out: string[] = [];
52
- for (const entity of entities) {
53
- for (const counter of entity.counts ?? []) {
54
- const trigger = counterTrigger(entity.table, counter);
55
- if (!added.has(`${counter.table}.${trigger.name}`)) continue;
56
- out.push(`select set_config('${CROSS_TENANT_SETTING}', 'on', true);`);
57
- out.push(recountSql(entity.table, counter));
51
+ for (const [table, triggers] of declared) {
52
+ for (const trigger of triggers) {
53
+ if (added.has(`${table}.${trigger.name}`)) out.push(...(trigger.recount ?? []));
58
54
  }
59
55
  }
60
56
  return out;
61
57
  }
62
58
 
59
+ /**
60
+ * `down`'s reinstall of a recorded trigger, pushed for the final reversal: the recount it recorded
61
+ * (a counter's, under ITS predicate) runs after the reinstall, so a rolled-back `where` leaves the
62
+ * counts the old trigger keeps. A record without one reinstalls only, as before 31.23.
63
+ */
64
+ const reinstall = (recorded: TriggerRecord): readonly string[] => [
65
+ ...[...(recorded.recount ?? [])].reverse(),
66
+ ...[...recorded.install].reverse(),
67
+ ];
68
+
63
69
  /**
64
70
  * Both directions, after every table exists. Declared and not recorded (or recorded with other
65
71
  * statements): install, and `down` drops it — or reinstalls what was recorded. Recorded and no
@@ -82,7 +88,7 @@ export function triggerPlan(
82
88
  plan.up.push(...trigger.install);
83
89
  // `down` is reversed whole: pushed in apply order, reversed back into it.
84
90
  if (before === undefined) plan.down.push(dropSql(table, trigger.name));
85
- else plan.down.push(...[...before.install].reverse());
91
+ else plan.down.push(...reinstall(before));
86
92
  added.add(`${table}.${trigger.name}`);
87
93
  }
88
94
  }
@@ -92,10 +98,10 @@ export function triggerPlan(
92
98
  for (const recorded of table.triggers ?? []) {
93
99
  if (wanted.some((each) => each.name === recorded.name)) continue;
94
100
  plan.up.push(dropSql(table.name, recorded.name));
95
- plan.down.push(...[...recorded.install].reverse());
101
+ plan.down.push(...reinstall(recorded));
96
102
  }
97
103
  }
98
- plan.up.push(...recounts(entities, added));
104
+ plan.up.push(...recounts(declared, added));
99
105
  }
100
106
 
101
107
  /** The snapshot, each table carrying the triggers declared on it — absent where there are none. */
package/src/index.ts CHANGED
@@ -69,6 +69,7 @@ export { rowSecurityDifferences, rowSecurityDrift } from './drift-row-security';
69
69
  export type {
70
70
  ColumnDescriptionLike,
71
71
  CounterDescriptionLike,
72
+ CounterWhereLike,
72
73
  EntityDescriptionLike,
73
74
  HistoryDescriptionLike,
74
75
  IndexDescriptionLike,
@@ -108,7 +109,14 @@ export type { RecordedStatement, RecordingClient, StubResponse } from './fake';
108
109
  export { recordingClient } from './fake';
109
110
  export type { GeneratedMigration, GenerateOptions } from './generate';
110
111
  export { generateMigration, slugify, snapshotOf } from './generate';
111
- export { recountDriftSql, recountSql } from './generate-counter';
112
+ export {
113
+ recountBatchSql,
114
+ recountDriftBatchSql,
115
+ recountDriftSql,
116
+ recountLockSql,
117
+ recountSql,
118
+ recountWindowSql,
119
+ } from './generate-counter';
112
120
  export { ACTOR_SETTING, PURGE_SETTING, REQUEST_SETTING } from './generate-history';
113
121
  export type { PartitionMaintenanceOptions } from './generate-partition';
114
122
  export { partitionMaintenance } from './generate-partition';
package/src/introspect.ts CHANGED
@@ -212,6 +212,12 @@ export interface TableDescription {
212
212
  export interface TriggerRecord {
213
213
  readonly name: string;
214
214
  readonly install: readonly string[];
215
+ /**
216
+ * A counter trigger's recount under ITS OWN predicate (`generate-counter.ts`): what `down` runs
217
+ * after reinstalling this record, so the counts follow the trigger that keeps them. Snapshot-only;
218
+ * absent on every other trigger and on a counter recorded before 31.23 (that `down` recounts nothing).
219
+ */
220
+ readonly recount?: readonly string[] | undefined;
215
221
  }
216
222
 
217
223
  /**
@@ -0,0 +1,24 @@
1
+ // Single responsibility: one keyset key's value as the cursor carries it — present, or NULL —
2
+ // and back. The tag scheme is entity's (`entity/src/cursor.ts`), replicated: db is tier 1.
3
+
4
+ import type { KeysetKey } from './keyset-seek';
5
+
6
+ const ABSENT_MARK = '~';
7
+ const PRESENT_MARK = '!';
8
+
9
+ /**
10
+ * A nullable key's place in the cursor is TAGGED, entity's scheme (`entity/src/cursor.ts`): `~`
11
+ * alone is NULL, `!` prefixes a present value — so a `text` key holding `~` is never read as
12
+ * absent. A not-null key is carried bare, as it was before nullable keys existed.
13
+ */
14
+ export const encodePart = (key: KeysetKey | undefined, value: string | null): string => {
15
+ if (key?.nullable !== true) return value ?? '';
16
+ return value === null ? ABSENT_MARK : `${PRESENT_MARK}${value}`;
17
+ };
18
+
19
+ export const decodePart = (key: KeysetKey, part: unknown): string | null | undefined => {
20
+ if (typeof part !== 'string') return undefined;
21
+ if (key.nullable !== true) return part;
22
+ if (part === ABSENT_MARK) return null;
23
+ return part.startsWith(PRESENT_MARK) ? part.slice(PRESENT_MARK.length) : undefined;
24
+ };
@@ -0,0 +1,94 @@
1
+ // Single responsibility: the SQL `keyset()` splices for an order — each key's `order by` term and
2
+ // the seek past a cursor's position, NULL's place in both written down for a nullable key.
3
+ // The shapes mirror `entity/src/pg-sql.ts` (`seekSql`); db is tier 1 and cannot import it.
4
+
5
+ import { join, raw, type SqlFragment, sql } from './sql';
6
+
7
+ /** The kinds a position can be bound back as, each with its own cast. A closed list. */
8
+ export type KeysetKind = 'timestamptz' | 'uuid' | 'text' | 'integer' | 'bigint';
9
+
10
+ export interface KeysetKey {
11
+ /** The ordered expression as written in the statement: `raw('p.created_at')`, or a `sql` one. */
12
+ readonly column: SqlFragment;
13
+ readonly kind: KeysetKind;
14
+ readonly direction: 'asc' | 'desc';
15
+ /** The key may be NULL on a row. Never the last key: the tiebreak must be not null. */
16
+ readonly nullable?: true | undefined;
17
+ /** NULL's place, nullable keys only. Default: `asc nulls last`, `desc nulls first`. */
18
+ readonly nulls?: 'first' | 'last' | undefined;
19
+ }
20
+
21
+ /** One key of a cursor's position: the column's text, or `null` where the boundary row had none. */
22
+ export type KeysetPosition = readonly (string | null)[];
23
+
24
+ export const CASTS: ReadonlyMap<KeysetKind, string> = new Map<KeysetKind, string>([
25
+ ['timestamptz', 'timestamptz'],
26
+ ['uuid', 'uuid'],
27
+ ['text', 'text'],
28
+ ['integer', 'integer'],
29
+ ['bigint', 'bigint'],
30
+ ]);
31
+
32
+ /** Where a nullable key's NULLs sort — the same defaults as the entity driver and the query layer. */
33
+ export const nullsOf = (key: KeysetKey): 'first' | 'last' =>
34
+ key.nulls ?? (key.direction === 'desc' ? 'first' : 'last');
35
+
36
+ const bind = (key: KeysetKey, text: string): SqlFragment =>
37
+ sql`${text}::${raw(CASTS.get(key.kind) ?? 'text')}`;
38
+
39
+ /**
40
+ * The splice re-derived from the closed set, as `entity/src/pg-sql.ts` does: never the caller's
41
+ * text. A not-null key stays bare so an index on `(created_at desc, id desc)` still answers it.
42
+ */
43
+ export const orderOf = (key: KeysetKey): SqlFragment => {
44
+ const direction = key.direction === 'desc' ? 'desc' : 'asc';
45
+ if (key.nullable !== true) return sql`${key.column} ${raw(direction)}`;
46
+ return sql`${key.column} ${raw(`${direction} nulls ${nullsOf(key) === 'first' ? 'first' : 'last'}`)}`;
47
+ };
48
+
49
+ const past = (key: KeysetKey, value: SqlFragment): SqlFragment =>
50
+ sql`${key.column} ${raw(key.direction === 'desc' ? '<' : '>')} ${value}`;
51
+
52
+ /**
53
+ * What sorts strictly after the position on this one key, as alternatives. A value is followed by
54
+ * the values past it, and by the NULLs too when they sort last. A NULL is followed by every value
55
+ * when NULLs sort first, and by nothing when they sort last — the later keys carry that page.
56
+ */
57
+ const after = (key: KeysetKey, value: string | null): SqlFragment[] => {
58
+ const last = nullsOf(key) === 'last';
59
+ if (value === null) return last ? [] : [sql`${key.column} is not null`];
60
+ const beyond = past(key, bind(key, value));
61
+ return key.nullable === true && last ? [beyond, sql`${key.column} is null`] : [beyond];
62
+ };
63
+
64
+ /** At the position on this key. `= $n` is never true of a NULL, so an absent one is `is null`. */
65
+ const equal = (key: KeysetKey, value: string | null): SqlFragment =>
66
+ value === null ? sql`${key.column} is null` : sql`${key.column} = ${bind(key, value)}`;
67
+
68
+ /**
69
+ * Uniform direction over not-null keys is ONE row comparison, the shape Postgres pushes into a
70
+ * multicolumn index as an Index Cond. A mixed order, or any nullable key, has none (a row
71
+ * comparison has no null order), so it is the or-chain — the same split as the entity driver's
72
+ * `seekSql`. The last key is not null, so the chain always holds at least one term.
73
+ */
74
+ export const seek = (keys: readonly KeysetKey[], position: KeysetPosition): SqlFragment => {
75
+ const valueAt = (index: number): string | null => position[index] ?? null;
76
+ const [first] = keys;
77
+ if (first === undefined) return sql`true`;
78
+ if (keys.length === 1) return past(first, bind(first, valueAt(0) ?? ''));
79
+ const rowComparable = keys.every(
80
+ (key) => key.direction === first.direction && key.nullable !== true,
81
+ );
82
+ if (rowComparable) {
83
+ const op = raw(first.direction === 'desc' ? '<' : '>');
84
+ const binds = keys.map((key, index) => bind(key, valueAt(index) ?? ''));
85
+ return sql`(${join(keys.map((key) => key.column))}) ${op} (${join(binds)})`;
86
+ }
87
+ const terms = keys.flatMap((key, index) => {
88
+ const prefix = keys.slice(0, index).map((prior, at) => equal(prior, valueAt(at)));
89
+ return after(key, valueAt(index)).map((term) =>
90
+ prefix.length === 0 ? term : sql`(${join([...prefix, term], ' and ')})`,
91
+ );
92
+ });
93
+ return terms.length === 1 && terms[0] !== undefined ? terms[0] : sql`(${join(terms, ' or ')})`;
94
+ };
package/src/keyset.ts CHANGED
@@ -13,22 +13,16 @@ import {
13
13
  renderCauseValue,
14
14
  } from '@ultimat3/core';
15
15
  import { DbError } from './errors';
16
+ import { decodePart, encodePart } from './keyset-position';
17
+ import { CASTS, type KeysetKey, type KeysetPosition, nullsOf, orderOf, seek } from './keyset-seek';
16
18
  import { join, raw, type SqlFragment, sql } from './sql';
17
19
 
18
- /** The kinds a position can be bound back as, each with its own cast. A closed list. */
19
- export type KeysetKind = 'timestamptz' | 'uuid' | 'text' | 'integer' | 'bigint';
20
-
21
- export interface KeysetKey {
22
- /** The ordered expression as written in the statement: `raw('p.created_at')`, or a `sql` one. */
23
- readonly column: SqlFragment;
24
- readonly kind: KeysetKind;
25
- readonly direction: 'asc' | 'desc';
26
- }
20
+ export type { KeysetKey, KeysetKind } from './keyset-seek';
27
21
 
28
22
  export interface KeysetOptions {
29
23
  /** This read and its arguments: a cursor from another scope is `X_CURSOR_INVALID`. */
30
24
  readonly scope: string;
31
- /** The order, last key the tiebreak. Every key must be not null on every row. */
25
+ /** The order, last key the tiebreak. A key not declared `nullable` must be not null on every row. */
32
26
  readonly keys: readonly KeysetKey[];
33
27
  /** The previous page's `nextCursor`; `null` for the first page. */
34
28
  readonly after: string | null;
@@ -49,18 +43,11 @@ export interface Keyset {
49
43
  page<Row extends object>(rows: readonly Row[]): Page<KeysetRow<Row>>;
50
44
  }
51
45
 
52
- const CASTS: ReadonlyMap<KeysetKind, string> = new Map<KeysetKind, string>([
53
- ['timestamptz', 'timestamptz'],
54
- ['uuid', 'uuid'],
55
- ['text', 'text'],
56
- ['integer', 'integer'],
57
- ['bigint', 'bigint'],
58
- ]);
59
-
60
46
  const NULL_KEY_FIX =
61
- "keyset({ keys: [{ column: sql`coalesce(p.published_at, p.created_at)`, kind: 'timestamptz', direction: 'desc' }, …] }) # or order by a not-null column";
47
+ "keyset({ keys: [{ column: raw('p.published_at'), kind: 'timestamptz', direction: 'desc', nullable: true }, { column: raw('p.id'), kind: 'uuid', direction: 'desc' }], … }) # declare the key nullable; the last key stays not null";
62
48
 
63
49
  const DIRECTIONS: ReadonlySet<string> = new Set(['asc', 'desc']);
50
+ const PLACEMENTS: ReadonlySet<string> = new Set(['first', 'last']);
64
51
 
65
52
  /**
66
53
  * A direction and a kind are spliced as SQL text, and a sort read off a query string arrives typed
@@ -78,6 +65,26 @@ const assertKey = (key: KeysetKey, at: number): void => {
78
65
  `keyset() key ${String(at)} has kind ${renderCauseValue(key.kind)}, which has no cast to bind a position back with`,
79
66
  "keyset({ keys: [{ column: raw('p.created_at'), kind: 'timestamptz', … }] }) # one of: timestamptz, uuid, text, integer, bigint",
80
67
  );
68
+ assert(
69
+ key.nulls === undefined || (key.nullable === true && PLACEMENTS.has(key.nulls)),
70
+ `keyset() key ${String(at)} has nulls ${renderCauseValue(key.nulls)}${key.nullable === true ? '' : ' without nullable: true'}; NULL placement is spliced into SQL and only a nullable key has one`,
71
+ "keyset({ keys: [{ column: raw('p.published_at'), kind: 'timestamptz', direction: 'desc', nullable: true, nulls: 'last' }, …] }) # nulls: 'first' | 'last'",
72
+ );
73
+ };
74
+
75
+ /**
76
+ * The last key breaks every tie, so it must be not null: two rows NULL on it are tied forever and
77
+ * one of them falls between pages. Refused at construction, before a row is read.
78
+ */
79
+ const assertTiebreak = (keys: readonly KeysetKey[]): void => {
80
+ const last = keys.at(-1);
81
+ if (last?.nullable !== true) return;
82
+ throw new DbError({
83
+ code: 'X_KEYSET_NULL_KEY',
84
+ cause: `keyset() key ${String(keys.length - 1)} (${last.column.text}) is the final tiebreak and is declared nullable: rows NULL on it tie with no order between them`,
85
+ fix: "keyset({ keys: [{ column: raw('p.published_at'), kind: 'timestamptz', direction: 'desc', nullable: true }, { column: raw('p.id'), kind: 'uuid', direction: 'desc' }], … }) # end on a not-null unique key",
86
+ meta: { key: keys.length - 1 },
87
+ });
81
88
  };
82
89
 
83
90
  const aliasOf = (index: number): string => `_keyset_${String(index)}`;
@@ -85,67 +92,42 @@ const aliasOf = (index: number): string => `_keyset_${String(index)}`;
85
92
  /**
86
93
  * The scope the cursor is signed under: the caller's, plus the order itself — so a cursor minted
87
94
  * under `desc` cannot seek an `asc` read, nor a `uuid` key be bound back as `text`. Hashed: the
88
- * key expressions are the statement's, not the client's to read.
95
+ * key expressions are the statement's, not the client's to read. A nullable key adds its NULL
96
+ * placement; a not-null key's scope is unchanged, so a cursor minted before nullable keys pages on.
89
97
  */
90
98
  const scopeOf = (scope: string, keys: readonly KeysetKey[]): string => {
91
99
  const order = keys
92
100
  .map(
93
101
  (key) =>
94
- `${key.column.text}${JSON.stringify(key.column.values.map(String))} ${key.kind} ${key.direction}`,
102
+ `${key.column.text}${JSON.stringify(key.column.values.map(String))} ${key.kind} ${key.direction}${key.nullable === true ? ` nulls ${nullsOf(key)}` : ''}`,
95
103
  )
96
104
  .join(',');
97
105
  const digest = new Bun.CryptoHasher('sha256').update(`${scope}|${order}`).digest('hex');
98
106
  return `keyset:${digest.slice(0, 16)}`;
99
107
  };
100
108
 
101
- const bind = (key: KeysetKey, text: string): SqlFragment =>
102
- sql`${text}::${raw(CASTS.get(key.kind) ?? 'text')}`;
103
-
104
- /** The splice re-derived from the closed set, as `entity/src/pg-sql.ts` does: never the caller's text. */
105
- const orderOf = (key: KeysetKey): SqlFragment => raw(key.direction === 'desc' ? 'desc' : 'asc');
106
-
107
- const past = (key: KeysetKey, value: SqlFragment): SqlFragment =>
108
- sql`${key.column} ${raw(key.direction === 'desc' ? '<' : '>')} ${value}`;
109
-
110
- /**
111
- * Uniform direction is ONE row comparison, the shape Postgres pushes into a multicolumn index as
112
- * an Index Cond. A mixed order has none, so it is the or-chain — the same split as the entity
113
- * driver's `seekSql`. No null branch in either: `page` refuses a null key before it is a cursor.
114
- */
115
- const seek = (keys: readonly KeysetKey[], position: readonly string[]): SqlFragment => {
116
- const binds = (): SqlFragment[] => keys.map((key, index) => bind(key, position[index] ?? ''));
117
- const [first] = keys;
118
- if (first === undefined) return sql`true`;
119
- if (keys.length === 1) return past(first, bind(first, position[0] ?? ''));
120
- if (keys.every((key) => key.direction === first.direction)) {
121
- const op = raw(first.direction === 'desc' ? '<' : '>');
122
- return sql`(${join(keys.map((key) => key.column))}) ${op} (${join(binds())})`;
123
- }
124
- const terms = keys.map((key, index) => {
125
- const equal = keys
126
- .slice(0, index)
127
- .map((prior, at) => sql`${prior.column} = ${bind(prior, position[at] ?? '')}`);
128
- const term = past(key, bind(key, position[index] ?? ''));
129
- return equal.length === 0 ? term : sql`(${join([...equal, term], ' and ')})`;
130
- });
131
- return sql`(${join(terms, ' or ')})`;
132
- };
133
-
134
- const positionOf = (cursor: string, scope: string, keys: readonly KeysetKey[]): string[] => {
109
+ const positionOf = (cursor: string, scope: string, keys: readonly KeysetKey[]): KeysetPosition => {
135
110
  const { key } = decodeCursor(cursor, scope);
136
- if (key.length !== keys.length || !key.every((part) => typeof part === 'string')) {
111
+ if (key.length !== keys.length) {
137
112
  throw new CursorInvalidError(
138
113
  `it carries ${key.length} key values, this order needs ${keys.length}`,
139
114
  );
140
115
  }
141
- return key as string[];
116
+ return keys.map((spec, at) => {
117
+ const value = decodePart(spec, key[at]);
118
+ if (value === undefined) {
119
+ throw new CursorInvalidError(`key value ${String(at)} is not a position this order can seek`);
120
+ }
121
+ return value;
122
+ });
142
123
  };
143
124
 
144
- /** Every key of `row`, as the text the server answered — refused when one is null. */
145
- const keyText = (row: object, keys: readonly KeysetKey[], index: number): string[] =>
125
+ /** Every key of `row`, as the text the server answered — refused when an undeclared one is null. */
126
+ const keyText = (row: object, keys: readonly KeysetKey[], index: number): (string | null)[] =>
146
127
  keys.map((key, at) => {
147
128
  const value: unknown = Reflect.get(row, aliasOf(at));
148
129
  if (typeof value === 'string') return value;
130
+ if (value === null && key.nullable === true) return null;
149
131
  if (value === null) {
150
132
  throw new DbError({
151
133
  code: 'X_KEYSET_NULL_KEY',
@@ -183,6 +165,7 @@ export function keyset(options: KeysetOptions): Keyset {
183
165
  "keyset({ scope: 'posts.feed', … }) # one name per read, plus its filter arguments",
184
166
  );
185
167
  keys.forEach(assertKey);
168
+ assertTiebreak(keys);
186
169
  const limit = finiteCount('keyset', 'limit', options.limit, 1);
187
170
  const scope = scopeOf(options.scope, keys);
188
171
  const where =
@@ -190,7 +173,7 @@ export function keyset(options: KeysetOptions): Keyset {
190
173
  return {
191
174
  select: join(keys.map((key, at) => sql`${key.column}::text as ${raw(`"${aliasOf(at)}"`)}`)),
192
175
  where,
193
- orderBy: join(keys.map((key) => sql`${key.column} ${orderOf(key)}`)),
176
+ orderBy: join(keys.map(orderOf)),
194
177
  limit: sql`${limit + 1}`,
195
178
  page<Row extends object>(rows: readonly Row[]): Page<KeysetRow<Row>> {
196
179
  const positions = rows.map((row, index) => keyText(row, keys, index));
@@ -199,7 +182,11 @@ export function keyset(options: KeysetOptions): Keyset {
199
182
  const last = positions[limit - 1];
200
183
  const next =
201
184
  rows.length > limit && last !== undefined
202
- ? encodeCursor({ scope, key: last, id: '' })
185
+ ? encodeCursor({
186
+ scope,
187
+ key: last.map((value, at) => encodePart(keys[at], value)),
188
+ id: '',
189
+ })
203
190
  : null;
204
191
  return pageOf(kept, next);
205
192
  },
@@ -4,7 +4,8 @@
4
4
 
5
5
  import {
6
6
  backoffDelay,
7
- isUltimateError,
7
+ type FailureStreak,
8
+ failureStreak,
8
9
  logger,
9
10
  renderThrowable,
10
11
  type Scheduler,
@@ -43,23 +44,9 @@ interface Held {
43
44
  /**
44
45
  * Refused dials since this session last held, across retirements: a restart is ONE streak — one
45
46
  * line when it opens, one when a dial lands (`db.listen.redialed`, with the count), never a line
46
- * per attempt; a refusal with a different cause (`causeOf`) logs again, naming the one it ends.
47
- * Local until core ships a limiter for it.
47
+ * per attempt; a refusal with a different cause logs again, naming the one it ends.
48
48
  */
49
- failures: number;
50
- cause: FailureCause | undefined;
51
- }
52
-
53
- interface FailureCause {
54
- readonly key: string;
55
- readonly label: Readonly<Record<string, string>>;
56
- }
57
-
58
- /** What makes two refusals the same one: the code, or, uncoded, the rendered message. */
59
- function causeOf(error: unknown): FailureCause {
60
- if (isUltimateError(error)) return { key: `code:${error.code}`, label: { code: error.code } };
61
- const message = renderThrowable(error);
62
- return { key: `error:${message}`, label: { error: message } };
49
+ readonly refusals: FailureStreak;
63
50
  }
64
51
 
65
52
  export function poolListeners(
@@ -98,29 +85,11 @@ export function poolListeners(
98
85
  return;
99
86
  }
100
87
  entry.session = session;
101
- if (entry.failures > 0) {
102
- logger.info('db.listen.redialed', { channel: entry.channel, failures: entry.failures });
103
- }
104
- entry.failures = 0;
105
- entry.cause = undefined;
88
+ entry.refusals.passed();
106
89
  },
107
90
  (error: unknown) => {
108
91
  if (overtaken()) return;
109
- const cause = causeOf(error);
110
- if (entry.cause?.key === cause.key) entry.failures += 1;
111
- else {
112
- const ended = entry.cause;
113
- logger.warn('db.listen.redial_failed', {
114
- channel: entry.channel,
115
- attempt,
116
- error: renderThrowable(error),
117
- ...(ended === undefined
118
- ? {}
119
- : { previous: { ...ended.label, failures: entry.failures } }),
120
- });
121
- entry.failures = 1;
122
- entry.cause = cause;
123
- }
92
+ entry.refusals.failed(error, { attempt });
124
93
  // Equal jitter: a fleet that lost its database together must not re-dial it together.
125
94
  const wait = backoffDelay({
126
95
  attempt,
@@ -144,8 +113,12 @@ export function poolListeners(
144
113
  dial: 0,
145
114
  cancelRetry: () => undefined,
146
115
  ended: false,
147
- failures: 0,
148
- cause: undefined,
116
+ refusals: failureStreak({
117
+ event: 'db.listen.redial_failed',
118
+ recoveredEvent: 'db.listen.redialed',
119
+ level: 'warn',
120
+ fields: { channel },
121
+ }),
149
122
  };
150
123
  held.add(entry);
151
124
  try {
@@ -140,8 +140,11 @@ function all<T>(value: unknown, one: (item: unknown) => T | undefined): readonly
140
140
 
141
141
  function trigger(value: unknown): TriggerRecord | undefined {
142
142
  if (!isRow(value)) return undefined;
143
- const { name, install } = value;
144
- return str(name) && strings(install) ? { name, install } : undefined;
143
+ const { name, install, recount } = value;
144
+ if (!str(name) || !strings(install)) return undefined;
145
+ // `recount` arrived in 31.23 on counter triggers; a record written before carries none.
146
+ if (recount === undefined) return { name, install };
147
+ return strings(recount) ? { name, install, recount } : undefined;
145
148
  }
146
149
 
147
150
  function tableOf(value: unknown): TableDescription | undefined {