@ultimat3/realtime 31.13.0 → 31.14.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
@@ -98,13 +98,10 @@ A rule marked `†` has its full text in [`docs/history/realtime-rules.md`](../.
98
98
  - **`desynced` is a mark with a reader**: the next delivery re-snapshots out of the shared window,
99
99
  then clears it; `result.refill` is checked BEFORE the mark. A quiet query's three other readers
100
100
  (drain, a landed read, `repairMarked`): `docs/history/realtime.md` (2026-11-09).
101
- - **A change the window already holds is refused** (`change.lsn <= entry.lsn`, counted as
102
- `staleChanges`). **A gap is detected**: the replicator stamps `producer` + `seq`; a skipped
103
- sequence — or a NEW producer after a known one — stales every window; `refillWindowInLane` replaces it.
104
- - **A bulk write stales only its entity's readers**: windows + channel topics, `invalidate(entity)`
105
- on both from `onBulk` (channels: not a `recordPublisher` table). **A stale window's re-read
106
- re-snapshots EVERY subscriber**, before the lsn guard, even on a non-match (`live-replicator-bulk`,
107
- `live-fanout` tests).
101
+ - **A change the window already holds is refused** (`change.lsn <= entry.lsn`, `staleChanges`).
102
+ **A gap is detected** (`producer` + `seq`; `SeqGapDetector.#chain`, `replicator-handover.ts`). †
103
+ - **`stop()` reads the walsender's goodbye before `Terminate`** (`pg-replication-goodbye.ts`). †
104
+ - **A bulk write stales only its entity's readers** (`onBulk`); a stale re-read re-snapshots all. †
108
105
  - **`startLiveReplicator` SUBSCRIBES to `entity.row`/`entity.bulk`**, never a slot: `stop()`
109
106
  releases its own; two both hear a write (`live-replicator.test.ts`). Its handlers never throw.
110
107
  - **A window is keyed by the PARSED input** (`LiveQueryDefinition.queryId`): a stripped junk key
@@ -154,10 +151,7 @@ A rule marked `†` has its full text in [`docs/history/realtime-rules.md`](../.
154
151
  `server.upgrade`. `null` = 401 `X_SOCKET_UNAUTHENTICATED`; a throw = 503
155
152
  `X_SOCKET_AUTH_UNAVAILABLE`. Absent = anonymous, and `start()` warns. The actor lives only in the
156
153
  `GrantBook`.
157
- - **The grant is recorded BEFORE `server.upgrade`** (Bun runs `open` synchronously inside it) and
158
- released on every path that never opens — `onUngranted` is REQUIRED on `UpgradeDeps`, and a
159
- `server.upgrade` that THROWS releases too. `sync-node-auth.test.ts`'s harness opens inside
160
- `upgrade()`, as Bun does.
154
+ - **The grant is recorded BEFORE `server.upgrade`**; `onUngranted` is REQUIRED on `UpgradeDeps`. †
161
155
  - **A grant expires; a socket does not**: expired grants are re-decided on an interval
162
156
  (`hub.onActorChange`, `registry.reauthorize`). No `refresh` = close `1008`; one that raises retries.
163
157
  - **Inbound frames run in a lane, never the socket**: `subscribe` is `sub:<sid>` or `topic:<name>`,
@@ -186,18 +180,10 @@ A rule marked `†` has its full text in [`docs/history/realtime-rules.md`](../.
186
180
  - Exactly one `replicator` per DB, by a session-level advisory lock. **`start()` and
187
181
  `PostgresAdvisoryLock.tryAcquire` are MEMOISED**; `stop()`/`release()` await the in-flight one. A start
188
182
  that FAILS hands the lock back; `running` is set once the feed pumps.
189
- - **The pump has one way out, `#die`**: failure, timer, connection, then `onEnd`. **A walsender
190
- that stops answering is dead** — 3 intervals read-silent, or a confirm unsettled
191
- (`pg-replication-liveness.ts`): destroyed, no goodbye. A run is fenced by its connection.
192
- - **A stream that ENDS, or a LOST lock, is restarted** from `lastLsn` on `retryDelayMs`; a lost
193
- connection (`connectionLost`) redials at once, then ≤ 2 s (`replicator-reconnect.ts`); feed then
194
- lock ABANDONED; `running` = pumping and no refused change owed (history, 2026-11-09).
195
- - **A slot is asked its `wal_status`**: `lost` is `X_REPLICATION_SLOT_INVALIDATED`; one created under
196
- a resume is `X_REPLICATION_SLOT_RECREATED`, drops `from`, and owes `x.change.-resync` (a node
197
- answers it as a reconnect) till published.
198
- - **A slot still held is waited for before START_REPLICATION** (`pg-slot-release.ts`): a walsender
199
- frees it AFTER the goodbye, so preflight reads `active_pid` and polls on the server's clock, ~5 s
200
- bound, then lets 55006 refuse (`pg-slot-release.test.ts`, the held-slot live test).
183
+ - **The pump has one way out, `#die`**; a silent walsender is dead (`pg-replication-liveness.ts`). †
184
+ - **A stream that ENDS, or a LOST lock, is restarted** (`replicator-reconnect.ts`). †
185
+ - **A slot is asked its `wal_status`** (`X_REPLICATION_SLOT_INVALIDATED` / `_RECREATED`). †
186
+ - **A slot still held is waited for before START_REPLICATION** (`pg-slot-release.ts`). †
201
187
  - **A row crosses the bus through its entity's columns** (`replicator-row.ts`): `parseEnvelope`
202
188
  revives by `entityForTable` + `$parse`, bytes as base64 — by declared kind, never by shape.
203
189
  - **Cleartext/md5 auth is answered only under `sslmode` `require`, `verify-*` or `disable`**.
@@ -224,7 +210,13 @@ A rule marked `†` has its full text in [`docs/history/realtime-rules.md`](../.
224
210
  - **Page state lives on `globalThis[Symbol.for('ultimate.realtime')]` (`page-store.ts`)**, never module
225
211
  scope — every island is its own bundle (`page-client.test.ts` builds two islands). Never
226
212
  `instanceof` across copies.
227
- - **The signal factory is per BUNDLE**: `installRealtime({ signal, sync })` (`reactivity.ts`). No
213
+ - **Every `use*` hook wraps its release in `ownedRelease` (`reactivity.ts`)**: run once, and
214
+ registered with the installed `cleanup` (Solid's `onCleanup`, passed by `island-realtime.ts`), so a
215
+ disposed component lets go with no `onCleanup` in the island. `use-hooks-cleanup.test.ts` holds it.
216
+ - **One mutator's online writes go one at a time** (`enterLane`, `page-store.ts`): a write's network
217
+ leg waits on the previous one of that name; an idle lane sends in the same tick (tests read the
218
+ POST synchronously). `use-mutation-lane.test.ts`.
219
+ - **The signal factory is per BUNDLE**: `installRealtime({ signal, sync, cleanup })` (`reactivity.ts`). No
228
220
  install and a DOM is `X_REALTIME_UNINSTALLED`; no DOM is a server render — hooks answer
229
221
  `pending`/online and create no page state. `useRecord` and `useQuery` return `AsyncState` accessors.
230
222
  - **The page runtime (`page-runtime.ts`) is installed once per page, never in an island**;
package/README.md CHANGED
@@ -225,7 +225,7 @@ the socket stack, the query client and core's transport — installed ONCE per p
225
225
  an island: the page boot carries it, and where no boot is rendered the island loads
226
226
  `/islands/page-runtime.<id>.js`, the one chunk `x build` builds from `@ultimat3/realtime/page-runtime`.
227
227
  The island bootstrap `x build` prepends awaits that runtime, then installs realtime for its bundle —
228
- `installRealtime({ signal: createSignal })` — so a hook is a thin reader and an island never
228
+ `installRealtime({ signal: createSignal, cleanup: onCleanup })` — so a hook is a thin reader and an island never
229
229
  constructs a client or a socket. The socket opens on the first live hook.
230
230
 
231
231
  ```ts
@@ -301,7 +301,8 @@ same type `@ultimat3/ui` renders.
301
301
  | Every member is a **getter**, every result an **accessor** | a value snapshotted at hook time never re-renders |
302
302
  | `input` is read **once** | nothing here re-runs it; a changed input is a new `useQuery` |
303
303
  | A timed re-read is `useQuery(ref, input, { poll: pollEvery(ms) })` | non-live refs only (a live ref refuses it by type: `LiveQueryOptions`); `refetch` through core's `visibleInterval`, so a hidden tab, a lost session and `release()` all stop it. A value, not a number: `useQuery` never references the timer, so only an island importing `pollEvery` carries it (the reference like control rose 39,210 → 41,477 B across wave 5a, nearly all of it this, 2026-11-05) |
304
- | The caller owns `release()` / `using` | this layer does not know what a mount is |
304
+ | A component's hooks release themselves | `x build`'s island bootstrap installs Solid's `onCleanup` as `RealtimeInstall.cleanup`, and every `use*` hook registers its own release there: an island that forgets `onCleanup(() => h.release())` no longer holds a socket subscription and a cap slot across every client navigation until `X_SUBSCRIPTION_LIMIT`. `release()` / `using` stay, for a hook held outside a component (no owner, nothing registered) or let go sooner; every release runs once however many of them fire |
305
+ | One mutator's online writes are sent in call order | one lane per mutator NAME, page-wide (`PageWrites.lanes`): the next write's POST starts when the previous one settled — answered, refused or queued. A like then an unlike POSTed together could commit in either order and leave the row contradicting the last overlay. Overlays still paint at once; another mutator's writes do not wait |
305
306
 
306
307
  **A server render** (no install, no DOM) answers `pending`, reports online and creates no page
307
308
  state; a `useMutation` call refuses with `X_LIVE_SERVER_RENDER`. With a DOM and no install, every
@@ -621,7 +622,16 @@ made it — a key already queued collapses as always, and nothing queued is ever
621
622
  24.0.0, #681). A bus that reconnected is the same repair, with no later message needed. Both
622
623
  fields are optional on the bus, so a publisher that does not sequence simply detects nothing.
623
624
  A `recordPublisher`'s changes are sequenced too (`source: 'publisher'`): a hole in one is a
624
- gap; a new publisher is not, because publishers run side by side. Durable replay (JetStream) is a separate decision — retention,
625
+ gap; a new publisher is not, because publishers run side by side. **A replicator restart
626
+ chains — a deploy too** (envelope v2): a run's first envelope carries `from`, where its feed
627
+ says it resumed (`ChangeFeedStartOptions.onResume`: the resume position, or the slot's
628
+ `confirmed_flush_lsn`), and a clean `stop()` publishes a handover on `x.change.-handover` — its
629
+ last `seq` and `through`, how far the slot was confirmed (`ChangeFeed.position()`). A node that
630
+ read up to `from` (changes, or a handover) takes the new run as a continuation: a stop + start,
631
+ or a new replicator process after a clean stop, re-snapshots nobody. A crash (no handover) whose
632
+ slot was confirmed past what the node read, a lost tail, a new slot, a resync, a feed that does
633
+ not implement `position`/`onResume`, and every older replicator or node still gap — either roll
634
+ order is safe; sync nodes first is what lets the replicator's own roll chain. Durable replay (JetStream) is a separate decision — retention,
625
635
  storage and replay window — and is deliberately not this mechanism.
626
636
  - **A bulk write re-reads only the windows over its entity.** `updateWhere`/`deleteWhere` name a
627
637
  filter, not rows, so the in-process replicator calls `registry.invalidate(entity)`: windows whose
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/realtime",
3
- "version": "31.13.0",
3
+ "version": "31.14.0",
4
4
  "description": "Three-tier realtime: channels, live queries, local-first sync — one protocol, one mutator shape",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -52,10 +52,10 @@
52
52
  "test": "bun test"
53
53
  },
54
54
  "dependencies": {
55
- "@ultimat3/core": "31.13.0",
56
- "@ultimat3/entity": "31.13.0",
57
- "@ultimat3/policy": "31.13.0",
58
- "@ultimat3/query": "31.13.0",
55
+ "@ultimat3/core": "31.14.0",
56
+ "@ultimat3/entity": "31.14.0",
57
+ "@ultimat3/policy": "31.14.0",
58
+ "@ultimat3/query": "31.14.0",
59
59
  "nats": "2.29.3"
60
60
  }
61
61
  }
package/src/changefeed.ts CHANGED
@@ -7,6 +7,7 @@ import { finiteOption } from '@ultimat3/core';
7
7
  import { ReplicationFailedError } from './errors';
8
8
  import type { LiveRow } from './json';
9
9
  import { PgReplicationStream, type ReplicationStreamStats } from './pg-replication';
10
+ import { laterLsn } from './pg-replication-position';
10
11
  import type { PgTarget } from './pg-socket';
11
12
  import type { PgStream } from './pg-wire';
12
13
  import type { Rng } from './thundering-herd';
@@ -72,6 +73,13 @@ export interface ChangeFeedStartOptions {
72
73
  * now. Called at most once per `start()`, before its first change.
73
74
  */
74
75
  readonly onResync?: (reason: string) => void;
76
+ /**
77
+ * Where this stream resumed: it delivers every change above `at`. Called at most once per
78
+ * `start()`, before its first change, and only when the feed KNOWS — a stream "from now", a new
79
+ * slot and a resync say nothing. A sync node reads it as the run's place in the chain
80
+ * (`ChangeEnvelope.from`), so a claim it cannot keep is a lost change no node notices.
81
+ */
82
+ readonly onResume?: (at: string) => void;
75
83
  }
76
84
 
77
85
  export interface ChangeFeed {
@@ -86,6 +94,13 @@ export interface ChangeFeed {
86
94
  abandon(): void;
87
95
  /** Highest lsn delivered to the handler; the replicator persists this to survive a restart. */
88
96
  lastLsn(): string | null;
97
+ /**
98
+ * Every change at or below this position has been delivered — by this run, or before it began.
99
+ * Read after a clean `stop()` it is how far the stream got (a slot's confirmed position), which
100
+ * a replicator hands over so its successor in another process chains on. `null` or absent: the
101
+ * feed cannot say, and the next run reads as a gap.
102
+ */
103
+ position?(): string | null;
89
104
  }
90
105
 
91
106
  /** 16-hex zero-padded so string comparison equals numeric comparison. */
@@ -117,6 +132,10 @@ export class MemoryChangeFeed implements ChangeFeed {
117
132
  #tail: Promise<void> = Promise.resolve();
118
133
  #position = 0n;
119
134
  #lastLsn: string | null = null;
135
+ /** Where the current run resumed, when it said (`onResume`). */
136
+ #from: string | null = null;
137
+ /** The highest lsn retention let go of: a resume at or above it replays complete. */
138
+ #evicted: string | null = null;
120
139
 
121
140
  constructor(options: MemoryChangeFeedOptions = {}) {
122
141
  this.#retain = finiteOption('the change feed', 'retain', options.retain ?? 1024);
@@ -125,7 +144,13 @@ export class MemoryChangeFeed implements ChangeFeed {
125
144
  async start(options: ChangeFeedStartOptions): Promise<void> {
126
145
  this.#handler = options.onChange;
127
146
  const from = options.from;
147
+ this.#from = null;
128
148
  if (from === undefined) return;
149
+ // A claim only the retained window can keep: below what it let go of, changes are skipped.
150
+ if (this.#evicted === null || this.#evicted <= from) {
151
+ this.#from = from;
152
+ options.onResume?.(from);
153
+ }
129
154
  for (const event of this.#retained) {
130
155
  if (event.lsn > from) await this.#deliver(event);
131
156
  }
@@ -144,11 +169,20 @@ export class MemoryChangeFeed implements ChangeFeed {
144
169
  return this.#lastLsn;
145
170
  }
146
171
 
172
+ position(): string | null {
173
+ return laterLsn(this.#from, this.#lastLsn);
174
+ }
175
+
147
176
  /** Append a fully-formed event. Used by tests that need an exact lsn or txid. */
148
177
  async emit(event: ChangeEvent): Promise<void> {
149
178
  if (this.#retain > 0) {
150
179
  this.#retained.push(event);
151
- while (this.#retained.length > this.#retain) this.#retained.shift();
180
+ while (this.#retained.length > this.#retain) {
181
+ const evicted = this.#retained.shift();
182
+ if (evicted !== undefined) this.#evicted = laterLsn(this.#evicted, evicted.lsn);
183
+ }
184
+ } else {
185
+ this.#evicted = laterLsn(this.#evicted, event.lsn);
152
186
  }
153
187
  await this.#deliver(event);
154
188
  }
@@ -259,6 +293,7 @@ export class PostgresChangeFeed implements ChangeFeed {
259
293
  onChange: options.onChange,
260
294
  onEnd: options.onEnd,
261
295
  onResync: options.onResync,
296
+ onResume: options.onResume,
262
297
  });
263
298
  }
264
299
 
@@ -274,6 +309,10 @@ export class PostgresChangeFeed implements ChangeFeed {
274
309
  return this.#stream.lastLsn();
275
310
  }
276
311
 
312
+ position(): string | null {
313
+ return this.#stream.position();
314
+ }
315
+
277
316
  /** Delivered / skipped / replayed counts, for `/readyz` and the `x dev` dashboard. */
278
317
  stats(): ReplicationStreamStats {
279
318
  return this.#stream.stats();
@@ -8,7 +8,7 @@ import { SubscriptionLimitError } from './errors';
8
8
  import type { JsonValue } from './json';
9
9
  import type { LiveQueryDefinition, PreparedWindow } from './live-contract';
10
10
  import { DEFAULT_MAX_ENTRIES, type LiveQueryRegistryOptions } from './live-query-options';
11
- import { type QueryEntry, queryEntry } from './query-window';
11
+ import { type QueryEntry, queryEntry, watchStale } from './query-window';
12
12
 
13
13
  /** What the entry table reads off the registry's options. */
14
14
  export type LiveEntriesOptions = Pick<
@@ -20,6 +20,14 @@ export class LiveEntries {
20
20
  readonly #byQid = new Map<string, QueryEntry>();
21
21
  /** `shape.entities` → the entries reading it. A shape is fixed at birth, so this never moves. */
22
22
  readonly #byTable = new Map<string, Set<QueryEntry>>();
23
+ /** The entries whose `stale` is set, kept as it moves (`watchStale`) — what `targets` adds. */
24
+ readonly #owing = new Set<QueryEntry>();
25
+ /** Entries `queryEntry` did not build: no accessor reports them, so `targets` reads each one. */
26
+ readonly #unwatched = new Set<QueryEntry>();
27
+ readonly #onStale = (entry: QueryEntry, stale: boolean): void => {
28
+ if (stale) this.#owing.add(entry);
29
+ else this.#owing.delete(entry);
30
+ };
23
31
  readonly #options: LiveEntriesOptions;
24
32
  readonly #maxEntries: number;
25
33
 
@@ -117,12 +125,17 @@ export class LiveEntries {
117
125
  }
118
126
  readers.add(entry);
119
127
  }
128
+ if (!watchStale(entry, this.#onStale)) this.#unwatched.add(entry);
129
+ else if (entry.stale) this.#owing.add(entry);
120
130
  }
121
131
 
122
132
  delete(qid: string): void {
123
133
  const entry = this.#byQid.get(qid);
124
134
  if (entry === undefined) return;
125
135
  this.#byQid.delete(qid);
136
+ watchStale(entry, null, this.#onStale);
137
+ this.#owing.delete(entry);
138
+ this.#unwatched.delete(entry);
126
139
  for (const table of entry.shape.entities) {
127
140
  const readers = this.#byTable.get(table);
128
141
  if (readers === undefined) continue;
@@ -144,12 +157,15 @@ export class LiveEntries {
144
157
  * one): a change to a table it does not read is no hole in that read. `stale` is a boolean per
145
158
  * entry, read without a lane; the expensive part — a lane entered, a closure queued, a fanout
146
159
  * awaited — is paid by these entries only.
147
- * Measured: 10k windows on other tables, 34.6 ms → 0.23 ms per change (29 → 4,430/s).
160
+ * Measured: 10k windows on other tables, 34.6 ms → 0.23 ms per change (29 → 4,430/s). The stale
161
+ * ones are a set kept as `stale` moves, never a walk of the table: the walk was ~0.86 ms a change
162
+ * at 50k entries with none of them stale (`scripts/bench/live-entries-targets.bench.ts`).
148
163
  */
149
164
  targets(table: string): QueryEntry[] {
150
165
  const readers = this.readersOf(table);
151
166
  const out = [...readers];
152
- for (const entry of this.#byQid.values()) {
167
+ for (const entry of this.#owing) if (!readers.has(entry)) out.push(entry);
168
+ for (const entry of this.#unwatched) {
153
169
  if (entry.stale && !readers.has(entry)) out.push(entry);
154
170
  }
155
171
  return out;
@@ -47,7 +47,7 @@ export class RealtimeUninstalledError extends RealtimeError {
47
47
  super({
48
48
  code: 'X_REALTIME_UNINSTALLED',
49
49
  cause: `${args.hook}() ran in a browser island whose bundle never called installRealtime(), or on a page whose runtime (@ultimat3/realtime/boot) never loaded`,
50
- fix: "x build # the island bootstrap installs it; a hand-built island imports '@ultimat3/realtime/boot' (the page runtime) and calls installRealtime({ signal: createSignal }) from '@ultimat3/realtime' before its first render",
50
+ fix: "x build # the island bootstrap installs it; a hand-built island imports '@ultimat3/realtime/boot' (the page runtime) and calls installRealtime({ signal: createSignal, cleanup: onCleanup }) from '@ultimat3/realtime' before its first render",
51
51
  });
52
52
  }
53
53
  }
@@ -58,7 +58,7 @@ export class SyncUnconfiguredError extends RealtimeError {
58
58
  super({
59
59
  code: 'X_SYNC_UNCONFIGURED',
60
60
  cause: `${args.hook}() needs the page socket, and installRealtime() was given no sync target`,
61
- fix: "x build # the island bootstrap passes it; a hand-built island calls installRealtime({ signal: createSignal, sync: { url, buildId } }) from '@ultimat3/realtime'",
61
+ fix: "x build # the island bootstrap passes it; a hand-built island calls installRealtime({ signal: createSignal, cleanup: onCleanup, sync: { url, buildId } }) from '@ultimat3/realtime'",
62
62
  });
63
63
  }
64
64
  }
package/src/page-store.ts CHANGED
@@ -71,6 +71,40 @@ export interface PageWrites {
71
71
  readonly pending: Map<string, number>;
72
72
  failed: number;
73
73
  readonly listeners: Set<() => void>;
74
+ /**
75
+ * Per mutator name, the settling of its latest write: the next one's network leg waits on it
76
+ * (`enterLane`). Optional, so a page object another bundle's copy built still takes a write.
77
+ */
78
+ lanes?: Map<string, Promise<void>>;
79
+ }
80
+
81
+ /** A write's place in its mutator's lane: wait on `ready` (when busy), `leave` once settled. */
82
+ export interface WriteLane {
83
+ /** The previous write's settling; `undefined` when the lane was idle — send in this tick. */
84
+ readonly ready: Promise<void> | undefined;
85
+ leave(): void;
86
+ }
87
+
88
+ /**
89
+ * Joins the lane of `name`, page-wide — every hook and island of one mutator share it, because
90
+ * the order that matters is the server's commit order of that mutator's writes.
91
+ */
92
+ export function enterLane(writes: PageWrites, name: string): WriteLane {
93
+ if (writes.lanes === undefined) writes.lanes = new Map();
94
+ const lanes = writes.lanes;
95
+ const ready = lanes.get(name);
96
+ let open: () => void = () => undefined;
97
+ const mine = new Promise<void>((resolve) => {
98
+ open = resolve;
99
+ });
100
+ lanes.set(name, mine);
101
+ return {
102
+ ready,
103
+ leave: () => {
104
+ open();
105
+ if (lanes.get(name) === mine) lanes.delete(name);
106
+ },
107
+ };
74
108
  }
75
109
 
76
110
  export const PAGE_KEY: unique symbol = Symbol.for('ultimate.realtime');
@@ -287,6 +287,24 @@ export class PgConnection {
287
287
  await this.#stream.write(copyDoneMessage());
288
288
  }
289
289
 
290
+ /**
291
+ * After `endCopy()`: read the walsender's answer — CopyData still in flight, its CopyDone, the
292
+ * CommandComplete — through `ReadyForQuery`, so `close()` leaves no byte unread. Unread bytes at
293
+ * close are a TCP reset, and the server logs `Connection reset by peer` for every shutdown.
294
+ * `false` when `deadline` settled first; the read left behind ends with the socket. The caller
295
+ * owns the reader: nothing else may be reading this connection.
296
+ */
297
+ async awaitCopyEnd(deadline: Promise<void>): Promise<boolean> {
298
+ const drained = (async (): Promise<boolean> => {
299
+ for (;;) {
300
+ const message = await this.#reader.next();
301
+ if (message === undefined || message.tag === 'Z') return message !== undefined;
302
+ if (message.tag === 'c') this.#copyBoth = false;
303
+ }
304
+ })().catch(() => false);
305
+ return Promise.race([drained, deadline.then(() => false)]);
306
+ }
307
+
290
308
  async close(): Promise<void> {
291
309
  if (this.#closed) return;
292
310
  this.#closed = true;
@@ -73,6 +73,26 @@ export async function preflight(
73
73
  return 'existing';
74
74
  }
75
75
 
76
+ /**
77
+ * How far the slot was confirmed — read AFTER `awaitSlotReleased`, so a predecessor's last confirm
78
+ * (its clean `stop()`) has landed. Where a stream started with no resume position begins, and so
79
+ * the place in the chain a new replicator process says it resumed at. `null`: never confirmed, or
80
+ * a text this reader does not know (`0/16B3748` is the only spelling Postgres has).
81
+ */
82
+ export async function slotConfirmed(
83
+ connection: PgConnection,
84
+ slot: string,
85
+ ): Promise<bigint | null> {
86
+ assertIdentifier('slot', slot);
87
+ const [row] = await connection.query(
88
+ `SELECT confirmed_flush_lsn FROM pg_replication_slots WHERE slot_name = '${slot}'`,
89
+ );
90
+ const text = row?.[0];
91
+ if (typeof text !== 'string' || !/^[0-9A-Fa-f]{1,8}\/[0-9A-Fa-f]{1,8}$/.test(text)) return null;
92
+ const [high = '0', low = '0'] = text.split('/');
93
+ return (BigInt(`0x${high}`) << 32n) | BigInt(`0x${low}`);
94
+ }
95
+
76
96
  /**
77
97
  * The fourth preflight question, and the one that does NOT refuse: which entity tables have NO
78
98
  * replica identity. Once such a table is in the publication, Postgres refuses its UPDATE and
@@ -8,8 +8,8 @@ import { ReplicationSlotRecreatedError } from './errors';
8
8
  import { printLsn } from './pg-bytes';
9
9
  import { PgConnection } from './pg-connection';
10
10
  import { paramsChannelTables } from './pg-identity-tables';
11
- import { preflight } from './pg-preflight';
12
- import { commitPositionOf } from './pg-replication-position';
11
+ import { preflight, slotConfirmed } from './pg-preflight';
12
+ import { changeLsn, commitPositionOf, laterLsn } from './pg-replication-position';
13
13
  import { bunPgStream, parsePgUrl } from './pg-socket';
14
14
 
15
15
  /** The identifiers the stream already put through `assertIdentifier`. */
@@ -30,14 +30,23 @@ export interface SlotGap {
30
30
 
31
31
  export interface DialedStream {
32
32
  readonly connection: PgConnection;
33
- /** Where START_REPLICATION began — what the stream confirms until its first commit. */
33
+ /** Where START_REPLICATION began — never below the slot's — and confirmed until a commit. */
34
34
  readonly confirmed: bigint;
35
35
  /** The resume filter for this run: `undefined` once the slot it pointed into is gone. */
36
36
  readonly from: string | undefined;
37
37
  /** Why every reader must re-read now, or `null` when the stream is continuous. */
38
38
  readonly resync: string | null;
39
+ /**
40
+ * The stream delivers every change above this (`ChangeFeedStartOptions.onResume`): the later of
41
+ * the resume filter and the slot's confirmed position as a change lsn — the server starts at
42
+ * neither below the slot's. `null` for a new slot — it begins at the server's current WAL, and
43
+ * what came before it was never streamed.
44
+ */
45
+ readonly resumed: string | null;
39
46
  }
40
47
 
48
+ const maxPosition = (a: bigint, b: bigint): bigint => (a >= b ? a : b);
49
+
41
50
  /**
42
51
  * Open, preflight, START_REPLICATION. On any failure after the socket opened, the session is closed
43
52
  * before the failure is rethrown: the dial failure explains the boot, a close that also failed
@@ -76,7 +85,18 @@ export async function dialReplication(
76
85
  // FIELDS, never interpolation; the message is the CODE alone (`pg-preflight.ts`).
77
86
  logger.warn(said.code, { cause: said.cause, fix: said.fix, slot: names.slot, from: under });
78
87
  }
79
- const confirmed = resumeFrom === undefined ? 0n : commitPositionOf(resumeFrom);
88
+ // An existing slot is always asked where it stands. With no resume position it restarts there
89
+ // (asked for explicitly, which Postgres treats exactly as `0/0`). With one, Postgres forwards a
90
+ // start below it to it: another process confirmed past this one's last delivery, and claiming
91
+ // the older position would let a sync node chain over changes nobody will send again.
92
+ const fromSlot = slot === 'existing' ? await slotConfirmed(connection, names.slot) : null;
93
+ const confirmed =
94
+ resumeFrom === undefined
95
+ ? (fromSlot ?? 0n)
96
+ : maxPosition(commitPositionOf(resumeFrom), fromSlot ?? 0n);
97
+ // `<commit>00000000`: no row has sequence 0, so every change of a transaction committing at or
98
+ // after the slot's position is above it — and those are the ones the server sends.
99
+ const resumed = laterLsn(resumeFrom ?? null, fromSlot === null ? null : changeLsn(fromSlot, 0));
80
100
  await connection.startCopyBoth(
81
101
  `START_REPLICATION SLOT ${names.slot} LOGICAL ${printLsn(confirmed)} ` +
82
102
  `(proto_version '1', publication_names '${names.publication}', messages 'true')`,
@@ -87,7 +107,7 @@ export async function dialReplication(
87
107
  ? `replication slot "${names.slot}" was recreated under resume position ${under}: ` +
88
108
  'the changes in between were never streamed'
89
109
  : null;
90
- return { connection, confirmed, from: resumeFrom, resync };
110
+ return { connection, confirmed, from: resumeFrom, resync, resumed };
91
111
  } catch (failure) {
92
112
  await connection.close().catch(() => undefined);
93
113
  throw failure;
@@ -0,0 +1,41 @@
1
+ // Single responsibility: the read a replication stream's `stop()` owes the walsender between its
2
+ // CopyDone and its Terminate — bounded, because a silent server must not hold a SIGTERM.
3
+
4
+ import type { PgConnection } from './pg-connection';
5
+ import type { Scheduler } from './thundering-herd';
6
+
7
+ /**
8
+ * How long `stop()` reads the walsender's goodbye before closing anyway. A healthy server answers a
9
+ * CopyDone in one round trip; one that does not is not worth a slower shutdown.
10
+ */
11
+ export const COPY_DRAIN_MS = 1_000;
12
+
13
+ /**
14
+ * The walsender answers a CopyDone with its own, a CommandComplete and a ReadyForQuery. Closed over
15
+ * unread, the socket answered with a reset: one `Connection reset by peer` in the server log per
16
+ * deploy. `pump` holds the one reader, so it is waited out first — it returns on its next message,
17
+ * once the stream has let the connection go — and the rest is read here. Both share one
18
+ * `COPY_DRAIN_MS` bound; past it the close goes ahead unread. `true` when `ReadyForQuery` was read.
19
+ */
20
+ export async function drainGoodbye(
21
+ connection: PgConnection,
22
+ pump: Promise<void> | null,
23
+ schedule: Scheduler,
24
+ ): Promise<boolean> {
25
+ let cancel = (): void => undefined;
26
+ const deadline = new Promise<void>((resolve) => {
27
+ cancel = schedule(resolve, COPY_DRAIN_MS);
28
+ });
29
+ try {
30
+ const late = deadline.then(() => false);
31
+ // Settled either way: a pump's own failure is `stop()`'s to report, not a reason to skip this.
32
+ const settled = pump?.then(
33
+ () => true,
34
+ () => true,
35
+ );
36
+ const handed = settled === undefined || (await Promise.race([settled, late]));
37
+ return handed && (await connection.awaitCopyEnd(deadline));
38
+ } finally {
39
+ cancel();
40
+ }
41
+ }
@@ -20,6 +20,10 @@ const STANDBY_STATUS = 0x72;
20
20
  export const changeLsn = (commitLsn: bigint, sequence: number): string =>
21
21
  commitLsn.toString(16).padStart(16, '0') + sequence.toString(16).padStart(8, '0');
22
22
 
23
+ /** The higher of two positions, either possibly unknown. */
24
+ export const laterLsn = (a: string | null, b: string | null): string | null =>
25
+ a === null ? b : b === null || a >= b ? a : b;
26
+
23
27
  /** The commit position inside a change lsn — where a resume asks the server to restart. */
24
28
  export const commitPositionOf = (lsn: string): bigint => BigInt(`0x${lsn.slice(0, 16) || '0'}`);
25
29
 
@@ -10,17 +10,20 @@ import { ByteReader } from './pg-bytes';
10
10
  import type { PgConnection } from './pg-connection';
11
11
  import { assertIdentifier } from './pg-identifier';
12
12
  import { dialReplication, type SlotGap } from './pg-replication-dial';
13
+ import { drainGoodbye } from './pg-replication-goodbye';
13
14
  import {
14
15
  type ConfirmAttempt,
15
16
  StreamLiveness,
16
17
  silenceReason,
17
18
  unsettledReason,
18
19
  } from './pg-replication-liveness';
19
- import { changeLsn, standbyStatus } from './pg-replication-position';
20
+ import { changeLsn, laterLsn, standbyStatus } from './pg-replication-position';
20
21
  import { replicatedImages, tenantOf } from './pg-replication-row';
21
22
  import type { ReplicationStreamStats } from './pg-replication-stats';
22
23
  import type { PhysicalRow } from './pg-values';
23
24
  import { keyedWrite, PgOutputDecoder, type PgOutputMessage, type PgRelation } from './pgoutput';
25
+ import type { Scheduler } from './thundering-herd';
26
+ import { unrefScheduler } from './unref-scheduler';
24
27
 
25
28
  // Moved next door; their importers (`server.ts`, `changefeed.ts`, the tests) keep this path.
26
29
  export { changeLsn, commitPositionOf } from './pg-replication-position';
@@ -55,6 +58,8 @@ export interface ReplicationStreamHandlers {
55
58
  readonly onEnd?: ((reason: string) => void) | undefined;
56
59
  /** The stream is continuous no more — its slot was recreated under `from` — so re-read all. */
57
60
  readonly onResync?: ((reason: string) => void) | undefined;
61
+ /** Where the stream resumed — every change above it is delivered (`DialedStream.resumed`). */
62
+ readonly onResume?: ((at: string) => void) | undefined;
58
63
  }
59
64
 
60
65
  /**
@@ -74,6 +79,8 @@ export class PgReplicationStream {
74
79
  #transaction: Transaction | null = null;
75
80
  #confirmed = 0n;
76
81
  #lastLsn: string | null = null;
82
+ /** Where this run resumed, when known — the floor of `position()`. */
83
+ #resumed: string | null = null;
77
84
  #running = false;
78
85
  #pump: Promise<void> | null = null;
79
86
  #delivered = 0;
@@ -87,9 +94,12 @@ export class PgReplicationStream {
87
94
  readonly #slotGap: SlotGap = { createdUnder: null };
88
95
  #intervalMs = DEFAULT_STATUS_INTERVAL_MS;
89
96
  #onEnd: ((reason: string) => void) | undefined;
97
+ /** The goodbye's deadline timer (`drainGoodbye`); a test fires it. */
98
+ readonly #schedule: Scheduler;
90
99
 
91
- constructor(options: PostgresChangeFeedOptions) {
100
+ constructor(options: PostgresChangeFeedOptions, schedule: Scheduler = unrefScheduler) {
92
101
  this.#options = options;
102
+ this.#schedule = schedule;
93
103
  this.#clock = options.clock ?? systemClock;
94
104
  this.#entities = new Set(options.entities.map((name) => assertIdentifier('entity', name)));
95
105
  // All three names are checked here rather than in `start()`: a mistyped REPLICATION_SLOT is a
@@ -103,6 +113,12 @@ export class PgReplicationStream {
103
113
  return this.#lastLsn;
104
114
  }
105
115
 
116
+ /** `ChangeFeed.position`: everything below the confirmed commit, the resume point, or delivered. */
117
+ position(): string | null {
118
+ const confirmed = this.#confirmed > 0n ? changeLsn(this.#confirmed, 0) : null;
119
+ return laterLsn(laterLsn(this.#resumed, confirmed), this.#lastLsn);
120
+ }
121
+
106
122
  stats(): ReplicationStreamStats {
107
123
  return {
108
124
  delivered: this.#delivered,
@@ -128,6 +144,7 @@ export class PgReplicationStream {
128
144
  const connection = dialed.connection;
129
145
  this.#connection = connection;
130
146
  this.#confirmed = dialed.confirmed;
147
+ this.#resumed = dialed.resumed;
131
148
  this.#running = true;
132
149
  // A restart that kept the last death in `stats()` would report a live stream as failed.
133
150
  this.#failure = null;
@@ -149,6 +166,7 @@ export class PgReplicationStream {
149
166
  // Before the first change of the new slot can reach anyone: every reader re-reads NOW, rather
150
167
  // than a quiet table staying stale until its next write.
151
168
  if (dialed.resync !== null) handlers.onResync?.(dialed.resync);
169
+ else if (dialed.resumed !== null) handlers.onResume?.(dialed.resumed);
152
170
  }
153
171
 
154
172
  /**
@@ -164,15 +182,18 @@ export class PgReplicationStream {
164
182
  const connection = this.#connection;
165
183
  this.#connection = null;
166
184
  const failures: unknown[] = [];
185
+ let ended = false;
167
186
  try {
168
187
  // Confirming before the goodbye is what stops a restart from replaying the whole window.
169
188
  if (connection?.inCopyBoth === true) {
170
189
  await this.#confirm(connection);
171
190
  await connection.endCopy();
191
+ ended = true;
172
192
  }
173
193
  } catch (failure) {
174
194
  failures.push(failure);
175
195
  }
196
+ if (ended && connection !== null) await drainGoodbye(connection, this.#pump, this.#schedule);
176
197
  try {
177
198
  await connection?.close();
178
199
  } catch (failure) {