@pgxsinkit/client 0.1.36 → 0.1.41

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 +1373 -8308
  12. package/dist/index.js.map +25 -131
  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
package/src/index.ts CHANGED
@@ -19,11 +19,17 @@ import type {
19
19
  SyncTableUpdateInput,
20
20
  WriteMode,
21
21
  } from "@pgxsinkit/contracts";
22
- import { getSyncRegistrySchema } from "@pgxsinkit/contracts";
22
+ import { fingerprintRegistry, getSyncRegistrySchema } from "@pgxsinkit/contracts";
23
23
 
24
+ import { type BootReport, type BootReportBuilder, createBootReportBuilder } from "./boot-report";
24
25
  import { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from "./convergence";
25
26
  import { syncDebug, timeAsync } from "./debug";
27
+ import { type DataExportOptions, type DataExportResult, performDataExport } from "./export-data";
28
+ import { type DiagnosticExportOptions, type DiagnosticExportResult, performDiagnosticExport } from "./export-dump";
29
+ import { performStoreExport, type StoreExportOptions, type StoreExportResult } from "./export-store";
26
30
  import { assertLazyRefsActivated, buildLazyGuardIndex, findReferencedLazyKeysInSql } from "./lazy-guard";
31
+ import { createLifecycleSlot } from "./lifecycle-slot";
32
+ import { wrapLiveQueryForMaterialization } from "./live-rows-sql";
27
33
  import {
28
34
  type LocalStoreVersionEvent,
29
35
  clearLazyGroupActivation,
@@ -38,12 +44,73 @@ import {
38
44
  type MutationKind,
39
45
  type WriteUnit,
40
46
  } from "./mutation";
41
- import { buildDesyncTableSql, buildDropReadCacheSql, buildWipeLocalStoreSql, generateLocalSchemaSql } from "./schema";
47
+ import {
48
+ buildDataExportCloneCleanupSql,
49
+ buildDataExportEnumHeaderSql,
50
+ buildDesyncTableSql,
51
+ buildDropReadCacheSql,
52
+ buildWipeLocalStoreSql,
53
+ collectDataExportSyncedTableNames,
54
+ generateLocalSchemaSql,
55
+ } from "./schema";
42
56
  import { startConfiguredSync } from "./shape-sync";
57
+ import {
58
+ classifyNonPersistentDataDir,
59
+ NonPersistentStoreError,
60
+ normaliseStorePathInput,
61
+ readTestStoreMarker,
62
+ resolveStoreDataDir,
63
+ RestoreTargetExistsError,
64
+ storeTargetExists,
65
+ type StorePathInput,
66
+ } from "./store-path";
43
67
  import { createSyncEngine, type SyncEngine } from "./sync";
44
68
  import { buildShapeHeaders } from "./sync-auth";
45
69
 
46
70
  export { generateLocalSchemaSql };
71
+ export { wrapLiveQueryForMaterialization } from "./live-rows-sql";
72
+ export type { BootReport } from "./boot-report";
73
+ export {
74
+ type CloneDumpPhases,
75
+ type CloneDumpResult,
76
+ type DiagnosticExportDeps,
77
+ type DiagnosticExportOptions,
78
+ type DiagnosticExportResult,
79
+ performDiagnosticExport,
80
+ runThrowawayCloneDump,
81
+ } from "./export-dump";
82
+ export {
83
+ type DataExportDeps,
84
+ DataExportDrainError,
85
+ type DataExportOptions,
86
+ type DataExportResult,
87
+ DEFAULT_DRAIN_TIMEOUT_MS,
88
+ type DrainJournalOption,
89
+ type DrainJournalOptions,
90
+ performDataExport,
91
+ } from "./export-data";
92
+ export {
93
+ type DataExportReport,
94
+ deriveStoreId,
95
+ type DiagnosticDumpReport,
96
+ type ExportReport,
97
+ type ExportReportCommon,
98
+ performDatadirDump,
99
+ performStoreExport,
100
+ type StoreBackupReport,
101
+ type StoreExportDeps,
102
+ type StoreExportOptions,
103
+ type StoreExportResult,
104
+ } from "./export-store";
105
+ export { createLifecycleSlot, LifecycleBusyError, type LifecycleSlot } from "./lifecycle-slot";
106
+ export {
107
+ InvalidStorePathError,
108
+ NonPersistentStoreError,
109
+ resolveStoreDataDir,
110
+ RestoreTargetExistsError,
111
+ storeIndexedDbDatabaseName,
112
+ storeTargetExists,
113
+ } from "./store-path";
47
114
  export {
48
115
  type ConvergenceClient,
49
116
  type ConvergenceDriver,
@@ -81,6 +148,7 @@ export {
81
148
  type BridgeMessageType,
82
149
  type BridgePort,
83
150
  encodeEnvelope,
151
+ type ExportArtefactWire,
84
152
  identityCodec,
85
153
  isBridgeEnvelope,
86
154
  type LiveDiffPayload,
@@ -137,13 +205,42 @@ export interface PgliteBootAssets {
137
205
  fsBundle?: Blob;
138
206
  }
139
207
 
208
+ /** Options for {@link createClientPGlite}. */
209
+ export interface CreateClientPGliteOptions {
210
+ /**
211
+ * Pre-warmed PGlite boot assets (see {@link CreateSyncClientOptions.pgliteBootAssets}). Awaited and
212
+ * passed into `PGlite.create`; a rejected warm is caught to `undefined` (falls back to PGlite's own
213
+ * asset load), so it never fails the create.
214
+ */
215
+ bootAssets?: Promise<PgliteBootAssets>;
216
+ /**
217
+ * @internal Test-only storage-backend override (ADR-0036). `"memory"` resolves the store to a
218
+ * scheme-selected in-memory store — the sanctioned unit-test/ephemeral lane. Never a product
219
+ * configuration: reached only through `@pgxsinkit/client/testing`, never consumer-facing.
220
+ */
221
+ backendOverride?: "memory";
222
+ /**
223
+ * A store-backup tarball to seed the new store from (ADR-0035 decision 6, restore) — a `File`/`Blob` as
224
+ * produced by {@link SyncClient.exportStore}. Passed straight to PGlite's `loadDataDir`, so the created
225
+ * store boots ON the backup's datadir. Restore is a CREATION-path feature: the caller (`createSyncClient`)
226
+ * has already proven the target does not yet exist ({@link storeTargetExists}); this option carries no
227
+ * freshness check of its own. A corrupt/foreign tarball surfaces as a PGlite boot failure here.
228
+ */
229
+ restoreFrom?: File | Blob;
230
+ }
231
+
140
232
  /**
141
233
  * Create the raw local PGlite store the sync client runs on — the SAME `PGlite.create` call
142
234
  * {@link createSyncClient} makes internally (the `electric` + `live` extensions, pre-warmed boot-asset
143
235
  * consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists
144
236
  * and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)
145
237
  * instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare
146
- * hooks, journal recovery and store-version reconcile, exactly as its own `dataDir` path does.
238
+ * hooks, journal recovery and store-version reconcile, exactly as its own `storePath` path does.
239
+ *
240
+ * Takes a plain store path (ADR-0036), never a storage URL — the backend is DERIVED (IndexedDB in a
241
+ * browser/worker, the filesystem on Bun/Node); a scheme-bearing path throws {@link InvalidStorePathError}.
242
+ * Also accepts the testing helper's output (`createClientPGlite(memoryStoreForTests("x"))`) so a test can
243
+ * mint a memory store without naming a backend.
147
244
  *
148
245
  * The instance is deliberately **schemaless** — the registry-derived local schema is role/registry
149
246
  * dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive
@@ -153,9 +250,14 @@ export interface PgliteBootAssets {
153
250
  * rejected warm is caught to `undefined`, so PGlite falls back to loading its own assets — never a failure.
154
251
  */
155
252
  export async function createClientPGlite(
156
- dataDir: string,
157
- options?: { bootAssets?: Promise<PgliteBootAssets> },
253
+ store: StorePathInput,
254
+ options?: CreateClientPGliteOptions,
158
255
  ): Promise<ClientPGlite> {
256
+ // Normalise the store argument to a plain path (+ any internal memory override the testing helper carried),
257
+ // then derive the concrete PGlite dataDir URL (ADR-0036) — the single resolution point. A scheme-bearing/
258
+ // empty storePath throws here, so the old dataDir-URL contract fails loudly, never silently re-interpreted.
259
+ const normalised = normaliseStorePathInput(store);
260
+ const dataDir = resolveStoreDataDir(normalised.storePath, options?.backendOverride ?? normalised.backendOverride);
159
261
  // Stamp only the storage scheme (e.g. "idb:" / "memory:"), never the full path — the path can carry an
160
262
  // identity-specific store name, and the boot rail stays monotonic-and-scheme only.
161
263
  const dataDirScheme = dataDir.slice(0, dataDir.indexOf(":") + 1);
@@ -175,6 +277,11 @@ export async function createClientPGlite(
175
277
  // `electric` namespace is provisioned later, exactly as the registry-derived schema is.
176
278
  PGlite.create(dataDir, {
177
279
  ...(bootAssets ?? {}),
280
+ // Restore (ADR-0035 decision 6): seed the brand-new store from the backup tarball. PGlite's
281
+ // `loadDataDir` unpacks it into the datadir being created, so the store boots ON the backup's bytes —
282
+ // the whole synced cache, Overlay, and Mutation journal that travelled inside it. Absent on a normal
283
+ // create (the store initdbs empty).
284
+ ...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),
178
285
  extensions: {
179
286
  live,
180
287
  },
@@ -209,7 +316,15 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
209
316
  */
210
317
  writeRequestHeaders?: Record<string, string>;
211
318
  syncEnabled?: boolean;
212
- dataDir?: string;
319
+ /**
320
+ * The local store's name (ADR-0036) — a PLAIN path/name, never a PGlite storage URL. The storage backend
321
+ * is DERIVED from the environment (IndexedDB in a browser/worker, the filesystem on Bun/Node); a
322
+ * scheme-bearing string (anything containing `://`) is rejected with {@link InvalidStorePathError}
323
+ * at boot. Defaults to a built-in overlay store name when omitted. A memory-backed store is not a product
324
+ * configuration — for the test/ephemeral lane, spread `memoryStoreForTests(...)` from
325
+ * `@pgxsinkit/client/testing` instead of naming one here.
326
+ */
327
+ storePath?: string;
213
328
  /**
214
329
  * Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight
215
330
  * into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —
@@ -231,11 +346,16 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
231
346
  * post-create boot steps against it — no schema exec, prepare hooks, or store-version reconcile
232
347
  * (journal recovery still runs, as it does on every path). Use it only when the caller has already
233
348
  * applied the registry schema itself. Contrast the three PGlite-provenance seams:
234
- * - {@link dataDir} (default) — the client creates the store AND runs every post-create step.
349
+ * - {@link storePath} (default) — the client creates the store AND runs every post-create step.
235
350
  * - {@link precreatedPglite} — the caller creates the raw store (via {@link createClientPGlite}), but
236
- * the client still runs every post-create step (schema/prepare/reconcile), exactly as `dataDir` does.
351
+ * the client still runs every post-create step (schema/prepare/reconcile), exactly as `storePath` does.
237
352
  * - `pgliteInstance` — the caller creates AND provisions the store; the client runs none of them.
238
353
  *
354
+ * A caller-owned instance is REFUSED with {@link NonPersistentStoreError} if it is provably
355
+ * non-persistent (a `new PGlite()` default, or an in-memory store) — pgxsinkit's durability semantics
356
+ * assume a persisted store (ADR-0036). Acknowledge a deliberate test store by spreading
357
+ * `testStoreAcknowledgment()` from `@pgxsinkit/client/testing`.
358
+ *
239
359
  * Mutually exclusive with {@link precreatedPglite} (supplying both throws).
240
360
  */
241
361
  pgliteInstance?: ClientPGlite;
@@ -243,18 +363,45 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
243
363
  * A raw PGlite instance the caller created EAGERLY (via {@link createClientPGlite}) — typically on an
244
364
  * earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the
245
365
  * client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and store-version
246
- * reconcile all run exactly as on the {@link dataDir} path. This is the difference from
366
+ * reconcile all run exactly as on the {@link storePath} path. This is the difference from
247
367
  * {@link pgliteInstance} (which skips schema/prepare/reconcile because the caller owns them); see that
248
368
  * option's JSDoc for the three-way distinction.
249
369
  *
250
370
  * The promise form lets the still-pending eager create be handed straight in. Precedence/validation:
251
371
  * - Supplying both this and {@link pgliteInstance} throws — they claim different ownership.
252
- * - {@link dataDir} is used ONLY as the fallback store id if this promise REJECTS: a failed eager
253
- * create is caught, logged on the boot rail, and the normal `dataDir` create path runs instead (also
372
+ * - {@link storePath} is used ONLY as the fallback store name if this promise REJECTS: a failed eager
373
+ * create is caught, logged on the boot rail, and the normal `storePath` create path runs instead (also
254
374
  * consuming {@link pgliteBootAssets} if provided). The pattern is a pure accelerator, never a boot
255
375
  * dependency.
376
+ * - A successfully-adopted instance is subject to the same {@link NonPersistentStoreError} refusal as
377
+ * {@link pgliteInstance} (checked after resolution, so the refusal propagates rather than being
378
+ * swallowed by the reject-fallback).
256
379
  */
257
380
  precreatedPglite?: Promise<ClientPGlite>;
381
+ /**
382
+ * Restore the store from a **store backup** (ADR-0035 decision 6) — a `File`/`Blob` tarball as produced by
383
+ * {@link SyncClient.exportStore}. The client creates its store with the backup handed to PGlite's
384
+ * `loadDataDir`, so it boots ON the backup's datadir (synced cache + Overlay + Mutation journal, all the
385
+ * bytes that travelled inside it). Three restore-only rules apply, none of them optional:
386
+ *
387
+ * - **Fresh target only.** Refused with {@link RestoreTargetExistsError} if a store already exists at the
388
+ * resolved {@link storePath} — restore never overlays a live store (that would corrupt the datadir); the
389
+ * remedy is a deliberate {@link SyncClient.destroy} of the existing store first.
390
+ * - **Always boots offline.** The engine boots with sync OFF regardless of {@link syncEnabled}/{@link autoSync}
391
+ * or anything captured in the backup — no shape streams, no read fetch, no flush, no convergence passes.
392
+ * Restore wins over an explicit online option (a debug-rail warning notes the override). The app inspects
393
+ * {@link SyncClient.diagnostics}, releases/discards the quarantined rows, then a subsequent NORMAL boot of
394
+ * the (now-persisted) store brings sync online — `loadDataDir` happens exactly once, on this restore boot.
395
+ * - **Journal quarantined.** Every non-terminal recovered row (`pending`/`sending`/`failed`) is moved to
396
+ * `quarantined` — nothing recovered from a backup auto-flushes (the write path has no `mutationId` dedupe
397
+ * ledger, so replay is unsafe on last-write-wins tables). Release (`retryFailed`) or discard
398
+ * (`discardQuarantined`) them explicitly.
399
+ *
400
+ * Mutually exclusive with {@link pgliteInstance} AND {@link precreatedPglite} — restore owns the store's
401
+ * creation (`loadDataDir` is a create-time seed), so a caller-supplied instance conflicts (supplying either
402
+ * with `restoreFrom` throws).
403
+ */
404
+ restoreFrom?: File | Blob;
258
405
  /**
259
406
  * PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new
260
407
  * and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync
@@ -317,6 +464,26 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
317
464
  * instead of silently diverging from the server; recovery is a later commit or a restart/refetch.
318
465
  */
319
466
  onSyncError?: (error: Error) => void;
467
+ /**
468
+ * Boot observability (ADR-0034): invoked exactly once, at boot completion, with the finalized
469
+ * {@link BootReport}. The push counterpart of {@link SyncClient.bootReport} (the pull) for consumers that
470
+ * want the numbers without polling — dashboards, CI budget gates. Never fired before initial sync; a
471
+ * `stop()`/`destroy()` before then means it never fires.
472
+ */
473
+ onBootReport?: (report: BootReport) => void;
474
+ /**
475
+ * @internal Boot mode stamped into the {@link BootReport} (ADR-0034). `defineSyncWorker` sets `"worker"`;
476
+ * absent → `"in-process"`. Not a behavior knob — it only labels the report.
477
+ */
478
+ bootMode?: BootReport["mode"];
479
+ /**
480
+ * @internal Provision timing for a boot that ADOPTS a pre-provisioned store (ADR-0034). When the store was
481
+ * minted ahead of boot (a spare's off-thread initdb), the provisioner stamps its create cost and ready
482
+ * time here; the boot reports them as {@link BootReport.provision} and sets `phases.pgliteCreateMs = null`.
483
+ * A promise because the stamp settles with the spare's `create`. Only honoured on the {@link precreatedPglite}
484
+ * adoption path (ignored on a fallback create). `provisionReadyAt` must share this process's monotonic clock.
485
+ */
486
+ provisionStamp?: Promise<{ initdbMs: number; provisionReadyAt: number }>;
320
487
  }
321
488
 
322
489
  export interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {
@@ -419,7 +586,22 @@ export interface PrepareQueryInput<TRegistry extends SyncTableRegistry> {
419
586
  export interface SubscribeLiveRowsInput {
420
587
  sql: string;
421
588
  params: readonly unknown[];
422
- /** The result's PK columns — the diff-keying identity across the bridge (§4). Omit for a keyless query. */
589
+ /**
590
+ * The unique output aliases to render the query's columns under so it is SAFE TO MATERIALISE, in the
591
+ * compiled SQL's column order (one per output column). Drizzle emits no output aliases, so a JOIN whose
592
+ * tables share a column name compiles to duplicate output names — which PGlite's `live` extension
593
+ * refuses to materialise (`column "title" specified more than once`) and which silently collapse
594
+ * same-named columns even in a plain query. When supplied, the seam wraps the query so every output
595
+ * column gets its alias and rows come back KEYED BY THESE ALIASES; the consumer's row-mapper must read
596
+ * by alias (the `@pgxsinkit/react` hooks do). Omit for a raw or non-colliding query — the seam then
597
+ * leaves the SQL untouched and rows stay keyed by the underlying column names (backward-compatible).
598
+ */
599
+ fields?: readonly string[];
600
+ /**
601
+ * The result's PK columns — the diff-keying identity across the bridge (§4). Omit for a keyless query.
602
+ * When {@link fields} is supplied the result columns are the aliases, so a PK column here must be named
603
+ * by its ALIAS (the aliased result column), not the underlying source column.
604
+ */
423
605
  pkColumns?: readonly string[];
424
606
  /**
425
607
  * Lazy relations (ADR-0021) to activate before the query runs — forwarded to the worker so it can
@@ -450,12 +632,18 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
450
632
  * Wipe the entire local store (synced cache + overlay + journal) and close the handle
451
633
  * (ADR-0005). Refuses if mutations are still owed to the server unless `force` is set, so
452
634
  * it never silently drops un-flushed writes. Distinct from `stop()`, which only halts sync.
635
+ * Runs under the single lifecycle slot (ADR-0035 decision 4): a concurrent export — or another
636
+ * `destroy`/`discardEphemeral`/`dropReadCache` — rejects with a {@link LifecycleBusyError} rather
637
+ * than interleaving the wipe with a running export.
453
638
  */
454
639
  destroy: (options?: { force?: boolean }) => Promise<void>;
455
640
  /**
456
641
  * Drop and rebuild the reconstructible synced read cache, preserving the overlay and
457
642
  * mutation journal (ADR-0006). The next sync refills it. Use to recover from a corrupt or
458
- * stale read cache without losing un-flushed writes.
643
+ * stale read cache without losing un-flushed writes. Runs under the single lifecycle slot
644
+ * (ADR-0035 decision 4) — it drops and rebuilds the synced tables, so an export must not capture a
645
+ * half-rebuilt cache; a concurrent export (or `destroy`/`discardEphemeral`) rejects with a
646
+ * {@link LifecycleBusyError}.
459
647
  */
460
648
  dropReadCache: () => Promise<void>;
461
649
  flush: (table?: SyncTableName<TRegistry>) => Promise<void>;
@@ -555,6 +743,24 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
555
743
  * relation, idle-eviction is otherwise automatic at session end.
556
744
  */
557
745
  desync: (key: SyncTableName<TRegistry>) => Promise<void>;
746
+ /**
747
+ * Drop an **ephemeral** relation's local rows and revert it to dormant (ADR-0021) — the narrow,
748
+ * scoped twin of {@link desync}. It runs the identical group-teardown machinery (stop the group stream,
749
+ * clear the persisted lazy activation, reset the persisted subscription, clean-truncate every member),
750
+ * but under a STRICTER gate: EVERY member of the relation's consistency group must be `retention:
751
+ * "ephemeral"` — it refuses (naming the offender) if any member is persistent. Where a `desync` from one
752
+ * tab reverts the shared group for every attached tab (the SharedWorker footgun), `discardEphemeral` is
753
+ * safe under multi-tab because an ephemeral window is per-delivery-session and inherently single-consumer
754
+ * — nothing durable, and no other tab, depends on it. Refuses an `eager` relation (always-on, would
755
+ * immediately re-sync) and a group that owes the server unsettled writes, exactly as `desync` does. The
756
+ * finalize primitive for a secure-delivery window: drop the local rows at session end without touching a
757
+ * durable relation. Note the drop is local-lifecycle only: a later re-subscription re-activates the lazy
758
+ * group and re-streams whatever the SERVER still serves — post-finalize non-redelivery is the server
759
+ * gate's guarantee (e.g. a consumed server-owned cursor), not this method's. Runs under the single
760
+ * lifecycle slot (ADR-0035 decision 4): a concurrent export (or `destroy`/`dropReadCache`) rejects with a
761
+ * {@link LifecycleBusyError} rather than interleaving the cache truncate with a running export.
762
+ */
763
+ discardEphemeral: (key: SyncTableName<TRegistry>) => Promise<void>;
558
764
  /**
559
765
  * The read-path safety seam (ADR-0021): scan the compiled `sql` for the lazy relations it reads
560
766
  * (∪ the optional `use`), activate them, and await their initial sync — so a lazy relation
@@ -600,6 +806,59 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
600
806
  input: SubscribeLiveRowsInput,
601
807
  onRows: (rows: TRow[]) => void,
602
808
  ) => Promise<LiveRowsSubscription<TRow>>;
809
+ /**
810
+ * Boot observability (ADR-0034): the engine's most recent COMPLETED boot report, or `null` before the
811
+ * first boot finalizes (and after a `stop()`/`destroy()` that preceded initial sync). Pull — so a
812
+ * late-attaching tab can read a boot that predates it; in worker mode it round-trips to the worker's
813
+ * stored report. The push counterpart is the `onBootReport` client option.
814
+ */
815
+ bootReport: () => Promise<BootReport | null>;
816
+ /**
817
+ * Take a **store backup** (ADR-0035): a full-fidelity, PGlite-restorable tarball of the whole local
818
+ * store — synced cache, Overlay, and Mutation journal (unflushed writes included) — via PGlite's
819
+ * `dumpDataDir`. Taken LIVE (a `CHECKPOINT` serialised behind engine work, then the dump; no engine
820
+ * suspension, no tab disruption), so it never blocks and is the only lossless export an offline device
821
+ * with unflushed writes can take. Awaits engine-ready rather than rejecting during boot, then runs under
822
+ * the single lifecycle slot: a second export (or, later, `destroy`/`discardEphemeral`) attempted while
823
+ * one is in flight rejects immediately with a {@link LifecycleBusyError} — retry once it settles.
824
+ * Resolves to the artefact `File` plus an {@link ExportReport} (phase timings + a diagnostics snapshot).
825
+ */
826
+ exportStore: (options?: StoreExportOptions) => Promise<StoreExportResult>;
827
+ /**
828
+ * Take a **diagnostic dump** (ADR-0035): human-readable SQL of EVERYTHING the store holds — synced tables,
829
+ * the `_overlay`/`_mutations` journal (unflushed writes included — the evidence a diagnostic exists for),
830
+ * the `pgxsinkit` metadata schema, the read-model views, and the reconcile functions/triggers — via
831
+ * `pg_dump`. To keep `pg_dump`'s `DEALLOCATE ALL` away from the live engine, the dump runs against a
832
+ * memory-backed THROWAWAY clone booted from a live datadir dump (ADR-0035 addendum): the running store is
833
+ * never suspended and no tab is disrupted. Awaits engine-ready rather than rejecting during boot, then
834
+ * runs under the single lifecycle slot — a concurrent export (or `destroy`/`discardEphemeral`) rejects
835
+ * immediately with a {@link LifecycleBusyError}. Resolves to the SQL `File` (`application/sql`) plus a
836
+ * {@link DiagnosticDumpReport} (phase timings + a diagnostics snapshot). Active ephemeral (`pg_temp`)
837
+ * clusters are absent by construction (ADR-0035 decision 5 — `pg_dump` ignores temp objects).
838
+ */
839
+ exportDiagnostics: (options?: DiagnosticExportOptions) => Promise<DiagnosticExportResult>;
840
+ /**
841
+ * Take a **data export** (ADR-0035): the PORTABLE artefact — the synced tables and the enum types they
842
+ * depend on, schema + data, nothing of pgxsinkit's machinery — as SQL loadable into a vanilla Postgres. It
843
+ * is a generated enum DDL header concatenated ahead of `pg_dump -t <table> ... --no-owner` (one `-t` per
844
+ * physical synced table; ephemeral/read-projection entries excluded by construction), run against the same
845
+ * memory-backed THROWAWAY clone the diagnostic dump uses — so the live engine is never touched.
846
+ *
847
+ * Unlike the other two exports it GUARDS the journal (decision 3): a strict export requires a DRAINED
848
+ * journal — all mutation counts zero, including `acked` writes whose synced echo has not landed (they live
849
+ * only in the Overlay). The drain flushes drainable rows and awaits convergence up to
850
+ * `drainJournal.timeoutMs` (default `15_000`); non-drainable states (`failed`/`quarantined`/`conflicted`)
851
+ * fail FAST with a {@link DataExportDrainError} carrying the diagnostics. `drainJournal: false` is the
852
+ * escape hatch — export synced state as-is (unflushed writes absent; `report.escapeHatch` records it). An
853
+ * offline device with a clean journal exports strictly and instantly; one with a dirty journal cannot
854
+ * produce a strict export (its lossless option is `exportStore`).
855
+ *
856
+ * Awaits engine-ready rather than rejecting during boot, then runs the whole drain+dump under the single
857
+ * lifecycle slot — a concurrent export (or `destroy`/`discardEphemeral`) rejects with a
858
+ * {@link LifecycleBusyError}. Resolves to the SQL `File` (`application/sql`) plus a {@link DataExportReport}
859
+ * (drain + clone-pipeline phase timings, the applied `-t` table list, and the escape-hatch flag).
860
+ */
861
+ exportData: (options?: DataExportOptions) => Promise<DataExportResult>;
603
862
  }
604
863
 
605
864
  export type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind };
@@ -657,32 +916,148 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
657
916
  );
658
917
  }
659
918
 
660
- // Bind the boot-asset option once for the two create paths (fresh `dataDir`, and the `precreatedPglite`
661
- // reject-fallback), so both consume the same pre-warm.
662
- const createBootAssets = options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : undefined;
663
- const fallbackDataDir = options.dataDir ?? "idb://pgxsinkit-overlay-v1";
919
+ // Restore (ADR-0035 decision 6) owns the store's CREATION — the backup tarball is a `loadDataDir` seed on
920
+ // the fresh store — so it cannot coexist with a caller-supplied instance (which claims the store already
921
+ // exists and is provisioned). Fail loudly rather than silently ignore one.
922
+ const restoreBoot = options.restoreFrom != null;
923
+ if (restoreBoot && (options.pgliteInstance || options.precreatedPglite)) {
924
+ throw new Error(
925
+ "createSyncClient: `restoreFrom` is mutually exclusive with `pgliteInstance` / `precreatedPglite` — restore boots a brand-new store from the backup (a create-time `loadDataDir` seed), so it cannot adopt a caller-owned instance. Drop the instance option, or drop `restoreFrom` (ADR-0035).",
926
+ );
927
+ }
928
+
929
+ // Restore ALWAYS boots offline (ADR-0035 decision 6), regardless of `syncEnabled`/`autoSync` or anything
930
+ // captured in the backup: no shape streams, no read fetch, no flush, no convergence passes. The app deals
931
+ // with the quarantined journal, then a subsequent NORMAL boot brings sync online. Restore wins over an
932
+ // explicit online option — warn on the debug rail so the override is visible rather than silent.
933
+ if (restoreBoot && (options.syncEnabled === true || options.autoSync != null)) {
934
+ syncDebug("boot restore forces offline — ignoring the online sync option for this restore boot", {
935
+ syncEnabled: options.syncEnabled === true,
936
+ autoSync: options.autoSync != null,
937
+ });
938
+ }
939
+ const syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);
940
+ // ADR-0032 S4 overlap flag, computed once up front so the boot report and the prefetch gate agree.
941
+ const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
942
+
943
+ // Boot observability (ADR-0034): build a structured report across the boot, finalized once at initial
944
+ // sync. Created FIRST so its monotonic anchor precedes every timed phase (including the PGlite create).
945
+ const bootReportBuilder: BootReportBuilder = createBootReportBuilder({
946
+ mode: options.bootMode ?? "in-process",
947
+ freshStore: options.freshStore === true,
948
+ overlapPrefetch,
949
+ registryFingerprint: fingerprintRegistry(options.registry),
950
+ });
951
+ // The single engine lifecycle slot (ADR-0035 decision 4). The three exports plus the destructive
952
+ // lifecycle ops — `destroy()`, `discardEphemeral()`, and `dropReadCache()` — all serialise through it,
953
+ // so a wipe/rebuild can never interleave a running export (nor vice versa): the slot rejects the second
954
+ // entrant with a typed LifecycleBusyError in either direction.
955
+ const lifecycleSlot = createLifecycleSlot();
956
+
957
+ let finalizedBootReport: BootReport | null = null;
958
+ const finalizeBootReport = () => {
959
+ if (finalizedBootReport) return;
960
+ finalizedBootReport = bootReportBuilder.finalize();
961
+ options.onBootReport?.(finalizedBootReport);
962
+ };
963
+
964
+ // The testing marker (ADR-0036 decision 3), read once off the options object: `"memory"` selects the
965
+ // memory backend for a client-owned create AND acknowledges the BYO seam; `"acknowledged"` only unlocks
966
+ // the BYO refusal. Absent for every production consumer — the marker rides in only via
967
+ // `@pgxsinkit/client/testing`, never named in a public type.
968
+ const testStoreMarker = readTestStoreMarker(options);
969
+ const backendOverride = testStoreMarker === "memory" ? ("memory" as const) : undefined;
970
+
971
+ // Bind the create options once for the two client-owned create paths (fresh `storePath`, and the
972
+ // `precreatedPglite` reject-fallback), so both consume the same pre-warm + resolve the same backend.
973
+ const createClientOptions: CreateClientPGliteOptions = {
974
+ ...(options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {}),
975
+ ...(backendOverride ? { backendOverride } : {}),
976
+ // Restore (ADR-0035 decision 6): seed the fresh store from the backup via `loadDataDir`. Restore is
977
+ // mutually exclusive with the BYO instance seams (checked above), so it only ever rides a client-owned
978
+ // create — never the adopt paths, which leave `restoreFrom` unread.
979
+ ...(restoreBoot ? { restoreFrom: options.restoreFrom } : {}),
980
+ };
981
+ const fallbackStorePath = options.storePath ?? "pgxsinkit-overlay-v1";
982
+
983
+ // Fresh-target gate (ADR-0035 decision 6): restore refuses a store that already exists — it boots a
984
+ // brand-new store and never overlays a live one. Checked BEFORE the create so we never touch (let alone
985
+ // half-write) an existing datadir; the memory test lane is fresh by construction, so this is a no-op there.
986
+ if (restoreBoot) {
987
+ if (await storeTargetExists(fallbackStorePath, backendOverride)) {
988
+ throw new RestoreTargetExistsError(fallbackStorePath);
989
+ }
990
+ }
991
+ // Time a client-owned `createClientPGlite` into `phases.pgliteCreateMs`; an ADOPTED store (spare or
992
+ // caller-supplied) leaves it `null` (create ran elsewhere — see the provision block below).
993
+ const timedCreate = async (): Promise<ClientPGlite> => {
994
+ const startedAt = performance.now();
995
+ const created = await createClientPGlite(fallbackStorePath, createClientOptions);
996
+ bootReportBuilder.setPgliteCreateMs(performance.now() - startedAt);
997
+ return created;
998
+ };
999
+
1000
+ // Refuse a caller-owned instance that is PROVABLY non-persistent (ADR-0036 decision 4), unless a testing
1001
+ // acknowledgment is present. `classifyNonPersistentDataDir` inspects the instance's own dataDir (the
1002
+ // `ClientPGlite` interface hides it, so via a narrow cast) — the two provably-non-persistent shapes are
1003
+ // an undefined dataDir (PGlite's in-memory default) and an explicit memory store. Checked AFTER a
1004
+ // successful resolution of the BYO promise, so the refusal PROPAGATES rather than being swallowed by the
1005
+ // `precreatedPglite` reject-fallback below (which only catches a create that never produced a store).
1006
+ const refuseIfNonPersistent = (instance: ClientPGlite): void => {
1007
+ if (testStoreMarker !== undefined) return; // a deliberate test store — acknowledged.
1008
+ const observed = classifyNonPersistentDataDir((instance as { dataDir?: string }).dataDir);
1009
+ if (observed !== null) throw new NonPersistentStoreError(observed);
1010
+ };
664
1011
 
665
1012
  let pglite: ClientPGlite;
1013
+ // Whether the boot adopted the caller's `precreatedPglite` (vs. falling back to a fresh create) — gates
1014
+ // whether the provision stamp is honoured (ADR-0034).
1015
+ let adoptedPrecreated = false;
666
1016
  if (options.pgliteInstance) {
667
1017
  // The caller created AND provisioned this store; the client runs NONE of the post-create boot steps
668
- // (schema/prepare/reconcile) — see the `pgliteInstance` JSDoc.
1018
+ // (schema/prepare/reconcile) — see the `pgliteInstance` JSDoc. No create here → `pgliteCreateMs` null.
1019
+ refuseIfNonPersistent(options.pgliteInstance);
669
1020
  pglite = options.pgliteInstance;
670
1021
  } else if (options.precreatedPglite) {
671
1022
  // The caller created the raw store eagerly via `createClientPGlite`; the client still owns every
672
1023
  // post-create step below. A REJECTED eager create must never fail the boot: fall back to the normal
673
- // `dataDir` create here, so the pattern stays a pure accelerator.
674
- pglite = await options.precreatedPglite.catch((error: unknown) => {
675
- syncDebug("boot precreated pglite rejected — falling back to dataDir create", {
676
- error: error instanceof Error ? error.message : String(error),
1024
+ // `storePath` create, so the pattern stays a pure accelerator. Reify the promise's outcome first, THEN
1025
+ // branch — so the {@link NonPersistentStoreError} refusal runs on a SUCCESSFULLY resolved instance,
1026
+ // outside any catch, and PROPAGATES (never swallowed by the reject-fallback, which is only for a create
1027
+ // that never produced a store).
1028
+ const outcome = await options.precreatedPglite.then(
1029
+ (instance) => ({ ok: true as const, instance }),
1030
+ (error: unknown) => ({ ok: false as const, error }),
1031
+ );
1032
+ if (outcome.ok) {
1033
+ refuseIfNonPersistent(outcome.instance);
1034
+ pglite = outcome.instance;
1035
+ adoptedPrecreated = true;
1036
+ } else {
1037
+ syncDebug("boot precreated pglite rejected — falling back to storePath create", {
1038
+ error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),
677
1039
  });
678
- return createClientPGlite(fallbackDataDir, createBootAssets);
679
- });
1040
+ pglite = await timedCreate();
1041
+ }
680
1042
  } else {
681
- pglite = await createClientPGlite(fallbackDataDir, createBootAssets);
1043
+ pglite = await timedCreate();
1044
+ }
1045
+
1046
+ // Provision block (ADR-0034): when the boot adopted a pre-provisioned store and the provisioner stamped
1047
+ // its create timing, report the spare's initdb cost + how long it sat ready, and leave `pgliteCreateMs`
1048
+ // null (the create was paid at provision time, off this boot's clock).
1049
+ if (adoptedPrecreated && options.provisionStamp) {
1050
+ const stamp = await options.provisionStamp.catch(() => null);
1051
+ if (stamp) {
1052
+ bootReportBuilder.setProvision({
1053
+ initdbMs: stamp.initdbMs,
1054
+ provisionedMsBeforeBoot: Math.max(0, bootReportBuilder.bootStartPerf - stamp.provisionReadyAt),
1055
+ });
1056
+ }
682
1057
  }
683
1058
 
684
1059
  // Attach the sync engine explicitly, over the already-created instance, on ALL three provenance paths
685
- // (pgliteInstance, precreatedPglite, dataDir) — ADR-0032 S1. The engine is no longer a create-time
1060
+ // (pgliteInstance, precreatedPglite, storePath) — ADR-0032 S1. The engine is no longer a create-time
686
1061
  // extension, so the raw store (a `createClientPGlite` mint, or a caller's own instance) carries no
687
1062
  // `electric` namespace until this point; the property assignment gives `ClientPGlite` its exact former
688
1063
  // structural shape (live + electric) so every `pglite.electric.…` call site is unchanged. It is attached
@@ -693,7 +1068,6 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
693
1068
  const engine: SyncEngine = await createSyncEngine(pglite);
694
1069
  (pglite as { electric: SyncEngine["namespace"] }).electric = engine.namespace;
695
1070
 
696
- const syncEnabled = options.syncEnabled ?? true;
697
1071
  // Whether the read path's first initial sync has completed, so a recovery from `auth-needed` returns to
698
1072
  // the right steady-state phase (`ready` if already caught up, else `syncing`).
699
1073
  let initialSyncCompleted = false;
@@ -709,7 +1083,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
709
1083
  // overlaps those phases instead of running strictly after them. Gated to the schema-owning paths (the
710
1084
  // `pgliteInstance` path runs no schema step, so it has nothing to hide); warm stores keep the exact
711
1085
  // sequential path. See the `freshStore` option's JSDoc for who sets the hint (the board's claim path).
712
- const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
1086
+ // (`overlapPrefetch` is computed once up front — see the boot-report builder above.)
713
1087
  let openDbGate: () => void = () => {};
714
1088
  const dbReady = overlapPrefetch
715
1089
  ? new Promise<void>((resolve) => {
@@ -724,6 +1098,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
724
1098
  registry: options.registry,
725
1099
  promotedGroups,
726
1100
  ...(dbReady ? { dbReady } : {}),
1101
+ // Boot observability (ADR-0034): the collector opens a per-boot-group accumulator (rows/requests/fetch/
1102
+ // apply wall) for the eager + promoted groups; lazy on-demand starts get none, so they never enter the report.
1103
+ bootCollector: bootReportBuilder,
727
1104
  // Persist a durable lazy group's activation on first on-demand start, so the next boot promotes it.
728
1105
  onLazyActivated: (groupKey) => {
729
1106
  void writeLazyGroupActivation(pglite, options.registry, groupKey);
@@ -752,6 +1129,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
752
1129
  // Boot complete: the first initial sync landed and `ready` is about to resolve. One monotonic stamp
753
1130
  // closes the boot rail opened by `boot pglite.create` (the stamp itself is the number).
754
1131
  syncDebug("boot client ready");
1132
+ // Boot observability (ADR-0034): finalize the report at exactly this moment — the `boot client ready`
1133
+ // rail line — and fire the one-shot `onBootReport` push. Idempotent, so the sync-disabled path's own
1134
+ // finalize below never double-fires it.
1135
+ finalizeBootReport();
755
1136
  resolveReady();
756
1137
  },
757
1138
  onSyncError: (error) => {
@@ -808,10 +1189,12 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
808
1189
  // commits gated on `dbReady`). A fresh store has no persisted lazy activations and no subscriptions to
809
1190
  // reset, so both DB reads the sequential path makes first are skipped here.
810
1191
  let earlySync: ReturnType<typeof startConfiguredSync> | null = null;
1192
+ let earlySyncStartedAt = 0;
811
1193
  if (overlapPrefetch) {
812
1194
  status.isRunning = true;
813
1195
  status.phase = "syncing";
814
1196
  options.onStatusChange?.(status);
1197
+ earlySyncStartedAt = performance.now();
815
1198
  earlySync = startConfiguredSync(
816
1199
  pglite as unknown as Parameters<typeof startConfiguredSync>[0],
817
1200
  buildStartOptions(new Set()),
@@ -821,15 +1204,15 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
821
1204
  if (!options.pgliteInstance) {
822
1205
  if (options.prepareLocalDbBeforeSchema) {
823
1206
  const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;
824
- await timeAsync("boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
1207
+ await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
825
1208
  }
826
1209
 
827
1210
  const schemaSql = generateLocalSchemaSql(options.registry);
828
- await timeAsync("boot local schema", () => pglite.exec(schemaSql));
1211
+ await bootReportBuilder.phase("schemaExec", "boot local schema", () => pglite.exec(schemaSql));
829
1212
 
830
1213
  if (options.prepareLocalDb) {
831
1214
  const prepareLocalDb = options.prepareLocalDb;
832
- await timeAsync("boot prepare(local-db)", () => prepareLocalDb(pglite));
1215
+ await bootReportBuilder.phase("prepare", "boot prepare(local-db)", () => prepareLocalDb(pglite));
833
1216
  }
834
1217
  }
835
1218
 
@@ -856,12 +1239,30 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
856
1239
  // Reclaim any in-flight mutations interrupted by a previous shutdown (ADR-0005), then
857
1240
  // reconcile the local store against the current registry fingerprint before sync starts
858
1241
  // (ADR-0006). Skipped when the caller supplies their own pglite (they own its schema).
859
- await timeAsync("boot journal recovery", () => mutationRuntime.recoverSending());
1242
+ await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () => mutationRuntime.recoverSending());
1243
+
1244
+ // Restore-boot quarantine (ADR-0035 decision 6): the moment a store is booted FROM a backup, every
1245
+ // non-terminal recovered journal row (`pending`/`sending`/`failed`) is parked in `quarantined` so nothing
1246
+ // recovered auto-flushes — the write path has no `mutationId` dedupe ledger, making replay unsafe on
1247
+ // last-write-wins tables (silent stale reverts) and colliding on a recreated PK. Runs ONLY on the restore
1248
+ // boot (loadDataDir happens exactly once); a subsequent normal boot of the persisted store never re-runs
1249
+ // it. Placed AFTER `recoverSending` (which lifts any `sending` back to `pending`) so a single pass over
1250
+ // pending/sending/failed catches the lot. The app then inspects `diagnostics()` and releases/discards them.
1251
+ if (restoreBoot) {
1252
+ await mutationRuntime.quarantineRecovered();
1253
+ }
860
1254
 
861
1255
  let versionEvent: LocalStoreVersionEvent | null = null;
862
1256
 
1257
+ // Registry-fingerprint mismatch on restore (ADR-0035 decision 6): an old backup restored against a NEWER
1258
+ // registry needs NO special handling — the existing local-schema-evolution path (ADR-0006) owns it, and
1259
+ // restore composes with it for free. On this restore boot the quarantine above ran FIRST, so every
1260
+ // recovered row now counts toward `owedMutations` (pending+sending+failed+quarantined) inside
1261
+ // `rebuildReadCacheOrDefer`: a stale fingerprint therefore DEFERS the read-cache rebuild rather than
1262
+ // dropping the quarantined writes, exactly as it would for any store that owes work. The rebuild completes
1263
+ // on a later boot once the app has released/discarded the quarantine and drained the journal.
863
1264
  if (!options.pgliteInstance) {
864
- versionEvent = await timeAsync("boot store-version reconcile", () =>
1265
+ versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () =>
865
1266
  reconcileLocalStoreVersion({
866
1267
  db: pglite,
867
1268
  registry: options.registry,
@@ -889,8 +1290,11 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
889
1290
  if (earlySync) {
890
1291
  // Overlap path: the shape streams have been prefetching since before schema exec; adopt the handle
891
1292
  // (it resolves as soon as the streams are subscribed — catch-up drains via the gate just lifted, and
892
- // `onInitialSync` still gates `ready` on a fully-consistent first paint).
1293
+ // `onInitialSync` still gates `ready` on a fully-consistent first paint). The construction was kicked
1294
+ // off before schema exec, so time it here (concurrent-segment wall) into `phases.syncStartMs`.
893
1295
  sync = await earlySync;
1296
+ bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);
1297
+ bootReportBuilder.markSyncStartDone();
894
1298
  } else {
895
1299
  // Sequential path (warm store / no fresh hint): the exact pre-S4 ordering — reset any rebuilt
896
1300
  // subscriptions, promote durable lazy groups, then start (catch-up strictly after the local phases).
@@ -910,20 +1314,28 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
910
1314
  // (ADR-0021 §2); the sync engine does no DB read of its own.
911
1315
  const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);
912
1316
 
913
- sync = await timeAsync("boot sync start", () =>
1317
+ sync = await bootReportBuilder.phase("syncStart", "boot sync start", () =>
914
1318
  startConfiguredSync(
915
1319
  pglite as unknown as Parameters<typeof startConfiguredSync>[0],
916
1320
  buildStartOptions(promotedGroups),
917
1321
  ),
918
1322
  );
1323
+ bootReportBuilder.markSyncStartDone();
919
1324
  }
920
1325
  } else {
921
1326
  status.phase = "ready";
922
1327
  options.onStatusChange?.(status);
1328
+ // Sync disabled: there is no `onInitialSync` gate, but boot IS complete — finalize the report at the
1329
+ // same moment `ready` resolves (ADR-0034). Idempotent with the sync path's finalize.
1330
+ finalizeBootReport();
923
1331
  resolveReady();
924
1332
  }
925
1333
 
926
- if (options.autoSync) {
1334
+ // Restore boots offline (ADR-0035 decision 6): never stand up the convergence driver on a restore boot,
1335
+ // so an `autoSync` trigger the caller passed (even an online one) drives NO flush/reconcile passes — the
1336
+ // recovered journal is quarantined and must stay put until the app releases it and a normal boot goes
1337
+ // online. On every other boot the driver behaves exactly as before.
1338
+ if (options.autoSync && !restoreBoot) {
927
1339
  convergenceDriver = createConvergenceDriver({
928
1340
  client: {
929
1341
  flush: () => mutationRuntime.flush(),
@@ -981,26 +1393,28 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
981
1393
  return activeSync.isTableStarted(key);
982
1394
  };
983
1395
 
984
- const desync: SyncClient<TRegistry>["desync"] = async (key) => {
985
- const entry = options.registry[key];
986
- if (entry == null) throw new Error(`desync: unknown table ${String(key)}`);
987
- if (entry.subscription !== "lazy") {
988
- throw new Error(
989
- `desync('${String(key)}') refused: only a lazy relation can be desynced — an eager relation is always-on and would immediately re-sync.`,
990
- );
991
- }
992
-
993
- // ADR-0021 §2/§4: desync operates on the whole consistency GROUP — a group is one subscription / one
994
- // transaction frontier, so reverting one member to dormant reverts them all. Gather the group's tables
995
- // (a table with no `consistencyGroup` is its own singleton group).
1396
+ // ADR-0021 §2/§4: the tables of `entry`'s consistency GROUP — a group is one subscription / one
1397
+ // transaction frontier, so reverting one member to dormant reverts them all (a table with no
1398
+ // `consistencyGroup` is its own singleton group).
1399
+ const groupTableKeysFor = (key: SyncTableName<TRegistry>, entry: SyncTableEntry): SyncTableName<TRegistry>[] => {
996
1400
  const targetGroup = entry.consistencyGroup;
997
- const groupTableKeys = (
1401
+ return (
998
1402
  targetGroup == null
999
1403
  ? [key]
1000
1404
  : (Object.keys(options.registry) as SyncTableName<TRegistry>[]).filter(
1001
1405
  (candidate) => options.registry[candidate]!.consistencyGroup === targetGroup,
1002
1406
  )
1003
1407
  ) as SyncTableName<TRegistry>[];
1408
+ };
1409
+
1410
+ // The shared group-teardown body of {@link desync} and {@link discardEphemeral} (ADR-0021 §2/§4). Both
1411
+ // revert a lazy relation's whole consistency group to dormant: refuse if any writable member owes
1412
+ // unsettled writes, stop the group stream, clear the persisted lazy activation, delete the persisted
1413
+ // Electric subscription (so re-activation re-streams from scratch), then clean-truncate every member's
1414
+ // local cluster. `label` names the calling primitive in the owed-writes refusal so each keeps its own
1415
+ // diagnostic (desync stays byte-identical). Callers apply their own lazy/retention gates BEFORE this.
1416
+ const tearDownLazyGroup = async (key: SyncTableName<TRegistry>, entry: SyncTableEntry, label: string) => {
1417
+ const groupTableKeys = groupTableKeysFor(key, entry);
1004
1418
 
1005
1419
  // Refuse if ANY writable member owes the server unsent/unsettled writes: the truncate clears the
1006
1420
  // journal, so dropping un-acked local intent would be silent data loss. Flush (or discard) those first.
@@ -1013,7 +1427,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1013
1427
  }
1014
1428
  if (owed > 0) {
1015
1429
  throw new Error(
1016
- `desync('${String(key)}') refused: ${owed} unsettled mutation(s) in the group's local journal. Flush or discard them first.`,
1430
+ `${label}('${String(key)}') refused: ${owed} unsettled mutation(s) in the group's local journal. Flush or discard them first.`,
1017
1431
  );
1018
1432
  }
1019
1433
 
@@ -1036,6 +1450,52 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1036
1450
  }
1037
1451
  };
1038
1452
 
1453
+ const desync: SyncClient<TRegistry>["desync"] = async (key) => {
1454
+ const entry = options.registry[key];
1455
+ if (entry == null) throw new Error(`desync: unknown table ${String(key)}`);
1456
+ if (entry.subscription !== "lazy") {
1457
+ throw new Error(
1458
+ `desync('${String(key)}') refused: only a lazy relation can be desynced — an eager relation is always-on and would immediately re-sync.`,
1459
+ );
1460
+ }
1461
+ await tearDownLazyGroup(key, entry, "desync");
1462
+ };
1463
+
1464
+ const discardEphemeral: SyncClient<TRegistry>["discardEphemeral"] = (key) =>
1465
+ // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4): discardEphemeral
1466
+ // clean-truncates an ephemeral group's local cache, so an export must never interleave it (nor it an
1467
+ // export) — the slot's typed LifecycleBusyError fires in both directions. The existing lazy/ephemeral
1468
+ // gates below stay EXACTLY as they were, now inside the slot run. (`desync` is deliberately NOT slotted:
1469
+ // only the ADR-0035-named destructive ops — destroy/discardEphemeral/dropReadCache — serialise here.)
1470
+ lifecycleSlot.run("discardEphemeral", async () => {
1471
+ const entry = options.registry[key];
1472
+ if (entry == null) throw new Error(`discardEphemeral: unknown table ${String(key)}`);
1473
+ // Keep the lazy gate desync has: eager+ephemeral is NOT forbidden by the type system (retention and
1474
+ // subscription are independent scalars on the entry — see contracts config.ts / registry.ts), and an
1475
+ // eager relation would immediately re-stream, so the same refusal applies here.
1476
+ if (entry.subscription !== "lazy") {
1477
+ throw new Error(
1478
+ `discardEphemeral('${String(key)}') refused: only a lazy relation can be discarded — an eager relation is always-on and would immediately re-sync.`,
1479
+ );
1480
+ }
1481
+ // STRICTER gate than desync: every member of the consistency group must be ephemeral. Retention is read
1482
+ // as `entry.retention ?? "persistent"` (absent → persistent, matching validateRegistryLifecycleGroups and
1483
+ // the schema generator); a read PROJECTION surfaces its declared retention on the same `retention` field
1484
+ // (withRetention/asEphemeral/defineReadProjection all set it), so this one read covers tables and
1485
+ // projections alike. Refuse (naming the offender) if any member is persistent — discardEphemeral is the
1486
+ // multi-tab-safe primitive for per-delivery-session windows, and truncating a persistent member's cache
1487
+ // would drop durable local data; use desync for a persistent lazy relation.
1488
+ for (const member of groupTableKeysFor(key, entry)) {
1489
+ if ((options.registry[member]!.retention ?? "persistent") !== "ephemeral") {
1490
+ throw new Error(
1491
+ `discardEphemeral('${String(key)}') refused: group member '${String(member)}' is persistent — ` +
1492
+ `discardEphemeral only drops an ephemeral relation's local rows. Use desync for a persistent lazy relation.`,
1493
+ );
1494
+ }
1495
+ }
1496
+ await tearDownLazyGroup(key, entry, "discardEphemeral");
1497
+ });
1498
+
1039
1499
  const transaction: SyncClient<TRegistry>["transaction"] = async ({ mode }, run) => {
1040
1500
  // The block's table handles only COLLECT mutations; the whole set is enqueued atomically as one unit.
1041
1501
  const collected: MutationBatchItem<TRegistry>[] = [];
@@ -1147,38 +1607,52 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1147
1607
  await engine.close();
1148
1608
  await pglite.close();
1149
1609
  },
1150
- destroy: async (destroyOptions) => {
1151
- if (!destroyOptions?.force) {
1152
- const stats = await mutationRuntime.readMutationStats();
1153
- const owed =
1154
- stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;
1155
-
1156
- if (owed > 0) {
1157
- throw new Error(
1158
- `destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,
1159
- );
1610
+ destroy: (destroyOptions) =>
1611
+ // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4), so a destructive wipe can
1612
+ // never interleave a running export (nor an export interleave this wipe) — the slot's typed
1613
+ // LifecycleBusyError fires in both directions. The refuse-if-owed guard stays EXACTLY as it was, now
1614
+ // inside the slot run.
1615
+ lifecycleSlot.run("destroy", async () => {
1616
+ if (!destroyOptions?.force) {
1617
+ const stats = await mutationRuntime.readMutationStats();
1618
+ const owed =
1619
+ stats.pendingCount +
1620
+ stats.sendingCount +
1621
+ stats.failedCount +
1622
+ stats.quarantinedCount +
1623
+ stats.conflictedCount;
1624
+
1625
+ if (owed > 0) {
1626
+ throw new Error(
1627
+ `destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,
1628
+ );
1629
+ }
1160
1630
  }
1161
- }
1162
1631
 
1163
- // Drain any in-flight convergence pass before wiping, so a pass never writes into a store
1164
- // being torn down underneath it.
1165
- await convergenceDriver?.stop();
1166
- sync?.unsubscribe();
1167
- status.isRunning = false;
1168
- options.onStatusChange?.(status);
1169
- await pglite.exec(buildWipeLocalStoreSql(options.registry));
1170
- // Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment
1171
- // the former extension close hook fired during `pglite.close()` (ADR-0032 S1).
1172
- await engine.close();
1173
- await pglite.close();
1174
- },
1175
- dropReadCache: async () => {
1176
- await pglite.exec(buildDropReadCacheSql(options.registry));
1177
- await pglite.exec(generateLocalSchemaSql(options.registry));
1178
- // Reset the Electric subscriptions so the rebuilt synced tables re-stream from scratch
1179
- // rather than the bookkeeping believing they are already caught up (ADR-0006).
1180
- await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
1181
- },
1632
+ // Drain any in-flight convergence pass before wiping, so a pass never writes into a store
1633
+ // being torn down underneath it.
1634
+ await convergenceDriver?.stop();
1635
+ sync?.unsubscribe();
1636
+ status.isRunning = false;
1637
+ options.onStatusChange?.(status);
1638
+ await pglite.exec(buildWipeLocalStoreSql(options.registry));
1639
+ // Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment
1640
+ // the former extension close hook fired during `pglite.close()` (ADR-0032 S1).
1641
+ await engine.close();
1642
+ await pglite.close();
1643
+ }),
1644
+ dropReadCache: () =>
1645
+ // Under the SAME lifecycle slot as the exports (ADR-0035 decision 4). WHY dropReadCache is slotted and
1646
+ // not just destroy/discardEphemeral: it DROPS and rebuilds the synced read-cache tables, so an export
1647
+ // racing it would capture a half-rebuilt cache in the artefact (some tables dropped, some re-created,
1648
+ // none re-streamed yet). The slot makes the drop+rebuild atomic against any concurrent export.
1649
+ lifecycleSlot.run("dropReadCache", async () => {
1650
+ await pglite.exec(buildDropReadCacheSql(options.registry));
1651
+ await pglite.exec(generateLocalSchemaSql(options.registry));
1652
+ // Reset the Electric subscriptions so the rebuilt synced tables re-stream from scratch
1653
+ // rather than the bookkeeping believing they are already caught up (ADR-0006).
1654
+ await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
1655
+ }),
1182
1656
  flush: (table) => mutationRuntime.flush(table),
1183
1657
  reconcile: (table) => mutationRuntime.reconcile(table),
1184
1658
  retryFailed: (table) => mutationRuntime.retryFailed(table),
@@ -1207,6 +1681,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1207
1681
  ensureSynced,
1208
1682
  isSynced,
1209
1683
  desync,
1684
+ discardEphemeral,
1210
1685
  prepareQuery,
1211
1686
  transaction,
1212
1687
  groupReady: async (table) => {
@@ -1221,8 +1696,12 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1221
1696
  // hooks made inline before the seam existed (`pglite.live.query` → `initialResults.rows` + `subscribe`),
1222
1697
  // so the in-process path is unchanged. `pkColumns` is unused here: PGlite's live query already diffs
1223
1698
  // incrementally against its own materialized state; the column set only matters for the worker bridge.
1224
- subscribeLiveRows: async ({ sql, params }, onRows) => {
1225
- const registered = await pglite.live.query<Record<string, unknown>>(sql, params as unknown[]);
1699
+ subscribeLiveRows: async ({ sql, params, fields }, onRows) => {
1700
+ // Render the query safe to materialise: a JOIN with same-named columns fails `live.query`'s
1701
+ // temp-view creation (`column "title" specified more than once`) unless every output column has a
1702
+ // unique alias. No `fields` → SQL unchanged (backward-compatible name-keyed rows).
1703
+ const materialSql = wrapLiveQueryForMaterialization(sql, fields);
1704
+ const registered = await pglite.live.query<Record<string, unknown>>(materialSql, params as unknown[]);
1226
1705
  const listener = (results: { rows: Record<string, unknown>[] }) => {
1227
1706
  onRows(results.rows as never);
1228
1707
  };
@@ -1234,6 +1713,68 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1234
1713
  },
1235
1714
  };
1236
1715
  },
1716
+ // Boot observability (ADR-0034): the finalized report (null before initial sync completes / after an
1717
+ // early stop). Resolves from the builder-owned ref this client holds — no round trip in-process.
1718
+ bootReport: async () => finalizedBootReport,
1719
+ exportStore: async (exportOptions) => {
1720
+ // Await engine-ready first (ADR-0035: exports wait out a boot rather than rejecting during it), THEN
1721
+ // take the lifecycle slot — a concurrent export/lifecycle op is refused with a typed busy error.
1722
+ await ready;
1723
+ // Name the backup from the configured plain store PATH (ADR-0036), never the PGlite instance's
1724
+ // resolved dataDir URL — a resolved URL is internal plumbing and must not leak into an artefact name
1725
+ // as something to imitate. The store id is the path's last segment (see `deriveStoreId`).
1726
+ return lifecycleSlot.run("exportStore", () =>
1727
+ performStoreExport(
1728
+ {
1729
+ pglite,
1730
+ readMutationStats: () => mutationRuntime.readMutationStats(),
1731
+ ...(options.storePath != null ? { storePath: options.storePath } : {}),
1732
+ },
1733
+ exportOptions,
1734
+ ),
1735
+ );
1736
+ },
1737
+ exportDiagnostics: async (exportOptions) => {
1738
+ // Same lifecycle discipline as `exportStore` (ADR-0035): await engine-ready first (wait out a boot
1739
+ // rather than reject during it), THEN take the single slot so a concurrent export/lifecycle op is
1740
+ // refused with a typed busy error. The diagnostic dump runs the live datadir dump on `pglite`, then
1741
+ // clones it in memory — the live engine every reference here holds is never closed (the addendum's
1742
+ // whole reason for the throwaway clone over the abandoned suspend/reopen seam).
1743
+ await ready;
1744
+ return lifecycleSlot.run("exportDiagnostics", () =>
1745
+ performDiagnosticExport(
1746
+ {
1747
+ pglite,
1748
+ readMutationStats: () => mutationRuntime.readMutationStats(),
1749
+ ...(options.storePath != null ? { storePath: options.storePath } : {}),
1750
+ },
1751
+ exportOptions,
1752
+ ),
1753
+ );
1754
+ },
1755
+ exportData: async (exportOptions) => {
1756
+ // Same lifecycle discipline (ADR-0035): await engine-ready first (wait out a boot rather than reject),
1757
+ // THEN take the single slot. The DRAIN runs inside the slot (the caller-side placement decision 3
1758
+ // makes): flush needs the running engine and is not lifecycle-exclusive, but the artefact must be
1759
+ // taken right after the drain, so export owns the store's lifecycle for the whole drain+dump. The
1760
+ // `-t` allowlist + enum header are resolved from the registry through the SAME projection the DDL
1761
+ // generator uses — never re-derived by string convention.
1762
+ await ready;
1763
+ return lifecycleSlot.run("exportData", () =>
1764
+ performDataExport(
1765
+ {
1766
+ pglite,
1767
+ readMutationStats: () => mutationRuntime.readMutationStats(),
1768
+ flush: () => mutationRuntime.flush(),
1769
+ syncedTableNames: collectDataExportSyncedTableNames(options.registry),
1770
+ enumHeaderSql: buildDataExportEnumHeaderSql(options.registry),
1771
+ cloneCleanupSql: buildDataExportCloneCleanupSql(options.registry),
1772
+ ...(options.storePath != null ? { storePath: options.storePath } : {}),
1773
+ },
1774
+ exportOptions,
1775
+ ),
1776
+ );
1777
+ },
1237
1778
  };
1238
1779
 
1239
1780
  return client;