@pgxsinkit/client 0.1.46 → 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.
@@ -25,6 +25,7 @@ import type { DiagnosticExportOptions, DiagnosticExportResult } from "../export-
25
25
  import type { StoreExportOptions, StoreExportResult } from "../export-store";
26
26
  import {
27
27
  buildRegistryReadHandles,
28
+ type LiveQueryDiagnostics,
28
29
  type LiveRowsSubscription,
29
30
  type MutationBatchItem,
30
31
  type MutationDetail,
@@ -156,6 +157,11 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
156
157
  // `live-hydrated` on the same port as the diff stream, strictly after the catch-up rows — so
157
158
  // resolution here guarantees the rows have already been applied by the materializer.
158
159
  const hydratedPending = new Map<string, () => void>();
160
+ // Set once this tab detaches (explicit `stop()` OR a terminal `pagehide`). Guards NEW operations (they
161
+ // reject at once) and lets `detachFromWorker` settle every outstanding promise — the port listener is torn
162
+ // down on detach, so an unsettled `rpc`/`live-initial` waiter would otherwise hang forever (ADR-0040 P2).
163
+ let detached = false;
164
+ const detachError = () => new Error("[pgxsinkit] client detached — the tab released its worker attachment");
159
165
 
160
166
  // ─── Status + readiness ──────────────────────────────────────────────────────────────────────────
161
167
  const status: SyncRuntimeStatus = { phase: "booting", isRunning: false };
@@ -328,6 +334,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
328
334
 
329
335
  // ─── RPC helper ──────────────────────────────────────────────────────────────────────────────────
330
336
  const rpc = <T>(op: RpcOp, args: unknown[]): Promise<T> => {
337
+ // A detached client has no live port listener, so a worker reply could never resolve this — reject at
338
+ // once rather than register a forever-pending waiter (ADR-0040 P2).
339
+ if (detached) return Promise.reject(detachError());
331
340
  const id = newId("rpc");
332
341
  return new Promise<T>((resolve, reject) => {
333
342
  rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject });
@@ -342,6 +351,59 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
342
351
  attachAckResolve = resolve;
343
352
  attachAckReject = reject;
344
353
  });
354
+
355
+ // ─── Detach (explicit stop AND page teardown) ──────────────────────────────────────────────────────
356
+ // The platform fires NO close event on a SharedWorker port — a tab that simply closes would leave its
357
+ // subscriptions (and their per-write rerun cost) alive in the worker for the worker's whole lifetime
358
+ // (ADR-0040 decision 1; surfaced by the two-tab board e2e). So the same detach runs from `stop()` AND from
359
+ // `pagehide` with `persisted === false` — the terminal signal of a real close/navigate-away. A
360
+ // bfcache-parked page (`persisted === true`) keeps its attachment: its port survives parking and resumes
361
+ // on restore, so detaching there would strand the restored page. Idempotent — pagehide then stop is safe.
362
+ //
363
+ // Installed BEFORE the attach handshake is posted/awaited (ADR-0040 P2): a tab that closes DURING a slow
364
+ // worker boot must still send `detach` and reject the pending attach-ack, rather than leaving the worker
365
+ // holding stale port/token bookkeeping for a page that is already gone. Pre-ack every pending map below is
366
+ // empty, so the settlement loops are no-ops except for the attach-ack rejection.
367
+ const detachFromWorker = (): void => {
368
+ if (detached) return;
369
+ detached = true;
370
+ status.isRunning = false;
371
+ // Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2).
372
+ for (const queryId of diffHandlers.keys()) postBridgeMessage(port, codec, "unsubscribe", { queryId });
373
+ diffHandlers.clear();
374
+ postBridgeMessage(port, codec, "detach", null);
375
+ // Settle every tab-side promise now the port listener is about to go (ADR-0040 P2) — otherwise an
376
+ // operation still awaiting a worker reply hangs forever. RPCs and initial subscribes promise DATA, so
377
+ // REJECT them (fabricating a value is worse than a clear failure); hydration and group-ready waiters are
378
+ // DONENESS signals, so RESOLVE them (their awaiters are void-chained hook code that should settle, not
379
+ // throw). The attach-ack is rejected too so a detach DURING boot rejects `attachSyncClient` (a no-op once
380
+ // it has already settled).
381
+ attachAckReject?.(detachError());
382
+ for (const pending of rpcPending.values()) pending.reject(detachError());
383
+ rpcPending.clear();
384
+ for (const pending of initialPending.values()) pending.reject(detachError());
385
+ initialPending.clear();
386
+ for (const resolve of hydratedPending.values()) resolve();
387
+ hydratedPending.clear();
388
+ for (const waiters of groupWaiters.values()) for (const resolve of waiters) resolve();
389
+ groupWaiters.clear();
390
+ if (pagehideListener) pageWindow?.removeEventListener("pagehide", pagehideListener);
391
+ port.removeEventListener("message", listener);
392
+ port.close?.();
393
+ };
394
+ // Structural window guard — this file compiles without the DOM lib (it also runs under tests/workers).
395
+ interface PageLifecycleWindowLike {
396
+ addEventListener(type: "pagehide", handler: (event: { persisted: boolean }) => void): void;
397
+ removeEventListener(type: "pagehide", handler: (event: { persisted: boolean }) => void): void;
398
+ }
399
+ const pageWindow = (globalThis as { window?: PageLifecycleWindowLike }).window;
400
+ const pagehideListener = pageWindow
401
+ ? (event: { persisted: boolean }) => {
402
+ if (!event.persisted) detachFromWorker();
403
+ }
404
+ : undefined;
405
+ if (pagehideListener) pageWindow?.addEventListener("pagehide", pagehideListener);
406
+
345
407
  const initialToken = options.getToken ? await options.getToken() : null;
346
408
  // The testing memory-backend override travels as an explicit wire field, not the symbol marker — a symbol
347
409
  // does not survive `postMessage` structured clone (ADR-0036). Read it off the spread helper's options here.
@@ -376,9 +438,11 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
376
438
  try {
377
439
  await attachAck;
378
440
  } catch (error) {
379
- // The worker's engine boot failed (ADR-0032 FIX 1): tear down this tab's listener so no port handler
380
- // leaks, then let the boot error propagate out of `attachSyncClient`.
381
- port.removeEventListener("message", listener);
441
+ // The worker's engine boot failed (ADR-0032 FIX 1) OR a terminal pagehide rejected the ack mid-boot
442
+ // (ADR-0040 P2): run the full detach so BOTH the message listener AND the pagehide listener are removed
443
+ // (no port/window handler leaks), then let the error propagate out of `attachSyncClient`. Idempotent, so
444
+ // a pagehide that already detached makes this a cheap no-op.
445
+ detachFromWorker();
382
446
  throw error;
383
447
  }
384
448
  status.isRunning = true;
@@ -388,6 +452,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
388
452
  input: SubscribeLiveRowsInput,
389
453
  onRows: (rows: TRow[]) => void,
390
454
  ): Promise<LiveRowsSubscription<TRow>> => {
455
+ // A detached client has no port listener, so `live-initial` could never arrive — reject at once rather
456
+ // than register a forever-pending initial waiter (ADR-0040 P2).
457
+ if (detached) throw detachError();
391
458
  const queryId = newId("live");
392
459
  const id = newId("sub");
393
460
  const materializer = new LiveRowsMaterializer<TRow>(input.pkColumns);
@@ -409,6 +476,8 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
409
476
  ...(input.fields ? { fields: [...input.fields] } : {}),
410
477
  ...(input.pkColumns ? { pkColumns: [...input.pkColumns] } : {}),
411
478
  ...(input.use ? { use: [...input.use] } : {}),
479
+ // Per-subscription keep-alive hint (ADR-0040 decision 4) forwarded to the worker's manager.
480
+ ...(input.keepAliveMs != null ? { keepAliveMs: input.keepAliveMs } : {}),
412
481
  },
413
482
  id,
414
483
  );
@@ -420,11 +489,13 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
420
489
  throw error;
421
490
  }
422
491
  const initialRows = materializer.seed(initial.rows as TRow[]);
423
- // Lazy relations present → build the `hydrated` promise the worker settles via `live-hydrated`
424
- // (posted after the catch-up rows on the same port — rows-before-signal). Resolved on unsubscribe
425
- // too, so an abandoned subscription never leaves a forever-pending promise behind.
492
+ // Pending groups present → build the `hydrated` promise the worker settles via `live-hydrated` (posted
493
+ // after the catch-up rows on the same port — rows-before-signal). A missing/empty `hydratingTables`
494
+ // means every referenced group (eager OR lazy) was already ready (steady state) or sync is disabled:
495
+ // no hydration is pending, so no promise. Resolved on unsubscribe too, so an abandoned subscription
496
+ // never leaves a forever-pending promise behind.
426
497
  let hydrated: Promise<void> | undefined;
427
- if (initial.lazyTables) {
498
+ if (initial.hydratingTables && initial.hydratingTables.length > 0) {
428
499
  hydrated = new Promise<void>((resolve) => {
429
500
  hydratedPending.set(queryId, resolve);
430
501
  });
@@ -437,8 +508,8 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
437
508
  hydratedPending.delete(queryId);
438
509
  postBridgeMessage(port, codec, "unsubscribe", { queryId });
439
510
  },
440
- // The lazy relations the worker's guard activated for this query — streams started, catch-up
441
- // possibly still in flight; `hydrated` resolves once the caught-up rows have been delivered.
511
+ // The lazy relations the worker's guard activated for this query (observability). `hydrated` — driven
512
+ // by `hydratingTables`, not this — resolves once every pending group's caught-up rows are delivered.
442
513
  ...(initial.lazyTables ? { lazyTables: initial.lazyTables } : {}),
443
514
  ...(hydrated ? { hydrated } : {}),
444
515
  };
@@ -486,13 +557,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
486
557
  await ready;
487
558
  },
488
559
  stop: async () => {
489
- // Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2).
490
- status.isRunning = false;
491
- for (const queryId of diffHandlers.keys()) postBridgeMessage(port, codec, "unsubscribe", { queryId });
492
- diffHandlers.clear();
493
- postBridgeMessage(port, codec, "detach", null);
494
- port.removeEventListener("message", listener);
495
- port.close?.();
560
+ detachFromWorker();
496
561
  },
497
562
  destroy: notSupported("client.destroy"),
498
563
  dropReadCache: notSupported("client.dropReadCache"),
@@ -532,6 +597,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
532
597
  // `prepareQuery` is a no-op — the live-rows subscription is already guarded worker-side (ADR-0021).
533
598
  // Empty `lazyTables`: the real scan's keys travel back on the subscription itself (`live-initial`).
534
599
  prepareQuery: async () => ({ lazyTables: [] }),
600
+ // The worker computes the pending hydrating tables inside its `subscribe` handler (on its owned client)
601
+ // and reports them back on `live-initial` (`hydratingTables`), so the tab-side seam is a no-op here.
602
+ hydratingTablesFor: () => [],
535
603
  transaction: async ({ mode }: { mode: WriteMode }, run) => {
536
604
  // Collect the unit's mutations tab-side (the run callback cannot cross the wire), then RPC the
537
605
  // serialized items + mode; the worker replays them into a real `client.transaction` (matching acks).
@@ -568,6 +636,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
568
636
  return rpc<SyncTransactionResult>("transaction", [{ mode, items: collected }]);
569
637
  },
570
638
  groupReady: async (table) => {
639
+ // A detached client will never receive further `groupReady`/status edges — reject at once rather than
640
+ // register a waiter that detach already drained (ADR-0040 P2).
641
+ if (detached) throw detachError();
571
642
  const groupKey = groupKeyForTable(table);
572
643
  if (groupKey == null || readyGroups.has(groupKey)) return;
573
644
  await new Promise<void>((resolve) => {
@@ -580,6 +651,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
580
651
  // Boot observability (ADR-0034): pull the worker engine's stored boot report over the bridge — returns
581
652
  // the same report regardless of when this tab attached (a late tab reads a boot that predates it).
582
653
  bootReport: () => rpc<BootReport | null>("bootReport", []),
654
+ // Live-query diagnostics (ADR-0040 decision 5): pull the worker manager's per-entry snapshot over the
655
+ // bridge (digests + counts only — plain objects that structured-clone across the wire).
656
+ liveQueryDiagnostics: () => rpc<LiveQueryDiagnostics[]>("liveQueryDiagnostics", []),
583
657
  // Store backup (ADR-0035): the worker runs the live export on its owned client (its lifecycle slot
584
658
  // serialises it against every tab). The dump crosses back as a transferred `ArrayBuffer`; rebuild the
585
659
  // `File` tab-side from the wire form — NOT in the notSupported set (unlike the local `pglite` reads).
@@ -26,7 +26,12 @@ import {
26
26
  import { wrapLiveQueryForMaterialization } from "../live-rows-sql";
27
27
  import type { LocalStoreVersionEvent } from "../local-store";
28
28
  import { readTestStoreMarker, TEST_STORE_BACKEND, type TestStoreMarker } from "../store-path";
29
- import { computeLiveDiff, seedLiveDiffState } from "./live-diff";
29
+ import {
30
+ createLiveQueryManager,
31
+ type LiveQueryManager,
32
+ type LiveSubscription,
33
+ validateLiveQueryPolicy,
34
+ } from "./live-query-manager";
30
35
  import {
31
36
  type AttachPayload,
32
37
  type BridgeCodec,
@@ -103,6 +108,23 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
103
108
  precreatedPglite?: CreateSyncClientOptions<TRegistry>["precreatedPglite"];
104
109
  /** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */
105
110
  pgliteInstance?: CreateSyncClientOptions<TRegistry>["pgliteInstance"];
111
+ /**
112
+ * Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last
113
+ * subscriber leaves, a nonzero effective keep-alive retains its PGlite registration + diff state for a grace
114
+ * period so a matching resubscribe (e.g. a re-mounted route across tabs) reuses it verbatim — no ~400 ms
115
+ * re-materialization. Bounded by explicit budgets; DEFAULTS OFF (`defaultKeepAliveMs: 0` → tear a query
116
+ * down the instant its last consumer leaves, byte-identical to the pre-keep-alive behaviour). Standing
117
+ * argument for the 0 default: a retained entry STILL pays a full SQL rerun + diff on every dependent write —
118
+ * PGlite live queries cannot be paused — so retention only pays off for a genuinely hot, re-mounted query.
119
+ */
120
+ liveQueries?: {
121
+ /** Baseline retention (ms) for a zero-subscriber entry; floored by each subscriber's own hint. Default 0. */
122
+ defaultKeepAliveMs?: number;
123
+ /** Max simultaneously-retained (zero-subscriber) entries — LRU-evicted past this. Default 16. */
124
+ maxRetainedQueries?: number;
125
+ /** Max total rows across all retained entries — LRU-evicted past this. Default 50_000. */
126
+ maxRetainedRows?: number;
127
+ };
106
128
  }
107
129
 
108
130
  /** The worker-side host: attach ports, await the boot, and (for tests) tear down. */
@@ -116,7 +138,9 @@ export interface SyncWorkerHost<TRegistry extends SyncTableRegistry> {
116
138
  }
117
139
 
118
140
  interface LiveSub {
119
- unsubscribe: () => void;
141
+ // The manager-owned handle: `unsubscribe()` (awaited teardown, tracked inside the manager — ADR-0040
142
+ // decision 1) and a coalesced `refresh()` the hydration chain drives.
143
+ subscription: LiveSubscription;
120
144
  port: BridgePort;
121
145
  }
122
146
 
@@ -127,6 +151,8 @@ interface LiveSub {
127
151
  export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
128
152
  options: DefineSyncWorkerOptions<TRegistry>,
129
153
  ): SyncWorkerHost<TRegistry> {
154
+ // Fail at construction, not first subscribe, on a bad keep-alive policy (ADR-0040 decision 4 — bounded).
155
+ validateLiveQueryPolicy(options.liveQueries);
130
156
  const codec = options.codec ?? identityCodec;
131
157
  const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;
132
158
  const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;
@@ -142,6 +168,40 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
142
168
 
143
169
  const ports = new Set<BridgePort>();
144
170
  const liveSubs = new Map<string, LiveSub>();
171
+ // The live-query lifecycle (PGlite registration, diff listener, and the ADR-0040 decision-1 awaited-teardown
172
+ // set) lives in a single manager owned per engine. Created lazily on first subscribe because it needs the
173
+ // booted client's `live` namespace (`active.pglite.live`); the worker never restarts its engine in place
174
+ // (ADR-0040 decision 7), so one manager serves the host's whole lifetime. `close()` disposes it.
175
+ let liveManager: LiveQueryManager | null = null;
176
+ const ensureLiveManager = (active: SyncClient<TRegistry>): LiveQueryManager =>
177
+ (liveManager ??= createLiveQueryManager({
178
+ live: active.pglite.live,
179
+ ...(options.liveQueries ? { policy: options.liveQueries } : {}),
180
+ }));
181
+ // Subscribes that have entered `handleSubscribe` but not yet reached `liveSubs.set` (they are mid-await on
182
+ // prepareQuery / hydration / manager setup). Registered SYNCHRONOUSLY at entry, keyed by `queryId`, so an
183
+ // `unsubscribe`/`detach` arriving during those awaits can mark the pending subscribe CANCELLED — otherwise
184
+ // it would finish and store a subscription for an already-gone port, escaping the awaited-teardown boundary
185
+ // (ADR-0040 decision 1). Removed in `handleSubscribe`'s finally.
186
+ const pendingSubscribes = new Map<string, { port: BridgePort; cancelled: boolean }>();
187
+ // Host shutdown state (ADR-0040 decision 1 — the pending-before-manager close race). `close()` flips
188
+ // `closing` and awaits every in-flight `handleSubscribe` task BEFORE disposing the manager, so a subscribe
189
+ // still mid-await when close begins can neither create a registration afterwards (it early-bails on
190
+ // `closing`) nor escape the awaited-teardown boundary. `inFlightSubscribes` holds each whole-call task.
191
+ let closing = false;
192
+ const inFlightSubscribes = new Set<Promise<void>>();
193
+ // One stable, opaque diagnostics scope per bridge port (ADR-0040 decision 5) — so a snapshot's `scopeCount`
194
+ // reads as the distinct-tab count. Never part of the fingerprint; a lazy per-port counter.
195
+ const portScopes = new WeakMap<BridgePort, string>();
196
+ let nextScopeId = 0;
197
+ const scopeForPort = (port: BridgePort): string => {
198
+ let scope = portScopes.get(port);
199
+ if (scope === undefined) {
200
+ scope = `port-${nextScopeId++}`;
201
+ portScopes.set(port, scope);
202
+ }
203
+ return scope;
204
+ };
145
205
 
146
206
  // ─── Pre-spawned (schemaless) store — the spare flow (ADR-0032 decision 5) ────────────────────────
147
207
  // A `provision` mints the raw PGlite (initdb only) and holds it idle here; the first real `attach`
@@ -410,6 +470,11 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
410
470
  // Boot observability (ADR-0034): the worker engine's stored report (or null). Pull, so a late tab
411
471
  // reads a boot predating it; the report structured-clones across the bridge as a plain object.
412
472
  return active.bootReport();
473
+ case "liveQueryDiagnostics":
474
+ // Live-query diagnostics (ADR-0040 decision 5): the manager lives in THIS host closure (not on
475
+ // `active`), so read it directly. Plain-object records (digests + counts only) structured-clone
476
+ // across the bridge; `[]` when nothing has subscribed yet (the manager is created lazily).
477
+ return liveManager?.snapshot() ?? [];
413
478
  case "exportStore": {
414
479
  // Store backup (ADR-0035): run the live export on the worker's OWN client (its lifecycle slot
415
480
  // serialises it against every tab's export). A `File` cannot cross the bridge as a transferable, so
@@ -444,67 +509,139 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
444
509
  };
445
510
 
446
511
  // ─── Live-query bridge (ADR-0032 S2 §4) ──────────────────────────────────────────────────────────
447
- const handleSubscribe = async (port: BridgePort, id: string | undefined, payload: SubscribePayload) => {
512
+ // `queryId`s are minted by a PER-TAB counter (`live-1`, `live-2`, …), so two tabs collide on the bare id —
513
+ // every worker-side bookkeeping key MUST be port-scoped or one tab's unsubscribe/close tears down another
514
+ // tab's identically-numbered subscription (latent since ADR-0032; exposed the moment tab close started
515
+ // sending unsubscribes — the two-tab board e2e's scenario (c)). The wire keeps the bare `queryId` (the
516
+ // port disambiguates); only the worker's maps compose it with the port's scope.
517
+ const subKeyFor = (port: BridgePort, queryId: string): string => `${scopeForPort(port)}:${queryId}`;
518
+
519
+ const handleSubscribe = (port: BridgePort, id: string | undefined, payload: SubscribePayload): Promise<void> => {
520
+ // Register the in-flight subscribe SYNCHRONOUSLY (before the first await) so an `unsubscribe`/`detach`/
521
+ // `close` arriving mid-await can mark it cancelled (ADR-0040 decision 1 — no subscription escapes teardown).
522
+ const pending = { port, cancelled: false };
523
+ const subKey = subKeyFor(port, payload.queryId);
524
+ pendingSubscribes.set(subKey, pending);
525
+ // Track the WHOLE call so `close()` awaits it before disposing the manager: the task is added to
526
+ // `inFlightSubscribes` synchronously here and removed in its own finally, so close can never observe an
527
+ // empty set while a subscribe is still awaiting prepareQuery / hydration / manager setup.
528
+ // `let task!` (not `const`): the finally references `task` to remove itself, and it only runs after the
529
+ // first await — by then the assignment below has completed, so the definite-assignment assertion is safe.
530
+ let task!: Promise<void>;
531
+ task = (async () => {
532
+ try {
533
+ await handleSubscribeInner(port, id, payload, pending, subKey);
534
+ } finally {
535
+ pendingSubscribes.delete(subKey);
536
+ inFlightSubscribes.delete(task);
537
+ }
538
+ })();
539
+ inFlightSubscribes.add(task);
540
+ return task;
541
+ };
542
+
543
+ const handleSubscribeInner = async (
544
+ port: BridgePort,
545
+ id: string | undefined,
546
+ payload: SubscribePayload,
547
+ pending: { port: BridgePort; cancelled: boolean },
548
+ subKey: string,
549
+ ) => {
448
550
  const active = client ?? (await bootPromise);
449
551
  if (!active) throw new Error("subscribe before attach");
450
- const { queryId, sql, params, pkColumns, use, fields } = payload;
552
+ const { queryId, sql, params, pkColumns, use, fields, keepAliveMs } = payload;
451
553
  // Activate any lazy relations the query reads BEFORE registering the live query (ADR-0021) — the worker
452
554
  // owns the real client, so its `prepareQuery` does the real work; the tab's `prepareQuery` is a no-op.
453
555
  // Scan the ORIGINAL sql (the wrap only adds an outer `SELECT * FROM (...)`; table refs are inside).
454
556
  // The activated keys travel back on the initial snapshot: activation is stream-start, not catch-up,
455
557
  // so the tab needs them to await `groupReady` (its `hydrating` signal) without blocking this register.
456
558
  const prepared = await active.prepareQuery({ sql, ...(use ? { use: use as SyncTableName<TRegistry>[] } : {}) });
559
+ // Hydration spans EVERY referenced consistency group (eager AND lazy), computed on the real client the
560
+ // worker owns: the referenced tables whose group is not yet caught up at subscribe time. Empty (steady
561
+ // state / sync disabled) → no `hydrated` gating at all; otherwise it drives both the `live-initial`
562
+ // `hydratingTables` field (the tab's `hydrating` source) and the `live-hydrated` block below.
563
+ const hydratingTables = active.hydratingTablesFor({ sql, ...(use ? { use: use as string[] } : {}) });
457
564
 
458
- const live = active.pglite.live;
459
565
  // Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view
460
566
  // creation (`column "title" specified more than once`) unless every output column has a unique alias.
461
- // No `fields` → SQL unchanged (backward-compatible name-keyed rows; the aliased path keys by alias).
567
+ // No `fields` → SQL unchanged (backward-compatible name-keyed rows; the aliased path keys by alias). The
568
+ // wrap stays caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL as its query input.
462
569
  const materialSql = wrapLiveQueryForMaterialization(sql, fields);
463
- // Single-column PK → PGlite's incremental machinery (`live.incrementalQuery`): it maintains the ordered
464
- // result via an internal `__after__` linked list and only recomputes changed rows. Composite/keyless →
465
- // `live.query` (full ordered result each fire) and we diff worker-side. Either way the CROSS-WIRE shape
466
- // is a diff computed by `computeLiveDiff` — neither live API emits an ordered, identity-friendly delta.
467
- const registered =
468
- pkColumns && pkColumns.length === 1
469
- ? await live.incrementalQuery<Record<string, unknown>>(materialSql, params as unknown[], pkColumns[0]!)
470
- : await live.query<Record<string, unknown>>(materialSql, params as unknown[]);
471
-
472
- const state = seedLiveDiffState(registered.initialResults.rows, pkColumns);
473
- // Initial snapshot verbatim (not a diff), correlated to the subscribe request so the tab resolves.
474
- postBridgeMessage(
475
- port,
476
- codec,
477
- "live-initial",
570
+ // Early bail BEFORE the manager is created (ADR-0040 decision 1 — the pending-before-manager close race):
571
+ // if the host is closing, this subscribe was cancelled, or its port detached WHILE we awaited prepareQuery
572
+ // / hydration, do NOT call `ensureLiveManager` — creating a registration now would race the engine close
573
+ // with a fire-and-forget teardown nothing awaits (a manager born after `close()` disposed is never
574
+ // disposed). Post the rpc error for this subscribe id so a still-live tab's `subscribeLiveRows` rejects
575
+ // instead of hanging, and return without touching the manager. The post-setup check below still catches a
576
+ // cancellation that lands DURING manager setup (after the manager already exists).
577
+ if (closing || pending.cancelled || !ports.has(port)) {
578
+ postBridgeMessage(
579
+ port,
580
+ codec,
581
+ "rpc-result",
582
+ {
583
+ ok: false,
584
+ error: { message: "[pgxsinkit] subscribe cancelled — the worker is closing or the port detached" },
585
+ },
586
+ id,
587
+ );
588
+ return;
589
+ }
590
+ // The manager owns registration + diff + teardown; the bridge posting (per-`queryId`, with the caller-owned
591
+ // `lazyTables`/`hydratingTables` observability fields) stays here — those are per-subscriber pre-steps.
592
+ const subscription = await ensureLiveManager(active).subscribe(
593
+ { materialSql, params: params as unknown[], ...(pkColumns ? { pkColumns } : {}) },
478
594
  {
479
- queryId,
480
- rows: registered.initialResults.rows,
481
- ...(prepared.lazyTables.length > 0 ? { lazyTables: prepared.lazyTables.map(String) } : {}),
595
+ deliverInitial: (rows) => {
596
+ // Initial snapshot verbatim (not a diff), correlated to the subscribe request so the tab resolves.
597
+ postBridgeMessage(
598
+ port,
599
+ codec,
600
+ "live-initial",
601
+ {
602
+ queryId,
603
+ rows,
604
+ // `lazyTables` = the activated lazy relations (observability); `hydratingTables` = the referenced
605
+ // groups (eager OR lazy) still catching up, which the tab turns into its `hydrated` promise.
606
+ ...(prepared.lazyTables.length > 0 ? { lazyTables: prepared.lazyTables.map(String) } : {}),
607
+ ...(hydratingTables.length > 0 ? { hydratingTables: [...hydratingTables] } : {}),
608
+ },
609
+ id,
610
+ );
611
+ },
612
+ deliverDiff: (diff) => {
613
+ postBridgeMessage(port, codec, "live-diff", { queryId, ...diff });
614
+ },
482
615
  },
483
- id,
616
+ // The per-subscriber keep-alive hint (ADR-0040 decision 4) — kept OUT of the spec so it never touches
617
+ // the fingerprint (decision 3). Absent → no hint (the manager falls back to its policy default). The
618
+ // `scope` is one stable id per port (decision 5 diagnostics), also fingerprint-excluded.
619
+ { ...(keepAliveMs != null ? { keepAliveMs } : {}), scope: scopeForPort(port) },
484
620
  );
485
-
486
- const listener = (results: { rows: Record<string, unknown>[] }) => {
487
- // `subscribe` fires only on a real change (never the initial), so every fire yields a genuine delta.
488
- const diff = computeLiveDiff(state, results.rows);
489
- postBridgeMessage(port, codec, "live-diff", { queryId, ...diff });
490
- };
491
- registered.subscribe(listener);
492
- liveSubs.set(queryId, {
493
- port,
494
- unsubscribe: () => void registered.unsubscribe(listener),
495
- });
621
+ // The port was detached, or this query was unsubscribed, WHILE we awaited (prepareQuery / hydration /
622
+ // manager setup all yield). Neither cleanup path found a `liveSubs` entry — so undo the just-created
623
+ // subscription here and DO NOT record it, else it would outlive its port (ADR-0040 decision 1). A
624
+ // `live-initial` may already have been posted to a dead port; that is harmless (a closed port's
625
+ // postMessage is a no-op) and not worth preventing. `closing` is included so a `close()` that began DURING
626
+ // manager setup still unwinds this just-created subscription rather than recording it.
627
+ if (closing || pending.cancelled || !ports.has(port)) {
628
+ void subscription.unsubscribe();
629
+ return;
630
+ }
631
+ liveSubs.set(subKey, { port, subscription });
496
632
 
497
633
  // Hydration completion travels the SAME port as the diff stream, so ordering is guaranteed: await the
498
- // lazy groups' catch-up, force one refresh of the live query against the caught-up store (its listener
499
- // posts the rows as a live-diff, synchronously inside the refresh), THEN post `live-hydrated`. The tab
500
- // therefore always has the caught-up rows before its `hydrated` resolves — a readiness signal on a side
501
- // channel (e.g. the `groupReady` broadcast) can beat the rows and flash a false "empty" state.
502
- if (prepared.lazyTables.length > 0) {
503
- void Promise.all(prepared.lazyTables.map((key) => active.groupReady(key)))
634
+ // pending groups' catch-up (eager AND lazy), force one refresh of the live query against the caught-up
635
+ // store (its listener posts the rows as a live-diff, synchronously inside the refresh), THEN post
636
+ // `live-hydrated`. The tab therefore always has the caught-up rows before its `hydrated` resolves — a
637
+ // readiness signal on a side channel (e.g. the `groupReady` broadcast) can beat the rows and flash a
638
+ // false "empty" state. Skipped entirely when nothing is pending (steady state / sync disabled).
639
+ if (hydratingTables.length > 0) {
640
+ void Promise.all(hydratingTables.map((key) => active.groupReady(key as SyncTableName<TRegistry>)))
504
641
  .then(async () => {
505
- if (!liveSubs.has(queryId)) return; // unsubscribed while catching up
506
- await registered.refresh();
507
- if (!liveSubs.has(queryId)) return;
642
+ if (!liveSubs.has(subKey)) return; // unsubscribed while catching up
643
+ await subscription.refresh();
644
+ if (!liveSubs.has(subKey)) return;
508
645
  postBridgeMessage(port, codec, "live-hydrated", { queryId });
509
646
  })
510
647
  .catch(() => undefined); // a torn-down engine mid-catch-up must not surface as an unhandled rejection
@@ -680,10 +817,19 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
680
817
  }
681
818
  case "unsubscribe": {
682
819
  const { queryId } = payload as { queryId: string };
683
- const sub = liveSubs.get(queryId);
820
+ // Compose the SAME port-scoped key the subscribe used — a bare queryId lookup would collide with
821
+ // another tab's identically-numbered subscription (see `subKeyFor`).
822
+ const subKey = subKeyFor(port, queryId);
823
+ const sub = liveSubs.get(subKey);
684
824
  if (sub) {
685
- sub.unsubscribe();
686
- liveSubs.delete(queryId);
825
+ // Non-blocking for the caller: the manager retains the teardown promise so `close()` awaits it.
826
+ void sub.subscription.unsubscribe();
827
+ liveSubs.delete(subKey);
828
+ } else {
829
+ // No live entry yet → the subscribe is still mid-await. Mark it cancelled so `handleSubscribe`
830
+ // tears down the subscription it is about to create instead of recording it (ADR-0040 decision 1).
831
+ const inFlight = pendingSubscribes.get(subKey);
832
+ if (inFlight) inFlight.cancelled = true;
687
833
  }
688
834
  break;
689
835
  }
@@ -701,12 +847,18 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
701
847
 
702
848
  const detachPort = (port: BridgePort) => {
703
849
  ports.delete(port);
704
- for (const [queryId, sub] of liveSubs) {
850
+ for (const [subKey, sub] of liveSubs) {
705
851
  if (sub.port === port) {
706
- sub.unsubscribe();
707
- liveSubs.delete(queryId);
852
+ // Non-blocking: the manager retains the teardown promise so `close()` awaits it (ADR-0040 decision 1).
853
+ void sub.subscription.unsubscribe();
854
+ liveSubs.delete(subKey);
708
855
  }
709
856
  }
857
+ // Also cancel every subscribe for this port still mid-await — its `handleSubscribe` will tear down the
858
+ // subscription it is about to create rather than record it for a detached port (ADR-0040 decision 1).
859
+ for (const pending of pendingSubscribes.values()) {
860
+ if (pending.port === port) pending.cancelled = true;
861
+ }
710
862
  };
711
863
 
712
864
  const connect = (port: BridgePort) => {
@@ -730,8 +882,18 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
730
882
  connect,
731
883
  whenBooted,
732
884
  close: async () => {
733
- for (const sub of liveSubs.values()) sub.unsubscribe();
885
+ // Quiesce pending subscribes FIRST (ADR-0040 decision 1 — the pending-before-manager race): flip
886
+ // `closing`, mark every mid-await subscribe cancelled, and await every in-flight `handleSubscribe` task.
887
+ // This guarantees the manager exists (if any subscribe created one) BEFORE `dispose()` runs, and that no
888
+ // subscribe can create a registration afterwards — each resumes into the `closing` early-bail instead.
889
+ closing = true;
890
+ for (const pending of pendingSubscribes.values()) pending.cancelled = true;
891
+ await Promise.allSettled([...inFlightSubscribes]);
892
+ // Dispose the manager BEFORE `active.stop()` (ADR-0040 decision 1): it tears down every remaining live
893
+ // registration and awaits ALL teardowns, so no fire-and-forget unsubscribe is still in flight when the
894
+ // engine closes (the close-vs-unsubscribe hang). No-op when nothing ever subscribed.
734
895
  liveSubs.clear();
896
+ await liveManager?.dispose();
735
897
  ports.clear();
736
898
  setSyncDebugSink(undefined);
737
899
  const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);