@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.
@@ -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
  );
@@ -488,13 +557,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
488
557
  await ready;
489
558
  },
490
559
  stop: async () => {
491
- // Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2).
492
- status.isRunning = false;
493
- for (const queryId of diffHandlers.keys()) postBridgeMessage(port, codec, "unsubscribe", { queryId });
494
- diffHandlers.clear();
495
- postBridgeMessage(port, codec, "detach", null);
496
- port.removeEventListener("message", listener);
497
- port.close?.();
560
+ detachFromWorker();
498
561
  },
499
562
  destroy: notSupported("client.destroy"),
500
563
  dropReadCache: notSupported("client.dropReadCache"),
@@ -573,6 +636,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
573
636
  return rpc<SyncTransactionResult>("transaction", [{ mode, items: collected }]);
574
637
  },
575
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();
576
642
  const groupKey = groupKeyForTable(table);
577
643
  if (groupKey == null || readyGroups.has(groupKey)) return;
578
644
  await new Promise<void>((resolve) => {
@@ -585,6 +651,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
585
651
  // Boot observability (ADR-0034): pull the worker engine's stored boot report over the bridge — returns
586
652
  // the same report regardless of when this tab attached (a late tab reads a boot that predates it).
587
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", []),
588
657
  // Store backup (ADR-0035): the worker runs the live export on its owned client (its lifecycle slot
589
658
  // serialises it against every tab). The dump crosses back as a transferred `ArrayBuffer`; rebuild the
590
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,10 +509,47 @@ 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).
@@ -460,47 +562,73 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
460
562
  // `hydratingTables` field (the tab's `hydrating` source) and the `live-hydrated` block below.
461
563
  const hydratingTables = active.hydratingTablesFor({ sql, ...(use ? { use: use as string[] } : {}) });
462
564
 
463
- const live = active.pglite.live;
464
565
  // Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view
465
566
  // creation (`column "title" specified more than once`) unless every output column has a unique alias.
466
- // 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.
467
569
  const materialSql = wrapLiveQueryForMaterialization(sql, fields);
468
- // Single-column PK → PGlite's incremental machinery (`live.incrementalQuery`): it maintains the ordered
469
- // result via an internal `__after__` linked list and only recomputes changed rows. Composite/keyless →
470
- // `live.query` (full ordered result each fire) and we diff worker-side. Either way the CROSS-WIRE shape
471
- // is a diff computed by `computeLiveDiff` — neither live API emits an ordered, identity-friendly delta.
472
- const registered =
473
- pkColumns && pkColumns.length === 1
474
- ? await live.incrementalQuery<Record<string, unknown>>(materialSql, params as unknown[], pkColumns[0]!)
475
- : await live.query<Record<string, unknown>>(materialSql, params as unknown[]);
476
-
477
- const state = seedLiveDiffState(registered.initialResults.rows, pkColumns);
478
- // Initial snapshot verbatim (not a diff), correlated to the subscribe request so the tab resolves.
479
- postBridgeMessage(
480
- port,
481
- codec,
482
- "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 } : {}) },
483
594
  {
484
- queryId,
485
- rows: registered.initialResults.rows,
486
- // `lazyTables` = the activated lazy relations (observability); `hydratingTables` = the referenced
487
- // groups (eager OR lazy) still catching up, which the tab turns into its `hydrated` promise.
488
- ...(prepared.lazyTables.length > 0 ? { lazyTables: prepared.lazyTables.map(String) } : {}),
489
- ...(hydratingTables.length > 0 ? { hydratingTables: [...hydratingTables] } : {}),
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
+ },
490
615
  },
491
- 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) },
492
620
  );
493
-
494
- const listener = (results: { rows: Record<string, unknown>[] }) => {
495
- // `subscribe` fires only on a real change (never the initial), so every fire yields a genuine delta.
496
- const diff = computeLiveDiff(state, results.rows);
497
- postBridgeMessage(port, codec, "live-diff", { queryId, ...diff });
498
- };
499
- registered.subscribe(listener);
500
- liveSubs.set(queryId, {
501
- port,
502
- unsubscribe: () => void registered.unsubscribe(listener),
503
- });
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 });
504
632
 
505
633
  // Hydration completion travels the SAME port as the diff stream, so ordering is guaranteed: await the
506
634
  // pending groups' catch-up (eager AND lazy), force one refresh of the live query against the caught-up
@@ -511,9 +639,9 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
511
639
  if (hydratingTables.length > 0) {
512
640
  void Promise.all(hydratingTables.map((key) => active.groupReady(key as SyncTableName<TRegistry>)))
513
641
  .then(async () => {
514
- if (!liveSubs.has(queryId)) return; // unsubscribed while catching up
515
- await registered.refresh();
516
- 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;
517
645
  postBridgeMessage(port, codec, "live-hydrated", { queryId });
518
646
  })
519
647
  .catch(() => undefined); // a torn-down engine mid-catch-up must not surface as an unhandled rejection
@@ -689,10 +817,19 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
689
817
  }
690
818
  case "unsubscribe": {
691
819
  const { queryId } = payload as { queryId: string };
692
- 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);
693
824
  if (sub) {
694
- sub.unsubscribe();
695
- 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;
696
833
  }
697
834
  break;
698
835
  }
@@ -710,12 +847,18 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
710
847
 
711
848
  const detachPort = (port: BridgePort) => {
712
849
  ports.delete(port);
713
- for (const [queryId, sub] of liveSubs) {
850
+ for (const [subKey, sub] of liveSubs) {
714
851
  if (sub.port === port) {
715
- sub.unsubscribe();
716
- 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);
717
855
  }
718
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
+ }
719
862
  };
720
863
 
721
864
  const connect = (port: BridgePort) => {
@@ -739,8 +882,18 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
739
882
  connect,
740
883
  whenBooted,
741
884
  close: async () => {
742
- 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.
743
895
  liveSubs.clear();
896
+ await liveManager?.dispose();
744
897
  ports.clear();
745
898
  setSyncDebugSink(undefined);
746
899
  const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);
@@ -0,0 +1,128 @@
1
+ // Canonical fingerprint for a live query (ADR-0040 decisions 2 & 3). Two identical live queries — same
2
+ // POST-WRAP SQL, same bound params, same key mode — must map to ONE PGlite registration; anything that
3
+ // changes what PGlite actually runs (or how the diff is keyed) must map to a DISTINCT one. The fingerprint
4
+ // covers EXECUTION-relevant inputs only: the materialized SQL, a TYPED encoding of the params, and the PK
5
+ // columns (which pick `live.incrementalQuery` vs `live.query` and drive the diff key). `use` is deliberately
6
+ // NOT an input — activation/hydration are per-subscriber pre-steps that never influence the registration
7
+ // (ADR-0040 decision 3), so keying on `use` would only split sharing.
8
+ //
9
+ // The param codec runs over the DECODED (structured-clone) values and TAGS every leaf by type, so a value
10
+ // can never collide with a different-typed value that happens to stringify the same — a `Date` never with
11
+ // its ISO string, a `Uint8Array` never with its hex text, a number never with its numeric string.
12
+
13
+ /** The map key (full canonical string — the dedup identity) plus a short digest for diagnostics (Slice 5). */
14
+ export interface LiveQueryFingerprint {
15
+ /** The exact dedup key: two subscriptions share a registration iff their `key` is identical. */
16
+ key: string;
17
+ /** A short, opaque hash of `key` — for diagnostics/observability only, NEVER used for dedup. */
18
+ digest: string;
19
+ }
20
+
21
+ // Per-call unique token for values we cannot canonicalize (unknown prototypes). A random suffix guarantees
22
+ // two opaque values never collide; the counter guarantees uniqueness even within one millisecond.
23
+ let opaqueCounter = 0;
24
+ function opaqueToken(): string {
25
+ return `${(opaqueCounter++).toString(36)}.${Math.random().toString(36).slice(2)}`;
26
+ }
27
+
28
+ /** Lowercase hex of a byte buffer — portable (no `Buffer`/`btoa`, so it runs in a browser SharedWorker). */
29
+ function toHex(bytes: Uint8Array): string {
30
+ let hex = "";
31
+ for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
32
+ return hex;
33
+ }
34
+
35
+ function isPlainObject(value: object): boolean {
36
+ const proto = Object.getPrototypeOf(value);
37
+ return proto === Object.prototype || proto === null;
38
+ }
39
+
40
+ /** A JSON-safe, type-tagged encoding node: a `[tag, …payload]` tuple whose first element is the type tag. */
41
+ type Encoded = readonly [string, ...unknown[]];
42
+
43
+ /**
44
+ * Encode one decoded value into a type-TAGGED, JSON-SAFE STRUCTURE (a `[tag, …]` tuple), never a flat string.
45
+ * The tag is the first array element, so two values of different types can never collide, and because the
46
+ * whole tuple is serialized ONCE with `JSON.stringify` (below), JSON does all the escaping/framing — a
47
+ * delimiter-bearing string in an array or object can no longer masquerade as extra members (the flat-string
48
+ * codec's collision class, e.g. `[["x,s:y"]]` vs `[["x","y"]]`). Recurses through arrays (order-significant)
49
+ * and plain objects (keys SORTED, so object key order never changes the fingerprint).
50
+ */
51
+ function encodeValue(value: unknown): Encoded {
52
+ if (value === null) return ["z"]; // null
53
+ if (value === undefined) return ["v"]; // undefined (distinct from null)
54
+ switch (typeof value) {
55
+ case "boolean":
56
+ return ["b", value];
57
+ case "number":
58
+ // `String` already canonicalizes signed zero (`String(-0) === "0"`) and renders NaN/±Infinity
59
+ // deterministically; NaN is an ALLOWED value here (two NaN params share a fingerprint), not a bail-out.
60
+ return ["n", String(value)];
61
+ case "bigint":
62
+ return ["i", value.toString()];
63
+ case "string":
64
+ return ["s", value];
65
+ case "object": {
66
+ if (value instanceof Date) return ["d", value.getTime()]; // tagged epoch-ms — never equals an ISO string
67
+ if (value instanceof Uint8Array) return ["x", toHex(value)];
68
+ if (value instanceof ArrayBuffer) return ["x", toHex(new Uint8Array(value))];
69
+ // Honour the view's window: encoding the WHOLE underlying buffer would falsely collide two different
70
+ // views sharing one buffer (a wrong-dedup — the exact hazard this codec exists to prevent).
71
+ if (ArrayBuffer.isView(value)) {
72
+ const view = value as ArrayBufferView;
73
+ return ["x", toHex(new Uint8Array(view.buffer, view.byteOffset, view.byteLength))];
74
+ }
75
+ if (Array.isArray(value)) return ["a", value.map(encodeValue)];
76
+ if (isPlainObject(value)) {
77
+ const record = value as Record<string, unknown>;
78
+ const members = Object.keys(record)
79
+ .sort()
80
+ .map((k) => [k, encodeValue(record[k])] as const);
81
+ return ["o", members];
82
+ }
83
+ // Unknown prototype (a class instance, Map, Set, …): we cannot canonicalize it safely, so tag it
84
+ // `opaque` with a per-call unique token — it will NEVER dedup with anything (including an identical
85
+ // instance) and NEVER falsely collide. Correctness over sharing for the values we don't understand.
86
+ return ["q", opaqueToken()];
87
+ }
88
+ default:
89
+ // function / symbol — not producible by structured clone, but stay safe: treat as opaque.
90
+ return ["q", opaqueToken()];
91
+ }
92
+ }
93
+
94
+ /** FNV-1a (32-bit) → 8 hex chars. Diagnostics only; the FULL `key` string is the dedup identity, never this. */
95
+ function shortDigest(key: string): string {
96
+ let hash = 0x811c9dc5;
97
+ for (let i = 0; i < key.length; i++) {
98
+ hash ^= key.charCodeAt(i);
99
+ hash = Math.imul(hash, 0x01000193);
100
+ }
101
+ return (hash >>> 0).toString(16).padStart(8, "0");
102
+ }
103
+
104
+ /**
105
+ * Fingerprint a live query. `materialSql` is the POST-WRAP SQL (the manager's registration input); `params`
106
+ * are the decoded bound params; `pkColumns` selects the key mode. Returns the full canonical `key` (the dedup
107
+ * identity) and a short `digest` for diagnostics.
108
+ */
109
+ export function fingerprintLiveQuery(
110
+ materialSql: string,
111
+ params: readonly unknown[],
112
+ pkColumns?: readonly string[],
113
+ ): LiveQueryFingerprint {
114
+ // Single-column PK → PGlite `live.incrementalQuery`; composite/keyless → `live.query` + worker-side diff.
115
+ // The mode AND the exact pk columns both matter: same SQL with a different pk column is a different
116
+ // registration (different diff key), and incremental vs full are different PGlite machines.
117
+ const mode = pkColumns && pkColumns.length === 1 ? "inc" : "full";
118
+ // ONE `JSON.stringify` over a fixed-shape object of type-tagged encoding STRUCTURES: the SQL is its own JSON
119
+ // string element (cannot bleed into params), and JSON escaping makes the whole key unambiguous — no manual
120
+ // delimiter framing anywhere, so no delimiter-bearing value can forge extra structure.
121
+ const key = JSON.stringify({
122
+ sql: materialSql,
123
+ params: params.map(encodeValue),
124
+ pk: pkColumns ? [...pkColumns] : null,
125
+ mode,
126
+ });
127
+ return { key, digest: shortDigest(key) };
128
+ }