@pgxsinkit/client 0.1.36 → 0.1.40

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 (64) hide show
  1. package/dist/boot-report.d.ts +134 -0
  2. package/dist/boot-report.d.ts.map +1 -0
  3. package/dist/export-data.d.ts +100 -0
  4. package/dist/export-data.d.ts.map +1 -0
  5. package/dist/export-dump.d.ts +92 -0
  6. package/dist/export-dump.d.ts.map +1 -0
  7. package/dist/export-store.d.ts +214 -0
  8. package/dist/export-store.d.ts.map +1 -0
  9. package/dist/index.d.ts +206 -13
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +886 -69
  12. package/dist/index.js.map +21 -14
  13. package/dist/lazy-guard.d.ts +4 -3
  14. package/dist/lazy-guard.d.ts.map +1 -1
  15. package/dist/lifecycle-slot.d.ts +31 -0
  16. package/dist/lifecycle-slot.d.ts.map +1 -0
  17. package/dist/live-rows-sql.d.ts +21 -0
  18. package/dist/live-rows-sql.d.ts.map +1 -0
  19. package/dist/mutation-state.d.ts +9 -2
  20. package/dist/mutation-state.d.ts.map +1 -1
  21. package/dist/mutation.d.ts +12 -0
  22. package/dist/mutation.d.ts.map +1 -1
  23. package/dist/schema.d.ts +33 -0
  24. package/dist/schema.d.ts.map +1 -1
  25. package/dist/shape-sync.d.ts +10 -0
  26. package/dist/shape-sync.d.ts.map +1 -1
  27. package/dist/store-path.d.ts +132 -0
  28. package/dist/store-path.d.ts.map +1 -0
  29. package/dist/sync/index.d.ts +1 -1
  30. package/dist/sync/index.d.ts.map +1 -1
  31. package/dist/sync/types.d.ts +8 -0
  32. package/dist/sync/types.d.ts.map +1 -1
  33. package/dist/testing.d.ts +27 -0
  34. package/dist/testing.d.ts.map +1 -0
  35. package/dist/testing.js +17 -0
  36. package/dist/testing.js.map +11 -0
  37. package/dist/worker/attach-sync-client.d.ts +23 -2
  38. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  39. package/dist/worker/define-sync-worker.d.ts +5 -4
  40. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  41. package/dist/worker/protocol.d.ts +89 -8
  42. package/dist/worker/protocol.d.ts.map +1 -1
  43. package/package.json +9 -4
  44. package/skills/core/SKILL.md +14 -1
  45. package/skills/operating/SKILL.md +75 -15
  46. package/src/boot-report.ts +287 -0
  47. package/src/export-data.ts +300 -0
  48. package/src/export-dump.ts +239 -0
  49. package/src/export-store.ts +309 -0
  50. package/src/index.ts +623 -82
  51. package/src/lazy-guard.ts +23 -9
  52. package/src/lifecycle-slot.ts +66 -0
  53. package/src/live-rows-sql.ts +45 -0
  54. package/src/mutation-state.ts +11 -2
  55. package/src/mutation.ts +42 -0
  56. package/src/schema.ts +120 -1
  57. package/src/shape-sync.ts +21 -0
  58. package/src/store-path.ts +249 -0
  59. package/src/sync/index.ts +11 -0
  60. package/src/sync/types.ts +9 -0
  61. package/src/testing.ts +53 -0
  62. package/src/worker/attach-sync-client.ts +101 -6
  63. package/src/worker/define-sync-worker.ts +196 -30
  64. package/src/worker/protocol.ts +110 -10
@@ -16,11 +16,16 @@ import {
16
16
  createClientPGlite,
17
17
  type CreateSyncClientOptions,
18
18
  createSyncClient,
19
+ type DataExportOptions,
20
+ type DiagnosticExportOptions,
19
21
  type MutationBatchItem,
20
22
  type RawQueryOptions,
23
+ type StoreExportOptions,
21
24
  type SyncClient,
22
25
  } from "../index";
26
+ import { wrapLiveQueryForMaterialization } from "../live-rows-sql";
23
27
  import type { LocalStoreVersionEvent } from "../local-store";
28
+ import { readTestStoreMarker, TEST_STORE_BACKEND, type TestStoreMarker } from "../store-path";
24
29
  import { computeLiveDiff, seedLiveDiffState } from "./live-diff";
25
30
  import {
26
31
  type AttachPayload,
@@ -28,6 +33,7 @@ import {
28
33
  type BridgeEnvelope,
29
34
  type BridgeEvent,
30
35
  type BridgePort,
36
+ type ExportArtefactWire,
31
37
  identityCodec,
32
38
  isBridgeEnvelope,
33
39
  postBridgeMessage,
@@ -59,16 +65,17 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
59
65
  * How the worker creates its raw PGlite store (provision + fresh-attach paths). Defaults to
60
66
  * {@link createClientPGlite}, which loads PGlite's own boot assets — in a browser worker those hit the
61
67
  * same-origin HTTP cache the tab's login-screen warm already primed (ADR-0032 S3). Injected in tests.
68
+ * Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.
62
69
  */
63
- createPglite?: (dataDir: string) => Promise<ClientPGlite>;
70
+ createPglite?: (storePath: string, backendOverride?: "memory") => Promise<ClientPGlite>;
64
71
  electricUrl: string;
65
72
  writeUrl: string;
66
73
  /** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */
67
74
  requestHeaders?: Record<string, string>;
68
75
  /** Write-only headers merged over {@link requestHeaders} (e.g. region/DB-affinity). See `createSyncClient`. */
69
76
  writeRequestHeaders?: Record<string, string>;
70
- /** Default PGlite store id if the first attach carries none (`memory://…` in tests, `idb://…` in a browser). */
71
- dataDir?: string;
77
+ /** Default plain store PATH (ADR-0036) if the first attach carries none — a name, not a storage URL. */
78
+ storePath?: string;
72
79
  maxMutationAttempts?: number;
73
80
  syncEnabled?: boolean;
74
81
  /**
@@ -90,7 +97,7 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
90
97
  /**
91
98
  * A raw PGlite the worker uses instead of creating its own (forwarded to `createSyncClient`'s
92
99
  * {@link CreateSyncClientOptions.precreatedPglite}) — the client still applies schema/reconcile. In a
93
- * browser worker the store is minted internally (`dataDir`); this is the seam for a prepopulated store in
100
+ * browser worker the store is minted internally (`storePath`); this is the seam for a prepopulated store in
94
101
  * tests, and the future spare-worker claim (ADR-0032 decision 5).
95
102
  */
96
103
  precreatedPglite?: CreateSyncClientOptions<TRegistry>["precreatedPglite"];
@@ -123,7 +130,15 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
123
130
  const codec = options.codec ?? identityCodec;
124
131
  const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;
125
132
  const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;
126
- const createPglite = options.createPglite ?? ((dataDir: string) => createClientPGlite(dataDir));
133
+ const createPglite =
134
+ options.createPglite ??
135
+ ((storePath: string, backendOverride?: "memory") =>
136
+ createClientPGlite(storePath, backendOverride ? { backendOverride } : undefined));
137
+ // A testing acknowledgment (ADR-0036) spread into THIS worker's options — needed when a test injects a
138
+ // non-persistent BYO store (`precreatedPglite` / `pgliteInstance` / a memory-returning `createPglite`),
139
+ // which `createSyncClient` would otherwise refuse. Forwarded to the boot below. A browser worker never
140
+ // sets it; a memory selection carried on the attach wire wins over it.
141
+ const workerTestMarker = readTestStoreMarker(options);
127
142
 
128
143
  const ports = new Set<BridgePort>();
129
144
  const liveSubs = new Map<string, LiveSub>();
@@ -132,7 +147,13 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
132
147
  // A `provision` mints the raw PGlite (initdb only) and holds it idle here; the first real `attach`
133
148
  // adopts it as `precreatedPglite` (the client still runs schema/journal recovery/reconcile). Provision
134
149
  // is role-agnostic — the registry is chosen at attach — so the same warmed store serves either role.
135
- let provisioned: { dataDir: string; pglite: Promise<ClientPGlite> } | null = null;
150
+ // `stamp` carries the spare's create timing (ADR-0034): a boot adopting this store reports the initdb cost
151
+ // as `BootReport.provision` (with `phases.pgliteCreateMs = null`) instead of timing a create it never ran.
152
+ let provisioned: {
153
+ storePath: string;
154
+ pglite: Promise<ClientPGlite>;
155
+ stamp: Promise<{ initdbMs: number; provisionReadyAt: number }>;
156
+ } | null = null;
136
157
 
137
158
  // ─── Outbound-convergence gate — the tab's Offline toggle over the bridge (ADR-0032 S3) ───────────
138
159
  // The worker owns convergence; the tab forwards its Offline flag as `set-online`. When suppressed the
@@ -170,6 +191,42 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
170
191
  };
171
192
  const broadcastEvent = (event: BridgeEvent) => broadcast("event", event);
172
193
 
194
+ // ─── Debug-rail buffer + replay (ADR-0034) ───────────────────────────────────────────────────────
195
+ // The engine boots on the first ATTACH, but the front half of boot (provision, and the boot rail's
196
+ // schema/journal/reconcile lines) can be emitted before any debug-enabled tab is listening — so they
197
+ // vanished. Install the sink at construction (not at boot) into a bounded ring buffer, so the whole boot
198
+ // is captured from worker start; the buffer is REPLAYED (marked `[replay]`) to the first attach, while the
199
+ // back half streams live over the bridge. Bounded so a long-lived worker never grows the buffer unbounded.
200
+ const RAIL_BUFFER_MAX = 500;
201
+ const railBuffer: Array<{ stamp: number; line: string; data?: Record<string, unknown> }> = [];
202
+ let railReplayed = false;
203
+ setSyncDebugSink((line, stamp, data) => {
204
+ if (railBuffer.length >= RAIL_BUFFER_MAX) railBuffer.shift();
205
+ railBuffer.push({ stamp, line, ...(data ? { data } : {}) });
206
+ broadcastEvent({ kind: "debug", stamp, line, ...(data ? { data } : {}) });
207
+ });
208
+ const nowStamp = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
209
+ // Replay the pre-attach rail buffer to the first attaching port. Taken as a snapshot BEFORE this attach's
210
+ // boot runs, so the boot's own lines (which stream live to this now-connected port) are never doubled.
211
+ const replayRailBufferTo = (port: BridgePort) => {
212
+ if (railReplayed) return;
213
+ railReplayed = true;
214
+ const buffered = [...railBuffer];
215
+ postBridgeMessage(port, codec, "event", {
216
+ kind: "debug",
217
+ stamp: nowStamp(),
218
+ line: `[replay] replaying ${buffered.length} buffered rail line(s)`,
219
+ } satisfies BridgeEvent);
220
+ for (const entry of buffered) {
221
+ postBridgeMessage(port, codec, "event", {
222
+ kind: "debug",
223
+ stamp: entry.stamp,
224
+ line: `[replay] ${entry.line}`,
225
+ ...(entry.data ? { data: entry.data } : {}),
226
+ } satisfies BridgeEvent);
227
+ }
228
+ };
229
+
173
230
  const emitStatus = (status: SyncRuntimeStatus) => {
174
231
  broadcastEvent({ kind: "status", status });
175
232
  // Derive a per-group `groupReady` event for each group that newly reached ready, so a tab gets both the
@@ -202,33 +259,64 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
202
259
  // The tab is the auth owner: seed the cache with the token it presented at attach (decision 3).
203
260
  tokenCache.push(attach.token);
204
261
  bootedRole = attach.config?.role;
205
- // Forward the debug rail to tabs, stamped with the WORKER's monotonic clock (decision 7). Installed
206
- // before boot so the boot rail itself crosses the bridge.
207
- setSyncDebugSink((line, stamp, data) => {
208
- broadcastEvent({ kind: "debug", stamp, line, ...(data ? { data } : {}) });
209
- });
262
+ // The debug-rail sink is installed at construction (ADR-0034) so it buffers from worker start and
263
+ // forwards live to tabs, stamped with the WORKER's monotonic clock (decision 7) — see above.
210
264
  // Resolve the registry from the attach's role (ADR-0032 S3): a single worker file bakes both variants
211
265
  // and the claim/attach settles which one boots — the spare was provisioned before the role was known.
212
266
  const registry = options.resolveRegistry?.(attach.config?.role) ?? options.registry;
213
- // dataDir-first, matching the `provision` handler's resolution (below): the board sends BOTH a bare
214
- // `storeId` (SharedWorker naming, tab-side) AND the real `dataDir` (`idb://pgxsinkit-board-<id>`), and
215
- // the PGlite store lives at `dataDir` — so the provisioned store's dataDir must be what we adopt on.
267
+ // storePath-first, matching the `provision` handler's resolution (below): the board sends BOTH a bare
268
+ // `storeId` (SharedWorker naming, tab-side) AND the real `storePath` (`pgxsinkit-board-<id>`), and the
269
+ // PGlite store lives at `storePath` — so the provisioned store's path must be what we adopt on.
216
270
  // `storeId` is only a last-ditch fallback for a caller that passes it as the store path.
217
- const dataDir = attach.dataDir ?? attach.storeId ?? options.dataDir ?? "idb://pgxsinkit-overlay-v1";
271
+ const storePath = attach.storePath ?? attach.storeId ?? options.storePath ?? "pgxsinkit-overlay-v1";
272
+ // The testing memory-backend override rides as an explicit wire field (a symbol does not survive
273
+ // structured clone, ADR-0036); re-stamp it as the internal marker on the createSyncClient options below.
274
+ // A memory selection on the attach wins over the worker's own acknowledgment (memory implies acknowledged).
275
+ const backendOverride = attach.testStoreBackend;
276
+ const testMarker: TestStoreMarker | undefined = backendOverride === "memory" ? "memory" : workerTestMarker;
277
+ // Restore (ADR-0035 decision 6): the tab decomposed the backup into a transferred `ArrayBuffer` + mime
278
+ // (`RestoreArtefactWire`); recompose a `Blob` to hand `createSyncClient` as `restoreFrom`. Restore OWNS the
279
+ // store's creation (a `loadDataDir` seed), so it is mutually exclusive with adopting a pre-provisioned or
280
+ // caller-supplied instance — when restoring, we suppress the adopt paths below rather than let
281
+ // createSyncClient throw the exclusion error.
282
+ const restoreFrom = attach.restore
283
+ ? new Blob([attach.restore.buffer], { type: attach.restore.mimeType })
284
+ : undefined;
218
285
  // Adopt a matching pre-provisioned store (its initdb already ran off-thread) as `precreatedPglite`;
219
- // createSyncClient falls back to a fresh `dataDir` create if that promise rejects — a pure accelerator.
220
- const precreatedPglite =
221
- provisioned && provisioned.dataDir === dataDir ? provisioned.pglite : options.precreatedPglite;
222
- if (precreatedPglite === provisioned?.pglite) {
223
- syncDebug("worker adopting provisioned store", { dataDir });
286
+ // createSyncClient falls back to a fresh `storePath` create if that promise rejects — a pure accelerator.
287
+ // Never adopt when restoring (restore boots a brand-new store from the backup, not the provisioned one).
288
+ const adoptingProvisioned = restoreFrom == null && provisioned != null && provisioned.storePath === storePath;
289
+ const precreatedPglite = adoptingProvisioned
290
+ ? provisioned!.pglite
291
+ : restoreFrom
292
+ ? undefined
293
+ : options.precreatedPglite;
294
+ // The adopted spare's create timing feeds `BootReport.provision` (ADR-0034); absent otherwise.
295
+ const provisionStamp = adoptingProvisioned ? provisioned!.stamp : undefined;
296
+ if (adoptingProvisioned) {
297
+ syncDebug("worker adopting provisioned store", { storePath });
298
+ }
299
+ if (restoreFrom) {
300
+ syncDebug("worker restoring store from backup", { storePath, byteLength: attach.restore!.buffer.byteLength });
224
301
  }
225
302
  bootPromise = createSyncClient<TRegistry>({
226
303
  registry,
227
304
  electricUrl: options.electricUrl,
228
305
  writeUrl: options.writeUrl,
229
- dataDir,
306
+ storePath,
307
+ // Re-stamp the internal testing marker (ADR-0036) so `createSyncClient`'s option handling selects the
308
+ // memory backend on its fallback create and/or bypasses the BYO refusal for an injected test store —
309
+ // the wire field / worker acknowledgment are the cross-clone carriers for it.
310
+ ...(testMarker ? { [TEST_STORE_BACKEND]: testMarker } : {}),
311
+ // Restore rides the boot attach (ADR-0035 decision 6): createSyncClient seeds the fresh store via
312
+ // `loadDataDir`, boots offline, and quarantines the recovered journal.
313
+ ...(restoreFrom ? { restoreFrom } : {}),
314
+ // Boot observability (ADR-0034): label the report `worker`, and forward the provision stamp so an
315
+ // adopted spare's initdb cost is reported rather than a create this boot never ran.
316
+ bootMode: "worker",
317
+ ...(provisionStamp ? { provisionStamp } : {}),
230
318
  ...(precreatedPglite ? { precreatedPglite } : {}),
231
- ...(options.pgliteInstance ? { pgliteInstance: options.pgliteInstance } : {}),
319
+ ...(options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {}),
232
320
  // Fresh-store prefetch overlap (ADR-0032 S4): the tab's claim path proved this store a schemaless
233
321
  // spare and forwarded the hint in the attach config, so the shape catch-up overlaps schema exec +
234
322
  // journal recovery + reconcile. Never inferred from "adopting a provisioned store": the board
@@ -249,6 +337,9 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
249
337
  onReject: (details) => broadcastEvent({ kind: "reject", details }),
250
338
  onSchemaChange: (event: LocalStoreVersionEvent) => broadcastEvent({ kind: "schema-change", event }),
251
339
  onSyncError: (error) => broadcastEvent({ kind: "sync-error", message: error.message }),
340
+ // Boot observability (ADR-0034): broadcast the finalized report to currently-attached ports (one-shot
341
+ // push). Later tabs read the same report via the `bootReport` pull RPC — there is no replay event.
342
+ onBootReport: (report) => broadcastEvent({ kind: "boot-report", report }),
252
343
  });
253
344
  return bootPromise;
254
345
  };
@@ -299,6 +390,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
299
390
  return active.discardConflict(args[0] as TableKey, args[1] as Record<string, string>);
300
391
  case "discardQuarantined":
301
392
  return active.discardQuarantined(args[0] as TableKey, args[1] as Record<string, string>);
393
+ case "desync":
394
+ return active.desync(args[0] as TableKey);
395
+ case "discardEphemeral":
396
+ return active.discardEphemeral(args[0] as TableKey);
302
397
  case "readMutationDetails":
303
398
  return active.readMutationDetails(args[0] as TableKey | undefined);
304
399
  case "diagnostics":
@@ -311,6 +406,36 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
311
406
  return active.rawQuery(args[0] as string, args[1] as unknown[] | undefined, args[2] as RawQueryOptions);
312
407
  case "rawExec":
313
408
  return active.rawExec(args[0] as string, args[1] as RawQueryOptions);
409
+ case "bootReport":
410
+ // Boot observability (ADR-0034): the worker engine's stored report (or null). Pull, so a late tab
411
+ // reads a boot predating it; the report structured-clones across the bridge as a plain object.
412
+ return active.bootReport();
413
+ case "exportStore": {
414
+ // Store backup (ADR-0035): run the live export on the worker's OWN client (its lifecycle slot
415
+ // serialises it against every tab's export). A `File` cannot cross the bridge as a transferable, so
416
+ // decompose it into an `ExportArtefactWire` — the `ArrayBuffer` is listed on `postMessage`'s transfer
417
+ // list in the `rpc` handler and rebuilt into a `File` tab-side.
418
+ const { file, report } = await active.exportStore(args[0] as StoreExportOptions | undefined);
419
+ const buffer = await file.arrayBuffer();
420
+ return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;
421
+ }
422
+ case "exportDiagnostics": {
423
+ // Diagnostic dump (ADR-0035): identical bridge shape to the store backup — the worker runs the live
424
+ // datadir dump → memory throwaway clone → `pg_dump` on its OWN client (same lifecycle slot), and the
425
+ // SQL crosses back as the same transferred-`ArrayBuffer` `ExportArtefactWire`.
426
+ const { file, report } = await active.exportDiagnostics(args[0] as DiagnosticExportOptions | undefined);
427
+ const buffer = await file.arrayBuffer();
428
+ return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;
429
+ }
430
+ case "exportData": {
431
+ // Data export (ADR-0035): identical bridge shape — the worker runs the drain-guarded `pg_dump -t`
432
+ // per-synced-table export on its OWN client (same lifecycle slot), and the portable SQL crosses back
433
+ // as the same transferred-`ArrayBuffer` `ExportArtefactWire`. A DataExportDrainError rejects the RPC
434
+ // like any other failure (serialised back to the tab).
435
+ const { file, report } = await active.exportData(args[0] as DataExportOptions | undefined);
436
+ const buffer = await file.arrayBuffer();
437
+ return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;
438
+ }
314
439
  default: {
315
440
  const exhaustive: never = op;
316
441
  throw new Error(`unknown rpc op ${String(exhaustive)}`);
@@ -322,20 +447,25 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
322
447
  const handleSubscribe = async (port: BridgePort, id: string | undefined, payload: SubscribePayload) => {
323
448
  const active = client ?? (await bootPromise);
324
449
  if (!active) throw new Error("subscribe before attach");
325
- const { queryId, sql, params, pkColumns, use } = payload;
450
+ const { queryId, sql, params, pkColumns, use, fields } = payload;
326
451
  // Activate any lazy relations the query reads BEFORE registering the live query (ADR-0021) — the worker
327
452
  // owns the real client, so its `prepareQuery` does the real work; the tab's `prepareQuery` is a no-op.
453
+ // Scan the ORIGINAL sql (the wrap only adds an outer `SELECT * FROM (...)`; table refs are inside).
328
454
  await active.prepareQuery({ sql, ...(use ? { use: use as SyncTableName<TRegistry>[] } : {}) });
329
455
 
330
456
  const live = active.pglite.live;
457
+ // Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view
458
+ // creation (`column "title" specified more than once`) unless every output column has a unique alias.
459
+ // No `fields` → SQL unchanged (backward-compatible name-keyed rows; the aliased path keys by alias).
460
+ const materialSql = wrapLiveQueryForMaterialization(sql, fields);
331
461
  // Single-column PK → PGlite's incremental machinery (`live.incrementalQuery`): it maintains the ordered
332
462
  // result via an internal `__after__` linked list and only recomputes changed rows. Composite/keyless →
333
463
  // `live.query` (full ordered result each fire) and we diff worker-side. Either way the CROSS-WIRE shape
334
464
  // is a diff computed by `computeLiveDiff` — neither live API emits an ordered, identity-friendly delta.
335
465
  const registered =
336
466
  pkColumns && pkColumns.length === 1
337
- ? await live.incrementalQuery<Record<string, unknown>>(sql, params as unknown[], pkColumns[0]!)
338
- : await live.query<Record<string, unknown>>(sql, params as unknown[]);
467
+ ? await live.incrementalQuery<Record<string, unknown>>(materialSql, params as unknown[], pkColumns[0]!)
468
+ : await live.query<Record<string, unknown>>(materialSql, params as unknown[]);
339
469
 
340
470
  const state = seedLiveDiffState(registered.initialResults.rows, pkColumns);
341
471
  // Initial snapshot verbatim (not a diff), correlated to the subscribe request so the tab resolves.
@@ -363,7 +493,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
363
493
  // Pre-spawn the raw store (initdb only), idle and schemaless, for the first attach to adopt
364
494
  // (ADR-0032 decision 5). A no-op once the engine has booted or a store is already provisioned.
365
495
  const provision = payload as ProvisionPayload;
366
- const dataDir = provision.dataDir ?? provision.storeId ?? options.dataDir ?? "idb://pgxsinkit-overlay-v1";
496
+ const storePath = provision.storePath ?? provision.storeId ?? options.storePath ?? "pgxsinkit-overlay-v1";
497
+ // The testing memory-backend override rides as an explicit wire field (ADR-0036) — a symbol does not
498
+ // survive structured clone, so the store's backend selection travels here and is passed to createPglite.
499
+ const backendOverride = provision.testStoreBackend;
367
500
  if (bootPromise != null || provisioned != null) {
368
501
  postBridgeMessage(port, codec, "provision-ack", {
369
502
  ok: true,
@@ -371,11 +504,19 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
371
504
  });
372
505
  break;
373
506
  }
374
- const pglite = createPglite(dataDir);
375
- provisioned = { dataDir, pglite };
507
+ // Stamp the spare's create timing (ADR-0034): initdb cost + the monotonic instant it became ready,
508
+ // so an adopting boot can compute how long it sat idle before adoption.
509
+ const provisionStartedAt = nowStamp();
510
+ const pglite = createPglite(storePath, backendOverride);
511
+ const stamp = pglite.then(() => {
512
+ const readyAt = nowStamp();
513
+ return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };
514
+ });
515
+ provisioned = { storePath, pglite, stamp };
376
516
  // Guard an unobserved rejection when no attach ever adopts it (the page navigated away).
377
517
  void pglite.catch(() => undefined);
378
- syncDebug("worker store provisioned", { dataDir });
518
+ void stamp.catch(() => undefined);
519
+ syncDebug("worker store provisioned", { storePath });
379
520
  void pglite.then(
380
521
  () =>
381
522
  postBridgeMessage(port, codec, "provision-ack", {
@@ -402,7 +543,25 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
402
543
  }
403
544
  case "attach": {
404
545
  const attach = payload as AttachPayload;
546
+ // Boot observability (ADR-0034): replay the pre-attach rail buffer (provision + any early lines) to
547
+ // the FIRST attaching tab, so the front half of boot is no longer invisible. Snapshotted before this
548
+ // attach's boot runs, so the boot's own lines (streamed live) are not doubled.
549
+ replayRailBufferTo(port);
405
550
  const alreadyBooted = bootPromise !== null;
551
+ // Restore rides the FIRST (boot) attach only (ADR-0035 decision 6): a restore attach that arrives once
552
+ // the engine has already booted CANNOT be honoured — `loadDataDir` is a create-time seed and the store
553
+ // is already live. Reject THIS attach with a typed error rather than silently ignoring the backup, so
554
+ // the caller learns their restore did not happen (the engine keeps running its existing store).
555
+ if (alreadyBooted && attach.restore != null) {
556
+ postBridgeMessage(port, codec, "attach-ack", {
557
+ alreadyBooted,
558
+ error: {
559
+ message:
560
+ "[pgxsinkit] cannot restore into a running store: the worker engine has already booted, and a store backup can only seed a brand-new store on the FIRST attach (ADR-0035 decision 6). Restore into a fresh worker instead.",
561
+ },
562
+ });
563
+ break;
564
+ }
406
565
  if (alreadyBooted) {
407
566
  // A later attach seeds auth WITHOUT clobbering a fresher cached token (ADR-0032 FIX 5) — the
408
567
  // first-boot `push` already ran, and only an explicit `token-push` (auth owner) may overwrite.
@@ -470,7 +629,14 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
470
629
  const active = client ?? (await bootPromise);
471
630
  if (!active) throw new Error("rpc before attach");
472
631
  const value = await dispatchRpc(active, op, args);
473
- postBridgeMessage(port, codec, "rpc-result", { ok: true, value }, id);
632
+ // An export artefact (backup tarball or diagnostic SQL) crosses zero-copy: transfer its
633
+ // `ArrayBuffer` (rebuilt into a `File` tab-side, ADR-0035). Every other op's value
634
+ // structured-clones in place with no transfer list.
635
+ const transfer =
636
+ op === "exportStore" || op === "exportDiagnostics" || op === "exportData"
637
+ ? [(value as ExportArtefactWire).buffer]
638
+ : undefined;
639
+ postBridgeMessage(port, codec, "rpc-result", { ok: true, value }, id, transfer);
474
640
  } catch (error) {
475
641
  postBridgeMessage(port, codec, "rpc-result", { ok: false, error: serializeError(error) }, id);
476
642
  }
@@ -10,6 +10,9 @@
10
10
 
11
11
  import type { SyncRuntimeStatus } from "@pgxsinkit/contracts";
12
12
 
13
+ import type { BootReport } from "../boot-report";
14
+ import type { ExportReport } from "../export-store";
15
+
13
16
  export const BRIDGE_CHANNEL = "pgxsinkit-bridge" as const;
14
17
  export const BRIDGE_PROTOCOL_VERSION = 1 as const;
15
18
 
@@ -90,8 +93,18 @@ export interface AuthTokenSnapshot {
90
93
  export interface ProvisionPayload {
91
94
  /** The bound store id (informational; naming is done tab-side via the SharedWorker name). */
92
95
  storeId?: string;
93
- /** The PGlite data dir to `create` ahead of attach (`idb://…` in a browser, `memory://…` in tests). */
94
- dataDir?: string;
96
+ /**
97
+ * The plain store PATH (ADR-0036) to `create` ahead of attach — a name, not a storage URL; the worker
98
+ * derives the backend (IndexedDB in a browser worker). When omitted, `storeId`/the worker default is used.
99
+ */
100
+ storePath?: string;
101
+ /**
102
+ * @internal INTERNAL WIRE FIELD (not consumer config, ADR-0036). Carries the testing memory-backend
103
+ * override across the bridge, because a symbol-keyed marker does NOT survive `postMessage` structured
104
+ * clone — so the worker's memory-store selection travels as this explicit field. Set only by the test
105
+ * lane (via the attaching helper); a browser worker never sends it.
106
+ */
107
+ testStoreBackend?: "memory";
95
108
  }
96
109
 
97
110
  /** worker → tab: the provision completed (or failed). Lets the login screen confirm the spare is warm. */
@@ -102,12 +115,46 @@ export interface ProvisionAckPayload {
102
115
  error?: { message: string };
103
116
  }
104
117
 
118
+ /**
119
+ * tab → worker: a store-backup tarball to restore from, carried on the boot {@link AttachPayload}
120
+ * (ADR-0035 decision 6). The mirror image of {@link ExportArtefactWire}: a `File`/`Blob` cannot cross the
121
+ * bridge as a transferable, so it is decomposed into its zero-copy `ArrayBuffer` (listed on `postMessage`'s
122
+ * transfer list) plus the metadata to rebuild it, and the worker reassembles a `Blob` from
123
+ * `buffer`/`mimeType` to hand `createSyncClient` as `restoreFrom`.
124
+ */
125
+ export interface RestoreArtefactWire {
126
+ /** The backup tarball bytes — transferred, not copied. */
127
+ buffer: ArrayBuffer;
128
+ /** The backup file name (informational; PGlite's `loadDataDir` reads the bytes, not the name). */
129
+ fileName: string;
130
+ /** The backup MIME type (`application/x-gzip` / `application/x-tar`), used to rebuild the `Blob`. */
131
+ mimeType: string;
132
+ }
133
+
105
134
  /** tab → worker: the attach handshake. The first attach boots the engine; later attaches join it. */
106
135
  export interface AttachPayload {
107
136
  /** The bound store id (SharedWorker naming resolves it tab-side before attach — ADR-0032 decision 5). */
108
137
  storeId?: string;
109
- /** Explicit PGlite data dir if the worker should create its own store; `memory://…` in tests. */
110
- dataDir?: string;
138
+ /**
139
+ * Explicit plain store PATH (ADR-0036) if the worker should create its own store — a name, not a storage
140
+ * URL; the worker derives the backend. When omitted, `storeId`/the worker default is used.
141
+ */
142
+ storePath?: string;
143
+ /**
144
+ * @internal INTERNAL WIRE FIELD (not consumer config, ADR-0036). Carries the testing memory-backend
145
+ * override across the bridge — a symbol-keyed marker does not survive structured clone, so the worker's
146
+ * memory-store selection travels as this explicit field. Set only by the test lane; never by a browser tab.
147
+ */
148
+ testStoreBackend?: "memory";
149
+ /**
150
+ * Restore the store from a backup on THIS attach (ADR-0035 decision 6) — the worker-mode carrier of
151
+ * `createSyncClient`'s `restoreFrom`. Restore rides the FIRST attach (the boot attach): a `File`/`Blob`
152
+ * cannot cross `postMessage` as a transferable, so the tab decomposes it into a transferred `ArrayBuffer`
153
+ * plus its name/mime — the {@link ExportArtefactWire} pattern in reverse — and the worker recomposes it
154
+ * into a `Blob` and hands it to `createSyncClient`. Absent on every ordinary attach. An attach that carries
155
+ * this AFTER the engine has already booted is REFUSED (you cannot restore into a running store).
156
+ */
157
+ restore?: RestoreArtefactWire;
111
158
  /** The tab's current auth token at attach time, or null when unauthenticated. */
112
159
  token: AuthTokenSnapshot | null;
113
160
  /**
@@ -175,10 +222,24 @@ export type RpcOp =
175
222
  | "recoverSending"
176
223
  | "discardConflict"
177
224
  | "discardQuarantined"
225
+ | "desync"
226
+ | "discardEphemeral"
178
227
  | "readMutationDetails"
179
228
  | "diagnostics"
180
229
  | "rawQuery"
181
- | "rawExec";
230
+ | "rawExec"
231
+ // Boot observability (ADR-0034): pull the worker engine's most recent completed boot report. Returns the
232
+ // stored report (or null) regardless of when this tab attached, so a late tab reads a boot predating it.
233
+ | "bootReport"
234
+ // Store backup (ADR-0035): the worker runs the live `exportStore` on its owned client; the dump crosses
235
+ // back as a transferred `ArrayBuffer` ({@link ExportArtefactWire}), rebuilt into a `File` tab-side.
236
+ | "exportStore"
237
+ // Diagnostic dump (ADR-0035): the worker runs `exportDiagnostics` on its owned client (live datadir dump
238
+ // → memory throwaway clone → `pg_dump`); the SQL crosses back as the same transferred `ArrayBuffer` wire.
239
+ | "exportDiagnostics"
240
+ // Data export (ADR-0035): the worker runs `exportData` on its owned client (drain the journal → throwaway
241
+ // clone → `pg_dump -t` per synced table); the portable SQL crosses back as the same transferred wire.
242
+ | "exportData";
182
243
 
183
244
  /** tab → worker: a write/read-of-mutation-state RPC. `id` correlates the matching {@link RpcResultPayload}. */
184
245
  export interface RpcPayload {
@@ -186,6 +247,26 @@ export interface RpcPayload {
186
247
  args: unknown[];
187
248
  }
188
249
 
250
+ /**
251
+ * worker → tab: the wire form of ANY local-store export (ADR-0035) — the store backup's tarball OR the
252
+ * diagnostic dump's SQL — carried as the `value` of an {@link RpcResultPayload}. The artefact crosses as a
253
+ * transferred `ArrayBuffer` (zero-copy — the sender lists `buffer` in `postMessage`'s transfer list) plus
254
+ * the metadata to rebuild it; the tab reconstructs a `File` from `buffer`/`fileName`/`mimeType`. A `File`
255
+ * cannot itself be transferred, so it is decomposed here and reassembled tab-side, exactly the pattern the
256
+ * codec's transferable seam anticipates for a zero-copy live-diff payload. `report` is the discriminated
257
+ * {@link ExportReport} union, so the tab knows which export it round-tripped.
258
+ */
259
+ export interface ExportArtefactWire {
260
+ /** The artefact bytes (tarball or SQL) — transferred, not copied. */
261
+ buffer: ArrayBuffer;
262
+ /** The generated (or caller-supplied) artefact file name. */
263
+ fileName: string;
264
+ /** The artefact MIME type (`application/x-gzip` / `application/x-tar` for a backup, `application/sql` for a dump). */
265
+ mimeType: string;
266
+ /** The export report (ADR-0035), structured-cloned as a plain object — the `kind`-discriminated union. */
267
+ report: ExportReport;
268
+ }
269
+
189
270
  /** worker → tab: an RPC outcome, mirroring today's in-process resolve/reject semantics. */
190
271
  export interface RpcResultPayload {
191
272
  ok: boolean;
@@ -200,10 +281,19 @@ export interface SubscribePayload {
200
281
  queryId: string;
201
282
  sql: string;
202
283
  params: unknown[];
284
+ /**
285
+ * The unique output aliases the worker wraps the query's columns under so it is safe to MATERIALISE
286
+ * (one per output column, in the compiled SQL's column order). ADDITIVE and backward-compatible: an
287
+ * older tab omits it and the worker leaves the SQL untouched (name-keyed rows, as before); a newer tab
288
+ * supplies it for a JOIN with same-named columns, which `live.query`/`live.incrementalQuery` otherwise
289
+ * refuse to materialise (`column "title" specified more than once`). When present, result columns are
290
+ * the aliases, so {@link pkColumns} must name a PK by its alias.
291
+ */
292
+ fields?: string[];
203
293
  /**
204
294
  * The result's primary-key columns, driving diff keying (§4). One column → the incremental path
205
295
  * (`live.incrementalQuery`); many → worker-side diff by composite PK; empty/absent → value-identity
206
- * fallback for a keyless query.
296
+ * fallback for a keyless query. When {@link fields} is supplied these name the ALIASED result columns.
207
297
  */
208
298
  pkColumns?: string[];
209
299
  /** Lazy relations to activate before the query runs (ADR-0021), forwarded to the worker's `prepareQuery`. */
@@ -242,6 +332,9 @@ export type BridgeEvent =
242
332
  | { kind: "schema-change"; event: unknown }
243
333
  | { kind: "sync-error"; message: string }
244
334
  | { kind: "timing"; label: string; ms: number; data?: Record<string, unknown> }
335
+ // Boot observability (ADR-0034): the one-shot boot report, broadcast to currently-attached ports when the
336
+ // engine's boot finalizes (the push counterpart of the `bootReport` pull). Later tabs read it via the pull.
337
+ | { kind: "boot-report"; report: BootReport }
245
338
  // The debug rail (ADR-0032 decision 7): stamped with the WORKER's monotonic clock and origin-tagged so a
246
339
  // tab can re-print it as `[pgxsinkit·w <stamp>ms] <line>` — a SharedWorker's own console is invisible.
247
340
  | { kind: "debug"; stamp: number; line: string; data?: Record<string, unknown> };
@@ -308,17 +401,24 @@ export function isBridgeEnvelope(data: unknown): data is BridgeEnvelope {
308
401
  );
309
402
  }
310
403
 
311
- /** Send a typed message over a port: encode → post (with any transferables). The one write choke point. */
404
+ /**
405
+ * Send a typed message over a port: encode → post (with any transferables). The one write choke point.
406
+ * `transfer` lets a caller declare payload-specific transferables (e.g. a store-backup's `ArrayBuffer`,
407
+ * ADR-0035) WITHOUT teaching the shared codec about that op — they are merged after any the codec itself
408
+ * produces, so both the codec's future zero-copy path and per-message transfers coexist.
409
+ */
312
410
  export function postBridgeMessage(
313
411
  port: BridgePort,
314
412
  codec: BridgeCodec,
315
413
  type: BridgeMessageType,
316
414
  payload: unknown,
317
415
  id?: string,
416
+ transfer?: BridgeTransferable[],
318
417
  ): void {
319
- const { envelope, transfer } = encodeEnvelope(codec, type, payload, id);
320
- if (transfer && transfer.length > 0) {
321
- port.postMessage(envelope, transfer);
418
+ const { envelope, transfer: codecTransfer } = encodeEnvelope(codec, type, payload, id);
419
+ const allTransfer = [...(codecTransfer ?? []), ...(transfer ?? [])];
420
+ if (allTransfer.length > 0) {
421
+ port.postMessage(envelope, allTransfer);
322
422
  } else {
323
423
  port.postMessage(envelope);
324
424
  }