@pgxsinkit/client 0.1.53 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +22 -0
  2. package/dist/adoption.d.ts +118 -0
  3. package/dist/adoption.d.ts.map +1 -0
  4. package/dist/boot-report.d.ts +54 -15
  5. package/dist/boot-report.d.ts.map +1 -1
  6. package/dist/convergence.d.ts +2 -1
  7. package/dist/convergence.d.ts.map +1 -1
  8. package/dist/export-store.d.ts +1 -1
  9. package/dist/export-store.d.ts.map +1 -1
  10. package/dist/index.d.ts +270 -52
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +4492 -1511
  13. package/dist/index.js.map +34 -24
  14. package/dist/live-rows-sql.d.ts +1 -1
  15. package/dist/local-store.d.ts +16 -31
  16. package/dist/local-store.d.ts.map +1 -1
  17. package/dist/local-tables.d.ts +4 -4
  18. package/dist/mutation.d.ts +12 -15
  19. package/dist/mutation.d.ts.map +1 -1
  20. package/dist/opfs-effects.d.ts +51 -0
  21. package/dist/opfs-effects.d.ts.map +1 -0
  22. package/dist/placement-probe.d.ts +75 -0
  23. package/dist/placement-probe.d.ts.map +1 -0
  24. package/dist/schema.d.ts +11 -16
  25. package/dist/schema.d.ts.map +1 -1
  26. package/dist/store-boot.d.ts +77 -0
  27. package/dist/store-boot.d.ts.map +1 -0
  28. package/dist/store-lifecycle.d.ts +153 -0
  29. package/dist/store-lifecycle.d.ts.map +1 -0
  30. package/dist/store-meta.d.ts +190 -0
  31. package/dist/store-meta.d.ts.map +1 -0
  32. package/dist/store-path.d.ts +77 -7
  33. package/dist/store-path.d.ts.map +1 -1
  34. package/dist/sync/apply.d.ts.map +1 -1
  35. package/dist/sync/shape-inbox.d.ts +1 -1
  36. package/dist/sync/types.d.ts +3 -3
  37. package/dist/testing.js.map +3 -3
  38. package/dist/worker/attach-sync-client.d.ts +235 -12
  39. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  40. package/dist/worker/define-sync-worker.d.ts +138 -22
  41. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  42. package/dist/worker/election-coordinator.d.ts +95 -0
  43. package/dist/worker/election-coordinator.d.ts.map +1 -0
  44. package/dist/worker/engine-control.d.ts +265 -0
  45. package/dist/worker/engine-control.d.ts.map +1 -0
  46. package/dist/worker/engine-router.d.ts +75 -0
  47. package/dist/worker/engine-router.d.ts.map +1 -0
  48. package/dist/worker/live-query-manager.d.ts.map +1 -1
  49. package/dist/worker/protocol.d.ts +15 -10
  50. package/dist/worker/protocol.d.ts.map +1 -1
  51. package/dist/worker/sw-placement.d.ts +37 -0
  52. package/dist/worker/sw-placement.d.ts.map +1 -0
  53. package/package.json +4 -3
  54. package/skills/core/SKILL.md +15 -12
  55. package/skills/operating/SKILL.md +103 -46
  56. package/src/adoption.ts +275 -0
  57. package/src/boot-report.ts +70 -17
  58. package/src/convergence.ts +2 -1
  59. package/src/export-store.ts +1 -1
  60. package/src/index.ts +1109 -115
  61. package/src/live-rows-sql.ts +1 -1
  62. package/src/local-store.ts +18 -40
  63. package/src/local-tables.ts +2 -2
  64. package/src/mutation.ts +67 -49
  65. package/src/mutations-api.ts +3 -3
  66. package/src/opfs-effects.ts +160 -0
  67. package/src/placement-probe.ts +168 -0
  68. package/src/schema.ts +17 -22
  69. package/src/store-boot.ts +343 -0
  70. package/src/store-lifecycle.ts +227 -0
  71. package/src/store-meta.ts +459 -0
  72. package/src/store-path.ts +197 -22
  73. package/src/sync/apply.ts +63 -63
  74. package/src/sync/index.ts +2 -2
  75. package/src/sync/shape-inbox.ts +1 -1
  76. package/src/sync/types.ts +3 -3
  77. package/src/testing.ts +2 -2
  78. package/src/worker/attach-sync-client.ts +1556 -97
  79. package/src/worker/define-sync-worker.ts +723 -73
  80. package/src/worker/election-coordinator.ts +462 -0
  81. package/src/worker/engine-control.ts +379 -0
  82. package/src/worker/engine-router.ts +355 -0
  83. package/src/worker/live-query-manager.ts +4 -1
  84. package/src/worker/protocol.ts +13 -10
  85. package/src/worker/sw-placement.ts +64 -0
@@ -42,7 +42,37 @@ import {
42
42
  type SyncTransactionResult,
43
43
  } from "../index";
44
44
  import type { LocalStoreVersionEvent } from "../local-store";
45
+ import { createOpfsEffects, type OpfsEffectsDeps } from "../opfs-effects";
46
+ import { type DestructionEffects, runDestruction } from "../store-lifecycle";
47
+ import { deleteStoreMetaRecord, type StoreMetaDeps, writeStoreMetaRecord } from "../store-meta";
48
+ import { storeIndexedDbDatabaseName } from "../store-path";
45
49
  import { readTestStoreMarker } from "../store-path";
50
+ import {
51
+ CONTROL_PORT_DELIVERY_KEY,
52
+ DESTROY_QUERY_KEY,
53
+ DESTROY_VERDICT_KEY,
54
+ PLACEMENT_RESULT_KEY,
55
+ type PlacementQueryResult,
56
+ PLACEMENT_QUERY_KEY,
57
+ } from "./define-sync-worker";
58
+ import {
59
+ type CoordinatorDeps,
60
+ createElectionCoordinator,
61
+ type ElectionCoordinator,
62
+ type SwBridgePort,
63
+ } from "./election-coordinator";
64
+ import {
65
+ type EngineControlMessage,
66
+ engineIdentityEquals,
67
+ type EngineIdentity,
68
+ EngineRelocatedError,
69
+ engineRelocatedFromWire,
70
+ executionLimitMismatchFromWire,
71
+ type ExecutionLimitConfig,
72
+ isStaleIdentity,
73
+ readControlEnvelope,
74
+ wrapControlEnvelope,
75
+ } from "./engine-control";
46
76
  import { LiveRowsMaterializer } from "./live-diff";
47
77
  import {
48
78
  type AttachAckPayload,
@@ -71,14 +101,302 @@ import {
71
101
  interface WorkerLike {
72
102
  port?: BridgePort;
73
103
  postMessage?: (message: unknown, transfer?: BridgeTransferable[]) => void;
74
- addEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
75
- removeEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
104
+ addEventListener?: (
105
+ type: "message" | "error",
106
+ listener: (event: { data?: unknown; message?: unknown }) => void,
107
+ ) => void;
108
+ removeEventListener?: (
109
+ type: "message" | "error",
110
+ listener: (event: { data?: unknown; message?: unknown }) => void,
111
+ ) => void;
112
+ terminate?: () => void;
113
+ }
114
+
115
+ /**
116
+ * The elected engine worker handle the election coordinator drives (ADR-0049 D5, step 8): `terminate()` (a
117
+ * deliberate teardown / respawn), `onError` (a reported worker death → immediate respawn), and
118
+ * `deliverControlPort` (post the engine end of the announce control channel — `{ [CONTROL_PORT_DELIVERY_KEY]:
119
+ * true }` with the port transferred — so the elected worker's step-9 control plane starts on it). The consumer
120
+ * supplies a factory that constructs their own `defineSyncWorker` entry as a dedicated `Worker`; wrap it with
121
+ * {@link wrapEngineWorker}.
122
+ */
123
+ export interface ElectedEngineWorker {
124
+ terminate(): void;
125
+ onError(listener: (message: string) => void): void;
126
+ deliverControlPort(port: unknown): void;
127
+ }
128
+
129
+ /**
130
+ * Wrap a dedicated `Worker` (a consumer's `defineSyncWorker` engine entry) into the {@link ElectedEngineWorker}
131
+ * the coordinator drives (ADR-0049 step 10b). `deliverControlPort` posts `{ [CONTROL_PORT_DELIVERY_KEY]: true }`
132
+ * on the worker's implicit port with the control-channel end TRANSFERRED — exactly the delivery message the
133
+ * step-9 engine control plane listens for. `onError` subscribes to the worker's `error` event; `terminate`
134
+ * forwards to `worker.terminate()`.
135
+ */
136
+ /**
137
+ * The default {@link AttachSyncClientOptions.awaitOwnershipRelease} — a documented NO-OP (ADR-0049 step 11b
138
+ * follow-up 1). The OPFS-repacked VFS enforces single-owner access with EXCLUSIVE OPFS sync-access handles
139
+ * (`StoreOwnedError`), not a Web Lock, so there is no ownership lock to await from here without importing the
140
+ * VFS. The bounded wait for the dead worker's agent to release the handle lives entirely in the SUCCESSOR'S OPEN
141
+ * PATH: the respawned engine's `createOpfsRepacked` open retries on the owned-store contention error until it
142
+ * clears (the `openWithBoundedRetries` wrapper) — the fault-matrix "successor open retries on contention" row.
143
+ * So the coordinator can respawn immediately after a deliberate terminate; its VFS open is the real gate.
144
+ */
145
+ export function resolvedOwnershipRelease(): Promise<void> {
146
+ return Promise.resolve();
147
+ }
148
+
149
+ export function wrapEngineWorker(worker: WorkerLike): ElectedEngineWorker {
150
+ const post = (message: unknown, transfer: BridgeTransferable[]): void => {
151
+ if (worker.postMessage) worker.postMessage(message, transfer);
152
+ else worker.port?.postMessage(message, transfer);
153
+ };
154
+ return {
155
+ terminate: () => worker.terminate?.(),
156
+ onError: (listener) => {
157
+ worker.addEventListener?.("error", (event) => {
158
+ const message = (event as { message?: unknown }).message;
159
+ listener(typeof message === "string" ? message : "elected engine worker error");
160
+ });
161
+ },
162
+ deliverControlPort: (port) => post({ [CONTROL_PORT_DELIVERY_KEY]: true }, [port as BridgeTransferable]),
163
+ };
164
+ }
165
+
166
+ /**
167
+ * `destroy()` on an attached facade REFUSES when other tabs still hold the store (ADR-0049 D8, plan fault row
168
+ * "`destroy()` with peers attached → refused with a typed error — close peers first"). The SharedWorker — the
169
+ * only role that knows the attached-tab count — answers a peer-count query; more than one attached tab (this
170
+ * one plus at least one other) raises this. `peers` is the total attached-tab count, this tab included.
171
+ */
172
+ export class StoreDestroyRefusedError extends Error {
173
+ readonly peers: number;
174
+ constructor(peers: number) {
175
+ super(
176
+ `[pgxsinkit] destroy() refused: ${Math.max(0, peers - 1)} other tab(s) are still attached to this store. ` +
177
+ "Close the peer tabs first, then destroy — the store is shared and destroying it under a live peer would " +
178
+ "strand that tab's engine.",
179
+ );
180
+ this.name = "StoreDestroyRefusedError";
181
+ this.peers = peers;
182
+ }
76
183
  }
77
184
 
185
+ /**
186
+ * Attach WIRING failure (ADR-0049 D1/D5): the SharedWorker requires election (a router-only, handle-denied home)
187
+ * but the elected engine worker CANNOT be constructed — neither a `createEngineWorker` override was supplied NOR is
188
+ * the SharedWorker's own script URL derivable (a plain scope that cannot report `self.location.href`, or a
189
+ * non-module entry). Capability absence FALLS BACK (idbfs); a wiring failure ERRORS — the capability was present and
190
+ * the configuration was wrong, and silently downgrading storage would hide the defect. `[pgxsinkit]`-prefixed like
191
+ * the repo's other typed errors so a consumer can `instanceof`-branch it.
192
+ */
193
+ export class ElectedEngineUnconstructibleError extends Error {
194
+ constructor(detail: string) {
195
+ super(
196
+ `[pgxsinkit] cannot attach: this SharedWorker is router-only (election required) but the elected engine ` +
197
+ `worker cannot be constructed — ${detail}. Pass a \`createEngineWorker\` override for entries that cannot ` +
198
+ `be reconstructed from their URL as a module worker (classic-script / blob: / data: / CSP-constrained), ` +
199
+ `or use a SharedWorker whose script URL is derivable (ADR-0049 D5). This is a wiring defect, not a ` +
200
+ `capability fallback — the platform can hold sync-access handles here.`,
201
+ );
202
+ this.name = "ElectedEngineUnconstructibleError";
203
+ }
204
+ }
205
+
206
+ /** The minimal `indexedDB.deleteDatabase` surface (no DOM lib) — mirrors `store-boot.ts`'s idb delete seam. */
207
+ interface IdbDeleteSurface {
208
+ deleteDatabase(name: string): {
209
+ error?: unknown;
210
+ onsuccess: (() => void) | null;
211
+ onerror: (() => void) | null;
212
+ onblocked?: (() => void) | null;
213
+ };
214
+ }
215
+
216
+ /** Resolve the `deleteDatabase` surface: injected meta deps first (tests), else structural off `globalThis`. */
217
+ function resolveIdbDeleteSurface(meta?: StoreMetaDeps): IdbDeleteSurface | undefined {
218
+ if (meta != null && "indexedDB" in meta) return meta.indexedDB as unknown as IdbDeleteSurface | undefined;
219
+ return (globalThis as { indexedDB?: IdbDeleteSurface }).indexedDB;
220
+ }
221
+
222
+ /** Delete-if-present the store's PGlite idb database; only `onsuccess` proves completion. */
223
+ function deleteStoreIdbDatabase(storePath: string, meta?: StoreMetaDeps): Promise<void> {
224
+ const idb = resolveIdbDeleteSurface(meta);
225
+ if (idb?.deleteDatabase == null) return Promise.resolve();
226
+ const name = storeIndexedDbDatabaseName(storePath);
227
+ return new Promise<void>((resolve, reject) => {
228
+ let settled = false;
229
+ let timeout: ReturnType<typeof setTimeout> | undefined;
230
+ const finish = (error?: unknown) => {
231
+ if (settled) return;
232
+ settled = true;
233
+ if (timeout !== undefined) clearTimeout(timeout);
234
+ if (error === undefined) resolve();
235
+ else reject(error);
236
+ };
237
+ let request: {
238
+ error?: unknown;
239
+ onsuccess: (() => void) | null;
240
+ onerror: (() => void) | null;
241
+ onblocked?: (() => void) | null;
242
+ };
243
+ try {
244
+ request = idb.deleteDatabase(name);
245
+ } catch (error) {
246
+ finish(error);
247
+ return;
248
+ }
249
+ request.onsuccess = () => finish();
250
+ request.onerror = () => finish(request.error ?? new Error(`indexedDB deletion failed for ${name}`));
251
+ request.onblocked = () => undefined;
252
+ timeout = setTimeout(() => finish(new Error(`indexedDB deletion timed out while blocked for ${name}`)), 5_000);
253
+ });
254
+ }
255
+
256
+ /**
257
+ * Build the REAL {@link DestructionEffects} for a store — the OPFS commitment sentinel + store directory
258
+ * (`opfs-effects.ts`), the meta record (`store-meta.ts`), and the PGlite idb database. The destruction machine is
259
+ * backend-agnostic (`store-lifecycle.ts`): `deleteBackendStore` delete-if-presents BOTH the OPFS directory and
260
+ * the idb database, so it works whichever backend the store used. Injectable IO (`opfs`/`meta`) so the wiring is
261
+ * unit-testable with fakes.
262
+ */
263
+ export function createStoreDestructionEffects(
264
+ storePath: string,
265
+ deps?: { opfs?: OpfsEffectsDeps; meta?: StoreMetaDeps },
266
+ ): DestructionEffects {
267
+ const opfs = createOpfsEffects(storePath, deps?.opfs);
268
+ const meta = deps?.meta;
269
+ return {
270
+ setPhase: (phase) => writeStoreMetaRecord(storePath, { phase, updatedAt: Date.now() }, meta),
271
+ deleteSentinel: () => opfs.deleteSentinel(),
272
+ deleteBackendStore: async () => {
273
+ await opfs.deleteStoreDirectory();
274
+ await deleteStoreIdbDatabase(storePath, meta);
275
+ },
276
+ deleteMetaRecord: () => deleteStoreMetaRecord(storePath, meta),
277
+ };
278
+ }
279
+
280
+ /** The bounded ownership-retry options for {@link runStoreDestruction} (the VFS-lock-lag guard, D8/fault row). */
281
+ export interface StoreDestructionRetryOptions {
282
+ /** Max retries of `deleteBackendStore` on an ownership-lock-lag error before giving up (default 5). */
283
+ maxOwnershipRetries?: number;
284
+ /** Classify an error as VFS-ownership-lock lag (retryable). Default: OPFS `NoModificationAllowedError`-class. */
285
+ isOwnershipError?: (error: unknown) => boolean;
286
+ /** Between-retries delay; defaults to a real timer. Injected in tests. */
287
+ delay?: (ms: number) => Promise<void>;
288
+ /** The between-retries delay (ms); default 50. */
289
+ retryDelayMs?: number;
290
+ }
291
+
292
+ /** Default ownership-lag classifier: OPFS raises `NoModificationAllowedError`/`InvalidStateError` while a sync-access handle is open. */
293
+ function defaultIsOwnershipError(error: unknown): boolean {
294
+ const name = (error as { name?: string } | null)?.name;
295
+ if (name === "NoModificationAllowedError" || name === "InvalidStateError") return true;
296
+ const message = (error as { message?: unknown } | null)?.message;
297
+ const text = (typeof message === "string" ? message : "").toLowerCase();
298
+ return text.includes("owned") || text.includes("ownership") || text.includes("locked") || text.includes("in use");
299
+ }
300
+
301
+ /**
302
+ * Run the destructive lifecycle (ADR-0049 D8) with a BOUNDED ownership-lock-lag retry around the backend-store
303
+ * delete. The engine was just detached, so its VFS ownership lock may not have cleared yet — the fault row
304
+ * "VFS ownership-lock release lag → successor retries until clear, bounded" applies to destroy too. The other
305
+ * steps (set `deleting`, delete sentinel, delete the meta record) are idempotent and not retried here. Shared by
306
+ * the attached-facade supervisor (this module) and the in-process `destroy()` (index.ts).
307
+ */
308
+ export async function runStoreDestruction(
309
+ effects: DestructionEffects,
310
+ opts?: StoreDestructionRetryOptions,
311
+ ): Promise<void> {
312
+ const maxRetries = opts?.maxOwnershipRetries ?? 5;
313
+ const isOwnershipError = opts?.isOwnershipError ?? defaultIsOwnershipError;
314
+ const delay = opts?.delay ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
315
+ const retryDelayMs = opts?.retryDelayMs ?? 50;
316
+ const guarded: DestructionEffects = {
317
+ setPhase: (phase) => effects.setPhase(phase),
318
+ deleteSentinel: () => effects.deleteSentinel(),
319
+ deleteMetaRecord: () => effects.deleteMetaRecord(),
320
+ deleteBackendStore: async () => {
321
+ for (let attempt = 0; ; attempt += 1) {
322
+ try {
323
+ await effects.deleteBackendStore();
324
+ return;
325
+ } catch (error) {
326
+ if (attempt >= maxRetries || !isOwnershipError(error)) throw error;
327
+ await delay(retryDelayMs);
328
+ }
329
+ }
330
+ },
331
+ };
332
+ await runDestruction(guarded);
333
+ }
334
+
335
+ /** Narrow a raw SharedWorker placement reply (`{ [PLACEMENT_RESULT_KEY]: … }`), or `undefined` for foreign traffic. */
336
+ function readPlacementResult(data: unknown): PlacementQueryResult | undefined {
337
+ if (typeof data !== "object" || data === null) return undefined;
338
+ const result = (data as { [PLACEMENT_RESULT_KEY]?: unknown })[PLACEMENT_RESULT_KEY];
339
+ if (typeof result !== "object" || result === null) return undefined;
340
+ return result as PlacementQueryResult;
341
+ }
342
+
343
+ /** Narrow a raw SharedWorker destroy peer-count verdict (`{ [DESTROY_VERDICT_KEY]: { peers } }`), or `undefined`. */
344
+ function readDestroyVerdict(data: unknown): number | undefined {
345
+ if (typeof data !== "object" || data === null) return undefined;
346
+ const verdict = (data as { [DESTROY_VERDICT_KEY]?: unknown })[DESTROY_VERDICT_KEY];
347
+ if (typeof verdict !== "object" || verdict === null) return undefined;
348
+ const peers = (verdict as { peers?: unknown }).peers;
349
+ return typeof peers === "number" ? peers : undefined;
350
+ }
351
+
352
+ /**
353
+ * The `setTimeout`/`clearTimeout` pair the handoff-queue deadline and the bridge-silence reconnect schedule on
354
+ * (ADR-0049 step 7) — injectable for deterministic tests, exactly the discipline `engine-router.ts` follows so
355
+ * the whole placement seam is unit-testable with no real timers.
356
+ */
357
+ export interface AttachClientTimers {
358
+ setTimeout(fn: () => void, ms: number): unknown;
359
+ clearTimeout(handle: unknown): void;
360
+ }
361
+
362
+ /**
363
+ * The RPC ops that MUTATE the store/journal or push to the server — the ones whose lost response after a
364
+ * relocation is `outcome: "unknown"` (a journal update may already exist, there is no dedup key; ADR-0049 D10,
365
+ * invariant 5). Everything NOT in this set is a READ (or an idempotent activation) that is safe to repeat, so it
366
+ * settles `outcome: "not-dispatched"`. `ensureSynced` is deliberately a read here: activation is additive and
367
+ * idempotent (starting an already-active group is a no-op), so repeating it can never double-apply. The
368
+ * `export*` ops read the store into an artefact (no mutation) and are likewise safe to repeat.
369
+ */
370
+ const MUTATION_RPC_OPS: ReadonlySet<RpcOp> = new Set<RpcOp>([
371
+ "create",
372
+ "update",
373
+ "delete",
374
+ "batch",
375
+ "transaction",
376
+ "flush",
377
+ "reconcile",
378
+ "retryFailed",
379
+ "recoverSending",
380
+ "discardConflict",
381
+ "discardQuarantined",
382
+ "desync",
383
+ "discardEphemeral",
384
+ // `rawExec` is WRITE-CAPABLE (its docstring: any write it issues stays local and will NOT converge), so a
385
+ // dispatched rawExec with a lost response is `"unknown"` — retrying could double-apply a local write.
386
+ "rawExec",
387
+ ]);
388
+
78
389
  export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
79
390
  registry: TRegistry;
80
- /** A native `Worker` or `SharedWorker` (or anything port-shaped). Provide this OR {@link port}. */
81
- worker?: WorkerLike;
391
+ /**
392
+ * The worker input — PRIMARILY a FACTORY `() => SharedWorker` (ADR-0049 D5). A `SharedWorker` object cannot be
393
+ * reconstructed from itself, so the factory is what makes SharedWorker-death recovery (the keepalive
394
+ * reconstruction, and the {@link bridgeSilenceMs} bridge-silence reconnect) a GUARANTEE rather than an option:
395
+ * both re-invoke it for a fresh SharedWorker. A bare instance (a native `Worker`/`SharedWorker`, or anything
396
+ * port-shaped) is ALSO accepted for tests and exotic hosts — reconstruction is then structurally unavailable
397
+ * (diagnostics say so). Provide this OR {@link port}.
398
+ */
399
+ worker?: (() => WorkerLike) | WorkerLike;
82
400
  /** A raw transport port (a `MessageChannel` port in tests, a `SharedWorker.port` in a browser). */
83
401
  port?: BridgePort;
84
402
  /**
@@ -130,6 +448,87 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
130
448
  * attaches AFTER the boot never receives the push — it reads the report via {@link SyncClient.bootReport}.
131
449
  */
132
450
  onBootReport?: (report: BootReport) => void;
451
+ /**
452
+ * The bridge-silence deadline (ms) for non-leader reconnection (ADR-0049 D5). DISABLED when undefined (the
453
+ * default); the election coordinator (step 8) sets it. When set: a pending op left with NO bridge traffic
454
+ * since it was posted, past this deadline, triggers ONE reconnect attempt via the {@link worker} FACTORY (if the
455
+ * input is a factory) — construct a fresh SharedWorker, resolve its port, re-attach, flush the queue,
456
+ * re-subscribe. With a bare-instance input reconstruction is structurally unavailable, so no reconnect is armed.
457
+ * Scheduled on {@link timers}.
458
+ */
459
+ bridgeSilenceMs?: number;
460
+ /**
461
+ * The bounded handoff queue (ADR-0049 invariant 9). While the handoff window is open — after a relocation
462
+ * notice, before the replacement pipe's handshake completes — new data-path ops are QUEUED, not posted.
463
+ * `cap` overflow or `deadlineMs` expiry fails queued ops with `EngineRelocatedError("not-dispatched")` (they
464
+ * never left the tab, so they are safe to retry). Defaults: `cap` 256, `deadlineMs` 15000. The deadline is
465
+ * scheduled on {@link timers}.
466
+ */
467
+ handoffQueue?: { cap?: number; deadlineMs?: number };
468
+ /**
469
+ * Injectable timers for the handoff-queue deadline and the bridge-silence reconnect (ADR-0049 step 7) — the
470
+ * same deterministic-test seam `engine-router.ts` exposes. Defaults to `globalThis.setTimeout`/`clearTimeout`.
471
+ */
472
+ timers?: AttachClientTimers;
473
+ /**
474
+ * The elected engine worker OVERRIDE (ADR-0049 D5). In `elected-worker` placement (a router-only SharedWorker)
475
+ * the tab's election coordinator spawns the real engine as a dedicated `Worker`. NORMALLY NO WIRING IS NEEDED:
476
+ * the worker entry is dual-scope (one file serves both homes), the SharedWorker reports its own script URL in the
477
+ * placement reply, and the winning tab constructs the engine as `new Worker(swScriptUrl, { type: "module" })`
478
+ * itself. Supply this override ONLY for entries that cannot be reconstructed from their URL as a module worker
479
+ * (classic-script workers, `blob:`/`data:` URLs, CSP constraints); wrap the constructed worker with
480
+ * {@link wrapEngineWorker}. When election is required but NEITHER a derivable URL NOR this override is available,
481
+ * attach fails with the typed {@link ElectedEngineUnconstructibleError} — never a silent no-engine attach.
482
+ */
483
+ createEngineWorker?: () => ElectedEngineWorker;
484
+ /**
485
+ * The opt-in engine-construction EXECUTION LIMIT (ADR-0049 D5) as this tab carries it — every tab attaching to a
486
+ * store MUST carry the SAME value the worker was constructed with (`ExecutionLimitMismatchError` on a mismatch).
487
+ * DISABLED by default (`undefined` / absent `maxDispatchMs`) — no finite worst-case query duration exists, so
488
+ * enabling the limit (which converts slow to terminated by policy) is a deliberate consumer choice. When
489
+ * `maxDispatchMs` is set AND this tab is on an elected per-tab pipe, a dispatched RPC still outstanding past the
490
+ * limit is reported to the router as an `overdue-dispatch` (the router then probes the engine's control channel;
491
+ * a WASM-blocked engine cannot answer → the leader retires + respawns it). ELECTED PLACEMENT ONLY — on SW-direct
492
+ * the option is rejected as unsupported during attach rather than silently ignored.
493
+ */
494
+ executionLimit?: ExecutionLimitConfig;
495
+ /**
496
+ * The leader-keepalive ping cadence (ms) the election coordinator uses (ADR-0049 step 8). Default 20000. The
497
+ * keepalive is the ONE standing timer that detects SharedWorker death (unanswered pings) → reconstruct via the
498
+ * {@link worker} factory + re-announce the still-live engine. Lower it to detect SW death faster.
499
+ */
500
+ keepaliveIntervalMs?: number;
501
+ /** Consecutive unanswered keepalive pings before SharedWorker reconstruction (ADR-0049 step 8). Default 2. */
502
+ keepaliveMissThreshold?: number;
503
+ /**
504
+ * Await the VFS ownership release after a deliberate engine termination (ADR-0049 step 8). Defaults to the
505
+ * documented no-op {@link resolvedOwnershipRelease} — the HONEST MINIMUM (step 11b follow-up 1): the
506
+ * OPFS-repacked VFS enforces ownership with EXCLUSIVE OPFS sync-access handles (`StoreOwnedError` /
507
+ * `STORE_OWNED`), NOT a Web Lock, so there is no lock name to `navigator.locks.request(..., { ifAvailable })`
508
+ * against here. The bounded wait therefore lives in the SUCCESSOR'S OPEN PATH: the respawned elected engine
509
+ * worker's own `createOpfsRepacked` open throws the owned-store contention error and is retried with backoff
510
+ * (the `openWithBoundedRetries` wrapper in `createClientPGlite`) until the dead worker's agent releases the
511
+ * handle — exactly the fault-matrix row "VFS ownership-lock release lag → successor open retries on contention
512
+ * until clear, bounded, then boot failure". Supply a custom async wait only to inject a real probe (tests do).
513
+ */
514
+ awaitOwnershipRelease?: () => Promise<void>;
515
+ /**
516
+ * @internal test seam (ADR-0049 step 10b): override the election coordinator's IO — the Web Locks surface and
517
+ * the page-lifecycle subscription. Production reads `navigator.locks` structurally and subscribes to real
518
+ * `pagehide`/`pageshow`. Injected so the election wiring is unit-testable with a fake locks (no real
519
+ * `navigator.locks` under Bun).
520
+ */
521
+ electionIo?: {
522
+ locks?: CoordinatorDeps["locks"];
523
+ pageLifecycle?: CoordinatorDeps["pageLifecycle"];
524
+ };
525
+ /**
526
+ * @internal test seam (ADR-0049 step 10b): override the destruction effects the ATTACHED `destroy()` runs
527
+ * after it detaches. Production builds real OPFS + meta-record + idb effects from the store path
528
+ * ({@link createStoreDestructionEffects}); injected so the supervised-destroy path is unit-testable with fake
529
+ * effects (effect-order assertions, ownership-lock-lag retry).
530
+ */
531
+ createDestructionEffects?: (storePath: string) => DestructionEffects;
133
532
  }
134
533
 
135
534
  /**
@@ -149,21 +548,245 @@ export type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient
149
548
  setOnline: (online: boolean) => void;
150
549
  };
151
550
 
551
+ /**
552
+ * The IO a shared election coordinator is built from (ADR-0049 step 8) — the subset both {@link attachSyncClient}
553
+ * and the elected {@link provisionSyncWorker} pass so ONE coordinator serves a tab's whole (provision + attach)
554
+ * lifecycle per store (invariant 2 — never self-queued). A module-level builder (not a per-call closure) so both
555
+ * entry points construct the identical coordinator.
556
+ */
557
+ interface ElectedCoordinatorParams {
558
+ storePath: string;
559
+ /** The SW control port the coordinator posts announce/keepalive on (the FIRST creator's connection). */
560
+ controlPort: BridgePort;
561
+ createEngineWorker: () => ElectedEngineWorker;
562
+ /** The SharedWorker reconstruction factory (ADR-0049 D5) — drives the keepalive SW-death recovery. Absent for a
563
+ bare-instance input, where reconstruction is structurally unavailable. */
564
+ swFactory?: () => WorkerLike;
565
+ electionIo?: AttachSyncClientOptions<SyncTableRegistry>["electionIo"];
566
+ awaitOwnershipRelease?: () => Promise<void>;
567
+ timers: AttachClientTimers;
568
+ pageLifecycle?: CoordinatorDeps["pageLifecycle"];
569
+ keepaliveIntervalMs?: number;
570
+ keepaliveMissThreshold?: number;
571
+ }
572
+
573
+ /**
574
+ * Build the tab's election coordinator over a SW control port. The spawn adapter mints the announce control
575
+ * channel and delivers its ENGINE end to the freshly-spawned worker; `createControlChannel` yields the SAME
576
+ * channel so `announce` transfers the ROUTER end to the SharedWorker; a re-announce WITHOUT a respawn (keepalive
577
+ * SW reconstruction) re-delivers a fresh engine-end to the retained live engine (step 11b follow-up 2).
578
+ */
579
+ function buildElectedCoordinator(params: ElectedCoordinatorParams): ElectionCoordinator {
580
+ const factory = params.createEngineWorker;
581
+ let pendingChannel: MessageChannel | undefined;
582
+ let liveEngine: ElectedEngineWorker | undefined;
583
+ const locks = params.electionIo?.locks ??
584
+ (globalThis as { navigator?: { locks?: CoordinatorDeps["locks"] } }).navigator?.locks ?? {
585
+ request: () => Promise.resolve(),
586
+ };
587
+ const deps: CoordinatorDeps = {
588
+ locks,
589
+ spawnEngineWorker: () => {
590
+ const engine = factory();
591
+ liveEngine = engine;
592
+ const channel = new MessageChannel();
593
+ pendingChannel = channel;
594
+ engine.deliverControlPort(channel.port2);
595
+ return { terminate: () => engine.terminate(), onError: (listener) => engine.onError(listener) };
596
+ },
597
+ createControlChannel: () => {
598
+ if (pendingChannel !== undefined) {
599
+ const channel = pendingChannel;
600
+ pendingChannel = undefined;
601
+ return { port1: channel.port1, port2: channel.port2 };
602
+ }
603
+ const channel = new MessageChannel();
604
+ liveEngine?.deliverControlPort(channel.port2);
605
+ return { port1: channel.port1, port2: channel.port2 };
606
+ },
607
+ swPort: params.controlPort as unknown as SwBridgePort,
608
+ ...(params.swFactory
609
+ ? { reconstructSw: () => resolvePort({ worker: params.swFactory! }) as unknown as SwBridgePort }
610
+ : {}),
611
+ awaitOwnershipRelease: params.awaitOwnershipRelease ?? resolvedOwnershipRelease,
612
+ timers: params.timers,
613
+ ...(params.pageLifecycle ? { pageLifecycle: params.pageLifecycle } : {}),
614
+ };
615
+ return createElectionCoordinator(deps, {
616
+ storePath: params.storePath,
617
+ ...(params.keepaliveIntervalMs != null ? { keepaliveIntervalMs: params.keepaliveIntervalMs } : {}),
618
+ ...(params.keepaliveMissThreshold != null ? { keepaliveMissThreshold: params.keepaliveMissThreshold } : {}),
619
+ });
620
+ }
621
+
622
+ /**
623
+ * Per-store SHARED election coordinators (ADR-0049 step 8 — "one coordinator per tab per store; provision and
624
+ * attach share it"). Populated ONLY by an elected {@link provisionSyncWorker}; a later {@link attachSyncClient}
625
+ * on the SAME store (same page realm) ADOPTS it (`claimForAttach` — no second lock request, no second engine,
626
+ * invariant 2). Empty when no provision ran, so attach-only flows never touch it (no shared coordinator to adopt). Keyed
627
+ * by store path; ref-counted so it clears once every provision claim + adopting attach has released.
628
+ */
629
+ const sharedCoordinators = new Map<
630
+ string,
631
+ {
632
+ coordinator: ElectionCoordinator;
633
+ refs: number;
634
+ /**
635
+ * The provision's live engine pipe, held for HANDOVER (ADR-0049 step 8). The router mints exactly ONE proxy
636
+ * pipe per SW connection; when provision and attach share one port (the documented ordered-messages contract,
637
+ * e.g. the board), that pipe is delivered during provisioning — so the adopting attach must receive THIS pipe
638
+ * rather than wait for a `connect-port` that will never be re-sent. Cleared on take; closed if never taken.
639
+ */
640
+ provisionPipe?: { pipe: BridgePort; identity: EngineIdentity };
641
+ }
642
+ >();
643
+
644
+ /** Adopt an existing per-store coordinator (incrementing its ref), or register a freshly-built one. */
645
+ function adoptOrRegisterCoordinator(storePath: string, build: () => ElectionCoordinator): ElectionCoordinator {
646
+ let entry = sharedCoordinators.get(storePath);
647
+ if (entry === undefined) {
648
+ entry = { coordinator: build(), refs: 0 };
649
+ sharedCoordinators.set(storePath, entry);
650
+ }
651
+ entry.refs += 1;
652
+ return entry.coordinator;
653
+ }
654
+
655
+ /** Look up an already-registered per-store coordinator WITHOUT registering one (attach's adopt-if-present probe). */
656
+ function lookupSharedCoordinator(storePath: string): ElectionCoordinator | undefined {
657
+ return sharedCoordinators.get(storePath)?.coordinator;
658
+ }
659
+
660
+ /** Increment the ref of an already-registered coordinator (an adopting attach); no-op if none is registered. */
661
+ function retainSharedCoordinator(storePath: string): void {
662
+ const entry = sharedCoordinators.get(storePath);
663
+ if (entry !== undefined) entry.refs += 1;
664
+ }
665
+
666
+ /** Release one ref; the entry clears at zero so a later provision/attach starts a fresh coordinator. */
667
+ function releaseSharedCoordinator(storePath: string): void {
668
+ const entry = sharedCoordinators.get(storePath);
669
+ if (entry === undefined) return;
670
+ entry.refs -= 1;
671
+ if (entry.refs <= 0) {
672
+ entry.provisionPipe?.pipe.close?.();
673
+ sharedCoordinators.delete(storePath);
674
+ }
675
+ }
676
+
677
+ /** Stash the provision's engine pipe for the adopting attach's handover; no-op when no entry is registered. */
678
+ function stashProvisionPipe(storePath: string, pipe: BridgePort, identity: EngineIdentity): void {
679
+ const entry = sharedCoordinators.get(storePath);
680
+ if (entry !== undefined) entry.provisionPipe = { pipe, identity };
681
+ }
682
+
683
+ /** Take (and clear) the stashed provision pipe — exactly one adopting attach may consume it. */
684
+ function takeProvisionPipe(storePath: string): { pipe: BridgePort; identity: EngineIdentity } | undefined {
685
+ const entry = sharedCoordinators.get(storePath);
686
+ const stashed = entry?.provisionPipe;
687
+ if (entry !== undefined) delete entry.provisionPipe;
688
+ return stashed;
689
+ }
690
+
152
691
  export async function attachSyncClient<const TRegistry extends SyncTableRegistry>(
153
692
  options: AttachSyncClientOptions<TRegistry>,
154
693
  ): Promise<AttachedSyncClient<TRegistry>> {
155
694
  const codec = options.codec ?? identityCodec;
156
695
  const port = resolvePort(options);
696
+ // The SharedWorker reconstruction factory (ADR-0049 D5), or undefined for a bare-instance/port input. Drives the
697
+ // bridge-silence reconnect and the coordinator's keepalive SW-reconstruction; both re-invoke it for a fresh
698
+ // SharedWorker. Absent → reconstruction is structurally unavailable and those recovery paths are simply not armed.
699
+ const workerFactory = workerFactoryOf(options.worker);
700
+
701
+ // ─── ADR-0049 placement seams (data-port indirection, handoff window, reconnect) ──────────────────
702
+ // `controlPort` permanently carries the `{ pgx0049 }` control plane (relocation notices + `connect-port`);
703
+ // `dataPort` starts AS the control port (SW-direct / declared-idbfs / no-pgx0049: the data path never leaves the SW port) and SWAPS to a
704
+ // transferred pipe on `connect-port`. Every data-path send goes through `currentDataPort()` so the pending
705
+ // maps stay in place across a swap (invariant 6 — one direct pipe per tab; the router never sees payloads).
706
+ let controlPort: BridgePort = port;
707
+ let dataPort: BridgePort = port;
708
+ const currentDataPort = (): BridgePort => dataPort;
709
+ const timers: AttachClientTimers = options.timers ?? {
710
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
711
+ clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),
712
+ };
713
+ // The current engine identity (invariant 7 — the pair), set on each accepted `connect-port`; `hasPipe` marks
714
+ // that the data path has left the control port. The handoff window (`windowOpen`) queues new ops.
715
+ let currentEngineIdentity: EngineIdentity | undefined;
716
+ let hasPipe = false;
717
+ let windowOpen = false;
718
+ // Bounded handoff queue (invariant 9): thunks deferred while the window is open, each carrying a `reject` so
719
+ // cap-overflow / deadline-expiry can fail the caller with `EngineRelocatedError("not-dispatched")`.
720
+ const handoffQueue: Array<{ dispatch: () => void; reject: (error: Error) => void }> = [];
721
+ const queueCap = options.handoffQueue?.cap ?? 256;
722
+ const queueDeadlineMs = options.handoffQueue?.deadlineMs ?? 15000;
723
+ let queueDeadlineHandle: unknown;
724
+ // Bridge-silence reconnect (D5): armed on each dispatch when `bridgeSilenceMs` + a factory are set; ONE
725
+ // attempt. `bridgeSeenSinceArm` distinguishes a live-but-slow engine from true silence.
726
+ let silenceHandle: unknown;
727
+ let bridgeSeenSinceArm = false;
728
+ let reconnecting = false;
729
+ // ─── ADR-0049 election + supervised-destroy state ─────────────────────────────────────────────────
730
+ // The tab's election coordinator (created lazily on a router-only `electionRequired` placement reply — the
731
+ // elected engine factory is the `createEngineWorker` override or the URL-derived default) + its released-on-detach
732
+ // claim; and the pending destroy peer-count verdict resolver (the SharedWorker answers a `{ [DESTROY_QUERY_KEY] }`
733
+ // query with the attached-tab count).
734
+ let electionCoordinator: ElectionCoordinator | undefined;
735
+ let releaseElectionClaim: (() => void) | undefined;
736
+ let destroyVerdictResolver: ((peers: number) => void) | undefined;
737
+ let placementResult: PlacementQueryResult | undefined;
738
+ let swTeardownAckResolver: ((error?: { message: string; detail?: unknown }) => void) | undefined;
739
+ let swTeardownIdentity: EngineIdentity | undefined;
740
+ // Set to the store path when this attach ADOPTED a shared (provision-registered) coordinator — so detach
741
+ // releases the shared ref (ref-counted registry cleanup). Undefined when this tab built its own coordinator.
742
+ let adoptedSharedCoordinatorStore: string | undefined;
743
+ // The placement decision is single-shot: once we act on the first `electionRequired` reply we ignore any repeat.
744
+ let placementDecided = false;
745
+
746
+ // ─── ADR-0049 first-attach gate (placement-query-FIRST ordering — elected-mode ack routing) ───────
747
+ // `attachSyncClient` no longer gates on the SW-port attach ack: a router-only SharedWorker (elected-worker home)
748
+ // is payload-blind and DROPS the bridge `attach`, so that ack would never come there. Instead the attach resolves
749
+ // when the FIRST attach ack lands from EITHER home — the in-scope SW engine (SW-direct / declared-idbfs / no-SW
750
+ // baseline) OR the elected engine over the per-tab pipe (`onConnectPort`, after election delivers `connect-port`).
751
+ // It REJECTS on a boot-failure ack, on detach, or — when election is required but the engine worker cannot be
752
+ // constructed — with the typed {@link ElectedEngineUnconstructibleError} (a WIRING failure, never a hang). With a
753
+ // constructible engine, the coordinator's own election spawns it and delivers the pipe, so no attach deadline exists.
754
+ let firstAttachSettled = false;
755
+ let resolveFirstAttach!: () => void;
756
+ let rejectFirstAttach!: (error: Error) => void;
757
+ const firstAttachReady = new Promise<void>((resolve, reject) => {
758
+ resolveFirstAttach = resolve;
759
+ rejectFirstAttach = reject;
760
+ });
761
+ void firstAttachReady.catch(() => undefined);
762
+ const settleFirstAttach = (): void => {
763
+ if (firstAttachSettled) return;
764
+ firstAttachSettled = true;
765
+ resolveFirstAttach();
766
+ };
767
+ const failFirstAttach = (error: Error): void => {
768
+ if (firstAttachSettled) return;
769
+ firstAttachSettled = true;
770
+ rejectFirstAttach(error);
771
+ };
157
772
 
158
773
  // ─── Correlation + subscription bookkeeping ──────────────────────────────────────────────────────
159
774
  let nextId = 0;
160
775
  const newId = (prefix: string) => `${prefix}-${++nextId}`;
161
- const rpcPending = new Map<string, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();
776
+ // `kind` (ADR-0049 invariant 5): a lost response on a MUTATION settles `outcome: "unknown"`, on a READ
777
+ // `outcome: "not-dispatched"` (safe to repeat). Stamped at every `rpc` call site from {@link MUTATION_RPC_OPS}.
778
+ const rpcPending = new Map<
779
+ string,
780
+ { resolve: (value: unknown) => void; reject: (error: Error) => void; kind: "read" | "mutation" }
781
+ >();
162
782
  const initialPending = new Map<
163
783
  string,
164
784
  { resolve: (payload: LiveInitialPayload) => void; reject: (error: Error) => void }
165
785
  >();
166
786
  const diffHandlers = new Map<string, (diff: Omit<LiveDiffPayload, "queryId">) => void>();
787
+ // Live subscriptions that have completed their initial snapshot (keyed by queryId) — re-issued through the
788
+ // same subscribe machinery on a pipe swap so live queries re-establish (invariant 5; ADR-0041 re-attach).
789
+ const activeSubscriptions = new Map<string, { resubscribe: () => void }>();
167
790
  // Resolvers for per-subscription `hydrated` promises, keyed by queryId. The worker posts
168
791
  // `live-hydrated` on the same port as the diff stream, strictly after the catch-up rows — so
169
792
  // resolution here guarantees the rows have already been applied by the materializer.
@@ -192,11 +815,11 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
192
815
  // ─── Auth: push at attach + on notifyAuthChanged, answer pull-requests ────────────────────────────
193
816
  const pushToken = async () => {
194
817
  const token = options.getToken ? await options.getToken() : null;
195
- postBridgeMessage(port, codec, "token-push", token);
818
+ postBridgeMessage(currentDataPort(), codec, "token-push", token);
196
819
  };
197
820
  const answerPull = async (requestId: string) => {
198
821
  const token = options.getToken ? await options.getToken() : null;
199
- postBridgeMessage(port, codec, "token-response", { requestId, token });
822
+ postBridgeMessage(currentDataPort(), codec, "token-response", { requestId, token });
200
823
  };
201
824
 
202
825
  // ─── Inbound message routing ─────────────────────────────────────────────────────────────────────
@@ -289,6 +912,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
289
912
 
290
913
  const listener = (message: { data: unknown }) => {
291
914
  if (!isBridgeEnvelope(message.data)) return;
915
+ // Any bridge traffic on the data port proves the engine is answering — clears the bridge-silence suspicion
916
+ // (ADR-0049 D5), so a live-but-slow engine is never mistaken for a dead SharedWorker.
917
+ bridgeSeenSinceArm = true;
292
918
  const envelope = message.data;
293
919
  const payload = codec.decode(envelope.payload);
294
920
  switch (envelope.type) {
@@ -300,7 +926,13 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
300
926
  // fold any downstream milestones/failures the tail already crossed (a late attach). `engineReady`
301
927
  // covers a LATE attach whose engine already fired its monotonic `ready` before this ack (FIX 3).
302
928
  if (ack.error) {
303
- attachAckReject?.(rebuildError(ack.error));
929
+ const settle = pendingAttachAck;
930
+ pendingAttachAck = null;
931
+ const bootError = rebuildError(ack.error);
932
+ settle?.reject(bootError);
933
+ // A boot-failure ack on the FIRST attach (SW-direct) fails `attachSyncClient` (invariant: never hand out
934
+ // a client whose engine failed to boot); a no-op once the first attach already settled (a re-attack ack).
935
+ failFirstAttach(bootError);
304
936
  } else {
305
937
  if (ack.engineReady) markReady();
306
938
  resolveLocalReadReady();
@@ -310,7 +942,12 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
310
942
  if (ack.writeReadyError) failWriteReady(rebuildError(ack.writeReadyError));
311
943
  if (ack.bootSettled) settleBootSettled();
312
944
  if (ack.bootSettledError) failBootSettled(rebuildError(ack.bootSettledError));
313
- attachAckResolve?.(ack);
945
+ const settle = pendingAttachAck;
946
+ pendingAttachAck = null;
947
+ settle?.resolve(ack);
948
+ // The first attach ack from EITHER home (SW-direct engine, or the elected engine over the pipe) resolves
949
+ // `attachSyncClient`. Idempotent — a re-attach ack (pipe swap / reconnect) is a no-op here.
950
+ settleFirstAttach();
314
951
  }
315
952
  break;
316
953
  }
@@ -324,8 +961,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
324
961
  const pending = rpcPending.get(id);
325
962
  if (pending) {
326
963
  rpcPending.delete(id);
964
+ clearOverdue(id);
327
965
  if (result.ok) pending.resolve(result.value);
328
- else pending.reject(rebuildError(result.error));
966
+ else pending.reject(rebuildRpcError(result.error));
329
967
  break;
330
968
  }
331
969
  // A failed `subscribe` is reported as an `rpc-result` correlated by the subscribe's envelope id
@@ -334,7 +972,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
334
972
  const initial = initialPending.get(id);
335
973
  if (initial && !result.ok) {
336
974
  initialPending.delete(id);
337
- initial.reject(rebuildError(result.error));
975
+ initial.reject(rebuildRpcError(result.error));
338
976
  }
339
977
  break;
340
978
  }
@@ -368,28 +1006,438 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
368
1006
  break;
369
1007
  }
370
1008
  };
371
- port.addEventListener("message", listener);
372
- port.start?.();
1009
+ // ─── ADR-0049 control-plane listener (the `{ pgx0049 }` envelope) ─────────────────────────────────
1010
+ // Lives on the CONTROL port for this tab's whole lifetime. It reacts to exactly the placement messages: a
1011
+ // `connect-port` (with a transferred pipe) swaps the data path; a `leader-granted`/`engine-retiring` notice
1012
+ // opens the handoff window. Foreign traffic (data-path bridge envelopes, anything else) is untouched — the
1013
+ // control plane is INERT until pgx0049 traffic arrives, so a plain SW-port attach is pure data-path passthrough.
1014
+ const controlListener = (event: { data: unknown; ports?: readonly BridgePort[] }) => {
1015
+ // ADR-0049 step 10b: the SharedWorker's RAW placement reply + destroy peer-count verdict (distinct envelope
1016
+ // keys, NOT `pgx0049` control messages). Handle those first, then fall through to the control envelope.
1017
+ const placementResult = readPlacementResult(event.data);
1018
+ if (placementResult !== undefined) {
1019
+ onPlacementResult(placementResult);
1020
+ return;
1021
+ }
1022
+ const destroyPeers = readDestroyVerdict(event.data);
1023
+ if (destroyPeers !== undefined) {
1024
+ destroyVerdictResolver?.(destroyPeers);
1025
+ return;
1026
+ }
1027
+ const control = readControlEnvelope(event.data);
1028
+ if (control === undefined) return;
1029
+ switch (control.type) {
1030
+ case "connect-port":
1031
+ void onConnectPort(control.identity, event.ports?.[0]);
1032
+ break;
1033
+ case "control-ack":
1034
+ if (
1035
+ control.pingId === -1 &&
1036
+ swTeardownIdentity !== undefined &&
1037
+ engineIdentityEquals(control.identity, swTeardownIdentity)
1038
+ ) {
1039
+ swTeardownAckResolver?.(control.error);
1040
+ }
1041
+ break;
1042
+ case "leader-granted":
1043
+ case "engine-retiring":
1044
+ onRelocationNotice(control);
1045
+ break;
1046
+ default:
1047
+ break;
1048
+ }
1049
+ };
1050
+
1051
+ // The bridge listener starts on the data port (initially === the control port); the control listener stays on
1052
+ // the control port. In the no-pgx0049 case both sit on the one `port` and coexist (each ignores the other's
1053
+ // traffic), so the data path is unchanged.
1054
+ dataPort.addEventListener("message", listener);
1055
+ dataPort.start?.();
1056
+ controlPort.addEventListener("message", controlListener);
1057
+ controlPort.start?.();
1058
+
1059
+ // ─── Data-port swap + handoff-queue + reconnect machinery (ADR-0049) ──────────────────────────────
1060
+ /** Move the bridge listener onto `next`; close the previous pipe when replacing one (never the control port). */
1061
+ const swapDataPort = (next: BridgePort, closePrev: boolean): void => {
1062
+ const prev = dataPort;
1063
+ if (prev === next) return;
1064
+ next.addEventListener("message", listener);
1065
+ next.start?.();
1066
+ prev.removeEventListener("message", listener);
1067
+ // The control port keeps carrying `{ pgx0049 }` and MUST NOT be closed on the first swap; a replaced pipe is
1068
+ // dead and IS closed (invariant 5 — old-pipe pendings settled, the pipe closed, never replayed).
1069
+ if (closePrev && prev !== controlPort) prev.close?.();
1070
+ dataPort = next;
1071
+ };
1072
+
1073
+ /**
1074
+ * Settle EVERY in-flight pending op by outcome (ADR-0049 invariant 5) — used on a relocation notice, a pipe
1075
+ * replacement, and a reconnect. A MUTATION whose response is lost is `"unknown"` (its journal update may
1076
+ * exist; inspect/reconcile, never auto-retry); a dispatched READ is `"not-dispatched"` — the name means
1077
+ * "safe to retry" (a read cannot double-apply; ADR-0049 D10: "dispatched reads are safe to repeat — caller
1078
+ * policy"). Live-query initial pendings are reads → `"not-dispatched"`; `hydrated` promises are doneness
1079
+ * signals with no reject path, so they RESOLVE (the file's existing convention on teardown), and re-subscribe
1080
+ * re-hydrates. Nothing is ever auto-retried here.
1081
+ */
1082
+ const settleInFlight = (): void => {
1083
+ for (const [id, pending] of rpcPending) {
1084
+ rpcPending.delete(id);
1085
+ clearOverdue(id);
1086
+ pending.reject(new EngineRelocatedError(pending.kind === "mutation" ? "unknown" : "not-dispatched"));
1087
+ }
1088
+ for (const [id, pending] of initialPending) {
1089
+ initialPending.delete(id);
1090
+ pending.reject(new EngineRelocatedError("not-dispatched"));
1091
+ }
1092
+ for (const resolve of hydratedPending.values()) resolve();
1093
+ hydratedPending.clear();
1094
+ };
1095
+
1096
+ const clearQueueDeadline = (): void => {
1097
+ if (queueDeadlineHandle !== undefined) {
1098
+ timers.clearTimeout(queueDeadlineHandle);
1099
+ queueDeadlineHandle = undefined;
1100
+ }
1101
+ };
1102
+ const armQueueDeadline = (): void => {
1103
+ if (queueDeadlineHandle !== undefined) return;
1104
+ queueDeadlineHandle = timers.setTimeout(() => {
1105
+ queueDeadlineHandle = undefined;
1106
+ // The window outlived the deadline — the queued work never left the tab, so fail it "not-dispatched".
1107
+ const items = handoffQueue.splice(0);
1108
+ for (const item of items) item.reject(new EngineRelocatedError("not-dispatched"));
1109
+ }, queueDeadlineMs);
1110
+ };
1111
+ /** Enqueue a deferred data-path op while the window is open; cap overflow fails it "not-dispatched" at once. */
1112
+ const enqueue = (dispatch: () => void, reject: (error: Error) => void): void => {
1113
+ if (handoffQueue.length >= queueCap) {
1114
+ reject(new EngineRelocatedError("not-dispatched"));
1115
+ return;
1116
+ }
1117
+ handoffQueue.push({ dispatch, reject });
1118
+ armQueueDeadline();
1119
+ };
1120
+ /** Flush the queue in order after a successful re-attach; clears the deadline. */
1121
+ const flushQueue = (): void => {
1122
+ clearQueueDeadline();
1123
+ const items = handoffQueue.splice(0);
1124
+ for (const item of items) item.dispatch();
1125
+ };
1126
+
1127
+ const resubscribeAll = (): void => {
1128
+ for (const sub of activeSubscriptions.values()) sub.resubscribe();
1129
+ };
1130
+
1131
+ /** A relocation notice opens the handoff window: settle in-flight per invariant 5, then QUEUE new calls. */
1132
+ function onRelocationNotice(control: EngineControlMessage): void {
1133
+ if (detached) return;
1134
+ // `engine-retiring` is identity-tagged: ignore a STALE one (a superseded engine) once we have an identity;
1135
+ // `leader-granted` is untagged and always applies (it precedes any engine).
1136
+ if (
1137
+ control.type === "engine-retiring" &&
1138
+ currentEngineIdentity !== undefined &&
1139
+ isStaleIdentity(currentEngineIdentity, control.identity)
1140
+ ) {
1141
+ return;
1142
+ }
1143
+ if (windowOpen) return;
1144
+ windowOpen = true;
1145
+ settleInFlight();
1146
+ armQueueDeadline();
1147
+ }
1148
+
1149
+ /**
1150
+ * A `connect-port` delivers a transferred pipe (invariant 6). The FIRST one swaps the data path off the
1151
+ * control port and re-attaches over the pipe. A SUBSEQUENT one under a NEWER identity is a pipe REPLACEMENT
1152
+ * (a new SharedWorker handing fresh pipes): settle old-pipe in-flight, close the old pipe, swap, re-attach,
1153
+ * flush the queue, and re-subscribe every live query.
1154
+ */
1155
+ async function onConnectPort(identity: EngineIdentity, pipe: BridgePort | undefined): Promise<void> {
1156
+ if (detached || pipe === undefined) return;
1157
+ // A duplicate for the SAME identity we already piped is a no-op (never re-pipe the same engine).
1158
+ if (currentEngineIdentity !== undefined && engineIdentityEquals(currentEngineIdentity, identity)) return;
1159
+ const replacing = hasPipe;
1160
+ // Hold the window open across the swap+handshake so calls issued mid-flight queue rather than race.
1161
+ windowOpen = true;
1162
+ if (replacing) settleInFlight();
1163
+ currentEngineIdentity = identity;
1164
+ swapDataPort(pipe, replacing);
1165
+ hasPipe = true;
1166
+ try {
1167
+ await runAttachHandshake(pipe, false);
1168
+ } catch {
1169
+ // A failed re-attach leaves the window open; a later notice / connect-port can retry. Never auto-retried.
1170
+ return;
1171
+ }
1172
+ windowOpen = false;
1173
+ flushQueue();
1174
+ resubscribeAll();
1175
+ }
1176
+
1177
+ /** Arm the bridge-silence timer after a dispatch (D5) — only when a deadline AND a SharedWorker factory exist. */
1178
+ const armSilence = (): void => {
1179
+ if (options.bridgeSilenceMs === undefined || workerFactory === undefined) return;
1180
+ if (silenceHandle !== undefined || detached) return;
1181
+ bridgeSeenSinceArm = false;
1182
+ silenceHandle = timers.setTimeout(() => {
1183
+ silenceHandle = undefined;
1184
+ if (detached) return;
1185
+ // A pending op survived the deadline with NO bridge traffic since it was posted → the transport looks
1186
+ // dead. Reconnect ONCE. If traffic WAS seen but ops are still pending, re-arm (a slow-but-live engine).
1187
+ if (!bridgeSeenSinceArm && rpcPending.size > 0) void reconnect();
1188
+ else if (rpcPending.size > 0) armSilence();
1189
+ }, options.bridgeSilenceMs);
1190
+ };
1191
+
1192
+ /**
1193
+ * ONE bridge-silence reconnect attempt (ADR-0049 D5): construct a fresh SharedWorker via the worker FACTORY, move
1194
+ * both listeners to its port, settle the presumed-dead transport's in-flight per invariant 5, re-run the attach
1195
+ * handshake, then flush + re-subscribe. With a bare-instance input (no factory) this is unreachable — reconstruction
1196
+ * is structurally unavailable. Never more than one concurrent attempt.
1197
+ */
1198
+ async function reconnect(): Promise<void> {
1199
+ if (reconnecting || detached || workerFactory === undefined) return;
1200
+ reconnecting = true;
1201
+ let newPort: BridgePort;
1202
+ try {
1203
+ newPort = resolvePort({ worker: workerFactory });
1204
+ } catch {
1205
+ reconnecting = false;
1206
+ return;
1207
+ }
1208
+ settleInFlight();
1209
+ dataPort.removeEventListener("message", listener);
1210
+ controlPort.removeEventListener("message", controlListener);
1211
+ controlPort = newPort;
1212
+ dataPort = newPort;
1213
+ hasPipe = false;
1214
+ currentEngineIdentity = undefined;
1215
+ windowOpen = true;
1216
+ newPort.addEventListener("message", listener);
1217
+ newPort.addEventListener("message", controlListener);
1218
+ newPort.start?.();
1219
+ try {
1220
+ await runAttachHandshake(newPort, false);
1221
+ } catch {
1222
+ reconnecting = false;
1223
+ return;
1224
+ }
1225
+ windowOpen = false;
1226
+ flushQueue();
1227
+ resubscribeAll();
1228
+ reconnecting = false;
1229
+ }
1230
+
1231
+ // ─── ADR-0049 election wiring + supervised destroy ────────────────────────────────────────────────
1232
+ /** The store PATH this tab owns — the identity every store-IO surface (OPFS namespaces, meta record, idb db, leader lock) derives from. */
1233
+ const resolveDestroyStorePath = (): string => options.storePath ?? options.storeId ?? "pgxsinkit-overlay-v1";
1234
+ // The elected engine worker factory for THIS attach (ADR-0049 D5): the `createEngineWorker` OVERRIDE, else the
1235
+ // default derived from the SharedWorker's reported script URL (`new Worker(url, { type: "module" })`). Resolved on
1236
+ // the `electionRequired` reply; `undefined` means neither is available — a WIRING failure, not a fallback.
1237
+ let electedEngineFactory: (() => ElectedEngineWorker) | undefined;
1238
+
1239
+ /**
1240
+ * The SharedWorker reported the engine home. In `elected-worker` (router-only) mode this tab must elect its own
1241
+ * engine: resolve the engine factory (the `createEngineWorker` override, else the URL-derived default), build the
1242
+ * coordinator (once), and take one attach claim. When NEITHER a derivable URL NOR an override is available the
1243
+ * engine is genuinely unconstructible on a handle-denied home — a WIRING failure, so the attach fails with the
1244
+ * typed {@link ElectedEngineUnconstructibleError} (never a silent no-engine attach). `shared-worker` (SW-direct /
1245
+ * declared-idbfs) needs no election.
1246
+ */
1247
+ function onPlacementResult(result: PlacementQueryResult): void {
1248
+ if (detached || placementDecided) return;
1249
+ placementDecided = true;
1250
+ placementResult = result;
1251
+ // SW-direct / declared-idbfs (or a non-placement transport that never replies): the SW-port attach ack gates the flow.
1252
+ if (!result.electionRequired) return;
1253
+ // Elected-worker (router-only): resolve the engine factory. Auto-derivation from the reported script URL is the
1254
+ // default (dual-scope entry); the `createEngineWorker` override wins where an entry is not URL-reconstructible.
1255
+ electedEngineFactory = options.createEngineWorker ?? deriveEngineWorkerFactory(result.swScriptUrl);
1256
+ if (electedEngineFactory === undefined) {
1257
+ // The capability is PRESENT (this home requires election) but the engine cannot be constructed — a wiring
1258
+ // defect. Fail the attach typed; never a silent no-engine attach and never a storage downgrade (ADR-0049 D1).
1259
+ failFirstAttach(
1260
+ new ElectedEngineUnconstructibleError(
1261
+ result.swScriptUrl === undefined
1262
+ ? "the SharedWorker reported no derivable script URL and no `createEngineWorker` override was supplied"
1263
+ : "no `Worker` constructor is available in this scope to derive the module engine and no override was supplied",
1264
+ ),
1265
+ );
1266
+ return;
1267
+ }
1268
+ // ADOPT an existing PROVISION grant for this store if one is registered (ADR-0049 step 8, fault row
1269
+ // "provision then attach, same tab → attach adopts the provision grant; never self-queued"): reuse the same
1270
+ // coordinator + its already-granted lock + already-spawned engine — `claimForAttach` adds NO second lock
1271
+ // request and spawns NO second engine (invariant 2). The router pipes this tab's OWN connection to that engine
1272
+ // and the boot adopts the provisioned store (no double initdb). Absent → build this tab's own coordinator.
1273
+ const storePath = resolveDestroyStorePath();
1274
+ const adopted = lookupSharedCoordinator(storePath);
1275
+ if (adopted !== undefined) {
1276
+ retainSharedCoordinator(storePath);
1277
+ adoptedSharedCoordinatorStore = storePath;
1278
+ electionCoordinator = adopted;
1279
+ } else {
1280
+ electionCoordinator = buildElectionCoordinator();
1281
+ }
1282
+ releaseElectionClaim = electionCoordinator.claimForAttach();
1283
+ // Provision-pipe HANDOVER (ADR-0049 step 8): when this attach shares its SW port with the provision that
1284
+ // registered the adopted coordinator, the router's one-and-only pipe for this connection was already
1285
+ // delivered during provisioning — feed it into the normal connect-port path instead of waiting for a
1286
+ // re-send that never comes. On a fresh (non-shared) port the stash is empty and the router's ordinary
1287
+ // late-joiner `connect-port` drives the handshake as usual.
1288
+ if (adopted !== undefined) {
1289
+ const stashed = takeProvisionPipe(storePath);
1290
+ if (stashed !== undefined) void onConnectPort(stashed.identity, stashed.pipe);
1291
+ }
1292
+ }
1293
+
1294
+ /**
1295
+ * SW-direct stores are owned by the in-scope host, not an elected coordinator. Ask that host to quiesce and
1296
+ * close, then await its reserved teardown ack before detaching this tab and deleting the store. A timeout is
1297
+ * deliberately not treated as proof of worker death: destruction still runs and its bounded ownership retry
1298
+ * reports an honest failure while the durable `deleting` phase remains recoverable.
1299
+ */
1300
+ const awaitSharedHostTeardown = async (): Promise<void> => {
1301
+ const placement = placementResult;
1302
+ if (placement?.engineHome !== "shared-worker") return;
1303
+ const identity: EngineIdentity = { swInstanceId: placement.swInstanceId, generation: 0 };
1304
+ await new Promise<void>((resolve, reject) => {
1305
+ let settled = false;
1306
+ const timeout = timers.setTimeout(() => {
1307
+ if (settled) return;
1308
+ settled = true;
1309
+ swTeardownAckResolver = undefined;
1310
+ swTeardownIdentity = undefined;
1311
+ resolve();
1312
+ }, 5_000);
1313
+ swTeardownIdentity = identity;
1314
+ swTeardownAckResolver = (error) => {
1315
+ if (settled) return;
1316
+ settled = true;
1317
+ timers.clearTimeout(timeout);
1318
+ swTeardownAckResolver = undefined;
1319
+ swTeardownIdentity = undefined;
1320
+ if (error) reject(new Error(`[pgxsinkit] SW-direct host teardown failed: ${error.message}`));
1321
+ else resolve();
1322
+ };
1323
+ controlPort.postMessage(wrapControlEnvelope({ type: "engine-teardown", identity }));
1324
+ });
1325
+ };
1326
+
1327
+ /**
1328
+ * Construct the tab's election coordinator over the SW control port. The spawn adapter creates the announce
1329
+ * control channel and delivers its ENGINE end (`port2`) to the freshly-spawned worker (fixing step-8's
1330
+ * "port2 went nowhere"); `createControlChannel` then returns the SAME channel so the coordinator's `announce`
1331
+ * transfers the ROUTER end (`port1`) to the SharedWorker. `navigator.locks` is read structurally (injectable
1332
+ * for tests); the page-lifecycle subscription is the real `pagehide`/`pageshow` (also injectable).
1333
+ */
1334
+ function buildElectionCoordinator(): ElectionCoordinator {
1335
+ return buildElectedCoordinator({
1336
+ storePath: resolveDestroyStorePath(),
1337
+ controlPort,
1338
+ createEngineWorker: electedEngineFactory!,
1339
+ ...(workerFactory ? { swFactory: workerFactory } : {}),
1340
+ ...(options.electionIo ? { electionIo: options.electionIo } : {}),
1341
+ ...(options.awaitOwnershipRelease ? { awaitOwnershipRelease: options.awaitOwnershipRelease } : {}),
1342
+ timers,
1343
+ ...(pageLifecycle ? { pageLifecycle } : {}),
1344
+ ...(options.keepaliveIntervalMs != null ? { keepaliveIntervalMs: options.keepaliveIntervalMs } : {}),
1345
+ ...(options.keepaliveMissThreshold != null ? { keepaliveMissThreshold: options.keepaliveMissThreshold } : {}),
1346
+ });
1347
+ }
1348
+
1349
+ /** Ask the SharedWorker how many tabs are attached (this one included) — the destroy peer-refusal gate. */
1350
+ const queryDestroyPeers = (): Promise<number> =>
1351
+ new Promise<number>((resolve, reject) => {
1352
+ const timeout = timers.setTimeout(() => {
1353
+ destroyVerdictResolver = undefined;
1354
+ reject(new Error("[pgxsinkit] destroy() timed out waiting for the SharedWorker peer-count verdict."));
1355
+ }, options.handoffQueue?.deadlineMs ?? 15000);
1356
+ destroyVerdictResolver = (peers) => {
1357
+ timers.clearTimeout(timeout);
1358
+ destroyVerdictResolver = undefined;
1359
+ resolve(peers);
1360
+ };
1361
+ controlPort.postMessage({ [DESTROY_QUERY_KEY]: true });
1362
+ });
1363
+
1364
+ // ─── ADR-0049 D5: execution-limit OVERDUE-DISPATCH reporting (tab side) ────────────────────────────
1365
+ // When `executionLimit.maxDispatchMs` is set and this tab holds a per-tab pipe (elected engine), a dispatched
1366
+ // RPC still pending past the limit is reported ONCE to the router as an identity-tagged `overdue-dispatch`. The
1367
+ // router then probes the engine control channel; a WASM-blocked engine cannot answer on its event loop, so the
1368
+ // router (past its probe threshold) fans `engine-retiring` and the leader terminates + respawns it. The router
1369
+ // NEVER treats slow-below-threshold as death (a long query under the limit runs to completion). Per-id timers,
1370
+ // cleared on settlement; reported on the CONTROL port (where the router listens), stamped with the current
1371
+ // engine identity so the router discards a stale report. SW-direct has no pipe/identity, so it never arms.
1372
+ const overdueMs = options.executionLimit?.maxDispatchMs;
1373
+ const overdueTimers = new Map<string, unknown>();
1374
+ const clearOverdue = (id: string): void => {
1375
+ const handle = overdueTimers.get(id);
1376
+ if (handle !== undefined) {
1377
+ timers.clearTimeout(handle);
1378
+ overdueTimers.delete(id);
1379
+ }
1380
+ };
1381
+ const clearAllOverdue = (): void => {
1382
+ for (const handle of overdueTimers.values()) timers.clearTimeout(handle);
1383
+ overdueTimers.clear();
1384
+ };
1385
+ const armOverdue = (id: string): void => {
1386
+ if (overdueMs === undefined) return;
1387
+ overdueTimers.set(
1388
+ id,
1389
+ timers.setTimeout(() => {
1390
+ overdueTimers.delete(id);
1391
+ // Report only while the op is genuinely still outstanding on a live pipe (we know the engine identity).
1392
+ if (detached || !rpcPending.has(id) || currentEngineIdentity === undefined) return;
1393
+ controlPort.postMessage(
1394
+ wrapControlEnvelope({
1395
+ type: "overdue-dispatch",
1396
+ identity: currentEngineIdentity,
1397
+ elapsedMs: overdueMs,
1398
+ }),
1399
+ );
1400
+ }, overdueMs),
1401
+ );
1402
+ };
373
1403
 
374
1404
  // ─── RPC helper ──────────────────────────────────────────────────────────────────────────────────
375
1405
  const rpc = <T>(op: RpcOp, args: unknown[]): Promise<T> => {
376
1406
  // A detached client has no live port listener, so a worker reply could never resolve this — reject at
377
1407
  // once rather than register a forever-pending waiter (ADR-0040 P2).
378
1408
  if (detached) return Promise.reject(detachError());
379
- const id = newId("rpc");
1409
+ const kind: "read" | "mutation" = MUTATION_RPC_OPS.has(op) ? "mutation" : "read";
380
1410
  return new Promise<T>((resolve, reject) => {
381
- rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject });
382
- postBridgeMessage(port, codec, "rpc", { op, args }, id);
1411
+ const dispatch = () => {
1412
+ const id = newId("rpc");
1413
+ rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject, kind });
1414
+ postBridgeMessage(currentDataPort(), codec, "rpc", { op, args }, id);
1415
+ armSilence();
1416
+ armOverdue(id);
1417
+ };
1418
+ // While the handoff window is open, QUEUE rather than post (invariant 9); otherwise dispatch immediately.
1419
+ if (windowOpen) enqueue(dispatch, reject);
1420
+ else dispatch();
383
1421
  });
384
1422
  };
385
1423
 
386
1424
  // ─── Attach handshake ────────────────────────────────────────────────────────────────────────────
387
- let attachAckResolve: ((ack: AttachAckPayload) => void) | null = null;
388
- let attachAckReject: ((error: Error) => void) | null = null;
389
- const attachAck = new Promise<AttachAckPayload>((resolve, reject) => {
390
- attachAckResolve = resolve;
391
- attachAckReject = reject;
392
- });
1425
+ // Re-entrant (ADR-0049): the SAME handshake runs for the FIRST attach and for every re-attach (pipe swap,
1426
+ // reconnect). `pendingAttachAck` holds whichever handshake is currently awaiting its `attach-ack`; the bridge
1427
+ // listener settles it. `runAttachHandshake` posts `attach` over a target port and awaits the ack.
1428
+ let pendingAttachAck: { resolve: (ack: AttachAckPayload) => void; reject: (error: Error) => void } | null = null;
1429
+ const runAttachHandshake = (target: BridgePort, includeRestore: boolean): Promise<AttachAckPayload> =>
1430
+ new Promise<AttachAckPayload>((resolve, reject) => {
1431
+ pendingAttachAck = { resolve, reject };
1432
+ postBridgeMessage(
1433
+ target,
1434
+ codec,
1435
+ "attach",
1436
+ buildAttachPayload(includeRestore),
1437
+ undefined,
1438
+ includeRestore && restoreWire ? [restoreWire.buffer] : undefined,
1439
+ );
1440
+ });
393
1441
 
394
1442
  // ADR-0041 stage 2 — staged boot readiness on the worker-attached client. The `attach-ack` fires AT the
395
1443
  // engine's `localReadReady` (the Option B contract), so this client resolves `attachSyncClient` there and
@@ -460,17 +1508,26 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
460
1508
  if (detached) return;
461
1509
  detached = true;
462
1510
  status.isRunning = false;
463
- // Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2).
464
- for (const queryId of diffHandlers.keys()) postBridgeMessage(port, codec, "unsubscribe", { queryId });
1511
+ // Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2). Sent on the
1512
+ // CURRENT data port (ADR-0049: the pipe once swapped, else the control port).
1513
+ for (const queryId of diffHandlers.keys()) postBridgeMessage(currentDataPort(), codec, "unsubscribe", { queryId });
465
1514
  diffHandlers.clear();
466
- postBridgeMessage(port, codec, "detach", null);
1515
+ activeSubscriptions.clear();
1516
+ postBridgeMessage(currentDataPort(), codec, "detach", null);
1517
+ // ADR-0049 D8: tell the SharedWorker ROUTER this tab is gone, on the CONTROL port — the `detach` above rode
1518
+ // the per-tab PIPE, which the router never sees, so its `tabCount` (the destroy peer-refusal input) would
1519
+ // otherwise never fall. A `pgx0049` control envelope (the router stays payload-blind); harmless on a
1520
+ // non-placement transport (ignored) and when the control port IS the data port (SW-direct).
1521
+ controlPort.postMessage(wrapControlEnvelope({ type: "tab-detach" }));
467
1522
  // Settle every tab-side promise now the port listener is about to go (ADR-0040 P2) — otherwise an
468
1523
  // operation still awaiting a worker reply hangs forever. RPCs and initial subscribes promise DATA, so
469
1524
  // REJECT them (fabricating a value is worse than a clear failure); hydration and group-ready waiters are
470
1525
  // DONENESS signals, so RESOLVE them (their awaiters are void-chained hook code that should settle, not
471
1526
  // throw). The attach-ack is rejected too so a detach DURING boot rejects `attachSyncClient` (a no-op once
472
1527
  // it has already settled).
473
- attachAckReject?.(detachError());
1528
+ const settleAttachAck = pendingAttachAck;
1529
+ pendingAttachAck = null;
1530
+ settleAttachAck?.reject(detachError());
474
1531
  // ADR-0041 (FIX A): reject EVERY still-pending readiness STAGE with ONE typed `ClientDisposedError`, so
475
1532
  // `instanceof ClientDisposedError` behaves identically in worker and in-process mode (the class doc + the
476
1533
  // in-process client already promise the typed error on disposal). `detachError()` stays for RPC/subscription
@@ -478,6 +1535,10 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
478
1535
  // `localReadReady` is left as-is: pre-ack it never resolved (the attach itself rejected); post-ack it already
479
1536
  // resolved. The `milestone-error` path is untouched — that is a genuine engine failure, not disposal.
480
1537
  const disposedError = new ClientDisposedError();
1538
+ // ADR-0049: a detach BEFORE the first attach ack settles fails `attachSyncClient` (a detach-during-boot rejects
1539
+ // the attach rather than leaving it pending) — with the SAME "client detached" error the pre-firstAttachReady
1540
+ // handshake rejection used, preserving the ADR-0040 P2 contract (idempotent once the attach already resolved).
1541
+ failFirstAttach(detachError());
481
1542
  failWriteReady(disposedError);
482
1543
  failBootSettled(disposedError);
483
1544
  // The attached `ready` had NO reject path — a detach BEFORE initial sync would otherwise leave
@@ -488,20 +1549,41 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
488
1549
  }
489
1550
  for (const pending of rpcPending.values()) pending.reject(detachError());
490
1551
  rpcPending.clear();
1552
+ clearAllOverdue();
491
1553
  for (const pending of initialPending.values()) pending.reject(detachError());
492
1554
  initialPending.clear();
493
1555
  for (const resolve of hydratedPending.values()) resolve();
494
1556
  hydratedPending.clear();
495
1557
  for (const waiters of groupWaiters.values()) for (const resolve of waiters) resolve();
496
1558
  groupWaiters.clear();
1559
+ // ADR-0049: queued handoff ops settle with the detach error (rule 5), and the placement timers are cleared.
1560
+ const queued = handoffQueue.splice(0);
1561
+ for (const item of queued) item.reject(detachError());
1562
+ clearQueueDeadline();
1563
+ // ADR-0049 step 10b: release this tab's leader-lock claim (invariant 2 — one claim per attachment, released
1564
+ // on detach). Idempotent; a no-op when this tab never elected (SW-direct / no factory).
1565
+ releaseElectionClaim?.();
1566
+ releaseElectionClaim = undefined;
1567
+ // Release this tab's ref on an ADOPTED shared coordinator (ref-counted registry cleanup); no-op otherwise.
1568
+ if (adoptedSharedCoordinatorStore !== undefined) {
1569
+ releaseSharedCoordinator(adoptedSharedCoordinatorStore);
1570
+ adoptedSharedCoordinatorStore = undefined;
1571
+ }
1572
+ if (silenceHandle !== undefined) {
1573
+ timers.clearTimeout(silenceHandle);
1574
+ silenceHandle = undefined;
1575
+ }
497
1576
  if (pagehideListener) pageWindow?.removeEventListener("pagehide", pagehideListener);
498
- port.removeEventListener("message", listener);
499
- port.close?.();
1577
+ // Tear down BOTH listeners: the bridge listener on the data port, the control listener on the control port.
1578
+ dataPort.removeEventListener("message", listener);
1579
+ controlPort.removeEventListener("message", controlListener);
1580
+ dataPort.close?.();
1581
+ if (controlPort !== dataPort) controlPort.close?.();
500
1582
  };
501
1583
  // Structural window guard — this file compiles without the DOM lib (it also runs under tests/workers).
502
1584
  interface PageLifecycleWindowLike {
503
- addEventListener(type: "pagehide", handler: (event: { persisted: boolean }) => void): void;
504
- removeEventListener(type: "pagehide", handler: (event: { persisted: boolean }) => void): void;
1585
+ addEventListener(type: "pagehide" | "pageshow", handler: (event: { persisted: boolean }) => void): void;
1586
+ removeEventListener(type: "pagehide" | "pageshow", handler: (event: { persisted: boolean }) => void): void;
505
1587
  }
506
1588
  const pageWindow = (globalThis as { window?: PageLifecycleWindowLike }).window;
507
1589
  const pagehideListener = pageWindow
@@ -510,6 +1592,17 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
510
1592
  }
511
1593
  : undefined;
512
1594
  if (pagehideListener) pageWindow?.addEventListener("pagehide", pagehideListener);
1595
+ // ADR-0049 step 10b: the real page-lifecycle subscription the election coordinator's BFCache hooks use
1596
+ // (`pagehide.persisted` → release authority + retire; `pageshow` → re-queue + re-attach). Structural window
1597
+ // check, exactly like the detach `pagehide` above; injectable (`electionIo.pageLifecycle`) for tests.
1598
+ const pageLifecycle: CoordinatorDeps["pageLifecycle"] =
1599
+ options.electionIo?.pageLifecycle ??
1600
+ (pageWindow
1601
+ ? {
1602
+ onPageHide: (listener) => pageWindow.addEventListener("pagehide", (event) => listener(event.persisted)),
1603
+ onPageShow: (listener) => pageWindow.addEventListener("pageshow", () => listener()),
1604
+ }
1605
+ : undefined);
513
1606
 
514
1607
  const initialToken = options.getToken ? await options.getToken() : null;
515
1608
  // The testing memory-backend override travels as an explicit wire field, not the symbol marker — a symbol
@@ -525,30 +1618,47 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
525
1618
  mimeType: options.restoreFrom.type || "application/octet-stream",
526
1619
  }
527
1620
  : undefined;
528
- const attachPayload: AttachPayload = {
529
- token: initialToken,
530
- ...(options.storeId ? { storeId: options.storeId } : {}),
531
- ...(options.storePath ? { storePath: options.storePath } : {}),
532
- ...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
533
- ...(restoreWire ? { restore: restoreWire } : {}),
534
- ...(options.syncEnabled != null || options.role != null || options.freshStore != null
535
- ? {
536
- config: {
537
- ...(options.syncEnabled != null ? { syncEnabled: options.syncEnabled } : {}),
538
- ...(options.role != null ? { role: options.role } : {}),
539
- ...(options.freshStore != null ? { freshStore: options.freshStore } : {}),
540
- },
541
- }
542
- : {}),
543
- };
544
- postBridgeMessage(port, codec, "attach", attachPayload, undefined, restoreWire ? [restoreWire.buffer] : undefined);
1621
+ // The attach payload builder — reused by the FIRST attach and every re-attach (pipe swap / reconnect). Restore
1622
+ // rides ONLY the first attach (`includeRestore`); a re-attach never carries it (its buffer is already
1623
+ // transferred/detached, and you cannot restore into a running store).
1624
+ function buildAttachPayload(includeRestore: boolean): AttachPayload {
1625
+ return {
1626
+ token: initialToken,
1627
+ ...(options.storeId ? { storeId: options.storeId } : {}),
1628
+ ...(options.storePath ? { storePath: options.storePath } : {}),
1629
+ ...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
1630
+ ...(options.executionLimit ? { executionLimit: options.executionLimit } : {}),
1631
+ ...(includeRestore && restoreWire ? { restore: restoreWire } : {}),
1632
+ ...(options.syncEnabled != null || options.role != null || options.freshStore != null
1633
+ ? {
1634
+ config: {
1635
+ ...(options.syncEnabled != null ? { syncEnabled: options.syncEnabled } : {}),
1636
+ ...(options.role != null ? { role: options.role } : {}),
1637
+ ...(options.freshStore != null ? { freshStore: options.freshStore } : {}),
1638
+ },
1639
+ }
1640
+ : {}),
1641
+ };
1642
+ }
1643
+ // ─── ADR-0049 placement-query-FIRST attach ordering (elected-mode deadlock fix) ───────────────────
1644
+ // Post the placement query BEFORE the attach handshake. A router-only SharedWorker (elected-worker home) is
1645
+ // payload-blind and DROPS the bridge `attach`, so an SW-port ack would never come there and could never gate
1646
+ // the flow — but the bootstrap meta listener answers the placement query in BOTH SW modes, so this reliably
1647
+ // drives election. In SW-direct / declared-idbfs (and the no-placement / plain-port case) the reply is
1648
+ // `electionRequired: false` (or absent) and the SW-port attach below acks normally — a plain in-scope host attach.
1649
+ controlPort.postMessage({ [PLACEMENT_QUERY_KEY]: true });
1650
+ // Send the tab's attach handshake on the SW/control port. `firstAttachReady` settles off the FIRST ack from
1651
+ // EITHER home: the in-scope SW engine (SW-direct / baseline) acks THIS handshake; the elected engine acks the
1652
+ // per-tab PIPE handshake (`onConnectPort`, after election). In elected mode the router silently drops THIS
1653
+ // send (payload-blind — never taught to answer bridge envelopes); the gate then settles off the pipe, never the
1654
+ // SW port. `.catch` swallows the orphaned handshake promise (its `pendingAttachAck` is superseded by the pipe).
1655
+ void runAttachHandshake(currentDataPort(), true).catch(() => undefined);
545
1656
  try {
546
- await attachAck;
1657
+ await firstAttachReady;
547
1658
  } catch (error) {
548
- // The worker's engine boot failed (ADR-0032 FIX 1) OR a terminal pagehide rejected the ack mid-boot
549
- // (ADR-0040 P2): run the full detach so BOTH the message listener AND the pagehide listener are removed
550
- // (no port/window handler leaks), then let the error propagate out of `attachSyncClient`. Idempotent, so
551
- // a pagehide that already detached makes this a cheap no-op.
1659
+ // The engine boot failed (ADR-0032 FIX 1), a terminal pagehide rejected the ack mid-boot (ADR-0040 P2), or a
1660
+ // degraded election never delivered a pipe: run the full detach so BOTH listeners AND the pagehide handler are
1661
+ // removed (no leaks), then propagate. Idempotent — a pagehide that already detached makes this a cheap no-op.
552
1662
  detachFromWorker();
553
1663
  throw error;
554
1664
  }
@@ -563,31 +1673,36 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
563
1673
  // than register a forever-pending initial waiter (ADR-0040 P2).
564
1674
  if (detached) throw detachError();
565
1675
  const queryId = newId("live");
566
- const id = newId("sub");
567
1676
  const materializer = new LiveRowsMaterializer<TRow>(input.pkColumns);
568
1677
  diffHandlers.set(queryId, (diff) => {
569
1678
  onRows(materializer.apply(diff));
570
1679
  });
1680
+ // The subscribe payload — reused by the initial subscribe AND by the ADR-0049 re-subscribe on a pipe swap.
1681
+ const subscribePayload = {
1682
+ queryId,
1683
+ sql: input.sql,
1684
+ params: [...input.params],
1685
+ ...(input.fields ? { fields: [...input.fields] } : {}),
1686
+ ...(input.pkColumns ? { pkColumns: [...input.pkColumns] } : {}),
1687
+ ...(input.use ? { use: [...input.use] } : {}),
1688
+ // Per-subscription keep-alive hint (ADR-0040 decision 4) forwarded to the worker's manager.
1689
+ ...(input.keepAliveMs != null ? { keepAliveMs: input.keepAliveMs } : {}),
1690
+ };
571
1691
  let initial: LiveInitialPayload;
572
1692
  try {
573
1693
  initial = await new Promise<LiveInitialPayload>((resolve, reject) => {
1694
+ const id = newId("sub");
574
1695
  initialPending.set(id, { resolve, reject });
575
- postBridgeMessage(
576
- port,
577
- codec,
578
- "subscribe",
579
- {
580
- queryId,
581
- sql: input.sql,
582
- params: [...input.params],
583
- ...(input.fields ? { fields: [...input.fields] } : {}),
584
- ...(input.pkColumns ? { pkColumns: [...input.pkColumns] } : {}),
585
- ...(input.use ? { use: [...input.use] } : {}),
586
- // Per-subscription keep-alive hint (ADR-0040 decision 4) forwarded to the worker's manager.
587
- ...(input.keepAliveMs != null ? { keepAliveMs: input.keepAliveMs } : {}),
588
- },
589
- id,
590
- );
1696
+ // While the handoff window is open, QUEUE the subscribe (invariant 9); otherwise post at once.
1697
+ const dispatch = () => postBridgeMessage(currentDataPort(), codec, "subscribe", subscribePayload, id);
1698
+ if (windowOpen) {
1699
+ enqueue(dispatch, (error) => {
1700
+ initialPending.delete(id);
1701
+ reject(error);
1702
+ });
1703
+ } else {
1704
+ dispatch();
1705
+ }
591
1706
  });
592
1707
  } catch (error) {
593
1708
  // The worker rejected the subscribe (invalid SQL, etc.); the initial-payload waiter rejected via the
@@ -596,6 +1711,21 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
596
1711
  throw error;
597
1712
  }
598
1713
  const initialRows = materializer.seed(initial.rows as TRow[]);
1714
+ // Register the live query for ADR-0049 re-subscribe: on a pipe swap, re-issue the SAME subscribe (same
1715
+ // queryId → diffs still route to the same materializer/handler) and re-seed the materializer off the fresh
1716
+ // snapshot. This is the re-attach re-establishment of live queries (ADR-0041 staged readiness); its
1717
+ // multi-tab integration coverage is step 12. A rejected re-subscribe leaves the existing rows in place.
1718
+ const resubscribe = () => {
1719
+ const rid = newId("sub");
1720
+ initialPending.set(rid, {
1721
+ resolve: (fresh) => {
1722
+ onRows(materializer.seed(fresh.rows as TRow[]));
1723
+ },
1724
+ reject: () => undefined,
1725
+ });
1726
+ postBridgeMessage(currentDataPort(), codec, "subscribe", subscribePayload, rid);
1727
+ };
1728
+ activeSubscriptions.set(queryId, { resubscribe });
599
1729
  // Pending groups present → build the `hydrated` promise the worker settles via `live-hydrated` (posted
600
1730
  // after the catch-up rows on the same port — rows-before-signal). A missing/empty `hydratingTables`
601
1731
  // means every referenced group (eager OR lazy) was already ready (steady state) or sync is disabled:
@@ -611,9 +1741,10 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
611
1741
  initialRows,
612
1742
  unsubscribe: () => {
613
1743
  diffHandlers.delete(queryId);
1744
+ activeSubscriptions.delete(queryId);
614
1745
  hydratedPending.get(queryId)?.();
615
1746
  hydratedPending.delete(queryId);
616
- postBridgeMessage(port, codec, "unsubscribe", { queryId });
1747
+ postBridgeMessage(currentDataPort(), codec, "unsubscribe", { queryId });
617
1748
  },
618
1749
  // The lazy relations the worker's guard activated for this query (observability). `hydrated` — driven
619
1750
  // by `hydratingTables`, not this — resolves once every pending group's caught-up rows are delivered.
@@ -712,7 +1843,47 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
712
1843
  stop: async () => {
713
1844
  detachFromWorker();
714
1845
  },
715
- destroy: notSupported("client.destroy"),
1846
+ // ADR-0049 step 10b — SUPERVISED destroy from the attached facade. The SUPERVISOR is the TAB context, which
1847
+ // survives engine shutdown BY CONSTRUCTION: it detaches the engine, then runs the destructive lifecycle
1848
+ // itself (the tab has full OPFS/IndexedDB access). Ordering, per the plan's D8 fault rows:
1849
+ // 1. PEER REFUSAL FIRST — the SharedWorker alone knows the attached-tab count; more than one tab attached
1850
+ // (this one + a peer) → `StoreDestroyRefusedError` (close peers first). Runs BEFORE detach + any effect.
1851
+ // 2. REFUSE-IF-OWED (unless `force`) — a cheap journal read via the `diagnostics` RPC while still attached
1852
+ // (one round-trip; the honest minimum — the tab has no local journal). `force` skips it.
1853
+ // 3. DETACH, then run the destruction (set `deleting` → delete sentinel → delete backend store → delete
1854
+ // meta record) with a bounded ownership-lock-lag retry on the backend delete (the just-detached engine's
1855
+ // VFS ownership lock may lag). The initiating call resolves from the tab supervisor (invariant 13).
1856
+ destroy: async (destroyOptions) => {
1857
+ if (detached) throw detachError();
1858
+ const peers = await queryDestroyPeers();
1859
+ if (peers > 1) throw new StoreDestroyRefusedError(peers);
1860
+ if (!destroyOptions?.force) {
1861
+ const { mutation } = await client.diagnostics();
1862
+ const owed =
1863
+ mutation.pendingCount +
1864
+ mutation.sendingCount +
1865
+ mutation.failedCount +
1866
+ mutation.quarantinedCount +
1867
+ mutation.conflictedCount;
1868
+ if (owed > 0) {
1869
+ throw new Error(
1870
+ `destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,
1871
+ );
1872
+ }
1873
+ }
1874
+ const storePath = resolveDestroyStorePath();
1875
+ // ADR-0049 D8 ordering (elected placement): RETIRE this tab's own elected engine and AWAIT its teardown —
1876
+ // the point its EXCLUSIVE OPFS sync-access handle is provably released — BEFORE deleting. The engine is a
1877
+ // dedicated Worker torn down ASYNCHRONOUSLY via the coordinator's retirement handshake; without this
1878
+ // barrier `deleteBackendStore` raced that release and failed `NoModificationAllowedError`. Run it while the
1879
+ // control channel is still up (before detach closes the SW port). A no-op when this tab holds no engine.
1880
+ if (electionCoordinator !== undefined) await electionCoordinator.retireEngine();
1881
+ else await awaitSharedHostTeardown();
1882
+ // Detach the engine FIRST — the supervisor is this tab, which outlives the engine. Idempotent.
1883
+ detachFromWorker();
1884
+ const effects = options.createDestructionEffects?.(storePath) ?? createStoreDestructionEffects(storePath);
1885
+ await runStoreDestruction(effects);
1886
+ },
716
1887
  dropReadCache: notSupported("client.dropReadCache"),
717
1888
  flush: (table) => rpc<void>("flush", [table]),
718
1889
  reconcile: (table) => rpc<void>("reconcile", [table]),
@@ -887,7 +2058,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
887
2058
  void pushToken();
888
2059
  },
889
2060
  setOnline: (online: boolean) => {
890
- postBridgeMessage(port, codec, "set-online", { online });
2061
+ postBridgeMessage(currentDataPort(), codec, "set-online", { online });
891
2062
  },
892
2063
  };
893
2064
 
@@ -906,44 +2077,290 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
906
2077
  return client;
907
2078
  }
908
2079
 
2080
+ /** {@link provisionSyncWorker} options — attach's transport/store/factory seams, plus the provision expiry. */
2081
+ export type ProvisionSyncWorkerOptions<TRegistry extends SyncTableRegistry> = Pick<
2082
+ AttachSyncClientOptions<TRegistry>,
2083
+ | "worker"
2084
+ | "port"
2085
+ | "storeId"
2086
+ | "storePath"
2087
+ | "codec"
2088
+ | "createEngineWorker"
2089
+ | "electionIo"
2090
+ | "awaitOwnershipRelease"
2091
+ | "timers"
2092
+ > & {
2093
+ /**
2094
+ * How long (ms) the elected-mode provision claim (and its shared-coordinator ref) is held before an abandoned
2095
+ * warmed provision auto-retires (ADR-0049 step 8, "abandoned warmed provision → claim expiry"). Default 60000.
2096
+ * A later {@link attachSyncClient} on the same store ADOPTS the grant within this window (adding its own claim,
2097
+ * so the engine outlives the expiry). Inert on SW-direct.
2098
+ */
2099
+ provisionExpiryMs?: number;
2100
+ };
2101
+
2102
+ /** Options for deliberately retiring a SW-direct host before changing its construction identity. */
2103
+ export type RetireSyncWorkerHostOptions = Pick<
2104
+ AttachSyncClientOptions<SyncTableRegistry>,
2105
+ "worker" | "port" | "timers"
2106
+ > & {
2107
+ /** Bound for the placement + teardown handshake. Default 5000 ms. */
2108
+ timeoutMs?: number;
2109
+ };
2110
+
2111
+ /**
2112
+ * Quiesce and retire a SW-direct sync host without deleting its store.
2113
+ *
2114
+ * This is the construction-lifecycle companion to {@link provisionSyncWorker}: a caller that must replace a
2115
+ * SharedWorker under a different construction identity (for example, a different durability preference) first
2116
+ * awaits this barrier so the old extended-lifetime worker releases its database handle. Elected placement owns
2117
+ * retirement through its coordinator and is therefore rejected here. Retirement is refused while peer tabs are
2118
+ * attached: changing one tab's construction preference must not terminate a host other tabs are actively using.
2119
+ */
2120
+ export function retireSyncWorkerHost(options: RetireSyncWorkerHostOptions): Promise<void> {
2121
+ const port = resolvePort(options);
2122
+ const timers: AttachClientTimers = options.timers ?? {
2123
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
2124
+ clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),
2125
+ };
2126
+
2127
+ return new Promise<void>((resolve, reject) => {
2128
+ let identity: EngineIdentity | undefined;
2129
+ let settled = false;
2130
+ const finish = (result: { ok: true } | { ok: false; error: Error }): void => {
2131
+ if (settled) return;
2132
+ settled = true;
2133
+ timers.clearTimeout(timeout);
2134
+ port.removeEventListener("message", listener);
2135
+ if (result.ok) resolve();
2136
+ else reject(result.error);
2137
+ };
2138
+ const listener = (event: { data: unknown }): void => {
2139
+ const placement = readPlacementResult(event.data);
2140
+ if (placement !== undefined) {
2141
+ if (placement.electionRequired) {
2142
+ finish({
2143
+ ok: false,
2144
+ error: new Error(
2145
+ "[pgxsinkit] retireSyncWorkerHost only applies to a SW-direct host; elected placement retires " +
2146
+ "through its election coordinator.",
2147
+ ),
2148
+ });
2149
+ return;
2150
+ }
2151
+ identity = { swInstanceId: placement.swInstanceId, generation: 0 };
2152
+ port.postMessage({ [DESTROY_QUERY_KEY]: true });
2153
+ return;
2154
+ }
2155
+ const peers = readDestroyVerdict(event.data);
2156
+ if (peers !== undefined && identity !== undefined) {
2157
+ if (peers > 1) {
2158
+ finish({
2159
+ ok: false,
2160
+ error: new Error(
2161
+ `[pgxsinkit] SW-direct host retirement refused: ${peers} attached tabs still use this store. ` +
2162
+ "Close the peer tabs before changing the worker construction preference.",
2163
+ ),
2164
+ });
2165
+ return;
2166
+ }
2167
+ port.postMessage(wrapControlEnvelope({ type: "engine-teardown", identity }));
2168
+ return;
2169
+ }
2170
+ const control = readControlEnvelope(event.data);
2171
+ if (
2172
+ identity !== undefined &&
2173
+ control?.type === "control-ack" &&
2174
+ control.pingId === -1 &&
2175
+ engineIdentityEquals(control.identity, identity)
2176
+ ) {
2177
+ if (control.error) {
2178
+ finish({
2179
+ ok: false,
2180
+ error: new Error(`[pgxsinkit] SW-direct host teardown failed: ${control.error.message}`),
2181
+ });
2182
+ } else {
2183
+ finish({ ok: true });
2184
+ }
2185
+ }
2186
+ };
2187
+ const timeout = timers.setTimeout(
2188
+ () =>
2189
+ finish({
2190
+ ok: false,
2191
+ error: new Error("[pgxsinkit] timed out while retiring the SW-direct sync host."),
2192
+ }),
2193
+ options.timeoutMs ?? 5_000,
2194
+ );
2195
+ port.addEventListener("message", listener);
2196
+ port.start?.();
2197
+ port.postMessage({ [PLACEMENT_QUERY_KEY]: true });
2198
+ });
2199
+ }
2200
+
909
2201
  /**
910
- * Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen
911
- * against a freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the
912
- * raw store idle until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the
913
- * provision (its initdb settled); rejects only if the worker reports the create failed — the caller treats
914
- * either outcome as best-effort, since attach falls back to a fresh create regardless.
2202
+ * Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen against a
2203
+ * freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the raw store idle
2204
+ * until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the provision (its initdb
2205
+ * settled); rejects only if the worker reports the create failed — the caller treats either outcome as best-effort,
2206
+ * since attach falls back to a fresh create regardless.
2207
+ *
2208
+ * Routed through the SAME placement-query-first flow as {@link attachSyncClient} (ADR-0049 step 8): a SW-direct
2209
+ * (or declared-idbfs) SharedWorker takes the `provision` bridge envelope on the SW port; a
2210
+ * router-only (`electionRequired`) SharedWorker DROPS bridge envelopes, so provision drives the election
2211
+ * coordinator's PROVISION CLAIM (expiry-bounded) and delivers the `provision` over the elected engine's per-tab
2212
+ * PIPE. The coordinator is REGISTERED per store so a later attach on the same tab ADOPTS the grant — no second
2213
+ * lock, no second engine, no double initdb (invariant 2). Elected mode REQUIRES a {@link createEngineWorker}
2214
+ * factory (mirroring attach); its absence is a clear rejection, never a hang.
915
2215
  */
916
- export function provisionSyncWorker<TRegistry extends SyncTableRegistry>(
917
- options: Pick<AttachSyncClientOptions<TRegistry>, "worker" | "port" | "storeId" | "storePath" | "codec">,
2216
+ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
2217
+ options: ProvisionSyncWorkerOptions<TRegistry>,
918
2218
  ): Promise<void> {
919
2219
  const codec = options.codec ?? identityCodec;
920
2220
  const port = resolvePort(options);
921
- // The testing memory-backend override travels as an explicit wire field (a symbol does not survive
922
- // structured clone, ADR-0036) — read it off the spread helper's options and forward it to the worker.
2221
+ const timers: AttachClientTimers = options.timers ?? {
2222
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
2223
+ clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),
2224
+ };
2225
+ const storePath = options.storePath ?? options.storeId ?? "pgxsinkit-overlay-v1";
2226
+ // The testing memory-backend override travels as an explicit wire field (a symbol does not survive structured
2227
+ // clone, ADR-0036) — read it off the spread helper's options and forward it to the worker.
923
2228
  const memoryOverride = readTestStoreMarker(options) === "memory";
2229
+ const provisionPayload = {
2230
+ ...(options.storeId ? { storeId: options.storeId } : {}),
2231
+ ...(options.storePath ? { storePath: options.storePath } : {}),
2232
+ ...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
2233
+ };
2234
+ const pageLifecycle = readDefaultPageLifecycle();
2235
+
924
2236
  return new Promise<void>((resolve, reject) => {
925
- const listener = (message: { data: unknown }) => {
926
- if (!isBridgeEnvelope(message.data)) return;
927
- if (message.data.type !== "provision-ack") return;
928
- port.removeEventListener("message", listener);
929
- const ack = codec.decode(message.data.payload) as ProvisionAckPayload;
930
- if (ack.ok) resolve();
931
- else reject(new Error(ack.error?.message ?? "worker provision failed"));
2237
+ let settled = false;
2238
+ const ackRemovers: Array<() => void> = [];
2239
+ const controlListener = (event: { data: unknown; ports?: readonly BridgePort[] }): void => {
2240
+ const placement = readPlacementResult(event.data);
2241
+ if (placement !== undefined) {
2242
+ onPlacement(placement);
2243
+ return;
2244
+ }
2245
+ const control = readControlEnvelope(event.data);
2246
+ if (control?.type === "connect-port") onProvisionPipe(event.ports?.[0], control.identity);
932
2247
  };
933
- port.addEventListener("message", listener);
2248
+ const settle = (fn: () => void): void => {
2249
+ if (settled) return;
2250
+ settled = true;
2251
+ port.removeEventListener("message", controlListener);
2252
+ for (const remove of ackRemovers) remove();
2253
+ fn();
2254
+ };
2255
+
2256
+ // Await `provision-ack` on whichever port carries it: the SW port (SW-direct) or the elected engine's pipe.
2257
+ // In elected mode the SW-port `provision` is dropped by the router, so its ack never comes — the pipe's does.
2258
+ const awaitAckOn = (ackPort: BridgePort): void => {
2259
+ const ackListener = (message: { data: unknown }): void => {
2260
+ if (!isBridgeEnvelope(message.data) || message.data.type !== "provision-ack") return;
2261
+ const ack = codec.decode(message.data.payload) as ProvisionAckPayload;
2262
+ settle(() => (ack.ok ? resolve() : reject(new Error(ack.error?.message ?? "worker provision failed"))));
2263
+ };
2264
+ ackPort.addEventListener("message", ackListener);
2265
+ ackPort.start?.();
2266
+ ackRemovers.push(() => ackPort.removeEventListener("message", ackListener));
2267
+ };
2268
+ const postProvisionOn = (target: BridgePort): void => {
2269
+ awaitAckOn(target);
2270
+ postBridgeMessage(target, codec, "provision", provisionPayload);
2271
+ };
2272
+
2273
+ let placementDecided = false;
2274
+ let piped = false;
2275
+ const onProvisionPipe = (pipe: BridgePort | undefined, identity: EngineIdentity): void => {
2276
+ if (piped || pipe === undefined) return;
2277
+ piped = true;
2278
+ // The router piped this provision connection to the elected engine — deliver the `provision` over the pipe,
2279
+ // and STASH the pipe on the shared coordinator entry: the router mints one pipe per SW connection, so when a
2280
+ // later attach adopts this grant on the SAME port (the board's ordered-messages contract) it must receive
2281
+ // THIS pipe by handover — no second `connect-port` will ever arrive for an already-piped tab.
2282
+ stashProvisionPipe(storePath, pipe, identity);
2283
+ postProvisionOn(pipe);
2284
+ };
2285
+
2286
+ const onPlacement = (result: PlacementQueryResult): void => {
2287
+ if (placementDecided) return;
2288
+ placementDecided = true;
2289
+ // SW-direct (or a non-placement transport that never replies): the SW-port `provision` below carries it.
2290
+ if (!result.electionRequired) return;
2291
+ // Elected (router-only): the SW drops the `provision` bridge envelope, so ELECT and provision over the pipe.
2292
+ // Resolve the engine factory exactly as attach does — the `createEngineWorker` override, else the default
2293
+ // derived from the SharedWorker's reported script URL (dual-scope entry). Neither available → a WIRING failure.
2294
+ const engineFactory = options.createEngineWorker ?? deriveEngineWorkerFactory(result.swScriptUrl);
2295
+ if (engineFactory === undefined) {
2296
+ settle(() =>
2297
+ reject(
2298
+ new ElectedEngineUnconstructibleError(
2299
+ result.swScriptUrl === undefined
2300
+ ? "provisionSyncWorker: the SharedWorker reported no derivable script URL and no `createEngineWorker` override was supplied"
2301
+ : "provisionSyncWorker: no `Worker` constructor is available in this scope to derive the module engine and no override was supplied",
2302
+ ),
2303
+ ),
2304
+ );
2305
+ return;
2306
+ }
2307
+ const provisionSwFactory = workerFactoryOf(options.worker);
2308
+ const coordinator = adoptOrRegisterCoordinator(storePath, () =>
2309
+ buildElectedCoordinator({
2310
+ storePath,
2311
+ controlPort: port,
2312
+ createEngineWorker: engineFactory,
2313
+ ...(provisionSwFactory ? { swFactory: provisionSwFactory } : {}),
2314
+ ...(options.electionIo ? { electionIo: options.electionIo } : {}),
2315
+ ...(options.awaitOwnershipRelease ? { awaitOwnershipRelease: options.awaitOwnershipRelease } : {}),
2316
+ timers,
2317
+ ...(pageLifecycle ? { pageLifecycle } : {}),
2318
+ }),
2319
+ );
2320
+ // The PROVISION CLAIM elects → the coordinator spawns the engine + announces; the router pipes this
2321
+ // connection (→ `onProvisionPipe`). Bound by expiry: an abandoned warmed provision auto-retires (its claim
2322
+ // AND its shared-coordinator ref release together), so a store nobody adopts never pins the leader lock.
2323
+ const releaseProvisionClaim = coordinator.claimForProvision();
2324
+ const expiryMs = options.provisionExpiryMs ?? 60_000;
2325
+ timers.setTimeout(() => {
2326
+ releaseProvisionClaim();
2327
+ releaseSharedCoordinator(storePath);
2328
+ }, expiryMs);
2329
+ };
2330
+
2331
+ port.addEventListener("message", controlListener);
934
2332
  port.start?.();
935
- postBridgeMessage(port, codec, "provision", {
936
- ...(options.storeId ? { storeId: options.storeId } : {}),
937
- ...(options.storePath ? { storePath: options.storePath } : {}),
938
- ...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
939
- });
2333
+ // Placement-query-FIRST (mirror attach): answered in BOTH SW modes by the bootstrap meta listener. Send the
2334
+ // `provision` on the SW port immediately — SW-direct / declared-idbfs (the in-scope host) ack it here; a router-only
2335
+ // SW drops it and the elected pipe carries it instead. The first `provision-ack` from EITHER settles.
2336
+ port.postMessage({ [PLACEMENT_QUERY_KEY]: true });
2337
+ postProvisionOn(port);
940
2338
  });
941
2339
  }
942
2340
 
943
- /** Resolve the transport port from the options: an explicit port, a SharedWorker's `.port`, or a Worker itself. */
944
- function resolvePort(options: { port?: BridgePort; worker?: WorkerLike }): BridgePort {
2341
+ /** Resolve the default page-lifecycle subscription off `globalThis.window` (structural, no DOM lib) — for the
2342
+ elected provision coordinator's BFCache hooks; `undefined` in a non-window scope. Mirrors the attach client. */
2343
+ function readDefaultPageLifecycle(): CoordinatorDeps["pageLifecycle"] {
2344
+ interface PageLifecycleWindowLike {
2345
+ addEventListener(type: "pagehide" | "pageshow", handler: (event: { persisted: boolean }) => void): void;
2346
+ }
2347
+ const pageWindow = (globalThis as { window?: PageLifecycleWindowLike }).window;
2348
+ if (!pageWindow) return undefined;
2349
+ return {
2350
+ onPageHide: (listener) => pageWindow.addEventListener("pagehide", (event) => listener(event.persisted)),
2351
+ onPageShow: (listener) => pageWindow.addEventListener("pageshow", () => listener()),
2352
+ };
2353
+ }
2354
+
2355
+ /**
2356
+ * Resolve the transport port from the options: an explicit port, or a worker input (ADR-0049 D5) that is EITHER a
2357
+ * FACTORY `() => WorkerLike` (invoked here for a fresh instance — the reconnect/reconstruct callers pass the factory
2358
+ * so each call yields a new SharedWorker) OR a bare instance. From the instance: a SharedWorker's `.port`, or a
2359
+ * Worker itself (which IS the port).
2360
+ */
2361
+ function resolvePort(options: { port?: BridgePort; worker?: (() => WorkerLike) | WorkerLike }): BridgePort {
945
2362
  if (options.port) return options.port;
946
- const worker = options.worker;
2363
+ const worker = typeof options.worker === "function" ? (options.worker as () => WorkerLike)() : options.worker;
947
2364
  if (!worker) throw new Error("attachSyncClient: provide a `worker` or a `port`.");
948
2365
  if (worker.port) return worker.port;
949
2366
  if (worker.postMessage && worker.addEventListener && worker.removeEventListener) {
@@ -952,11 +2369,53 @@ function resolvePort(options: { port?: BridgePort; worker?: WorkerLike }): Bridg
952
2369
  throw new Error("attachSyncClient: the provided `worker` is neither a Worker nor a SharedWorker port.");
953
2370
  }
954
2371
 
2372
+ /**
2373
+ * The SharedWorker reconstruction FACTORY, or `undefined` when the input is a bare instance/port (ADR-0049 D5). A
2374
+ * factory input (`worker: () => SharedWorker`) makes SharedWorker-death recovery a guarantee — the bridge-silence
2375
+ * reconnect and the keepalive reconstruction re-invoke it. A bare-instance input has none: reconstruction is
2376
+ * structurally unavailable (a SharedWorker cannot be rebuilt from itself), so those paths are simply not armed.
2377
+ */
2378
+ function workerFactoryOf(worker: (() => WorkerLike) | WorkerLike | undefined): (() => WorkerLike) | undefined {
2379
+ return typeof worker === "function" ? (worker as () => WorkerLike) : undefined;
2380
+ }
2381
+
2382
+ /**
2383
+ * Auto-derive the elected engine worker factory from the SharedWorker's reported script URL (ADR-0049 D5). The
2384
+ * worker entry is dual-scope, so `new Worker(swScriptUrl, { type: "module" })` boots the SAME entry as a dedicated
2385
+ * engine — no consumer wiring. Returns `undefined` when there is no derivable URL or no `Worker` constructor in
2386
+ * scope (a plain test scope); the caller then requires the `createEngineWorker` override or fails typed.
2387
+ */
2388
+ function deriveEngineWorkerFactory(swScriptUrl: string | undefined): (() => ElectedEngineWorker) | undefined {
2389
+ if (swScriptUrl === undefined) return undefined;
2390
+ const WorkerCtor = (globalThis as { Worker?: new (url: string, options?: { type?: "module" }) => WorkerLike }).Worker;
2391
+ if (WorkerCtor === undefined) return undefined;
2392
+ return () => wrapEngineWorker(new WorkerCtor(swScriptUrl, { type: "module" }));
2393
+ }
2394
+
955
2395
  /** Rebuild an Error from the bridge's serialized `{message, detail}` shape, carrying `detail` through. */
956
2396
  function rebuildError(error: RpcResultPayload["error"]): Error {
2397
+ if (error && "detail" in error) {
2398
+ const mismatch = executionLimitMismatchFromWire(error.detail);
2399
+ if (mismatch !== undefined) return mismatch;
2400
+ }
957
2401
  const rebuilt = new Error(error?.message ?? "worker rpc failed");
958
2402
  if (error && "detail" in error && error.detail !== undefined) {
959
2403
  (rebuilt as Error & { detail?: unknown }).detail = error.detail;
960
2404
  }
961
2405
  return rebuilt;
962
2406
  }
2407
+
2408
+ /**
2409
+ * Rebuild an RPC/subscribe error, reconstructing the typed {@link EngineRelocatedError} when the bridge error's
2410
+ * `detail` carries the clone-safe `{ code: "engine-relocated", outcome }` wire form (ADR-0049 D10). This is the
2411
+ * attach-side reconstruction seam: a relocation failure crossing the pipe as a bridge error surfaces to the
2412
+ * consumer as an `instanceof EngineRelocatedError` with the honest `outcome`. Any other detail rebuilds as a
2413
+ * plain error carrying its `detail` (unchanged behavior).
2414
+ */
2415
+ function rebuildRpcError(error: RpcResultPayload["error"]): Error {
2416
+ if (error && "detail" in error) {
2417
+ const relocated = engineRelocatedFromWire(error.detail);
2418
+ if (relocated !== undefined) return relocated;
2419
+ }
2420
+ return rebuildError(error);
2421
+ }