@pgxsinkit/client 0.1.48 → 0.1.49

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.
@@ -0,0 +1,591 @@
1
+ // The worker-owned live-query manager (ADR-0040). It owns the PGlite `live` registration lifecycle, the
2
+ // single change listener + shared `LiveDiffState` per query, and the awaited-teardown bookkeeping (decision
3
+ // 1). Slice 3 added DEDUPLICATION: identical live queries (same fingerprint — see live-query-fingerprint.ts)
4
+ // share ONE registration and ONE diff computation, fanned out to every subscriber (decision 2). Slice 4 adds
5
+ // BOUNDED ZERO-SUBSCRIBER KEEP-ALIVE (decision 4): when the last subscriber of an entry leaves, a nonzero
6
+ // effective keep-alive retains the registration for a grace period so a matching resubscribe reuses it
7
+ // verbatim (no ~400 ms re-materialization); retention is bounded by explicit count/row budgets and defaults
8
+ // to OFF (keep-alive 0 → tear down immediately, byte-identical to Slice 3).
9
+ //
10
+ // What stays with the CALLER (`defineSyncWorker`), never this manager (ADR-0040 decision 3): lazy-relation
11
+ // activation (`prepareQuery`), hydration accounting (`hydratingTablesFor` → `groupReady`), the
12
+ // `live-initial`/`live-diff`/`live-hydrated` bridge posting with its per-`queryId` correlation, and
13
+ // `wrapLiveQueryForMaterialization` (the manager receives POST-WRAP SQL — the fingerprint's SQL input). Those
14
+ // are per-subscriber pre-/post-steps that never influence the shared registration or its rows; in particular
15
+ // `use` NEVER reaches here, so differing `use` sets share one registration.
16
+
17
+ import type { LiveNamespace, LiveQuery, LiveQueryResults } from "@electric-sql/pglite/live";
18
+
19
+ import { syncDebug } from "../debug";
20
+ import { computeLiveDiff, type LiveDiffState, seedLiveDiffState } from "./live-diff";
21
+ import { fingerprintLiveQuery } from "./live-query-fingerprint";
22
+ import type { LiveDiffPayload } from "./protocol";
23
+
24
+ type Row = Record<string, unknown>;
25
+
26
+ /** The wire diff a subscriber receives — exactly `computeLiveDiff`'s output, minus the caller's `queryId`. */
27
+ export type LiveDiffWire = Omit<LiveDiffPayload, "queryId">;
28
+
29
+ /** The two delivery callbacks a subscriber supplies; the caller wires these to its bridge posting. */
30
+ export interface LiveSubscriber {
31
+ /** The verbatim initial snapshot (NOT a diff), delivered ONCE before any diff (rows-before-diff ordering). */
32
+ deliverInitial(rows: readonly Row[]): void;
33
+ /** A subsequent change, already diffed against the last delivered set. */
34
+ deliverDiff(diff: LiveDiffWire): void;
35
+ }
36
+
37
+ /** Post-wrap SQL + bound params + optional single-column PK (selects `incrementalQuery` vs `query`). */
38
+ export interface LiveQuerySpec {
39
+ materialSql: string;
40
+ params: unknown[];
41
+ pkColumns?: readonly string[];
42
+ }
43
+
44
+ /** Per-subscription options (ADR-0040). */
45
+ export interface LiveSubscribeOptions {
46
+ /**
47
+ * How long (ms) THIS subscriber asks the entry to be retained after IT (and any siblings) leave. The
48
+ * entry's effective keep-alive is `max(policy default, the max hint of the current active generation)`
49
+ * (see the generation rule on `subscribe`); the worker count/row budgets stay authoritative over any hint.
50
+ * Absent / 0 → no retention from this subscriber. Must be a finite number ≥ 0.
51
+ */
52
+ keepAliveMs?: number;
53
+ /**
54
+ * An opaque grouping key for diagnostics only (ADR-0040 decision 5) — never part of the fingerprint, so it
55
+ * NEVER affects dedup or registration. The worker passes one stable scope per bridge port, so a snapshot's
56
+ * `scopeCount` reads as the distinct-tab count; the in-process client passes none.
57
+ */
58
+ scope?: string;
59
+ }
60
+
61
+ /** A live registration's handle: awaited/tracked teardown and a coalesced refresh. */
62
+ export interface LiveSubscription {
63
+ /** Non-blocking for the caller; the promise is retained internally so `dispose()` awaits it (decision 1). */
64
+ unsubscribe(): Promise<void>;
65
+ /** Force one recompute; concurrent calls SHARE one underlying `live.refresh()` (never N stacked reruns). */
66
+ refresh(): Promise<void>;
67
+ }
68
+
69
+ /** The manager's bounded keep-alive policy (ADR-0040 decision 4). All fields default; the block is opt-in. */
70
+ export interface LiveQueryPolicy {
71
+ /**
72
+ * Default retention (ms) for a zero-subscriber entry, floored by each subscriber's own `keepAliveMs` hint.
73
+ * Default 0 — the current route-scoped behaviour (tear a query down the moment its last consumer leaves).
74
+ * The standing argument for 0: a retained zero-subscriber entry STILL pays a full SQL rerun + diff on every
75
+ * dependent-table write — PGlite live queries cannot be paused, only torn down — so retention trades that
76
+ * standing cost for avoiding re-materialization, and is only worth it for a genuinely hot, re-mounted query.
77
+ */
78
+ defaultKeepAliveMs?: number;
79
+ /** Max simultaneously-retained (zero-subscriber) entries; LRU-evicted past this. Active entries never count. */
80
+ maxRetainedQueries?: number;
81
+ /** Max total rows held across ALL retained entries; LRU-evicted past this. Active entries never count. */
82
+ maxRetainedRows?: number;
83
+ }
84
+
85
+ type TimerHandle = unknown;
86
+
87
+ /**
88
+ * The signed-32-bit `setTimeout` delay ceiling (ADR-0040 decision 4). Browsers and Node clamp a delay above
89
+ * this to ~0, so a "30-day" keep-alive would EXPIRE IMMEDIATELY rather than retain — the opposite of intent.
90
+ * A keep-alive above this is rejected at the public boundary (never silently clamped), matching the ADR's
91
+ * deliberate refusal of de-facto permanent retention. The budgets (count/rows) are NOT timers and are uncapped.
92
+ */
93
+ const MAX_KEEP_ALIVE_MS = 2_147_483_647;
94
+
95
+ export interface LiveQueryManagerDeps {
96
+ /** The engine's `live` namespace — only the two registration entry points are used. */
97
+ live: Pick<LiveNamespace, "query" | "incrementalQuery">;
98
+ /** Bounded keep-alive policy (ADR-0040 decision 4); omitted → all defaults (retention off). */
99
+ policy?: LiveQueryPolicy;
100
+ /** Monotonic clock for keep-alive LRU accounting. Default `performance.now()` (Date.now fallback). */
101
+ now?: () => number;
102
+ /** Injectable eviction timer (tests drive it deterministically). Default `setTimeout`. */
103
+ setTimer?: (callback: () => void, ms: number) => TimerHandle;
104
+ /** Injectable timer cancel. Default `clearTimeout`. */
105
+ clearTimer?: (handle: TimerHandle) => void;
106
+ }
107
+
108
+ /**
109
+ * A structured-clone-safe, per-entry diagnostics record (ADR-0040 decision 5). It carries ONLY opaque
110
+ * fingerprint digests and counts/timings — NEVER SQL text, bound param values, or result-row values (those
111
+ * live only in the fingerprint's private `key`, which is deliberately absent here). Safe to cross the bridge
112
+ * and surface in support tooling.
113
+ */
114
+ export interface LiveQueryDiagnostics {
115
+ /** The opaque fingerprint digest (a short hash — see live-query-fingerprint.ts). NEVER the full key. */
116
+ digest: string;
117
+ /** Current subscriber count (0 while retained). */
118
+ subscriberCount: number;
119
+ /**
120
+ * Distinct subscription scopes on this entry. The worker passes one scope per bridge port, so in WORKER
121
+ * mode this is the number of distinct tabs on the query; the in-process client passes none, so it stays 1
122
+ * while any subscriber is attached (0 while retained).
123
+ */
124
+ scopeCount: number;
125
+ /** Rows currently held in the shared diff state. */
126
+ rowCount: number;
127
+ /** Whether this is a zero-subscriber entry currently kept alive (ADR-0040 decision 4). */
128
+ retained: boolean;
129
+ /** How many subscribes JOINED this entry rather than creating it (active-joins + retained rejoins). */
130
+ dedupHits: number;
131
+ /** Monotonic stamp (ms) when the entry was created. */
132
+ createdAt: number;
133
+ /** Time (ms) the registration setup took, or `null` until setup completes. */
134
+ setupMs: number | null;
135
+ /** Refresh timings for the shared registration (the hydration-chain / force refreshes). */
136
+ refresh: { count: number; lastMs: number | null; totalMs: number; maxMs: number };
137
+ /** Monotonic stamp (ms) of the last transition to zero subscribers, or `null` if never retained. */
138
+ lastUsedAt: number | null;
139
+ /** How long (ms) the entry has been retained (now − lastUsedAt), or `null` when not retained. */
140
+ retainedSinceMs: number | null;
141
+ /** A teardown is in flight (the entry is unsubscribing from PGlite). */
142
+ teardownPending: boolean;
143
+ }
144
+
145
+ export interface LiveQueryManager {
146
+ subscribe(spec: LiveQuerySpec, subscriber: LiveSubscriber, opts?: LiveSubscribeOptions): Promise<LiveSubscription>;
147
+ /** Tear down every live registration and await ALL teardowns (the Slice-1 close-vs-unsubscribe guard). */
148
+ dispose(): Promise<void>;
149
+ /**
150
+ * A point-in-time diagnostics snapshot (ADR-0040 decision 5): one plain-object record per live entry,
151
+ * carrying digests + counts/timings only — NO SQL, params, or rows. For the `liveQueryDiagnostics` RPC and
152
+ * support tooling.
153
+ */
154
+ snapshot(): LiveQueryDiagnostics[];
155
+ }
156
+
157
+ /**
158
+ * Validate a keep-alive policy at the public boundary (ADR-0040 decision 4 — bounded, no permanent retention).
159
+ * Every provided field must be a finite number ≥ 0; the two budgets must additionally be integers. Throws a
160
+ * `TypeError` naming the offending field so a misconfiguration fails at construction, not at first subscribe.
161
+ */
162
+ export function validateLiveQueryPolicy(policy: LiveQueryPolicy | undefined): void {
163
+ if (policy == null) return;
164
+ const ms = (name: keyof LiveQueryPolicy, value: number | undefined) => {
165
+ if (value !== undefined && (!Number.isFinite(value) || value < 0)) {
166
+ throw new TypeError(`[pgxsinkit] liveQueries.${String(name)} must be a finite number >= 0 (got ${value})`);
167
+ }
168
+ // A keep-alive above the signed-32-bit timer ceiling would clamp to ~0 and expire immediately (see
169
+ // MAX_KEEP_ALIVE_MS) — reject it rather than let a huge value become a no-retention footgun.
170
+ if (value !== undefined && value > MAX_KEEP_ALIVE_MS) {
171
+ throw new TypeError(
172
+ `[pgxsinkit] liveQueries.${String(name)} must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${value})`,
173
+ );
174
+ }
175
+ };
176
+ const int = (name: keyof LiveQueryPolicy, value: number | undefined) => {
177
+ if (value !== undefined && (!Number.isInteger(value) || value < 0)) {
178
+ throw new TypeError(`[pgxsinkit] liveQueries.${String(name)} must be a non-negative integer (got ${value})`);
179
+ }
180
+ };
181
+ ms("defaultKeepAliveMs", policy.defaultKeepAliveMs);
182
+ int("maxRetainedQueries", policy.maxRetainedQueries);
183
+ int("maxRetainedRows", policy.maxRetainedRows);
184
+ }
185
+
186
+ /** One deduplicated registration: a shared listener + diff state, fanned out to many subscribers. */
187
+ interface LiveEntry {
188
+ readonly key: string;
189
+ readonly digest: string;
190
+ /** Resolves once `registered`/`state`/`listener` are wired; rejects (and removes the entry) on setup failure. */
191
+ readonly setup: Promise<void>;
192
+ /**
193
+ * Fan-out map keyed by an opaque per-subscription token (so `(port, queryId)` callers stay independent),
194
+ * carrying each subscriber's keep-alive hint and diagnostics scope.
195
+ */
196
+ readonly subscribers: Map<symbol, { subscriber: LiveSubscriber; keepAliveMs: number; scope: string | undefined }>;
197
+ registered?: LiveQuery<Row>;
198
+ listener?: (results: LiveQueryResults<Row>) => void;
199
+ state?: LiveDiffState;
200
+ torn: boolean;
201
+ teardown?: Promise<void>;
202
+ refreshInFlight?: Promise<void>;
203
+ /** Monotonic stamp of the last transition to zero subscribers — the LRU key while retained. */
204
+ lastUsedAt?: number;
205
+ /** The live eviction timer while retained; cleared on rejoin, expiry, eviction, or dispose. */
206
+ evictionTimer?: TimerHandle;
207
+ /**
208
+ * The max keep-alive hint observed during the CURRENT active generation (reset to the joiner's hint on any
209
+ * 0→1 join, `max`'d on every later join). The last-out effective keep-alive is `max(default, this)` — so it
210
+ * is independent of the ORDER subscribers depart in (a hint no longer vanishes the instant its subscriber
211
+ * leaves), making equivalent subscriber sets behave identically.
212
+ */
213
+ generationKeepAliveMs: number;
214
+ // ── Diagnostics counters (ADR-0040 decision 5) — digests/counts/timings only, never SQL/params/rows ──
215
+ readonly createdAt: number;
216
+ dedupHits: number;
217
+ setupMs?: number;
218
+ refreshCount: number;
219
+ refreshLastMs?: number;
220
+ refreshTotalMs: number;
221
+ refreshMaxMs: number;
222
+ teardownPending: boolean;
223
+ }
224
+
225
+ export function createLiveQueryManager(deps: LiveQueryManagerDeps): LiveQueryManager {
226
+ validateLiveQueryPolicy(deps.policy);
227
+ const { live } = deps;
228
+ const policy = {
229
+ defaultKeepAliveMs: deps.policy?.defaultKeepAliveMs ?? 0,
230
+ maxRetainedQueries: deps.policy?.maxRetainedQueries ?? 16,
231
+ maxRetainedRows: deps.policy?.maxRetainedRows ?? 50_000,
232
+ };
233
+ const now = deps.now ?? (() => (typeof performance !== "undefined" ? performance.now() : Date.now()));
234
+ const setTimer = deps.setTimer ?? ((callback: () => void, ms: number) => setTimeout(callback, ms));
235
+ const clearTimer =
236
+ deps.clearTimer ?? ((handle: TimerHandle) => clearTimeout(handle as ReturnType<typeof setTimeout>));
237
+
238
+ // ADR-0040 decision 1 (originally define-sync-worker's Slice 1): a fire-and-forget live `unsubscribe()`
239
+ // still in flight when PGlite closes wedges the process forever. Every teardown promise is retained here so
240
+ // `dispose()` settles them ALL before the caller closes the engine; rejections are swallowed so an
241
+ // interrupted teardown never becomes an unhandled rejection.
242
+ const pendingTeardowns = new Set<Promise<void>>();
243
+ // The deduplication table: one entry per fingerprint (identical live queries share it).
244
+ const entries = new Map<string, LiveEntry>();
245
+ // Zero-subscriber entries currently being kept alive (ADR-0040 decision 4). ONLY these are counted against
246
+ // the budgets and eligible for LRU eviction; active (subscriber-holding) entries are never in this set.
247
+ const retained = new Set<LiveEntry>();
248
+ // In-flight `subscribe()` calls (each resolves only once its join/self-teardown has fully run). `dispose()`
249
+ // drains these so a subscribe completing mid-dispose is torn down instead of leaking a live query.
250
+ const setups = new Set<Promise<void>>();
251
+ // Manager-level count of dedup HITS — subscribes that joined an EXISTING entry (active-join or retained
252
+ // rejoin) rather than creating a registration. Surfaced on the debug rail (`live-query dedup-hit`).
253
+ let dedupHits = 0;
254
+ let disposed = false;
255
+
256
+ const createEntry = (key: string, digest: string, spec: LiveQuerySpec): LiveEntry => {
257
+ const entry: LiveEntry = {
258
+ key,
259
+ digest,
260
+ subscribers: new Map(),
261
+ torn: false,
262
+ generationKeepAliveMs: 0,
263
+ createdAt: now(),
264
+ dedupHits: 0,
265
+ refreshCount: 0,
266
+ refreshTotalMs: 0,
267
+ refreshMaxMs: 0,
268
+ teardownPending: false,
269
+ // Assigned synchronously just below — the IIFE reads `entry`, which is fully initialized by then.
270
+ setup: undefined as unknown as Promise<void>,
271
+ };
272
+ (entry as { setup: Promise<void> }).setup = (async () => {
273
+ const setupStartedAt = now();
274
+ const { materialSql, params, pkColumns } = spec;
275
+ // Single-column PK → PGlite's incremental machinery (`live.incrementalQuery`); composite/keyless →
276
+ // `live.query` (full ordered result each fire) + worker-side diff. Identical selection to the pre-dedup
277
+ // path; the fingerprint already encoded this choice as its `mode`.
278
+ const registered =
279
+ pkColumns && pkColumns.length === 1
280
+ ? await live.incrementalQuery<Row>(materialSql, params, pkColumns[0]!)
281
+ : await live.query<Row>(materialSql, params);
282
+ const state = seedLiveDiffState(registered.initialResults.rows, pkColumns);
283
+ const listener = (results: LiveQueryResults<Row>) => {
284
+ // `subscribe` fires only on a real change (never the initial), so every fire yields a genuine delta.
285
+ // ONE diff, computed once against the shared state, fanned to EVERY current subscriber (decision 2).
286
+ const diff = computeLiveDiff(state, results.rows);
287
+ // Isolate per subscriber: a throwing consumer (the in-process `onRows` reaches app code) must NOT
288
+ // starve its siblings — the shared state already advanced, so a skipped delivery is unrecoverable.
289
+ for (const record of entry.subscribers.values()) {
290
+ try {
291
+ record.subscriber.deliverDiff(diff);
292
+ } catch {
293
+ syncDebug("live-query subscriber-error", { digest: entry.digest });
294
+ }
295
+ }
296
+ // A retained (zero-subscriber) entry stays live and its rows can GROW past the row budget on a write.
297
+ // Re-enforce OUTSIDE this callback (a queued microtask) — eviction's PGlite `unsubscribe()` must not
298
+ // run inside PGlite's own notification call (ADR-0040 decision 4 — the budget stays authoritative).
299
+ if (retained.has(entry)) queueMicrotask(() => enforceBudgets());
300
+ };
301
+ registered.subscribe(listener);
302
+ entry.registered = registered;
303
+ entry.state = state;
304
+ entry.listener = listener;
305
+ entry.setupMs = now() - setupStartedAt;
306
+ syncDebug("live-query register", { digest, setupMs: Math.round(entry.setupMs) });
307
+ })();
308
+ // Failed setup: drop the entry so every joined waiter rejects and a LATER subscribe builds a fresh one.
309
+ entry.setup.catch(() => {
310
+ if (entries.get(key) === entry) entries.delete(key);
311
+ });
312
+ return entry;
313
+ };
314
+
315
+ const tearDownEntry = (entry: LiveEntry): Promise<void> => {
316
+ if (entry.torn) return entry.teardown ?? Promise.resolve();
317
+ entry.torn = true;
318
+ entry.teardownPending = true;
319
+ // Deliberately keep the torn entry in the map until its teardown COMPLETES: a resubscribe to the same
320
+ // fingerprint arriving mid-teardown must find it, await the teardown, and only THEN build a fresh entry
321
+ // (ADR-0040 decision 2 — never overlap a new registration with the old one's in-flight unsubscribe).
322
+ const teardown = (async () => {
323
+ // Wait out setup so there is a registration to unsubscribe (setup may still be in flight under dispose,
324
+ // or a resubscribe-during-teardown awaiting this promise). A failed setup leaves nothing to unwind.
325
+ await entry.setup.catch(() => {});
326
+ if (entry.registered && entry.listener) await entry.registered.unsubscribe(entry.listener);
327
+ })()
328
+ .catch(() => {
329
+ // A completed teardown failure is a one-shot event surfaced ONLY on the debug rail (ADR-0040
330
+ // decision 5): the entry is removed from the map in the finally below, so no ordinary snapshot could
331
+ // ever observe a per-entry flag — the rail line (buffered + replayable) is the sole failure signal.
332
+ syncDebug("live-query teardown-failed", { digest: entry.digest });
333
+ })
334
+ .finally(() => {
335
+ entry.teardownPending = false;
336
+ // Drop the slot only if still ours — a fresh entry never replaces it while we hold the map key, but
337
+ // stay defensive against a future keep-alive path swapping entries under the same fingerprint.
338
+ if (entries.get(entry.key) === entry) entries.delete(entry.key);
339
+ syncDebug("live-query teardown-complete", { digest: entry.digest });
340
+ });
341
+ entry.teardown = teardown;
342
+ pendingTeardowns.add(teardown);
343
+ void teardown.finally(() => pendingTeardowns.delete(teardown));
344
+ return teardown;
345
+ };
346
+
347
+ /** Stop retaining an entry (rejoin / eviction / dispose): clear its timer and drop it from the retained set. */
348
+ const cancelEviction = (entry: LiveEntry): void => {
349
+ if (entry.evictionTimer !== undefined) {
350
+ clearTimer(entry.evictionTimer);
351
+ entry.evictionTimer = undefined;
352
+ }
353
+ retained.delete(entry);
354
+ };
355
+
356
+ /** Total rows held across all retained (zero-subscriber) entries — the row-budget accumulator. */
357
+ const retainedRowTotal = (): number => {
358
+ let total = 0;
359
+ for (const entry of retained) total += entry.state?.previous.size ?? 0;
360
+ return total;
361
+ };
362
+
363
+ // Enforce the retention budgets (ADR-0040 decision 4): while either the count OR the total-row budget is
364
+ // exceeded, evict the LRU retained entry (smallest `lastUsedAt`). Budgets are AUTHORITATIVE over any hint,
365
+ // and ONLY zero-subscriber entries are ever counted or evicted — active entries are untouchable. Run on
366
+ // every transition INTO retained AND after a retained entry's rows grow (queued from the listener).
367
+ const enforceBudgets = (): void => {
368
+ if (disposed) return; // dispose owns teardown; a queued re-check after dispose is a no-op
369
+ while (retained.size > policy.maxRetainedQueries || retainedRowTotal() > policy.maxRetainedRows) {
370
+ // The count budget is checked first, so it is the reason whenever it is the one exceeded (a single
371
+ // over-budget entry that trips both is attributed to the count budget).
372
+ const reason = retained.size > policy.maxRetainedQueries ? "count-budget" : "row-budget";
373
+ let victim: LiveEntry | undefined;
374
+ for (const entry of retained) {
375
+ if (victim === undefined || (entry.lastUsedAt ?? 0) < (victim.lastUsedAt ?? 0)) victim = entry;
376
+ }
377
+ if (victim === undefined) break;
378
+ cancelEviction(victim);
379
+ syncDebug("live-query evicted", { digest: victim.digest, reason });
380
+ void tearDownEntry(victim);
381
+ }
382
+ };
383
+
384
+ const onEvictionTimer = (entry: LiveEntry): void => {
385
+ entry.evictionTimer = undefined;
386
+ // Guard the rejoin race: only tear down if the entry is STILL retained and zero-subscriber. A rejoin
387
+ // cancelled the timer and removed it from `retained`; a stale/cancelled timer is a no-op.
388
+ if (entry.torn || !retained.has(entry) || entry.subscribers.size > 0) return;
389
+ retained.delete(entry);
390
+ syncDebug("live-query evicted", { digest: entry.digest, reason: "expiry" });
391
+ void tearDownEntry(entry);
392
+ };
393
+
394
+ const removeSubscriber = (entry: LiveEntry, token: symbol): Promise<void> => {
395
+ // Idempotent per subscriber: a second unsubscribe for the same token is a no-op (returns any teardown).
396
+ if (!entry.subscribers.has(token)) return entry.teardown ?? Promise.resolve();
397
+ entry.subscribers.delete(token);
398
+ if (entry.subscribers.size > 0) return Promise.resolve(); // another subscriber still holds the registration
399
+ // ── Last subscriber out (ADR-0040 decision 4) ──: the effective keep-alive is the max of the policy
400
+ // default and the CURRENT generation's max hint — order-independent (see `generationKeepAliveMs`).
401
+ const effective = Math.max(policy.defaultKeepAliveMs, entry.generationKeepAliveMs);
402
+ // Never retain under dispose or on a torn entry: the drain in `dispose()` cancelled all timers and cleared
403
+ // `retained`, so retaining here would re-arm a timer the engine close can no longer cancel (a post-close
404
+ // stale timeout, the hang class decision 1 removed).
405
+ if (effective <= 0 || disposed || entry.torn) return tearDownEntry(entry);
406
+ // Retain: keep the registration + diff state live for the grace period (the listener keeps the state
407
+ // current with zero fan-out), start an eviction timer, and enforce the budgets on this new retention.
408
+ entry.lastUsedAt = now();
409
+ retained.add(entry);
410
+ entry.evictionTimer = setTimer(() => onEvictionTimer(entry), effective);
411
+ syncDebug("live-query retained", { digest: entry.digest, keepAliveMs: effective });
412
+ enforceBudgets();
413
+ return Promise.resolve();
414
+ };
415
+
416
+ const refreshEntry = (entry: LiveEntry): Promise<void> => {
417
+ if (entry.torn || !entry.registered) return Promise.resolve();
418
+ // Coalesce PER ENTRY, shared across all subscribers (ADR-0040 plan risk note): concurrent refreshes —
419
+ // e.g. several subscribers finishing hydration together — collapse to ONE underlying `live.refresh()`,
420
+ // whose single diff fans out to everyone. N hydrating subscribers never stack N full reruns. Time the
421
+ // underlying refresh into the entry's diagnostics stats (decision 5).
422
+ if (entry.refreshInFlight === undefined) {
423
+ const startedAt = now();
424
+ entry.refreshInFlight = entry.registered.refresh().finally(() => {
425
+ const ms = now() - startedAt;
426
+ entry.refreshCount++;
427
+ entry.refreshLastMs = ms;
428
+ entry.refreshTotalMs += ms;
429
+ if (ms > entry.refreshMaxMs) entry.refreshMaxMs = ms;
430
+ delete entry.refreshInFlight;
431
+ });
432
+ }
433
+ return entry.refreshInFlight;
434
+ };
435
+
436
+ const subscribe = async (
437
+ spec: LiveQuerySpec,
438
+ subscriber: LiveSubscriber,
439
+ opts?: LiveSubscribeOptions,
440
+ ): Promise<LiveSubscription> => {
441
+ // Reject synchronously once disposal has begun (ADR-0040 decision 1): a subscribe that started after
442
+ // dispose would create a registration whose self-teardown nothing awaits — the exact close race.
443
+ if (disposed) throw new Error("[pgxsinkit] live-query subscribe after dispose — the engine is closing");
444
+ const hint = opts?.keepAliveMs;
445
+ if (hint !== undefined && (!Number.isFinite(hint) || hint < 0)) {
446
+ throw new TypeError(`[pgxsinkit] keepAliveMs must be a finite number >= 0 (got ${hint})`);
447
+ }
448
+ // A hint above the signed-32-bit timer ceiling (see MAX_KEEP_ALIVE_MS) would clamp to ~0 and expire
449
+ // immediately — reject it at the boundary, same as the policy default (ADR-0040 decision 4).
450
+ if (hint !== undefined && hint > MAX_KEEP_ALIVE_MS) {
451
+ throw new TypeError(
452
+ `[pgxsinkit] keepAliveMs must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${hint})`,
453
+ );
454
+ }
455
+ const keepAliveMs = hint ?? 0;
456
+ const scope = opts?.scope;
457
+ // Track this whole call so `dispose()` can drain the post-await join before it settles the teardown set —
458
+ // otherwise a join completing mid-dispose would leak.
459
+ let markSetupDone!: () => void;
460
+ const setupDone = new Promise<void>((resolve) => {
461
+ markSetupDone = resolve;
462
+ });
463
+ setups.add(setupDone);
464
+
465
+ try {
466
+ const { key, digest } = fingerprintLiveQuery(spec.materialSql, spec.params, spec.pkColumns);
467
+
468
+ // Resolve a joinable, non-tearing entry (single-flight over BOTH setup and teardown):
469
+ // - existing & healthy → join it (shared registration);
470
+ // - existing & tearing down → await the teardown, then build a fresh entry (resubscribe-during-teardown);
471
+ // - absent → create it (its `setup` is the shared single-flight registration for concurrent joiners).
472
+ let entry = entries.get(key);
473
+ while (entry && entry.torn) {
474
+ await entry.teardown;
475
+ entry = entries.get(key);
476
+ }
477
+ // Rejoin within grace (ADR-0040 decision 4): a retained zero-subscriber entry is reused verbatim — cancel
478
+ // its eviction NOW (synchronously, before any await) so the timer cannot fire while we join; the snapshot
479
+ // below comes from the still-current diff state, exactly as for an active entry.
480
+ if (entry && retained.has(entry)) cancelEviction(entry);
481
+ // A dedup HIT (ADR-0040 decision 5): we are joining an EXISTING entry (active-join OR retained-rejoin)
482
+ // rather than creating a registration. The first subscriber of a fresh fingerprint is NOT a hit.
483
+ const isDedupHit = entry != null;
484
+ if (!entry) {
485
+ entry = createEntry(key, digest, spec);
486
+ entries.set(key, entry);
487
+ }
488
+ const joined = entry;
489
+ if (isDedupHit) {
490
+ dedupHits++;
491
+ joined.dedupHits++;
492
+ syncDebug("live-query dedup-hit", { digest: joined.digest, dedupHits });
493
+ }
494
+
495
+ // Await the SHARED setup: concurrent subscribers to one fingerprint all await the SAME promise, so there
496
+ // is exactly one registration. A failed setup rejects here for every joined waiter (the entry was already
497
+ // removed by `createEntry`'s catch), so a later subscribe starts clean.
498
+ await joined.setup;
499
+
500
+ // ── JOIN ATOMICALLY (ADR-0040 decision 2) ─────────────────────────────────────────────────────────
501
+ // Snapshot the entry's CURRENT rows from the shared diff state AND register this subscriber in the
502
+ // fan-out map in ONE synchronous section — there MUST be no `await` between the snapshot and the
503
+ // membership write. A listener fire (computeLiveDiff → deliverDiff) is synchronous, so with no yield here
504
+ // no diff can land between the two: the joiner can neither miss a diff (it would be added to the map
505
+ // first) nor be handed one its snapshot already reflects (the snapshot is taken first). The initial rows
506
+ // come from the diff state, NOT a fresh PGlite read — the registration is already current.
507
+ //
508
+ // Keep-alive GENERATION rule (ADR-0040 decision 4): a 0→1 join opens a new generation and RESETS the
509
+ // entry's generation hint to this joiner's; any later join `max`'s it. The last-out effective keep-alive
510
+ // is `max(default, generationKeepAliveMs)`, so it depends only on the SET of hints in a generation, not
511
+ // the order subscribers leave — equivalent subscriber sets behave identically.
512
+ const firstOfGeneration = joined.subscribers.size === 0;
513
+ joined.generationKeepAliveMs = firstOfGeneration
514
+ ? keepAliveMs
515
+ : Math.max(joined.generationKeepAliveMs, keepAliveMs);
516
+ const token = Symbol("live-subscriber");
517
+ const snapshot = [...joined.state!.previous.values()];
518
+ joined.subscribers.set(token, { subscriber, keepAliveMs, scope });
519
+ try {
520
+ subscriber.deliverInitial(snapshot);
521
+ } catch (error) {
522
+ // A failed initial delivery must not leak membership (the caller gets no handle to unsubscribe with).
523
+ // Roll the token back; if that emptied the entry, tear it down NOW — a failed join never retains.
524
+ joined.subscribers.delete(token);
525
+ if (joined.subscribers.size === 0) void tearDownEntry(joined);
526
+ throw error;
527
+ }
528
+ // ────────────────────────────────────────────────────────────────────────────────────────────────────
529
+
530
+ return {
531
+ unsubscribe: () => removeSubscriber(joined, token),
532
+ refresh: () => refreshEntry(joined),
533
+ };
534
+ } finally {
535
+ setups.delete(setupDone);
536
+ markSetupDone();
537
+ }
538
+ };
539
+
540
+ const dispose = async (): Promise<void> => {
541
+ disposed = true;
542
+ // Cancel every retention timer up front so none can fire mid-dispose.
543
+ for (const entry of entries.values()) {
544
+ if (entry.evictionTimer !== undefined) {
545
+ clearTimer(entry.evictionTimer);
546
+ entry.evictionTimer = undefined;
547
+ }
548
+ }
549
+ retained.clear();
550
+ // DRAIN to a stable empty state rather than a single snapshot: an in-flight subscribe (in `setups`) can
551
+ // complete its join AFTER a one-shot teardown pass and leave a registration whose teardown nothing awaits
552
+ // — the close race. `disposed` blocks NEW subscribes (they throw), and every teardown deletes its entry,
553
+ // so this loop terminates once no setup, entry, or teardown remains.
554
+ while (setups.size > 0 || entries.size > 0 || pendingTeardowns.size > 0) {
555
+ await Promise.allSettled([...setups]);
556
+ for (const entry of entries.values()) void tearDownEntry(entry);
557
+ await Promise.allSettled([...pendingTeardowns]);
558
+ }
559
+ };
560
+
561
+ const snapshot = (): LiveQueryDiagnostics[] => {
562
+ const records: LiveQueryDiagnostics[] = [];
563
+ for (const entry of entries.values()) {
564
+ const isRetained = retained.has(entry);
565
+ const scopes = new Set<string | undefined>();
566
+ for (const { scope } of entry.subscribers.values()) scopes.add(scope);
567
+ records.push({
568
+ digest: entry.digest,
569
+ subscriberCount: entry.subscribers.size,
570
+ scopeCount: scopes.size,
571
+ rowCount: entry.state?.previous.size ?? 0,
572
+ retained: isRetained,
573
+ dedupHits: entry.dedupHits,
574
+ createdAt: entry.createdAt,
575
+ setupMs: entry.setupMs ?? null,
576
+ refresh: {
577
+ count: entry.refreshCount,
578
+ lastMs: entry.refreshLastMs ?? null,
579
+ totalMs: entry.refreshTotalMs,
580
+ maxMs: entry.refreshMaxMs,
581
+ },
582
+ lastUsedAt: entry.lastUsedAt ?? null,
583
+ retainedSinceMs: isRetained && entry.lastUsedAt != null ? Math.max(0, now() - entry.lastUsedAt) : null,
584
+ teardownPending: entry.teardownPending,
585
+ });
586
+ }
587
+ return records;
588
+ };
589
+
590
+ return { subscribe, dispose, snapshot };
591
+ }
@@ -232,6 +232,9 @@ export type RpcOp =
232
232
  // Boot observability (ADR-0034): pull the worker engine's most recent completed boot report. Returns the
233
233
  // stored report (or null) regardless of when this tab attached, so a late tab reads a boot predating it.
234
234
  | "bootReport"
235
+ // Live-query diagnostics (ADR-0040 decision 5): pull the worker manager's per-entry snapshot (digests +
236
+ // counts/timings, NEVER SQL/params/rows). Returns [] before any subscription / when the manager is absent.
237
+ | "liveQueryDiagnostics"
235
238
  // Store backup (ADR-0035): the worker runs the live `exportStore` on its owned client; the dump crosses
236
239
  // back as a transferred `ArrayBuffer` ({@link ExportArtefactWire}), rebuilt into a `File` tab-side.
237
240
  | "exportStore"
@@ -299,6 +302,14 @@ export interface SubscribePayload {
299
302
  pkColumns?: string[];
300
303
  /** Lazy relations to activate before the query runs (ADR-0021), forwarded to the worker's `prepareQuery`. */
301
304
  use?: string[];
305
+ /**
306
+ * Per-subscription keep-alive hint (ms) for the worker's live-query manager (ADR-0040 decision 4): how long
307
+ * the shared registration should be retained after this subscription's last consumer leaves, so a matching
308
+ * resubscribe reuses it verbatim. ADDITIVE and backward-compatible both directions — an older tab omits it
309
+ * (the worker falls back to its `liveQueries.defaultKeepAliveMs`), and an older worker ignores it. Absent
310
+ * means "no hint".
311
+ */
312
+ keepAliveMs?: number;
302
313
  }
303
314
 
304
315
  /** worker → tab: the initial ordered snapshot for a subscription. `id` correlates the `subscribe` request. */