@pgxsinkit/client 0.1.48 → 0.1.50

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.
Files changed (40) hide show
  1. package/dist/boot-report.d.ts +76 -0
  2. package/dist/boot-report.d.ts.map +1 -1
  3. package/dist/index.d.ts +84 -3
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1549 -333
  6. package/dist/index.js.map +15 -12
  7. package/dist/local-store.d.ts +58 -0
  8. package/dist/local-store.d.ts.map +1 -1
  9. package/dist/local-tables.d.ts +340 -0
  10. package/dist/local-tables.d.ts.map +1 -1
  11. package/dist/mutation.d.ts +36 -0
  12. package/dist/mutation.d.ts.map +1 -1
  13. package/dist/mutations-api.d.ts +82 -0
  14. package/dist/mutations-api.d.ts.map +1 -0
  15. package/dist/schema.d.ts +62 -0
  16. package/dist/schema.d.ts.map +1 -1
  17. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  18. package/dist/worker/define-sync-worker.d.ts +17 -0
  19. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  20. package/dist/worker/live-query-fingerprint.d.ts +14 -0
  21. package/dist/worker/live-query-fingerprint.d.ts.map +1 -0
  22. package/dist/worker/live-query-manager.d.ts +130 -0
  23. package/dist/worker/live-query-manager.d.ts.map +1 -0
  24. package/dist/worker/protocol.d.ts +53 -2
  25. package/dist/worker/protocol.d.ts.map +1 -1
  26. package/package.json +2 -2
  27. package/skills/core/SKILL.md +1 -1
  28. package/skills/operating/SKILL.md +29 -1
  29. package/src/boot-report.ts +108 -0
  30. package/src/index.ts +648 -152
  31. package/src/local-store.ts +150 -3
  32. package/src/local-tables.ts +49 -1
  33. package/src/mutation.ts +256 -15
  34. package/src/mutations-api.ts +310 -0
  35. package/src/schema.ts +406 -193
  36. package/src/worker/attach-sync-client.ts +193 -15
  37. package/src/worker/define-sync-worker.ts +267 -53
  38. package/src/worker/live-query-fingerprint.ts +128 -0
  39. package/src/worker/live-query-manager.ts +591 -0
  40. package/src/worker/protocol.ts +49 -1
@@ -26,9 +26,15 @@ 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,
37
+ type BootMilestone,
32
38
  type BridgeCodec,
33
39
  type BridgeEnvelope,
34
40
  type BridgeEvent,
@@ -103,6 +109,23 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
103
109
  precreatedPglite?: CreateSyncClientOptions<TRegistry>["precreatedPglite"];
104
110
  /** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */
105
111
  pgliteInstance?: CreateSyncClientOptions<TRegistry>["pgliteInstance"];
112
+ /**
113
+ * Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last
114
+ * subscriber leaves, a nonzero effective keep-alive retains its PGlite registration + diff state for a grace
115
+ * period so a matching resubscribe (e.g. a re-mounted route across tabs) reuses it verbatim — no ~400 ms
116
+ * re-materialization. Bounded by explicit budgets; DEFAULTS OFF (`defaultKeepAliveMs: 0` → tear a query
117
+ * down the instant its last consumer leaves, byte-identical to the pre-keep-alive behaviour). Standing
118
+ * argument for the 0 default: a retained entry STILL pays a full SQL rerun + diff on every dependent write —
119
+ * PGlite live queries cannot be paused — so retention only pays off for a genuinely hot, re-mounted query.
120
+ */
121
+ liveQueries?: {
122
+ /** Baseline retention (ms) for a zero-subscriber entry; floored by each subscriber's own hint. Default 0. */
123
+ defaultKeepAliveMs?: number;
124
+ /** Max simultaneously-retained (zero-subscriber) entries — LRU-evicted past this. Default 16. */
125
+ maxRetainedQueries?: number;
126
+ /** Max total rows across all retained entries — LRU-evicted past this. Default 50_000. */
127
+ maxRetainedRows?: number;
128
+ };
106
129
  }
107
130
 
108
131
  /** The worker-side host: attach ports, await the boot, and (for tests) tear down. */
@@ -116,7 +139,9 @@ export interface SyncWorkerHost<TRegistry extends SyncTableRegistry> {
116
139
  }
117
140
 
118
141
  interface LiveSub {
119
- unsubscribe: () => void;
142
+ // The manager-owned handle: `unsubscribe()` (awaited teardown, tracked inside the manager — ADR-0040
143
+ // decision 1) and a coalesced `refresh()` the hydration chain drives.
144
+ subscription: LiveSubscription;
120
145
  port: BridgePort;
121
146
  }
122
147
 
@@ -127,6 +152,8 @@ interface LiveSub {
127
152
  export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
128
153
  options: DefineSyncWorkerOptions<TRegistry>,
129
154
  ): SyncWorkerHost<TRegistry> {
155
+ // Fail at construction, not first subscribe, on a bad keep-alive policy (ADR-0040 decision 4 — bounded).
156
+ validateLiveQueryPolicy(options.liveQueries);
130
157
  const codec = options.codec ?? identityCodec;
131
158
  const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;
132
159
  const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;
@@ -142,6 +169,40 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
142
169
 
143
170
  const ports = new Set<BridgePort>();
144
171
  const liveSubs = new Map<string, LiveSub>();
172
+ // The live-query lifecycle (PGlite registration, diff listener, and the ADR-0040 decision-1 awaited-teardown
173
+ // set) lives in a single manager owned per engine. Created lazily on first subscribe because it needs the
174
+ // booted client's `live` namespace (`active.pglite.live`); the worker never restarts its engine in place
175
+ // (ADR-0040 decision 7), so one manager serves the host's whole lifetime. `close()` disposes it.
176
+ let liveManager: LiveQueryManager | null = null;
177
+ const ensureLiveManager = (active: SyncClient<TRegistry>): LiveQueryManager =>
178
+ (liveManager ??= createLiveQueryManager({
179
+ live: active.pglite.live,
180
+ ...(options.liveQueries ? { policy: options.liveQueries } : {}),
181
+ }));
182
+ // Subscribes that have entered `handleSubscribe` but not yet reached `liveSubs.set` (they are mid-await on
183
+ // prepareQuery / hydration / manager setup). Registered SYNCHRONOUSLY at entry, keyed by `queryId`, so an
184
+ // `unsubscribe`/`detach` arriving during those awaits can mark the pending subscribe CANCELLED — otherwise
185
+ // it would finish and store a subscription for an already-gone port, escaping the awaited-teardown boundary
186
+ // (ADR-0040 decision 1). Removed in `handleSubscribe`'s finally.
187
+ const pendingSubscribes = new Map<string, { port: BridgePort; cancelled: boolean }>();
188
+ // Host shutdown state (ADR-0040 decision 1 — the pending-before-manager close race). `close()` flips
189
+ // `closing` and awaits every in-flight `handleSubscribe` task BEFORE disposing the manager, so a subscribe
190
+ // still mid-await when close begins can neither create a registration afterwards (it early-bails on
191
+ // `closing`) nor escape the awaited-teardown boundary. `inFlightSubscribes` holds each whole-call task.
192
+ let closing = false;
193
+ const inFlightSubscribes = new Set<Promise<void>>();
194
+ // One stable, opaque diagnostics scope per bridge port (ADR-0040 decision 5) — so a snapshot's `scopeCount`
195
+ // reads as the distinct-tab count. Never part of the fingerprint; a lazy per-port counter.
196
+ const portScopes = new WeakMap<BridgePort, string>();
197
+ let nextScopeId = 0;
198
+ const scopeForPort = (port: BridgePort): string => {
199
+ let scope = portScopes.get(port);
200
+ if (scope === undefined) {
201
+ scope = `port-${nextScopeId++}`;
202
+ portScopes.set(port, scope);
203
+ }
204
+ return scope;
205
+ };
145
206
 
146
207
  // ─── Pre-spawned (schemaless) store — the spare flow (ADR-0032 decision 5) ────────────────────────
147
208
  // A `provision` mints the raw PGlite (initdb only) and holds it idle here; the first real `attach`
@@ -254,6 +315,37 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
254
315
  resolveBooted = resolve;
255
316
  });
256
317
 
318
+ // ─── Boot milestone bridge (ADR-0041 stage 2) ────────────────────────────────────────────────────
319
+ // One engine crosses each background boot stage once. Broadcast a one-shot `milestone` as it crosses
320
+ // `writeReady`/`bootSettled` (or a `milestone-error` if the tail rejects the stage), and FOLD the current
321
+ // set into every `attach-ack` so a tab that attached after a stage fired resolves it from the ack. The
322
+ // ack itself fires AT `localReadReady` (the Option B contract), so that stage needs no milestone. Wired
323
+ // exactly once off the booted client's stage promises (`milestonesWired`), then driven purely by them.
324
+ const milestones = { writeReady: false, bootSettled: false };
325
+ const stageErrors: {
326
+ writeReady?: { message: string; detail?: unknown };
327
+ bootSettled?: { message: string; detail?: unknown };
328
+ } = {};
329
+ let milestonesWired = false;
330
+ const markMilestone = (stage: BootMilestone) => {
331
+ if (milestones[stage]) return;
332
+ milestones[stage] = true;
333
+ broadcastEvent({ kind: "milestone", stage });
334
+ };
335
+ const failMilestone = (stage: BootMilestone, error: unknown) => {
336
+ if (stageErrors[stage]) return;
337
+ const serialized = serializeError(error);
338
+ stageErrors[stage] = serialized;
339
+ broadcastEvent({ kind: "milestone-error", stage, error: serialized });
340
+ };
341
+ // Attach-ack fold fields for a LATE attach — the milestones/failures already crossed at ack time.
342
+ const milestoneAckFields = () => ({
343
+ ...(milestones.writeReady ? { writeReady: true as const } : {}),
344
+ ...(milestones.bootSettled ? { bootSettled: true as const } : {}),
345
+ ...(stageErrors.writeReady ? { writeReadyError: stageErrors.writeReady } : {}),
346
+ ...(stageErrors.bootSettled ? { bootSettledError: stageErrors.bootSettled } : {}),
347
+ });
348
+
257
349
  const boot = (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {
258
350
  if (bootPromise) return bootPromise;
259
351
  // The tab is the auth owner: seed the cache with the token it presented at attach (decision 3).
@@ -340,6 +432,11 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
340
432
  // Boot observability (ADR-0034): broadcast the finalized report to currently-attached ports (one-shot
341
433
  // push). Later tabs read the same report via the `bootReport` pull RPC — there is no replay event.
342
434
  onBootReport: (report) => broadcastEvent({ kind: "boot-report", report }),
435
+ // ADR-0041 stage 2 (Option B contract): `createSyncClient` resolves AT `localReadReady`, so the boot
436
+ // promise now resolves there too — the attach handler acks at local-read readiness and the write/sync
437
+ // tail runs in the background, announced to tabs via the `writeReady`/`bootSettled` milestone messages
438
+ // wired in the attach handler below. The stage-1 `await booted.bootSettled` shim is deleted: attach no
439
+ // longer waits for the whole boot, which is exactly the behavioural change this stage delivers.
343
440
  });
344
441
  return bootPromise;
345
442
  };
@@ -410,6 +507,11 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
410
507
  // Boot observability (ADR-0034): the worker engine's stored report (or null). Pull, so a late tab
411
508
  // reads a boot predating it; the report structured-clones across the bridge as a plain object.
412
509
  return active.bootReport();
510
+ case "liveQueryDiagnostics":
511
+ // Live-query diagnostics (ADR-0040 decision 5): the manager lives in THIS host closure (not on
512
+ // `active`), so read it directly. Plain-object records (digests + counts only) structured-clone
513
+ // across the bridge; `[]` when nothing has subscribed yet (the manager is created lazily).
514
+ return liveManager?.snapshot() ?? [];
413
515
  case "exportStore": {
414
516
  // Store backup (ADR-0035): run the live export on the worker's OWN client (its lifecycle slot
415
517
  // serialises it against every tab's export). A `File` cannot cross the bridge as a transferable, so
@@ -444,10 +546,47 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
444
546
  };
445
547
 
446
548
  // ─── Live-query bridge (ADR-0032 S2 §4) ──────────────────────────────────────────────────────────
447
- const handleSubscribe = async (port: BridgePort, id: string | undefined, payload: SubscribePayload) => {
549
+ // `queryId`s are minted by a PER-TAB counter (`live-1`, `live-2`, …), so two tabs collide on the bare id —
550
+ // every worker-side bookkeeping key MUST be port-scoped or one tab's unsubscribe/close tears down another
551
+ // tab's identically-numbered subscription (latent since ADR-0032; exposed the moment tab close started
552
+ // sending unsubscribes — the two-tab board e2e's scenario (c)). The wire keeps the bare `queryId` (the
553
+ // port disambiguates); only the worker's maps compose it with the port's scope.
554
+ const subKeyFor = (port: BridgePort, queryId: string): string => `${scopeForPort(port)}:${queryId}`;
555
+
556
+ const handleSubscribe = (port: BridgePort, id: string | undefined, payload: SubscribePayload): Promise<void> => {
557
+ // Register the in-flight subscribe SYNCHRONOUSLY (before the first await) so an `unsubscribe`/`detach`/
558
+ // `close` arriving mid-await can mark it cancelled (ADR-0040 decision 1 — no subscription escapes teardown).
559
+ const pending = { port, cancelled: false };
560
+ const subKey = subKeyFor(port, payload.queryId);
561
+ pendingSubscribes.set(subKey, pending);
562
+ // Track the WHOLE call so `close()` awaits it before disposing the manager: the task is added to
563
+ // `inFlightSubscribes` synchronously here and removed in its own finally, so close can never observe an
564
+ // empty set while a subscribe is still awaiting prepareQuery / hydration / manager setup.
565
+ // `let task!` (not `const`): the finally references `task` to remove itself, and it only runs after the
566
+ // first await — by then the assignment below has completed, so the definite-assignment assertion is safe.
567
+ let task!: Promise<void>;
568
+ task = (async () => {
569
+ try {
570
+ await handleSubscribeInner(port, id, payload, pending, subKey);
571
+ } finally {
572
+ pendingSubscribes.delete(subKey);
573
+ inFlightSubscribes.delete(task);
574
+ }
575
+ })();
576
+ inFlightSubscribes.add(task);
577
+ return task;
578
+ };
579
+
580
+ const handleSubscribeInner = async (
581
+ port: BridgePort,
582
+ id: string | undefined,
583
+ payload: SubscribePayload,
584
+ pending: { port: BridgePort; cancelled: boolean },
585
+ subKey: string,
586
+ ) => {
448
587
  const active = client ?? (await bootPromise);
449
588
  if (!active) throw new Error("subscribe before attach");
450
- const { queryId, sql, params, pkColumns, use, fields } = payload;
589
+ const { queryId, sql, params, pkColumns, use, fields, keepAliveMs } = payload;
451
590
  // Activate any lazy relations the query reads BEFORE registering the live query (ADR-0021) — the worker
452
591
  // owns the real client, so its `prepareQuery` does the real work; the tab's `prepareQuery` is a no-op.
453
592
  // Scan the ORIGINAL sql (the wrap only adds an outer `SELECT * FROM (...)`; table refs are inside).
@@ -460,47 +599,73 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
460
599
  // `hydratingTables` field (the tab's `hydrating` source) and the `live-hydrated` block below.
461
600
  const hydratingTables = active.hydratingTablesFor({ sql, ...(use ? { use: use as string[] } : {}) });
462
601
 
463
- const live = active.pglite.live;
464
602
  // Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view
465
603
  // 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).
604
+ // No `fields` → SQL unchanged (backward-compatible name-keyed rows; the aliased path keys by alias). The
605
+ // wrap stays caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL as its query input.
467
606
  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",
607
+ // Early bail BEFORE the manager is created (ADR-0040 decision 1 — the pending-before-manager close race):
608
+ // if the host is closing, this subscribe was cancelled, or its port detached WHILE we awaited prepareQuery
609
+ // / hydration, do NOT call `ensureLiveManager` — creating a registration now would race the engine close
610
+ // with a fire-and-forget teardown nothing awaits (a manager born after `close()` disposed is never
611
+ // disposed). Post the rpc error for this subscribe id so a still-live tab's `subscribeLiveRows` rejects
612
+ // instead of hanging, and return without touching the manager. The post-setup check below still catches a
613
+ // cancellation that lands DURING manager setup (after the manager already exists).
614
+ if (closing || pending.cancelled || !ports.has(port)) {
615
+ postBridgeMessage(
616
+ port,
617
+ codec,
618
+ "rpc-result",
619
+ {
620
+ ok: false,
621
+ error: { message: "[pgxsinkit] subscribe cancelled — the worker is closing or the port detached" },
622
+ },
623
+ id,
624
+ );
625
+ return;
626
+ }
627
+ // The manager owns registration + diff + teardown; the bridge posting (per-`queryId`, with the caller-owned
628
+ // `lazyTables`/`hydratingTables` observability fields) stays here — those are per-subscriber pre-steps.
629
+ const subscription = await ensureLiveManager(active).subscribe(
630
+ { materialSql, params: params as unknown[], ...(pkColumns ? { pkColumns } : {}) },
483
631
  {
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] } : {}),
632
+ deliverInitial: (rows) => {
633
+ // Initial snapshot verbatim (not a diff), correlated to the subscribe request so the tab resolves.
634
+ postBridgeMessage(
635
+ port,
636
+ codec,
637
+ "live-initial",
638
+ {
639
+ queryId,
640
+ rows,
641
+ // `lazyTables` = the activated lazy relations (observability); `hydratingTables` = the referenced
642
+ // groups (eager OR lazy) still catching up, which the tab turns into its `hydrated` promise.
643
+ ...(prepared.lazyTables.length > 0 ? { lazyTables: prepared.lazyTables.map(String) } : {}),
644
+ ...(hydratingTables.length > 0 ? { hydratingTables: [...hydratingTables] } : {}),
645
+ },
646
+ id,
647
+ );
648
+ },
649
+ deliverDiff: (diff) => {
650
+ postBridgeMessage(port, codec, "live-diff", { queryId, ...diff });
651
+ },
490
652
  },
491
- id,
653
+ // The per-subscriber keep-alive hint (ADR-0040 decision 4) — kept OUT of the spec so it never touches
654
+ // the fingerprint (decision 3). Absent → no hint (the manager falls back to its policy default). The
655
+ // `scope` is one stable id per port (decision 5 diagnostics), also fingerprint-excluded.
656
+ { ...(keepAliveMs != null ? { keepAliveMs } : {}), scope: scopeForPort(port) },
492
657
  );
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
- });
658
+ // The port was detached, or this query was unsubscribed, WHILE we awaited (prepareQuery / hydration /
659
+ // manager setup all yield). Neither cleanup path found a `liveSubs` entry — so undo the just-created
660
+ // subscription here and DO NOT record it, else it would outlive its port (ADR-0040 decision 1). A
661
+ // `live-initial` may already have been posted to a dead port; that is harmless (a closed port's
662
+ // postMessage is a no-op) and not worth preventing. `closing` is included so a `close()` that began DURING
663
+ // manager setup still unwinds this just-created subscription rather than recording it.
664
+ if (closing || pending.cancelled || !ports.has(port)) {
665
+ void subscription.unsubscribe();
666
+ return;
667
+ }
668
+ liveSubs.set(subKey, { port, subscription });
504
669
 
505
670
  // Hydration completion travels the SAME port as the diff stream, so ordering is guaranteed: await the
506
671
  // pending groups' catch-up (eager AND lazy), force one refresh of the live query against the caught-up
@@ -511,9 +676,9 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
511
676
  if (hydratingTables.length > 0) {
512
677
  void Promise.all(hydratingTables.map((key) => active.groupReady(key as SyncTableName<TRegistry>)))
513
678
  .then(async () => {
514
- if (!liveSubs.has(queryId)) return; // unsubscribed while catching up
515
- await registered.refresh();
516
- if (!liveSubs.has(queryId)) return;
679
+ if (!liveSubs.has(subKey)) return; // unsubscribed while catching up
680
+ await subscription.refresh();
681
+ if (!liveSubs.has(subKey)) return;
517
682
  postBridgeMessage(port, codec, "live-hydrated", { queryId });
518
683
  })
519
684
  .catch(() => undefined); // a torn-down engine mid-catch-up must not surface as an unhandled rejection
@@ -618,18 +783,42 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
618
783
  (booted) => {
619
784
  client = booted;
620
785
  resolveBooted(booted);
786
+ // Wire the engine's background stage promises to the milestone bridge exactly ONCE (ADR-0041
787
+ // stage 2). `createSyncClient` resolved at `localReadReady`, so by here the engine has crossed
788
+ // that stage — the ack below carries it implicitly. `writeReady`/`bootSettled` cross later (or
789
+ // fail): broadcast each as a one-shot `milestone`/`milestone-error` for currently-attached ports
790
+ // and fold the current set into every subsequent ack for late attachers.
791
+ if (!milestonesWired) {
792
+ milestonesWired = true;
793
+ void booted.writeReady.then(
794
+ () => markMilestone("writeReady"),
795
+ (error: unknown) => failMilestone("writeReady", error),
796
+ );
797
+ void booted.bootSettled.then(
798
+ () => markMilestone("bootSettled"),
799
+ (error: unknown) => failMilestone("bootSettled", error),
800
+ );
801
+ }
621
802
  // Track the engine's monotonic `ready` edge exactly once, so a LATER attach acked after the
622
803
  // initial sync landed can resolve its `ready` straight from the ack (ADR-0032 FIX 3).
623
804
  if (!engineReadyFired) {
624
- void booted.ready.then(() => {
625
- engineReadyFired = true;
626
- });
805
+ // ADR-0041: `ready` can now reject if the background write/sync tail fails after the client was
806
+ // handed out; swallow that here so it is not an unhandled rejection (the failure surfaces to
807
+ // tabs via the `milestone-error` broadcast / the stage-error ack fold instead).
808
+ void booted.ready.then(
809
+ () => {
810
+ engineReadyFired = true;
811
+ },
812
+ () => undefined,
813
+ );
627
814
  }
628
815
  // Ack AFTER the engine exists so the tab's subsequent traffic (rpc/subscribe) has a client to
629
- // hit; include current status + per-group readiness for a late-joining tab (decisions 4/6).
816
+ // hit; the ack fires AT `localReadReady` (Option B) and folds the current milestone set +
817
+ // engine-ready edge for a late-joining tab (ADR-0041 / ADR-0032 FIX 3).
630
818
  postBridgeMessage(port, codec, "attach-ack", {
631
819
  alreadyBooted,
632
820
  ...(engineReadyFired ? { engineReady: true } : {}),
821
+ ...milestoneAckFields(),
633
822
  });
634
823
  postBridgeMessage(port, codec, "event", { kind: "status", status: booted.status });
635
824
  },
@@ -689,10 +878,19 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
689
878
  }
690
879
  case "unsubscribe": {
691
880
  const { queryId } = payload as { queryId: string };
692
- const sub = liveSubs.get(queryId);
881
+ // Compose the SAME port-scoped key the subscribe used — a bare queryId lookup would collide with
882
+ // another tab's identically-numbered subscription (see `subKeyFor`).
883
+ const subKey = subKeyFor(port, queryId);
884
+ const sub = liveSubs.get(subKey);
693
885
  if (sub) {
694
- sub.unsubscribe();
695
- liveSubs.delete(queryId);
886
+ // Non-blocking for the caller: the manager retains the teardown promise so `close()` awaits it.
887
+ void sub.subscription.unsubscribe();
888
+ liveSubs.delete(subKey);
889
+ } else {
890
+ // No live entry yet → the subscribe is still mid-await. Mark it cancelled so `handleSubscribe`
891
+ // tears down the subscription it is about to create instead of recording it (ADR-0040 decision 1).
892
+ const inFlight = pendingSubscribes.get(subKey);
893
+ if (inFlight) inFlight.cancelled = true;
696
894
  }
697
895
  break;
698
896
  }
@@ -710,12 +908,18 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
710
908
 
711
909
  const detachPort = (port: BridgePort) => {
712
910
  ports.delete(port);
713
- for (const [queryId, sub] of liveSubs) {
911
+ for (const [subKey, sub] of liveSubs) {
714
912
  if (sub.port === port) {
715
- sub.unsubscribe();
716
- liveSubs.delete(queryId);
913
+ // Non-blocking: the manager retains the teardown promise so `close()` awaits it (ADR-0040 decision 1).
914
+ void sub.subscription.unsubscribe();
915
+ liveSubs.delete(subKey);
717
916
  }
718
917
  }
918
+ // Also cancel every subscribe for this port still mid-await — its `handleSubscribe` will tear down the
919
+ // subscription it is about to create rather than record it for a detached port (ADR-0040 decision 1).
920
+ for (const pending of pendingSubscribes.values()) {
921
+ if (pending.port === port) pending.cancelled = true;
922
+ }
719
923
  };
720
924
 
721
925
  const connect = (port: BridgePort) => {
@@ -739,8 +943,18 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
739
943
  connect,
740
944
  whenBooted,
741
945
  close: async () => {
742
- for (const sub of liveSubs.values()) sub.unsubscribe();
946
+ // Quiesce pending subscribes FIRST (ADR-0040 decision 1 — the pending-before-manager race): flip
947
+ // `closing`, mark every mid-await subscribe cancelled, and await every in-flight `handleSubscribe` task.
948
+ // This guarantees the manager exists (if any subscribe created one) BEFORE `dispose()` runs, and that no
949
+ // subscribe can create a registration afterwards — each resumes into the `closing` early-bail instead.
950
+ closing = true;
951
+ for (const pending of pendingSubscribes.values()) pending.cancelled = true;
952
+ await Promise.allSettled([...inFlightSubscribes]);
953
+ // Dispose the manager BEFORE `active.stop()` (ADR-0040 decision 1): it tears down every remaining live
954
+ // registration and awaits ALL teardowns, so no fire-and-forget unsubscribe is still in flight when the
955
+ // engine closes (the close-vs-unsubscribe hang). No-op when nothing ever subscribed.
743
956
  liveSubs.clear();
957
+ await liveManager?.dispose();
744
958
  ports.clear();
745
959
  setSyncDebugSink(undefined);
746
960
  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
+ }