@pgxsinkit/client 0.1.48 → 0.1.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/boot-report.d.ts +76 -0
  2. package/dist/boot-report.d.ts.map +1 -1
  3. package/dist/index.d.ts +84 -3
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1549 -333
  6. package/dist/index.js.map +15 -12
  7. package/dist/local-store.d.ts +58 -0
  8. package/dist/local-store.d.ts.map +1 -1
  9. package/dist/local-tables.d.ts +340 -0
  10. package/dist/local-tables.d.ts.map +1 -1
  11. package/dist/mutation.d.ts +36 -0
  12. package/dist/mutation.d.ts.map +1 -1
  13. package/dist/mutations-api.d.ts +82 -0
  14. package/dist/mutations-api.d.ts.map +1 -0
  15. package/dist/schema.d.ts +62 -0
  16. package/dist/schema.d.ts.map +1 -1
  17. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  18. package/dist/worker/define-sync-worker.d.ts +17 -0
  19. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  20. package/dist/worker/live-query-fingerprint.d.ts +14 -0
  21. package/dist/worker/live-query-fingerprint.d.ts.map +1 -0
  22. package/dist/worker/live-query-manager.d.ts +130 -0
  23. package/dist/worker/live-query-manager.d.ts.map +1 -0
  24. package/dist/worker/protocol.d.ts +53 -2
  25. package/dist/worker/protocol.d.ts.map +1 -1
  26. package/package.json +2 -2
  27. package/skills/core/SKILL.md +1 -1
  28. package/skills/operating/SKILL.md +29 -1
  29. package/src/boot-report.ts +108 -0
  30. package/src/index.ts +648 -152
  31. package/src/local-store.ts +150 -3
  32. package/src/local-tables.ts +49 -1
  33. package/src/mutation.ts +256 -15
  34. package/src/mutations-api.ts +310 -0
  35. package/src/schema.ts +406 -193
  36. package/src/worker/attach-sync-client.ts +193 -15
  37. package/src/worker/define-sync-worker.ts +267 -53
  38. package/src/worker/live-query-fingerprint.ts +128 -0
  39. package/src/worker/live-query-manager.ts +591 -0
  40. package/src/worker/protocol.ts +49 -1
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ import { defineRelations } from "drizzle-orm/relations";
7
7
  import type {
8
8
  MutationAck,
9
9
  MutationDiagnostics,
10
+ MutationSummary,
10
11
  RegistryRelations,
11
12
  RegistryTables,
12
13
  RegistryViews,
@@ -39,8 +40,10 @@ import {
39
40
  type LocalStoreVersionEvent,
40
41
  clearLazyGroupActivation,
41
42
  readActivatedLazyGroups,
43
+ readStoredLocalSchemaFingerprint,
42
44
  reconcileLocalStoreVersion,
43
45
  writeLazyGroupActivation,
46
+ writeStoredLocalSchemaFingerprint,
44
47
  } from "./local-store";
45
48
  import {
46
49
  createMutationRuntime,
@@ -49,13 +52,18 @@ import {
49
52
  type MutationKind,
50
53
  type WriteUnit,
51
54
  } from "./mutation";
55
+ import { createMutationsApi, type MutationsApi } from "./mutations-api";
52
56
  import {
53
57
  buildDataExportCloneCleanupSql,
54
58
  buildDataExportEnumHeaderSql,
55
59
  buildDesyncTableSql,
56
60
  buildDropReadCacheSql,
61
+ buildLocalMetaBootstrapSql,
57
62
  buildWipeLocalStoreSql,
58
63
  collectDataExportSyncedTableNames,
64
+ computeLocalSchemaFingerprint,
65
+ generateDurableLocalSchemaSql,
66
+ generateEphemeralLocalSchemaSql,
59
67
  generateLocalSchemaSql,
60
68
  } from "./schema";
61
69
  import { startConfiguredSync } from "./shape-sync";
@@ -71,6 +79,13 @@ import {
71
79
  } from "./store-path";
72
80
  import { createSyncEngine, type SyncEngine } from "./sync";
73
81
  import { buildShapeHeaders } from "./sync-auth";
82
+ import { LiveRowsMaterializer } from "./worker/live-diff";
83
+ import {
84
+ createLiveQueryManager,
85
+ type LiveQueryDiagnostics,
86
+ type LiveQueryManager,
87
+ validateLiveQueryPolicy,
88
+ } from "./worker/live-query-manager";
74
89
 
75
90
  export { generateLocalSchemaSql };
76
91
  export { wrapLiveQueryForMaterialization } from "./live-rows-sql";
@@ -140,6 +155,7 @@ export {
140
155
  rowKey,
141
156
  seedLiveDiffState,
142
157
  } from "./worker/live-diff";
158
+ export type { LiveQueryDiagnostics };
143
159
  export { createWorkerTokenCache, type WorkerTokenCache } from "./worker/token-cache";
144
160
  export {
145
161
  type AttachAckPayload,
@@ -179,6 +195,8 @@ export {
179
195
  LazyRelationNotActivatedError,
180
196
  } from "./lazy-guard";
181
197
  export {
198
+ type AllMutationsView,
199
+ getAllMutationsView,
182
200
  getJournalTable,
183
201
  getLocalMetaTable,
184
202
  getOverlayTable,
@@ -191,8 +209,47 @@ export {
191
209
  type ReadModelView,
192
210
  type SyncStateView,
193
211
  } from "./local-tables";
212
+ export {
213
+ createMutationsApi,
214
+ type MutationListOptions,
215
+ type MutationListSubscription,
216
+ type MutationsApi,
217
+ type MutationsApiDeps,
218
+ type MutationSummaryDetail,
219
+ type MutationSummarySubscription,
220
+ } from "./mutations-api";
194
221
  export type { LocalStoreVersionEvent };
195
222
 
223
+ /**
224
+ * A write-path method was invoked against a client whose `writeReady` stage has not resolved and the caller
225
+ * opted out of awaiting it (ADR-0041). pgxsinkit's own write methods always `await writeReady` internally, so
226
+ * this is NEVER thrown on the stage-1 default path. It is **reserved for the stage-2 opt-out surface** — the
227
+ * ADR's typed pre-`writeReady` rejection for a consumer who chooses not to await — so a pre-`writeReady` write
228
+ * fails loudly rather than silently no-oping. Exported now so that surface is a non-breaking addition later.
229
+ */
230
+ export class WriteNotReadyError extends Error {
231
+ constructor() {
232
+ super(
233
+ "pgxsinkit: write attempted before `writeReady` resolved. Await `client.writeReady` (the default write " +
234
+ "methods do this for you) before enqueuing, or gate the write on it.",
235
+ );
236
+ this.name = "WriteNotReadyError";
237
+ }
238
+ }
239
+
240
+ /**
241
+ * The client was stopped/destroyed (or its worker attachment detached) before a boot stage it exposed could
242
+ * resolve (ADR-0041 FIX 2). `stop()`/`destroy()` reject the still-pending `writeReady` and `ready` with this so
243
+ * a parked mutation or an `await client.ready` / `client.start()` fails FAST rather than hanging forever after
244
+ * teardown. `bootSettled` still RESOLVES (it means "teardown completion", not "boot succeeded").
245
+ */
246
+ export class ClientDisposedError extends Error {
247
+ constructor() {
248
+ super("pgxsinkit: the client was stopped/destroyed before this readiness stage resolved.");
249
+ this.name = "ClientDisposedError";
250
+ }
251
+ }
252
+
196
253
  // The store carries PGlite's own `live` extension (a genuine create-time extension) plus the pgxsinkit
197
254
  // sync engine's namespace, attached post-create by `createSyncClient` as the `electric` property (ADR-0032
198
255
  // S1) — no longer a create-time extension. The `electric` part is derived from `createSyncEngine`'s real
@@ -490,6 +547,18 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
490
547
  * adoption path (ignored on a fallback create). `provisionReadyAt` must share this process's monotonic clock.
491
548
  */
492
549
  provisionStamp?: Promise<{ initdbMs: number; provisionReadyAt: number }>;
550
+ /**
551
+ * Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4) — same block as
552
+ * {@link DefineSyncWorkerOptions.liveQueries}. Takes effect in BOTH client forms: the in-process client
553
+ * now owns its own manager (decision 6), so this policy governs its live-query dedup and retention just as
554
+ * it does the worker's. Defaults: `defaultKeepAliveMs` 0 (tear a query down the instant its last consumer
555
+ * leaves), `maxRetainedQueries` 16, `maxRetainedRows` 50_000.
556
+ */
557
+ liveQueries?: {
558
+ defaultKeepAliveMs?: number;
559
+ maxRetainedQueries?: number;
560
+ maxRetainedRows?: number;
561
+ };
493
562
  }
494
563
 
495
564
  export interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {
@@ -615,6 +684,13 @@ export interface SubscribeLiveRowsInput {
615
684
  * worker bridge). Ignored by the in-process client, whose `prepareQuery` already ran on the tab.
616
685
  */
617
686
  use?: readonly string[];
687
+ /**
688
+ * Per-subscription keep-alive hint (ms) for the live-query manager (ADR-0040 decision 4): retain this
689
+ * query's shared registration for the grace period after its last consumer leaves, so a re-mount reuses it
690
+ * verbatim (no re-materialization). Honoured in BOTH modes — the worker manager and the in-process manager
691
+ * (decision 6). Bounded by the `liveQueries` policy budgets. Absent → no hint.
692
+ */
693
+ keepAliveMs?: number;
618
694
  }
619
695
 
620
696
  /** A handle to a live-rows subscription: the initial ordered snapshot plus an idempotent unsubscribe. */
@@ -662,6 +738,30 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
662
738
  tables: {
663
739
  [TKey in SyncTableName<TRegistry>]: SyncClientTableHandle<TRegistry, TKey>;
664
740
  };
741
+ /**
742
+ * Local-read readiness (ADR-0041): resolves once PGlite is open, the durable schema is compatible
743
+ * (fingerprint fast path or completed evolution), store-version reconcile has run, and the drizzle read
744
+ * facade is built — so cached rows are queryable. Resolving this stage requires NO write runtime, NO sync
745
+ * start, and NO network I/O, so an offline boot resolves it promptly. Under the ADR-0041 Option B contract
746
+ * `createSyncClient()` (and, in stage 2, `attachSyncClient()`) resolves at exactly this stage; the write and
747
+ * sync tail continues in the background. Monotonic and idempotent.
748
+ */
749
+ localReadReady: Promise<void>;
750
+ /**
751
+ * Write readiness (ADR-0041): resolves once the mutation runtime is constructed and boot recovery has
752
+ * completed (plus restore quarantine on a restore boot) — enqueue is safe. Every write-path method awaits
753
+ * this internally, so a write issued the instant `localReadReady` resolves completes once `writeReady`
754
+ * lands rather than failing opaquely. Resolves with NO network I/O. Monotonic and idempotent.
755
+ */
756
+ writeReady: Promise<void>;
757
+ /**
758
+ * @internal Boot-settled signal (ADR-0041): resolves at today's full in-process resolution point — the
759
+ * write runtime, boot recovery, and sync START have all run (initial catch-up is NOT awaited; that is
760
+ * `ready`). The worker bridge awaits this before `attach-ack` so worker-mode external timing is unchanged
761
+ * in stage 1; stage 2 replaces it with per-stage milestone messages. Not part of the supported public
762
+ * surface — a diagnostics/bridge hook only.
763
+ */
764
+ bootSettled: Promise<void>;
665
765
  ready: Promise<void>;
666
766
  status: SyncRuntimeStatus;
667
767
  start: () => Promise<void>;
@@ -724,6 +824,14 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
724
824
  entityKey: Record<string, string>,
725
825
  ) => Promise<void>;
726
826
  diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{ mutation: MutationDiagnostics }>;
827
+ /**
828
+ * The registry-wide reactive mutation-status surface (proposal §5): a global per-status summary and a
829
+ * filtered normalized detail list over EVERY writable journal, each available one-shot or as a live
830
+ * subscription. Identical on the in-process and worker-attached client. Render a global sync indicator with
831
+ * ONE `subscribeSummary` instead of one journal live query per writable table; consumers never touch the
832
+ * generated journal relation names. See {@link MutationsApi}.
833
+ */
834
+ mutations: MutationsApi<TRegistry>;
727
835
  /**
728
836
  * The INSPECTION read surface (debug pages, REPLs, ad-hoc counts) — identical on the in-process and
729
837
  * worker-attached client (on the latter the statement runs in the worker). The statement runs raw
@@ -866,6 +974,13 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
866
974
  * stored report. The push counterpart is the `onBootReport` client option.
867
975
  */
868
976
  bootReport: () => Promise<BootReport | null>;
977
+ /**
978
+ * Live-query diagnostics (ADR-0040 decision 5): a point-in-time snapshot of the live-query manager's
979
+ * entries — opaque fingerprint digests plus counts/timings only, NEVER SQL, params, or row values. Both
980
+ * client forms return the real snapshot: in WORKER mode this pulls the worker manager's snapshot over the
981
+ * bridge; the IN-PROCESS client returns its own manager's snapshot directly.
982
+ */
983
+ liveQueryDiagnostics: () => Promise<LiveQueryDiagnostics[]>;
869
984
  /**
870
985
  * Take a **store backup** (ADR-0035): a full-fidelity, PGlite-restorable tarball of the whole local
871
986
  * store — synced cache, Overlay, and Mutation journal (unflushed writes included) — via PGlite's
@@ -914,7 +1029,7 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
914
1029
  exportData: (options?: DataExportOptions) => Promise<DataExportResult>;
915
1030
  }
916
1031
 
917
- export type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind };
1032
+ export type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind, MutationSummary };
918
1033
 
919
1034
  /**
920
1035
  * The structured-clone-safe subset of PGlite's `QueryOptions` the inspection surface carries. Kept
@@ -953,14 +1068,46 @@ export function replAdapter(
953
1068
  export async function createSyncClient<const TRegistry extends SyncTableRegistry>(
954
1069
  options: CreateSyncClientOptions<TRegistry>,
955
1070
  ): Promise<SyncClient<TRegistry>> {
1071
+ // Fail fast on a bad keep-alive policy — before any PGlite boot work (ADR-0040 decision 4 — bounded).
1072
+ validateLiveQueryPolicy(options.liveQueries);
956
1073
  const status: SyncRuntimeStatus = {
957
1074
  phase: "booting",
958
1075
  isRunning: false,
959
1076
  };
960
1077
 
961
1078
  let resolveReady!: () => void;
962
- const ready = new Promise<void>((resolve) => {
1079
+ let rejectReady!: (error: unknown) => void;
1080
+ const ready = new Promise<void>((resolve, reject) => {
963
1081
  resolveReady = resolve;
1082
+ rejectReady = reject;
1083
+ });
1084
+
1085
+ // Staged boot readiness (ADR-0041). Three monotonic, idempotent stages resolved as the boot crosses them:
1086
+ // - `localReadReady`: local-read core done (schema compatible + reconcile + drizzle facade) — zero network.
1087
+ // - `writeReady`: mutation runtime + boot recovery (+ restore quarantine) done — enqueue is safe.
1088
+ // - `bootSettled`: today's full resolution point (sync START done). The worker bridge awaits it (stage 1).
1089
+ // Under the Option B contract this function RESOLVES at `localReadReady` and runs the write/sync tail in the
1090
+ // background, so a returning offline consumer gets a readable client without waiting on the network. Each
1091
+ // stage's rejection is guarded (below) so an unconsumed stage never surfaces as an unhandled rejection —
1092
+ // real awaiters still observe the failure.
1093
+ // `localReadReady` has no reject binding: a local-read-core failure throws straight out of this async
1094
+ // function (so the returned promise rejects, exactly as a pre-ADR-0041 boot failure did) before the client
1095
+ // is handed out, leaving `localReadReady` pending on a store nobody holds — no awaiter, no leak.
1096
+ let resolveLocalReadReady!: () => void;
1097
+ const localReadReady = new Promise<void>((resolve) => {
1098
+ resolveLocalReadReady = resolve;
1099
+ });
1100
+ let resolveWriteReady!: () => void;
1101
+ let rejectWriteReady!: (error: unknown) => void;
1102
+ const writeReady = new Promise<void>((resolve, reject) => {
1103
+ resolveWriteReady = resolve;
1104
+ rejectWriteReady = reject;
1105
+ });
1106
+ let resolveBootSettled!: () => void;
1107
+ let rejectBootSettled!: (error: unknown) => void;
1108
+ const bootSettled = new Promise<void>((resolve, reject) => {
1109
+ resolveBootSettled = resolve;
1110
+ rejectBootSettled = reject;
964
1111
  });
965
1112
 
966
1113
  if (options.pgliteInstance && options.precreatedPglite) {
@@ -992,12 +1139,17 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
992
1139
  const syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);
993
1140
  // ADR-0032 S4 overlap flag, computed once up front so the boot report and the prefetch gate agree.
994
1141
  const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
1142
+ // How the store presents at boot (ADR-0034 `storeKind`): a restore boot seeds a brand-new store from a
1143
+ // backup; otherwise the caller's fresh-store hint (the same signal as `freshStore`) marks a fresh spare;
1144
+ // everything else is a warm (existing persisted) store. Restore wins — a restore boot is never "fresh".
1145
+ const storeKind: BootReport["storeKind"] = restoreBoot ? "restored" : options.freshStore === true ? "fresh" : "warm";
995
1146
 
996
1147
  // Boot observability (ADR-0034): build a structured report across the boot, finalized once at initial
997
1148
  // sync. Created FIRST so its monotonic anchor precedes every timed phase (including the PGlite create).
998
1149
  const bootReportBuilder: BootReportBuilder = createBootReportBuilder({
999
1150
  mode: options.bootMode ?? "in-process",
1000
1151
  freshStore: options.freshStore === true,
1152
+ storeKind,
1001
1153
  overlapPrefetch,
1002
1154
  registryFingerprint: fingerprintRegistry(options.registry),
1003
1155
  });
@@ -1260,8 +1412,35 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1260
1412
  await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
1261
1413
  }
1262
1414
 
1263
- const schemaSql = generateLocalSchemaSql(options.registry);
1264
- await bootReportBuilder.phase("schemaExec", "boot local schema", () => pglite.exec(schemaSql));
1415
+ // Durable-schema fingerprint fast path (slice 3 / proposal §3). The whole block stays inside the
1416
+ // `schemaExec` phase so `schemaExecMs` remains comparable across the fast (skip) and full (replay) paths.
1417
+ await bootReportBuilder.phase("schemaExec", "boot local schema", async () => {
1418
+ // (2) The minimal bootstrap first — one small crossing so the `local_schema_fingerprint` read/write
1419
+ // below has its `pgxsinkit_local_meta` table before the durable replay is decided.
1420
+ await pglite.exec(buildLocalMetaBootstrapSql(options.registry));
1421
+
1422
+ // (3) Generate the durable SQL (JS-only) and hash it; compare with the stored fingerprint.
1423
+ const currentFingerprint = computeLocalSchemaFingerprint(options.registry);
1424
+ const storedFingerprint = await readStoredLocalSchemaFingerprint(pglite, options.registry);
1425
+
1426
+ if (storedFingerprint === currentFingerprint) {
1427
+ // (4a) Match → SKIP the durable replay entirely; the persisted durable schema is already current.
1428
+ bootReportBuilder.setSchemaFastPath({ skipped: true, fingerprintMatch: true });
1429
+ } else {
1430
+ // (4b) Absent/mismatch → replay the durable schema, then stamp the fingerprint AFTER success only
1431
+ // (exec and stamp travel together — a throw here leaves the old/absent fingerprint for a retry).
1432
+ await pglite.exec(generateDurableLocalSchemaSql(options.registry));
1433
+ await writeStoredLocalSchemaFingerprint(pglite, options.registry, currentFingerprint);
1434
+ bootReportBuilder.setSchemaFastPath({ skipped: false, fingerprintMatch: false });
1435
+ }
1436
+
1437
+ // (5) ALWAYS apply the ephemeral schema (TEMP relations die with the old engine), skipping the
1438
+ // crossing when the registry declares no ephemeral entry (the generator returns "").
1439
+ const ephemeralSql = generateEphemeralLocalSchemaSql(options.registry);
1440
+ if (ephemeralSql.length > 0) {
1441
+ await pglite.exec(ephemeralSql);
1442
+ }
1443
+ });
1265
1444
 
1266
1445
  if (options.prepareLocalDb) {
1267
1446
  const prepareLocalDb = options.prepareLocalDb;
@@ -1286,6 +1465,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1286
1465
  db: pglite,
1287
1466
  registry: options.registry,
1288
1467
  writeUrl: options.writeUrl,
1468
+ // pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` marker table) unless the caller
1469
+ // supplied their own PGlite — then the marker is never touched and recovery falls back to legacy always-recover.
1470
+ ownsMetaTable: !options.pgliteInstance,
1289
1471
  onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
1290
1472
  ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
1291
1473
  ...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),
@@ -1295,32 +1477,32 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1295
1477
  ...(options.onReject ? { onReject: options.onReject } : {}),
1296
1478
  });
1297
1479
 
1298
- // Reclaim any in-flight mutations interrupted by a previous shutdown (ADR-0005), then
1299
- // reconcile the local store against the current registry fingerprint before sync starts
1300
- // (ADR-0006). Skipped when the caller supplies their own pglite (they own its schema).
1301
- await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () => mutationRuntime.recoverSending());
1302
-
1303
- // Restore-boot quarantine (ADR-0035 decision 6): the moment a store is booted FROM a backup, every
1304
- // non-terminal recovered journal row (`pending`/`sending`/`failed`) is parked in `quarantined` so nothing
1305
- // recovered auto-flushes — the write path has no `mutationId` dedupe ledger, making replay unsafe on
1306
- // last-write-wins tables (silent stale reverts) and colliding on a recreated PK. Runs ONLY on the restore
1307
- // boot (loadDataDir happens exactly once); a subsequent normal boot of the persisted store never re-runs
1308
- // it. Placed AFTER `recoverSending` (which lifts any `sending` back to `pending`) so a single pass over
1309
- // pending/sending/failed catches the lot. The app then inspects `diagnostics()` and releases/discards them.
1310
- if (restoreBoot) {
1311
- await mutationRuntime.quarantineRecovered();
1312
- }
1480
+ // Activation buffer (ADR-0041): a read (`ensureSynced`) OR a write (`onOrdinaryEnqueue`) can reference a
1481
+ // lazy group after `localReadReady` but BEFORE `sync` is wired (the Option B window). With a null `sync` the
1482
+ // seams cannot start a group, so BOTH feed this one buffer; the tail replays it once sync is wired, so the
1483
+ // activation is never LOST across the staged split (ADR-0039 semantics preserved). Null once replayed (or on
1484
+ // a tail failure — see the tail's rejection handler).
1485
+ let pendingActivations: Set<string> | null = new Set();
1313
1486
 
1314
1487
  let versionEvent: LocalStoreVersionEvent | null = null;
1315
1488
 
1316
- // Registry-fingerprint mismatch on restore (ADR-0035 decision 6): an old backup restored against a NEWER
1317
- // registry needs NO special handling — the existing local-schema-evolution path (ADR-0006) owns it, and
1318
- // restore composes with it for free. On this restore boot the quarantine above ran FIRST, so every
1319
- // recovered row now counts toward `owedMutations` (pending+sending+failed+quarantined) inside
1320
- // `rebuildReadCacheOrDefer`: a stale fingerprint therefore DEFERS the read-cache rebuild rather than
1321
- // dropping the quarantined writes, exactly as it would for any store that owes work. The rebuild completes
1322
- // on a later boot once the app has released/discarded the quarantine and drained the journal.
1323
- if (!options.pgliteInstance) {
1489
+ // Boot recovery (ADR-0005) driven by the durable recovery marker (slice 2), PLUS the restore quarantine
1490
+ // (ADR-0035 decision 6, gated on `restoreBoot` inside `runBootRecovery`). Hoisted so the restore path runs
1491
+ // it BEFORE read exposure (the ADR-0041 invariant) and the normal path defers it to the background write
1492
+ // tail. `runBootRecovery` owns the full decision — marker read, skip/legacy/transactional-recover, restore
1493
+ // quarantine, marker clear — and returns the honest `warmBoot` outcome (ADR-0034).
1494
+ const runBootRecoveryStage = async (): Promise<void> => {
1495
+ const recoveryOutcome = await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () =>
1496
+ mutationRuntime.runBootRecovery({ ownsMetaTable: !options.pgliteInstance, restore: restoreBoot }),
1497
+ );
1498
+ bootReportBuilder.setJournalRecovery(recoveryOutcome);
1499
+ };
1500
+
1501
+ // Store-version reconcile against the current registry fingerprint (ADR-0006). It reads the runtime's
1502
+ // journal stats to decide rebuild-vs-defer and `runtime.registryVersion` (static), so it needs only the
1503
+ // CONSTRUCTED runtime — not a completed recovery pass.
1504
+ const runReconcileStage = async (): Promise<void> => {
1505
+ if (options.pgliteInstance) return;
1324
1506
  versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () =>
1325
1507
  reconcileLocalStoreVersion({
1326
1508
  db: pglite,
@@ -1329,6 +1511,23 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1329
1511
  ...(options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}),
1330
1512
  }),
1331
1513
  );
1514
+ };
1515
+
1516
+ if (restoreBoot) {
1517
+ // Restore invariant (ADR-0041): the quarantine of every recovered write MUST complete before any read
1518
+ // facade is exposed, so recovery + quarantine run FIRST, then reconcile. Because the quarantine ran first,
1519
+ // every recovered row counts toward `owedMutations` (pending+sending+failed+quarantined) inside
1520
+ // `rebuildReadCacheOrDefer`, so a stale-fingerprint restore DEFERS the read-cache rebuild rather than
1521
+ // dropping the quarantined writes — unchanged from the pre-ADR-0041 recover→quarantine→reconcile order.
1522
+ // `localReadReady` and `writeReady` therefore coincide on a restore boot (both resolved after this point).
1523
+ await runBootRecoveryStage();
1524
+ await runReconcileStage();
1525
+ } else {
1526
+ // Normal boot (ADR-0041): reconcile is part of the local-read core and runs BEFORE recovery (which moves
1527
+ // to the write tail). The owed count already includes `sending`, so an UNRECOVERED crash journal defers a
1528
+ // rebuild exactly as a recovered one would (recovery only lifts `sending → pending`, both counted) — the
1529
+ // deferral outcome is byte-identical to the pre-ADR-0041 recover-then-reconcile order.
1530
+ await runReconcileStage();
1332
1531
  }
1333
1532
 
1334
1533
  const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));
@@ -1338,57 +1537,143 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1338
1537
  let sync: Awaited<ReturnType<typeof startConfiguredSync>> | null = null;
1339
1538
  let convergenceDriver: ConvergenceDriver | null = null;
1340
1539
 
1341
- status.isRunning = true;
1342
-
1343
- // Open the overlap commit gate now the local store is ready (schema exec + journal recovery + reconcile
1344
- // done): the catch-up the streams prefetched during those phases now drains in one commit train. A no-op
1345
- // on the sequential path (`openDbGate` is the empty default there).
1346
- openDbGate();
1347
-
1348
- if (syncEnabled) {
1349
- if (earlySync) {
1350
- // Overlap path: the shape streams have been prefetching since before schema exec; adopt the handle
1351
- // (it resolves as soon as the streams are subscribed — catch-up drains via the gate just lifted, and
1352
- // `onInitialSync` still gates `ready` on a fully-consistent first paint). The construction was kicked
1353
- // off before schema exec, so time it here (concurrent-segment wall) into `phases.syncStartMs`.
1354
- sync = await earlySync;
1355
- bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);
1356
- bootReportBuilder.markSyncStartDone();
1540
+ // Lifecycle guard (ADR-0041): `stop()`/`destroy()` can now be called while the background write/sync tail is
1541
+ // still in flight (React StrictMode mount/unmount is the canonical case). `disposed` lets the tail bail at
1542
+ // each stage boundary — before setting `isRunning`, before starting sync — so no shape stream starts after a
1543
+ // stop; and `stop`/`destroy` await `bootSettled` before teardown so the tail can never exec against a
1544
+ // closing PGlite.
1545
+ let disposed = false;
1546
+ // Resolves the moment `sync` is wired (and the activation buffer replayed); rejects if the boot is disposed
1547
+ // or the tail fails before wiring — so a read seam awaiting it in the pre-wire window unblocks rather than
1548
+ // hanging. On a sync-DISABLED boot it resolves at tail end (reads short-circuit before awaiting it anyway).
1549
+ let resolveSyncWired!: () => void;
1550
+ let rejectSyncWired!: (error: unknown) => void;
1551
+ const syncWired = new Promise<void>((resolve, reject) => {
1552
+ resolveSyncWired = resolve;
1553
+ rejectSyncWired = reject;
1554
+ });
1555
+ void syncWired.catch(() => undefined);
1556
+ // True once `sync` is genuinely wired — the read seams use this (not just `sync != null`) plus `syncEnabled`
1557
+ // to tell "sync disabled" (trivially ready) apart from "sync pending" (not yet ready / hydrating).
1558
+ const isSyncPending = (): boolean => syncEnabled && sync == null && !disposed;
1559
+
1560
+ // Quiesce the background write/sync tail before a teardown (ADR-0041 BLOCKER 2). `stop()`/`destroy()` can be
1561
+ // called while the tail is still in flight (React StrictMode mount/unmount). Flag disposal so the tail bails
1562
+ // at its next stage boundary (never starting sync after this), gracefully release any read seam parked on
1563
+ // `syncWired` (it then falls through to the local-only path), then AWAIT `bootSettled` — swallowing a tail
1564
+ // failure — so the tail has fully SETTLED before teardown touches the engine/PGlite. Any sync the tail did
1565
+ // manage to start is assigned to `sync` by the time this resolves, for the caller's `sync?.unsubscribe()`.
1566
+ const quiesceTailForTeardown = async (): Promise<void> => {
1567
+ disposed = true;
1568
+ // FIX 2: a stopped client can never reach `writeReady` / `ready`, so reject them (idempotent — a race with
1569
+ // the tail's own resolve is settled first-wins; a normal stop AFTER boot is a no-op on the already-resolved
1570
+ // promises) so a parked mutation or an `await ready` / `start()` fails FAST rather than hanging past
1571
+ // teardown. `bootSettled` still RESOLVES below as teardown completion. Both are guarded by the
1572
+ // `.catch(() => undefined)` at construction, so an unconsumed rejection never leaks.
1573
+ const disposedError = new ClientDisposedError();
1574
+ rejectWriteReady(disposedError);
1575
+ rejectReady(disposedError);
1576
+ resolveSyncWired();
1577
+ await bootSettled.catch(() => undefined);
1578
+ };
1579
+
1580
+ // The write/sync activation tail (ADR-0041 decision 3). On a NORMAL boot this runs in the BACKGROUND after
1581
+ // `localReadReady` resolves, so `createSyncClient` resolves at `localReadReady` (the Option B contract). On a
1582
+ // restore boot recovery already ran in the core, so the tail only opens the (unused) gate and settles. It
1583
+ // resolves `bootSettled` — today's full resolution point (sync START done; initial catch-up is NOT awaited,
1584
+ // that is `ready`), which the worker bridge awaits so worker-mode external timing is unchanged in stage 1.
1585
+ const runWriteAndSyncTail = async (): Promise<void> => {
1586
+ // Bail if the client was stopped before the tail even started (StrictMode mount/unmount): no write runtime
1587
+ // activation, no sync start. `bootSettled` still resolves (this returns), unblocking `stop()`'s await.
1588
+ if (disposed) return;
1589
+ // Normal boot: recovery runs here (restore already ran it in the core, before read exposure).
1590
+ if (!restoreBoot) {
1591
+ await runBootRecoveryStage();
1592
+ }
1593
+ if (disposed) return;
1594
+ // Write runtime + boot recovery complete — enqueue is safe. Stamp + resolve `writeReady` (idempotent: on a
1595
+ // restore boot it already resolved in the core alongside `localReadReady`).
1596
+ bootReportBuilder.setWriteReadyMs(performance.now() - bootReportBuilder.bootStartPerf);
1597
+ resolveWriteReady();
1598
+
1599
+ // Do NOT set `isRunning` / start sync after a stop (BLOCKER 2): bail here so no shape stream is ever
1600
+ // started once teardown has begun.
1601
+ if (disposed) return;
1602
+ status.isRunning = true;
1603
+
1604
+ // Open the overlap commit gate now the local store is ready (schema exec + journal recovery + reconcile
1605
+ // done): the catch-up the streams prefetched during those phases now drains in one commit train. A no-op
1606
+ // on the sequential path (`openDbGate` is the empty default there).
1607
+ openDbGate();
1608
+
1609
+ if (syncEnabled) {
1610
+ if (earlySync) {
1611
+ // Overlap path: the shape streams have been prefetching since before schema exec; adopt the handle
1612
+ // (it resolves as soon as the streams are subscribed — catch-up drains via the gate just lifted, and
1613
+ // `onInitialSync` still gates `ready` on a fully-consistent first paint). The construction was kicked
1614
+ // off before schema exec, so time it here (concurrent-segment wall) into `phases.syncStartMs`.
1615
+ sync = await earlySync;
1616
+ bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);
1617
+ bootReportBuilder.markSyncStartDone();
1618
+ } else {
1619
+ // Sequential path (warm store / no fresh hint): the exact pre-S4 ordering — reset any rebuilt
1620
+ // subscriptions, promote durable lazy groups, then start (catch-up strictly after the local phases).
1621
+ // After a read-cache rebuild the Electric subscription bookkeeping is stale (it would believe the
1622
+ // dropped shapes are still caught up and never backfill), so reset every shape subscription to force a
1623
+ // fresh re-stream (ADR-0006).
1624
+ const resetKeys =
1625
+ versionEvent?.status === "rebuilt"
1626
+ ? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]
1627
+ : options.resetSubscriptionKeys;
1628
+ await resetSubscriptionsIfRequested(pglite, resetKeys);
1629
+ // Re-check after the awaited reset: a stop during it must still abort BEFORE the network shape streams
1630
+ // start (BLOCKER 2 — cannot start sync after stop).
1631
+ if (disposed) return;
1632
+
1633
+ status.phase = "syncing";
1634
+ options.onStatusChange?.(status);
1635
+
1636
+ // Promote any `lazy + persistent` group activated on a previous boot back into the eager set
1637
+ // (ADR-0021 §2); the sync engine does no DB read of its own.
1638
+ const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);
1639
+ if (disposed) return;
1640
+
1641
+ sync = await bootReportBuilder.phase("syncStart", "boot sync start", () =>
1642
+ startConfiguredSync(
1643
+ pglite as unknown as Parameters<typeof startConfiguredSync>[0],
1644
+ buildStartOptions(promotedGroups),
1645
+ ),
1646
+ );
1647
+ bootReportBuilder.markSyncStartDone();
1648
+ }
1649
+ // If a stop landed DURING the sync-start await, unsubscribe the just-started streams here rather than
1650
+ // leaving them running (stop read `sync` as null before this assignment), then bail.
1651
+ if (disposed) {
1652
+ sync?.unsubscribe();
1653
+ sync = null;
1654
+ return;
1655
+ }
1357
1656
  } else {
1358
- // Sequential path (warm store / no fresh hint): the exact pre-S4 ordering — reset any rebuilt
1359
- // subscriptions, promote durable lazy groups, then start (catch-up strictly after the local phases).
1360
- // After a read-cache rebuild the Electric subscription bookkeeping is stale (it would believe the
1361
- // dropped shapes are still caught up and never backfill), so reset every shape subscription to force a
1362
- // fresh re-stream (ADR-0006).
1363
- const resetKeys =
1364
- versionEvent?.status === "rebuilt"
1365
- ? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]
1366
- : options.resetSubscriptionKeys;
1367
- await resetSubscriptionsIfRequested(pglite, resetKeys);
1368
-
1369
- status.phase = "syncing";
1657
+ status.phase = "ready";
1370
1658
  options.onStatusChange?.(status);
1659
+ // Sync disabled: there is no `onInitialSync` gate, but boot IS complete — finalize the report at the
1660
+ // same moment `ready` resolves (ADR-0034). Idempotent with the sync path's finalize.
1661
+ finalizeBootReport();
1662
+ resolveReady();
1663
+ }
1371
1664
 
1372
- // Promote any `lazy + persistent` group activated on a previous boot back into the eager set
1373
- // (ADR-0021 §2); the sync engine does no DB read of its own.
1374
- const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);
1375
-
1376
- sync = await bootReportBuilder.phase("syncStart", "boot sync start", () =>
1377
- startConfiguredSync(
1378
- pglite as unknown as Parameters<typeof startConfiguredSync>[0],
1379
- buildStartOptions(promotedGroups),
1380
- ),
1381
- );
1382
- bootReportBuilder.markSyncStartDone();
1665
+ // ADR-0039/0041: replay every activation (read via `ensureSynced` AND write via `onOrdinaryEnqueue`)
1666
+ // buffered while `sync` was still null. Now `sync` is wired, re-issuing them through `ensureSynced` starts
1667
+ // the referenced groups — the activation is preserved, never lost across the split. Awaited so the groups
1668
+ // are STARTED before `syncWired` resolves (a `ensureSynced`/`prepareQuery` awaiter then sees them active).
1669
+ const buffered = pendingActivations;
1670
+ pendingActivations = null;
1671
+ if (sync != null && buffered && buffered.size > 0) {
1672
+ await ensureSynced([...buffered] as SyncTableName<TRegistry>[]);
1383
1673
  }
1384
- } else {
1385
- status.phase = "ready";
1386
- options.onStatusChange?.(status);
1387
- // Sync disabled: there is no `onInitialSync` gate, but boot IS complete — finalize the report at the
1388
- // same moment `ready` resolves (ADR-0034). Idempotent with the sync path's finalize.
1389
- finalizeBootReport();
1390
- resolveReady();
1391
- }
1674
+ // Sync is wired (or disabled and boot complete): unblock any read seam that parked on `syncWired`.
1675
+ resolveSyncWired();
1676
+ };
1392
1677
 
1393
1678
  // Restore boots offline (ADR-0035 decision 6): never stand up the convergence driver on a restore boot,
1394
1679
  // so an `autoSync` trigger the caller passed (even an online one) drives NO flush/reconcile passes — the
@@ -1404,9 +1689,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1404
1689
  ...(options.onConvergencePass ? { onPass: options.onConvergencePass } : {}),
1405
1690
  });
1406
1691
 
1407
- // Start driving convergence once the initial sync is ready, so a pass never races the
1408
- // first shape load. stop()/destroy() halt it.
1409
- void ready.then(() => convergenceDriver?.start());
1692
+ // Start driving convergence once the initial sync is ready, so a pass never races the first shape load.
1693
+ // stop()/destroy() halt it. `ready` is now rejectable (ADR-0041: the background tail rejects it on
1694
+ // failure), so the rejection handler keeps the driver un-started and off the unhandled-rejection path.
1695
+ void ready.then(
1696
+ () => convergenceDriver?.start(),
1697
+ () => undefined,
1698
+ );
1410
1699
  }
1411
1700
 
1412
1701
  // Event-driven convergence: the moment a mutation is enqueued, ask the driver to run a pass so the
@@ -1414,20 +1703,27 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1414
1703
  // lets the interval be a rare fallback (and so run far less often). No-op when `autoSync` is off — the
1415
1704
  // caller drives `flush`/`reconcile` itself.
1416
1705
  const requestConvergence = () => convergenceDriver?.requestPass();
1706
+ // Every write-path method gates on `writeReady` (ADR-0041): a write issued the instant `localReadReady`
1707
+ // resolves awaits the write runtime + boot recovery rather than racing an unfinished boot or failing
1708
+ // opaquely. `writeReady` is already resolved on the steady-state client, so this is a settled-promise await.
1417
1709
  const mutate: SyncClient<TRegistry>["mutate"] = {
1418
1710
  create: async (table, input) => {
1711
+ await writeReady;
1419
1712
  await mutationRuntime.create(table, input);
1420
1713
  requestConvergence();
1421
1714
  },
1422
1715
  update: async (table, entityKey, patch) => {
1716
+ await writeReady;
1423
1717
  await mutationRuntime.update(table, entityKey, patch);
1424
1718
  requestConvergence();
1425
1719
  },
1426
1720
  delete: async (table, entityKey) => {
1721
+ await writeReady;
1427
1722
  await mutationRuntime.delete(table, entityKey);
1428
1723
  requestConvergence();
1429
1724
  },
1430
1725
  batch: async (items) => {
1726
+ await writeReady;
1431
1727
  await mutationRuntime.batch(items);
1432
1728
  requestConvergence();
1433
1729
  },
@@ -1487,8 +1783,19 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1487
1783
 
1488
1784
  // ─── Lazy-relation activation + the declared-safe query facade (ADR-0021) ──────────────────────
1489
1785
  const ensureSynced: SyncClient<TRegistry>["ensureSynced"] = async (keys) => {
1786
+ if (keys.length === 0) return;
1787
+ // Sync PENDING (ADR-0041 Option B window): `sync` is not yet wired but the boot IS syncing. Record the
1788
+ // keys in the shared buffer AND await `syncWired` — the tail replays the buffer and STARTS the groups
1789
+ // before resolving `syncWired`, so on return the relations are genuinely active (the tripwire passes).
1790
+ // Distinct from sync DISABLED, which falls through to the trivially-active local-only path below.
1791
+ if (sync == null && isSyncPending()) {
1792
+ if (pendingActivations != null) for (const key of keys) pendingActivations.add(key);
1793
+ await syncWired;
1794
+ }
1490
1795
  const activeSync = sync;
1491
- if (activeSync == null || keys.length === 0) return;
1796
+ // Sync disabled → local-only (or the client was disposed before wiring): every relation is trivially
1797
+ // "synced" — reads hit whatever is local, so there is nothing to start.
1798
+ if (activeSync == null) return;
1492
1799
  const groupKeys = new Set<string>();
1493
1800
  for (const key of keys) {
1494
1801
  const groupKey = activeSync.groupKeyForTable(key);
@@ -1509,6 +1816,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1509
1816
  // network, and a failed start self-heals on the group's next activation (a `.catch` keeps the rejection
1510
1817
  // off the unhandled-rejection path).
1511
1818
  activateOrdinaryWriteTables = (tables) => {
1819
+ // ADR-0041: a write can land after `writeReady` but before `sync` is wired. Buffer the reported tables
1820
+ // (the tail replays them once sync is up) so the activation is never lost — this seam is fire-and-forget
1821
+ // (`onOrdinaryEnqueue` has a sync signature), so it cannot await `syncWired` the way `ensureSynced` does.
1822
+ if (sync == null) {
1823
+ if (pendingActivations != null) for (const table of tables) pendingActivations.add(table);
1824
+ return;
1825
+ }
1512
1826
  const lazyTables = tables.filter((table) => lazyGuardIndex.lazyKeys.has(table)) as SyncTableName<TRegistry>[];
1513
1827
  if (lazyTables.length === 0) return;
1514
1828
  void ensureSynced(lazyTables).catch((error) => {
@@ -1519,8 +1833,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1519
1833
  // Per-table catch-up completion (ADR-0032 decision 6) — the body of `client.groupReady`, hoisted so the
1520
1834
  // live-rows seam can also await it when building a subscription's `hydrated` promise.
1521
1835
  const groupReadyForTable = async (table: SyncTableName<TRegistry>): Promise<void> => {
1836
+ // Sync PENDING (ADR-0041): wait for sync to wire before its catch-up can even be evaluated, so a group
1837
+ // referenced in the pre-wire window retains its catch-up meaning rather than resolving instantly.
1838
+ if (sync == null && isSyncPending()) {
1839
+ await syncWired;
1840
+ }
1522
1841
  const activeSync = sync;
1523
- // Sync disabled → local-only: every relation is trivially "ready" (nothing to await).
1842
+ // Sync disabled → local-only (or disposed before wiring): every relation is trivially "ready".
1524
1843
  if (activeSync == null) return;
1525
1844
  const groupKey = activeSync.groupKeyForTable(table as string);
1526
1845
  if (groupKey == null) return;
@@ -1532,8 +1851,11 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1532
1851
  // referenced group is already ready at subscribe time, no `hydrated` promise is built (no extra refresh).
1533
1852
  const isGroupReadyForTable = (table: string): boolean => {
1534
1853
  const activeSync = sync;
1535
- // Sync disabled → local-only: reads hit whatever is local, so a group is trivially "ready".
1536
- if (activeSync == null) return true;
1854
+ if (activeSync == null) {
1855
+ // Sync PENDING (ADR-0041): not yet wired → the group is NOT ready (its catch-up has not run). Sync
1856
+ // DISABLED → local-only, trivially ready.
1857
+ return !isSyncPending();
1858
+ }
1537
1859
  const groupKey = activeSync.groupKeyForTable(table);
1538
1860
  // No consistency group (unknown/writeonly) → nothing to await; treat as ready.
1539
1861
  if (groupKey == null) return true;
@@ -1542,11 +1864,12 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1542
1864
 
1543
1865
  // The referenced synced tables whose consistency group is NOT YET caught up (ADR-0021/0032): scan the
1544
1866
  // compiled SQL for every synced relation the query reads (∪ the explicit `use`), then keep only those
1545
- // whose group is still catching up. Empty when sync is disabled OR every referenced group is already
1546
- // ready — the steady-state fast path, where the live-rows seam builds no `hydrated` promise. Eager and
1547
- // lazy groups are treated identically here; only ACTIVATION (elsewhere) stays lazy-only.
1867
+ // whose group is still catching up. Empty when sync is DISABLED or every referenced group is already ready
1868
+ // — the steady-state fast path, where the live-rows seam builds no `hydrated` promise. When sync is PENDING
1869
+ // (ADR-0041 window) every referenced synced group is not-yet-ready, so all are returned as hydrating.
1548
1870
  const hydratingTablesFor = (query: { sql: string; use?: readonly string[] }): string[] => {
1549
- if (sync == null) return [];
1871
+ // Sync disabled → nothing hydrates. Sync pending → every referenced synced group is hydrating (below).
1872
+ if (sync == null && !isSyncPending()) return [];
1550
1873
  const referenced = new Set<string>(query.use ?? []);
1551
1874
  for (const key of findReferencedSyncedKeysInSql(query.sql, lazyGuardIndex)) referenced.add(key);
1552
1875
  return [...referenced].filter((table) => !isGroupReadyForTable(table));
@@ -1554,8 +1877,11 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1554
1877
 
1555
1878
  const isSynced: SyncClient<TRegistry>["isSynced"] = (key) => {
1556
1879
  const activeSync = sync;
1557
- // Sync disabled → local-only: reads hit whatever is in the local store, so nothing is "dormant".
1558
- if (activeSync == null) return true;
1880
+ if (activeSync == null) {
1881
+ // Sync PENDING (ADR-0041): not yet wired → the relation is not started (dormant). Sync DISABLED →
1882
+ // local-only, so nothing is "dormant".
1883
+ return !isSyncPending();
1884
+ }
1559
1885
  return activeSync.isTableStarted(key);
1560
1886
  };
1561
1887
 
@@ -1617,6 +1943,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1617
1943
  };
1618
1944
 
1619
1945
  const desync: SyncClient<TRegistry>["desync"] = async (key) => {
1946
+ // ADR-0041 (SHOULD-FIX 5): a destructive group-teardown reads the journal and stops a group's stream, so
1947
+ // it must not race the background tail's recovery updates / subscription reset / sync start. Gate on
1948
+ // `bootSettled` — these are rare admin ops, so the stronger gate is correct (a tail failure rejects here).
1949
+ await bootSettled;
1620
1950
  const entry = options.registry[key];
1621
1951
  if (entry == null) throw new Error(`desync: unknown table ${String(key)}`);
1622
1952
  if (entry.subscription !== "lazy") {
@@ -1627,42 +1957,49 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1627
1957
  await tearDownLazyGroup(key, entry, "desync");
1628
1958
  };
1629
1959
 
1630
- const discardEphemeral: SyncClient<TRegistry>["discardEphemeral"] = (key) =>
1631
- // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4): discardEphemeral
1632
- // clean-truncates an ephemeral group's local cache, so an export must never interleave it (nor it an
1633
- // export) — the slot's typed LifecycleBusyError fires in both directions. The existing lazy/ephemeral
1634
- // gates below stay EXACTLY as they were, now inside the slot run. (`desync` is deliberately NOT slotted:
1635
- // only the ADR-0035-named destructive ops — destroy/discardEphemeral/dropReadCache — serialise here.)
1636
- lifecycleSlot.run("discardEphemeral", async () => {
1637
- const entry = options.registry[key];
1638
- if (entry == null) throw new Error(`discardEphemeral: unknown table ${String(key)}`);
1639
- // Keep the lazy gate desync has: eager+ephemeral is NOT forbidden by the type system (retention and
1640
- // subscription are independent scalars on the entry — see contracts config.ts / registry.ts), and an
1641
- // eager relation would immediately re-stream, so the same refusal applies here.
1642
- if (entry.subscription !== "lazy") {
1643
- throw new Error(
1644
- `discardEphemeral('${String(key)}') refused: only a lazy relation can be discarded — an eager relation is always-on and would immediately re-sync.`,
1645
- );
1646
- }
1647
- // STRICTER gate than desync: every member of the consistency group must be ephemeral. Retention is read
1648
- // as `entry.retention ?? "persistent"` (absent → persistent, matching validateRegistryLifecycleGroups and
1649
- // the schema generator); a read PROJECTION surfaces its declared retention on the same `retention` field
1650
- // (withRetention/asEphemeral/defineReadProjection all set it), so this one read covers tables and
1651
- // projections alike. Refuse (naming the offender) if any member is persistent — discardEphemeral is the
1652
- // multi-tab-safe primitive for per-delivery-session windows, and truncating a persistent member's cache
1653
- // would drop durable local data; use desync for a persistent lazy relation.
1654
- for (const member of groupTableKeysFor(key, entry)) {
1655
- if ((options.registry[member]!.retention ?? "persistent") !== "ephemeral") {
1960
+ const discardEphemeral: SyncClient<TRegistry>["discardEphemeral"] = async (key) => {
1961
+ // ADR-0041 (SHOULD-FIX 5): gate the destructive teardown on `bootSettled` so it never races the tail.
1962
+ await bootSettled;
1963
+ return (
1964
+ // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4): discardEphemeral
1965
+ // clean-truncates an ephemeral group's local cache, so an export must never interleave it (nor it an
1966
+ // export) — the slot's typed LifecycleBusyError fires in both directions. The existing lazy/ephemeral
1967
+ // gates below stay EXACTLY as they were, now inside the slot run. (`desync` is deliberately NOT slotted:
1968
+ // only the ADR-0035-named destructive ops — destroy/discardEphemeral/dropReadCache — serialise here.)
1969
+ lifecycleSlot.run("discardEphemeral", async () => {
1970
+ const entry = options.registry[key];
1971
+ if (entry == null) throw new Error(`discardEphemeral: unknown table ${String(key)}`);
1972
+ // Keep the lazy gate desync has: eager+ephemeral is NOT forbidden by the type system (retention and
1973
+ // subscription are independent scalars on the entry — see contracts config.ts / registry.ts), and an
1974
+ // eager relation would immediately re-stream, so the same refusal applies here.
1975
+ if (entry.subscription !== "lazy") {
1656
1976
  throw new Error(
1657
- `discardEphemeral('${String(key)}') refused: group member '${String(member)}' is persistent — ` +
1658
- `discardEphemeral only drops an ephemeral relation's local rows. Use desync for a persistent lazy relation.`,
1977
+ `discardEphemeral('${String(key)}') refused: only a lazy relation can be discarded — an eager relation is always-on and would immediately re-sync.`,
1659
1978
  );
1660
1979
  }
1661
- }
1662
- await tearDownLazyGroup(key, entry, "discardEphemeral");
1663
- });
1980
+ // STRICTER gate than desync: every member of the consistency group must be ephemeral. Retention is read
1981
+ // as `entry.retention ?? "persistent"` (absent → persistent, matching validateRegistryLifecycleGroups and
1982
+ // the schema generator); a read PROJECTION surfaces its declared retention on the same `retention` field
1983
+ // (withRetention/asEphemeral/defineReadProjection all set it), so this one read covers tables and
1984
+ // projections alike. Refuse (naming the offender) if any member is persistent — discardEphemeral is the
1985
+ // multi-tab-safe primitive for per-delivery-session windows, and truncating a persistent member's cache
1986
+ // would drop durable local data; use desync for a persistent lazy relation.
1987
+ for (const member of groupTableKeysFor(key, entry)) {
1988
+ if ((options.registry[member]!.retention ?? "persistent") !== "ephemeral") {
1989
+ throw new Error(
1990
+ `discardEphemeral('${String(key)}') refused: group member '${String(member)}' is persistent — ` +
1991
+ `discardEphemeral only drops an ephemeral relation's local rows. Use desync for a persistent lazy relation.`,
1992
+ );
1993
+ }
1994
+ }
1995
+ await tearDownLazyGroup(key, entry, "discardEphemeral");
1996
+ })
1997
+ );
1998
+ };
1664
1999
 
1665
2000
  const transaction: SyncClient<TRegistry>["transaction"] = async ({ mode }, run) => {
2001
+ // Write-path gate (ADR-0041): the atomic unit enqueues + (pessimistic) flushes, so await `writeReady`.
2002
+ await writeReady;
1666
2003
  // The block's table handles only COLLECT mutations; the whole set is enqueued atomically as one unit.
1667
2004
  const collected: MutationBatchItem<TRegistry>[] = [];
1668
2005
  const txTables = Object.fromEntries(
@@ -1736,11 +2073,25 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1736
2073
  build: GuardedQueryFn<TRegistry, TRows>,
1737
2074
  use?: readonly SyncTableName<TRegistry>[],
1738
2075
  ): Promise<TRows> => {
2076
+ // Read gate (ADR-0041): a query must not run against a store whose local-read core has not finished. On
2077
+ // the in-process client this is a settled-promise await (the client is handed out at `localReadReady`),
2078
+ // but it is cheap and keeps the read path safe if a caller retained a query builder across the boundary.
2079
+ await localReadReady;
1739
2080
  const builder = build(client);
1740
2081
  await prepareQuery({ sql: builder.toSQL().sql, ...(use ? { use } : {}) });
1741
2082
  return builder;
1742
2083
  };
1743
2084
 
2085
+ // The live-query manager (ADR-0040) — the SAME module the worker uses (decision 6), so the in-process
2086
+ // client gets one lifecycle contract: dedup of identical concurrent subscriptions within this client,
2087
+ // bounded zero-subscriber keep-alive (`options.liveQueries`), and awaited teardown (decision 1 — `dispose()`
2088
+ // settles every un-awaited unsubscribe before `pglite.close()`, subsuming the old pending-teardowns set).
2089
+ // It cannot dedup across tabs (that is the worker's job) but keeps the contract identical across both forms.
2090
+ const liveManager: LiveQueryManager = createLiveQueryManager({
2091
+ live: pglite.live,
2092
+ ...(options.liveQueries ? { policy: options.liveQueries } : {}),
2093
+ });
2094
+
1744
2095
  const client: SyncClient<TRegistry> = {
1745
2096
  drizzle: drizzleDb,
1746
2097
  pglite,
@@ -1759,12 +2110,19 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1759
2110
  },
1760
2111
  ]),
1761
2112
  ) as SyncClient<TRegistry>["tables"],
2113
+ localReadReady,
2114
+ writeReady,
2115
+ bootSettled,
1762
2116
  ready,
1763
2117
  status,
1764
2118
  start: async () => {
1765
2119
  await ready;
1766
2120
  },
1767
2121
  stop: async () => {
2122
+ // ADR-0041: quiesce the background boot tail FIRST — flag disposal (so it never starts sync after this)
2123
+ // and await its settlement — so no shape stream is left running and nothing execs against the closing
2124
+ // PGlite. Any sync the tail started before disposal is now in `sync` for the unsubscribe below.
2125
+ await quiesceTailForTeardown();
1768
2126
  // Await any in-flight convergence pass before closing PGlite, so a pass never queries a
1769
2127
  // closed handle.
1770
2128
  await convergenceDriver?.stop();
@@ -1775,6 +2133,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1775
2133
  // point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order
1776
2134
  // preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.
1777
2135
  await engine.close();
2136
+ // Dispose the live-query manager before closing PGlite (ADR-0040 decisions 1 & 6): it cancels any
2137
+ // keep-alive timers and awaits every in-flight live `unsubscribe()`, so none races `pglite.close()`.
2138
+ await liveManager.dispose();
1778
2139
  await pglite.close();
1779
2140
  },
1780
2141
  destroy: (destroyOptions) =>
@@ -1783,6 +2144,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1783
2144
  // LifecycleBusyError fires in both directions. The refuse-if-owed guard stays EXACTLY as it was, now
1784
2145
  // inside the slot run.
1785
2146
  lifecycleSlot.run("destroy", async () => {
2147
+ // ADR-0041: quiesce the background boot tail BEFORE the owed-mutations read and the wipe, so neither
2148
+ // races the tail's recovery journal updates / sync start (BLOCKER 2). After this the tail has settled.
2149
+ await quiesceTailForTeardown();
1786
2150
  if (!destroyOptions?.force) {
1787
2151
  const stats = await mutationRuntime.readMutationStats();
1788
2152
  const owed =
@@ -1809,31 +2173,75 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1809
2173
  // Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment
1810
2174
  // the former extension close hook fired during `pglite.close()` (ADR-0032 S1).
1811
2175
  await engine.close();
2176
+ // Dispose the live-query manager before closing PGlite — same close-vs-unsubscribe hang guard as
2177
+ // `stop()` (ADR-0040 decisions 1 & 6).
2178
+ await liveManager.dispose();
1812
2179
  await pglite.close();
1813
2180
  }),
1814
- dropReadCache: () =>
1815
- // Under the SAME lifecycle slot as the exports (ADR-0035 decision 4). WHY dropReadCache is slotted and
1816
- // not just destroy/discardEphemeral: it DROPS and rebuilds the synced read-cache tables, so an export
1817
- // racing it would capture a half-rebuilt cache in the artefact (some tables dropped, some re-created,
1818
- // none re-streamed yet). The slot makes the drop+rebuild atomic against any concurrent export.
1819
- lifecycleSlot.run("dropReadCache", async () => {
1820
- await pglite.exec(buildDropReadCacheSql(options.registry));
1821
- await pglite.exec(generateLocalSchemaSql(options.registry));
1822
- // Reset the Electric subscriptions so the rebuilt synced tables re-stream from scratch
1823
- // rather than the bookkeeping believing they are already caught up (ADR-0006).
1824
- await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
1825
- }),
1826
- flush: (table) => mutationRuntime.flush(table),
1827
- reconcile: (table) => mutationRuntime.reconcile(table),
1828
- retryFailed: (table) => mutationRuntime.retryFailed(table),
1829
- recoverSending: (table) => mutationRuntime.recoverSending(table),
2181
+ dropReadCache: async () => {
2182
+ // ADR-0041 (SHOULD-FIX 5): the drop+rebuild resets subscriptions and rewrites the read cache, so it must
2183
+ // not race the background tail's sync start / subscription reset. Gate on `bootSettled` first.
2184
+ await bootSettled;
2185
+ return (
2186
+ // Under the SAME lifecycle slot as the exports (ADR-0035 decision 4). WHY dropReadCache is slotted and
2187
+ // not just destroy/discardEphemeral: it DROPS and rebuilds the synced read-cache tables, so an export
2188
+ // racing it would capture a half-rebuilt cache in the artefact (some tables dropped, some re-created,
2189
+ // none re-streamed yet). The slot makes the drop+rebuild atomic against any concurrent export.
2190
+ lifecycleSlot.run("dropReadCache", async () => {
2191
+ await pglite.exec(buildDropReadCacheSql(options.registry));
2192
+ await pglite.exec(generateLocalSchemaSql(options.registry));
2193
+ // A full durable-schema exec re-stamps the durable-schema fingerprint (slice 3): exec and stamp
2194
+ // travel together so the next boot's fast path can trust the rebuilt cache's fingerprint.
2195
+ await writeStoredLocalSchemaFingerprint(
2196
+ pglite,
2197
+ options.registry,
2198
+ computeLocalSchemaFingerprint(options.registry),
2199
+ );
2200
+ // Reset the Electric subscriptions so the rebuilt synced tables re-stream from scratch
2201
+ // rather than the bookkeeping believing they are already caught up (ADR-0006).
2202
+ await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
2203
+ })
2204
+ );
2205
+ },
2206
+ // Write-path methods gate on `writeReady` (ADR-0041): each enqueues, drains, or mutates a journal, so
2207
+ // none may run before the write runtime + boot recovery have completed. `writeReady` is already resolved
2208
+ // on the steady-state client, so these are settled-promise awaits.
2209
+ flush: async (table) => {
2210
+ await writeReady;
2211
+ return mutationRuntime.flush(table);
2212
+ },
2213
+ reconcile: async (table) => {
2214
+ await writeReady;
2215
+ return mutationRuntime.reconcile(table);
2216
+ },
2217
+ retryFailed: async (table) => {
2218
+ await writeReady;
2219
+ return mutationRuntime.retryFailed(table);
2220
+ },
2221
+ recoverSending: async (table) => {
2222
+ await writeReady;
2223
+ return mutationRuntime.recoverSending(table);
2224
+ },
2225
+ // NIT 7 (ADR-0041): these are READ diagnostics, deliberately UNGATED so they work at `localReadReady`. In
2226
+ // the narrow pre-`writeReady` window they may observe pre-recovery `sending` rows (boot recovery lifts
2227
+ // `sending → pending`), i.e. the honest current journal state before recovery has run — not a bug.
1830
2228
  readMutationDetails: (table) => mutationRuntime.readMutationDetails(table),
1831
2229
  mutate,
1832
- discardConflict: (table, entityKey) => mutationRuntime.discardConflict(table, entityKey),
1833
- discardQuarantined: (table, entityKey) => mutationRuntime.discardQuarantined(table, entityKey),
2230
+ discardConflict: async (table, entityKey) => {
2231
+ await writeReady;
2232
+ return mutationRuntime.discardConflict(table, entityKey);
2233
+ },
2234
+ discardQuarantined: async (table, entityKey) => {
2235
+ await writeReady;
2236
+ return mutationRuntime.discardQuarantined(table, entityKey);
2237
+ },
2238
+ // See the `readMutationDetails` note: a read, ungated, so pre-`writeReady` it may show pre-recovery counts.
1834
2239
  diagnostics: async (table) => ({
1835
2240
  mutation: await mutationRuntime.readMutationStats(table),
1836
2241
  }),
2242
+ // The registry-wide mutation-status API (slice 4). Assigned just below the object so it can close over
2243
+ // this client's own `subscribeLiveRows` + `pglite.query` seams — the SAME factory the worker facade uses.
2244
+ mutations: undefined as unknown as MutationsApi<TRegistry>,
1837
2245
  // Inspection surface (see the interface doc): straight through to the underlying store, no journal /
1838
2246
  // overlay involvement. The worker facade runs the identical call inside the worker's own client.
1839
2247
  rawQuery: (sql, params, options) => pglite.query(sql, params as unknown[] | undefined, options),
@@ -1856,20 +2264,42 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1856
2264
  transaction,
1857
2265
  groupReady: groupReadyForTable,
1858
2266
  hydratingTablesFor,
1859
- // The live-rows seam over PGlite's own `live` extension (ADR-0032 S2 §4) — the EXACT call the React
1860
- // hooks made inline before the seam existed (`pglite.live.query` → `initialResults.rows` + `subscribe`),
1861
- // so the in-process path is unchanged. `pkColumns` is unused here: PGlite's live query already diffs
1862
- // incrementally against its own materialized state; the column set only matters for the worker bridge.
1863
- subscribeLiveRows: async ({ sql, params, fields, use }, onRows) => {
2267
+ // The live-rows seam, now delegated to the shared `LiveQueryManager` (ADR-0040 decision 6) — identical
2268
+ // contract to the pre-adoption inline `pglite.live.query` seam, but with dedup of identical concurrent
2269
+ // subscriptions, keep-alive (`keepAliveMs`), and awaited teardown for free. The manager delivers a diff
2270
+ // stream (`deliverInitial` + `deliverDiff`); we fold it back into FULL ordered row arrays with a
2271
+ // per-subscription `LiveRowsMaterializer` (the SAME piece `attachSyncClient` uses tab-side), so the
2272
+ // public `onRows(rows)` / `initialRows` contract is byte-unchanged — and unchanged rows now keep `===`
2273
+ // identity across diffs (a bonus the raw `results.rows` path did not give). Keyless (no `pkColumns`)
2274
+ // exactly as the inline seam was: PGlite's `live.query` + the manager's value-identity diff.
2275
+ subscribeLiveRows: async ({ sql, params, fields, use, keepAliveMs }, onRows) => {
2276
+ // Read gate (ADR-0041): do not register a live query before the local-read core has finished (a
2277
+ // settled-promise await on the steady-state client — cheap, and stage-2-safe).
2278
+ await localReadReady;
1864
2279
  // Render the query safe to materialise: a JOIN with same-named columns fails `live.query`'s
1865
2280
  // temp-view creation (`column "title" specified more than once`) unless every output column has a
1866
- // unique alias. No `fields` → SQL unchanged (backward-compatible name-keyed rows).
2281
+ // unique alias. No `fields` → SQL unchanged (backward-compatible name-keyed rows). The wrap stays
2282
+ // caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL.
1867
2283
  const materialSql = wrapLiveQueryForMaterialization(sql, fields);
1868
- const registered = await pglite.live.query<Record<string, unknown>>(materialSql, params as unknown[]);
1869
- const listener = (results: { rows: Record<string, unknown>[] }) => {
1870
- onRows(results.rows as never);
1871
- };
1872
- registered.subscribe(listener);
2284
+ // Keyless materializer (matches the inline seam, which never passed pkColumns): initial rows seed it;
2285
+ // each diff folds into a fresh ordered array whose unchanged rows keep their object identity.
2286
+ const materializer = new LiveRowsMaterializer<Record<string, unknown>>(undefined);
2287
+ const subscription = await liveManager.subscribe(
2288
+ { materialSql, params: params as unknown[] },
2289
+ {
2290
+ // The initial snapshot is returned via `initialRows`, NOT `onRows` (which fires on CHANGES only) —
2291
+ // so `deliverInitial` just seeds the materializer; `initialRows` is read from it below.
2292
+ deliverInitial: (rows) => {
2293
+ materializer.seed(rows);
2294
+ },
2295
+ deliverDiff: (diff) => {
2296
+ onRows(materializer.apply(diff) as never);
2297
+ },
2298
+ },
2299
+ keepAliveMs != null ? { keepAliveMs } : undefined,
2300
+ );
2301
+ // Seeded synchronously by `deliverInitial` during `subscribe` above.
2302
+ const initialRows = materializer.current();
1873
2303
  let unsubscribed = false;
1874
2304
  // The query's lazy relations (guard scan ∪ `use`; the caller's `prepareQuery` already activated them)
1875
2305
  // are surfaced as `lazyTables` for observability — the relations held out of the eager boot set.
@@ -1880,22 +2310,25 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1880
2310
  // yet caught up at subscribe time. Empty (steady state / sync disabled) → NO `hydrated` promise, so a
1881
2311
  // post-boot subscription pays no extra refresh (exactly today's eager-only behaviour). Otherwise build
1882
2312
  // `hydrated` with rows-before-signal ordering: await the pending groups' catch-up, refresh the live
1883
- // query against the caught-up store (its listener delivers the rows synchronously inside the refresh),
1884
- // THEN resolve — so a UI flipping out of its loading state on this promise can never flash a false empty.
2313
+ // query (the manager's coalesced refresh; its listener delivers the caught-up rows as a diff → onRows,
2314
+ // synchronously inside the refresh), THEN resolve — so a UI flipping out of its loading state on this
2315
+ // promise can never flash a false empty.
1885
2316
  const hydratingTables = hydratingTablesFor({ sql, ...(use ? { use } : {}) });
1886
2317
  const hydrated =
1887
2318
  hydratingTables.length > 0
1888
2319
  ? Promise.all(hydratingTables.map((table) => groupReadyForTable(table as SyncTableName<TRegistry>)))
1889
2320
  .then(async () => {
1890
- if (!unsubscribed) await registered.refresh();
2321
+ if (!unsubscribed) await subscription.refresh();
1891
2322
  })
1892
2323
  .catch(() => undefined)
1893
2324
  : undefined;
1894
2325
  return {
1895
- initialRows: registered.initialResults.rows as never,
2326
+ initialRows: initialRows as never,
1896
2327
  unsubscribe: () => {
1897
2328
  unsubscribed = true;
1898
- void registered.unsubscribe(listener);
2329
+ // Non-blocking for the caller; the manager retains the teardown promise so `dispose()` (called by
2330
+ // `stop()`/`destroy()`) awaits it before closing PGlite (ADR-0040 decision 1 — the close race).
2331
+ void subscription.unsubscribe();
1899
2332
  },
1900
2333
  ...(lazyTables.length > 0 ? { lazyTables } : {}),
1901
2334
  ...(hydrated ? { hydrated } : {}),
@@ -1904,6 +2337,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1904
2337
  // Boot observability (ADR-0034): the finalized report (null before initial sync completes / after an
1905
2338
  // early stop). Resolves from the builder-owned ref this client holds — no round trip in-process.
1906
2339
  bootReport: async () => finalizedBootReport,
2340
+ // Live-query diagnostics (ADR-0040 decisions 5 & 6): the in-process client now owns a real manager, so
2341
+ // this returns its live snapshot (digests + counts/timings only — never SQL/params/rows).
2342
+ liveQueryDiagnostics: async () => liveManager.snapshot(),
1907
2343
  exportStore: async (exportOptions) => {
1908
2344
  // Await engine-ready first (ADR-0035: exports wait out a boot rather than rejecting during it), THEN
1909
2345
  // take the lifecycle slot — a concurrent export/lifecycle op is refused with a typed busy error.
@@ -1965,6 +2401,66 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1965
2401
  },
1966
2402
  };
1967
2403
 
2404
+ // Wire the mutation-status API over this client's shared seams (slice 4): its live-rows seam (over
2405
+ // `pglite.live` via the manager) and its one-shot `pglite.query`. The worker facade wires the SAME factory
2406
+ // over the bridge, so `client.mutations` behaves identically in both modes.
2407
+ client.mutations = createMutationsApi({
2408
+ registry: options.registry,
2409
+ subscribeLiveRows: client.subscribeLiveRows,
2410
+ query: (sql, params) => pglite.query<Record<string, unknown>>(sql, params),
2411
+ });
2412
+
2413
+ // ─── Local-read core complete → resolve `localReadReady`, then run the write/sync tail in the background ──
2414
+ // (ADR-0041 Option B.) The durable schema is compatible, store-version reconcile has run, and the drizzle
2415
+ // read facade + client are built — cached reads are safe now, with ZERO network. Stamp + resolve
2416
+ // `localReadReady`; on a restore boot `writeReady` coincides (recovery + quarantine already ran in the core,
2417
+ // before this read exposure — the ADR-0041 invariant). This function then RESOLVES at `localReadReady`.
2418
+ bootReportBuilder.setLocalReadReadyMs(performance.now() - bootReportBuilder.bootStartPerf);
2419
+ resolveLocalReadReady();
2420
+ if (restoreBoot) {
2421
+ bootReportBuilder.setWriteReadyMs(performance.now() - bootReportBuilder.bootStartPerf);
2422
+ resolveWriteReady();
2423
+ }
2424
+
2425
+ // Guard the downstream stages so a tail failure on an UNCONSUMED stage (e.g. `bootSettled` in-process, where
2426
+ // only the worker awaits it) never surfaces as an unhandled rejection — a real awaiter still observes it.
2427
+ void writeReady.catch(() => undefined);
2428
+ void bootSettled.catch(() => undefined);
2429
+ void ready.catch(() => undefined);
2430
+
2431
+ // Kick the write/sync tail (background). Its completion is today's full resolution point → `bootSettled`. A
2432
+ // tail failure lands AFTER `localReadReady` resolved, so it can no longer reject this function's returned
2433
+ // promise (as a pre-ADR-0041 boot failure would); surface it on every still-pending downstream stage instead
2434
+ // so their awaiters (a gated write, `ready`, the worker's `bootSettled`) fail loudly rather than hang.
2435
+ void runWriteAndSyncTail().then(
2436
+ () => {
2437
+ resolveBootSettled();
2438
+ // Belt-and-braces: if a `disposed` bail returned before the replay, drop the buffer so it cannot leak or
2439
+ // keep collecting (steady-state activations go straight through `ensureSynced` once `sync` is wired).
2440
+ pendingActivations = null;
2441
+ resolveSyncWired();
2442
+ },
2443
+ (error: unknown) => {
2444
+ syncDebug("boot write/sync tail failed after localReadReady", { error });
2445
+ // SHOULD-FIX 4: the tail failed at/before sync start, so buffered activations can never be replayed —
2446
+ // null the buffer (bounded, no unbounded growth) and name the loss on the debug rail.
2447
+ if (pendingActivations != null && pendingActivations.size > 0) {
2448
+ syncDebug("boot tail failure dropped buffered activations", { tables: [...pendingActivations] });
2449
+ }
2450
+ pendingActivations = null;
2451
+ // NIT 8: surface a signal beyond the stage rejections — move the runtime to `degraded` so a consumer
2452
+ // watching `status`/`onStatusChange` sees the boot failed, not just an awaiter of a stage promise.
2453
+ status.phase = "degraded";
2454
+ status.lastError = error instanceof Error ? error.message : String(error);
2455
+ options.onStatusChange?.(status);
2456
+ rejectWriteReady(error);
2457
+ rejectReady(error);
2458
+ rejectBootSettled(error);
2459
+ // Unblock any read seam parked on `syncWired` — it will see `sync == null` and fall back to local-only.
2460
+ rejectSyncWired(error);
2461
+ },
2462
+ );
2463
+
1968
2464
  return client;
1969
2465
  }
1970
2466