@pgxsinkit/client 0.1.49 → 0.1.51

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 (51) 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 +56 -3
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1106 -312
  6. package/dist/index.js.map +19 -18
  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 +80 -1
  16. package/dist/schema.d.ts.map +1 -1
  17. package/dist/shape-sync.d.ts +6 -0
  18. package/dist/shape-sync.d.ts.map +1 -1
  19. package/dist/sync/index.d.ts +1 -1
  20. package/dist/sync/index.d.ts.map +1 -1
  21. package/dist/sync/metadata-tables.d.ts +16 -0
  22. package/dist/sync/metadata-tables.d.ts.map +1 -1
  23. package/dist/sync/subscription-state.d.ts +10 -2
  24. package/dist/sync/subscription-state.d.ts.map +1 -1
  25. package/dist/sync/tags.d.ts +16 -4
  26. package/dist/sync/tags.d.ts.map +1 -1
  27. package/dist/sync/types.d.ts +12 -0
  28. package/dist/sync/types.d.ts.map +1 -1
  29. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  30. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  31. package/dist/worker/protocol.d.ts +44 -1
  32. package/dist/worker/protocol.d.ts.map +1 -1
  33. package/package.json +2 -2
  34. package/skills/core/SKILL.md +1 -1
  35. package/skills/operating/SKILL.md +1 -1
  36. package/src/boot-report.ts +108 -0
  37. package/src/index.ts +555 -136
  38. package/src/local-store.ts +150 -3
  39. package/src/local-tables.ts +49 -1
  40. package/src/mutation.ts +256 -15
  41. package/src/mutations-api.ts +310 -0
  42. package/src/schema.ts +428 -197
  43. package/src/shape-sync.ts +11 -0
  44. package/src/sync/index.ts +14 -1
  45. package/src/sync/metadata-tables.ts +41 -0
  46. package/src/sync/subscription-state.ts +29 -4
  47. package/src/sync/tags.ts +34 -9
  48. package/src/sync/types.ts +12 -0
  49. package/src/worker/attach-sync-client.ts +114 -5
  50. package/src/worker/define-sync-worker.ts +65 -4
  51. package/src/worker/protocol.ts +38 -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";
@@ -187,6 +195,8 @@ export {
187
195
  LazyRelationNotActivatedError,
188
196
  } from "./lazy-guard";
189
197
  export {
198
+ type AllMutationsView,
199
+ getAllMutationsView,
190
200
  getJournalTable,
191
201
  getLocalMetaTable,
192
202
  getOverlayTable,
@@ -199,8 +209,47 @@ export {
199
209
  type ReadModelView,
200
210
  type SyncStateView,
201
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";
202
221
  export type { LocalStoreVersionEvent };
203
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
+
204
253
  // The store carries PGlite's own `live` extension (a genuine create-time extension) plus the pgxsinkit
205
254
  // sync engine's namespace, attached post-create by `createSyncClient` as the `electric` property (ADR-0032
206
255
  // S1) — no longer a create-time extension. The `electric` part is derived from `createSyncEngine`'s real
@@ -689,6 +738,30 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
689
738
  tables: {
690
739
  [TKey in SyncTableName<TRegistry>]: SyncClientTableHandle<TRegistry, TKey>;
691
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>;
692
765
  ready: Promise<void>;
693
766
  status: SyncRuntimeStatus;
694
767
  start: () => Promise<void>;
@@ -751,6 +824,14 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
751
824
  entityKey: Record<string, string>,
752
825
  ) => Promise<void>;
753
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>;
754
835
  /**
755
836
  * The INSPECTION read surface (debug pages, REPLs, ad-hoc counts) — identical on the in-process and
756
837
  * worker-attached client (on the latter the statement runs in the worker). The statement runs raw
@@ -948,7 +1029,7 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
948
1029
  exportData: (options?: DataExportOptions) => Promise<DataExportResult>;
949
1030
  }
950
1031
 
951
- export type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind };
1032
+ export type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind, MutationSummary };
952
1033
 
953
1034
  /**
954
1035
  * The structured-clone-safe subset of PGlite's `QueryOptions` the inspection surface carries. Kept
@@ -995,8 +1076,38 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
995
1076
  };
996
1077
 
997
1078
  let resolveReady!: () => void;
998
- const ready = new Promise<void>((resolve) => {
1079
+ let rejectReady!: (error: unknown) => void;
1080
+ const ready = new Promise<void>((resolve, reject) => {
999
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;
1000
1111
  });
1001
1112
 
1002
1113
  if (options.pgliteInstance && options.precreatedPglite) {
@@ -1028,12 +1139,17 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1028
1139
  const syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);
1029
1140
  // ADR-0032 S4 overlap flag, computed once up front so the boot report and the prefetch gate agree.
1030
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";
1031
1146
 
1032
1147
  // Boot observability (ADR-0034): build a structured report across the boot, finalized once at initial
1033
1148
  // sync. Created FIRST so its monotonic anchor precedes every timed phase (including the PGlite create).
1034
1149
  const bootReportBuilder: BootReportBuilder = createBootReportBuilder({
1035
1150
  mode: options.bootMode ?? "in-process",
1036
1151
  freshStore: options.freshStore === true,
1152
+ storeKind,
1037
1153
  overlapPrefetch,
1038
1154
  registryFingerprint: fingerprintRegistry(options.registry),
1039
1155
  });
@@ -1296,8 +1412,35 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1296
1412
  await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
1297
1413
  }
1298
1414
 
1299
- const schemaSql = generateLocalSchemaSql(options.registry);
1300
- 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
+ });
1301
1444
 
1302
1445
  if (options.prepareLocalDb) {
1303
1446
  const prepareLocalDb = options.prepareLocalDb;
@@ -1322,6 +1465,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1322
1465
  db: pglite,
1323
1466
  registry: options.registry,
1324
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,
1325
1471
  onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
1326
1472
  ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
1327
1473
  ...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),
@@ -1331,32 +1477,32 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1331
1477
  ...(options.onReject ? { onReject: options.onReject } : {}),
1332
1478
  });
1333
1479
 
1334
- // Reclaim any in-flight mutations interrupted by a previous shutdown (ADR-0005), then
1335
- // reconcile the local store against the current registry fingerprint before sync starts
1336
- // (ADR-0006). Skipped when the caller supplies their own pglite (they own its schema).
1337
- await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () => mutationRuntime.recoverSending());
1338
-
1339
- // Restore-boot quarantine (ADR-0035 decision 6): the moment a store is booted FROM a backup, every
1340
- // non-terminal recovered journal row (`pending`/`sending`/`failed`) is parked in `quarantined` so nothing
1341
- // recovered auto-flushes — the write path has no `mutationId` dedupe ledger, making replay unsafe on
1342
- // last-write-wins tables (silent stale reverts) and colliding on a recreated PK. Runs ONLY on the restore
1343
- // boot (loadDataDir happens exactly once); a subsequent normal boot of the persisted store never re-runs
1344
- // it. Placed AFTER `recoverSending` (which lifts any `sending` back to `pending`) so a single pass over
1345
- // pending/sending/failed catches the lot. The app then inspects `diagnostics()` and releases/discards them.
1346
- if (restoreBoot) {
1347
- await mutationRuntime.quarantineRecovered();
1348
- }
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();
1349
1486
 
1350
1487
  let versionEvent: LocalStoreVersionEvent | null = null;
1351
1488
 
1352
- // Registry-fingerprint mismatch on restore (ADR-0035 decision 6): an old backup restored against a NEWER
1353
- // registry needs NO special handling — the existing local-schema-evolution path (ADR-0006) owns it, and
1354
- // restore composes with it for free. On this restore boot the quarantine above ran FIRST, so every
1355
- // recovered row now counts toward `owedMutations` (pending+sending+failed+quarantined) inside
1356
- // `rebuildReadCacheOrDefer`: a stale fingerprint therefore DEFERS the read-cache rebuild rather than
1357
- // dropping the quarantined writes, exactly as it would for any store that owes work. The rebuild completes
1358
- // on a later boot once the app has released/discarded the quarantine and drained the journal.
1359
- 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;
1360
1506
  versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () =>
1361
1507
  reconcileLocalStoreVersion({
1362
1508
  db: pglite,
@@ -1365,6 +1511,23 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1365
1511
  ...(options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}),
1366
1512
  }),
1367
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();
1368
1531
  }
1369
1532
 
1370
1533
  const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));
@@ -1374,57 +1537,143 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1374
1537
  let sync: Awaited<ReturnType<typeof startConfiguredSync>> | null = null;
1375
1538
  let convergenceDriver: ConvergenceDriver | null = null;
1376
1539
 
1377
- status.isRunning = true;
1378
-
1379
- // Open the overlap commit gate now the local store is ready (schema exec + journal recovery + reconcile
1380
- // done): the catch-up the streams prefetched during those phases now drains in one commit train. A no-op
1381
- // on the sequential path (`openDbGate` is the empty default there).
1382
- openDbGate();
1383
-
1384
- if (syncEnabled) {
1385
- if (earlySync) {
1386
- // Overlap path: the shape streams have been prefetching since before schema exec; adopt the handle
1387
- // (it resolves as soon as the streams are subscribed — catch-up drains via the gate just lifted, and
1388
- // `onInitialSync` still gates `ready` on a fully-consistent first paint). The construction was kicked
1389
- // off before schema exec, so time it here (concurrent-segment wall) into `phases.syncStartMs`.
1390
- sync = await earlySync;
1391
- bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);
1392
- 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
+ }
1393
1656
  } else {
1394
- // Sequential path (warm store / no fresh hint): the exact pre-S4 ordering — reset any rebuilt
1395
- // subscriptions, promote durable lazy groups, then start (catch-up strictly after the local phases).
1396
- // After a read-cache rebuild the Electric subscription bookkeeping is stale (it would believe the
1397
- // dropped shapes are still caught up and never backfill), so reset every shape subscription to force a
1398
- // fresh re-stream (ADR-0006).
1399
- const resetKeys =
1400
- versionEvent?.status === "rebuilt"
1401
- ? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]
1402
- : options.resetSubscriptionKeys;
1403
- await resetSubscriptionsIfRequested(pglite, resetKeys);
1404
-
1405
- status.phase = "syncing";
1657
+ status.phase = "ready";
1406
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
+ }
1407
1664
 
1408
- // Promote any `lazy + persistent` group activated on a previous boot back into the eager set
1409
- // (ADR-0021 §2); the sync engine does no DB read of its own.
1410
- const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);
1411
-
1412
- sync = await bootReportBuilder.phase("syncStart", "boot sync start", () =>
1413
- startConfiguredSync(
1414
- pglite as unknown as Parameters<typeof startConfiguredSync>[0],
1415
- buildStartOptions(promotedGroups),
1416
- ),
1417
- );
1418
- 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>[]);
1419
1673
  }
1420
- } else {
1421
- status.phase = "ready";
1422
- options.onStatusChange?.(status);
1423
- // Sync disabled: there is no `onInitialSync` gate, but boot IS complete — finalize the report at the
1424
- // same moment `ready` resolves (ADR-0034). Idempotent with the sync path's finalize.
1425
- finalizeBootReport();
1426
- resolveReady();
1427
- }
1674
+ // Sync is wired (or disabled and boot complete): unblock any read seam that parked on `syncWired`.
1675
+ resolveSyncWired();
1676
+ };
1428
1677
 
1429
1678
  // Restore boots offline (ADR-0035 decision 6): never stand up the convergence driver on a restore boot,
1430
1679
  // so an `autoSync` trigger the caller passed (even an online one) drives NO flush/reconcile passes — the
@@ -1440,9 +1689,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1440
1689
  ...(options.onConvergencePass ? { onPass: options.onConvergencePass } : {}),
1441
1690
  });
1442
1691
 
1443
- // Start driving convergence once the initial sync is ready, so a pass never races the
1444
- // first shape load. stop()/destroy() halt it.
1445
- 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
+ );
1446
1699
  }
1447
1700
 
1448
1701
  // Event-driven convergence: the moment a mutation is enqueued, ask the driver to run a pass so the
@@ -1450,20 +1703,27 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1450
1703
  // lets the interval be a rare fallback (and so run far less often). No-op when `autoSync` is off — the
1451
1704
  // caller drives `flush`/`reconcile` itself.
1452
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.
1453
1709
  const mutate: SyncClient<TRegistry>["mutate"] = {
1454
1710
  create: async (table, input) => {
1711
+ await writeReady;
1455
1712
  await mutationRuntime.create(table, input);
1456
1713
  requestConvergence();
1457
1714
  },
1458
1715
  update: async (table, entityKey, patch) => {
1716
+ await writeReady;
1459
1717
  await mutationRuntime.update(table, entityKey, patch);
1460
1718
  requestConvergence();
1461
1719
  },
1462
1720
  delete: async (table, entityKey) => {
1721
+ await writeReady;
1463
1722
  await mutationRuntime.delete(table, entityKey);
1464
1723
  requestConvergence();
1465
1724
  },
1466
1725
  batch: async (items) => {
1726
+ await writeReady;
1467
1727
  await mutationRuntime.batch(items);
1468
1728
  requestConvergence();
1469
1729
  },
@@ -1523,8 +1783,19 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1523
1783
 
1524
1784
  // ─── Lazy-relation activation + the declared-safe query facade (ADR-0021) ──────────────────────
1525
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
+ }
1526
1795
  const activeSync = sync;
1527
- 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;
1528
1799
  const groupKeys = new Set<string>();
1529
1800
  for (const key of keys) {
1530
1801
  const groupKey = activeSync.groupKeyForTable(key);
@@ -1545,6 +1816,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1545
1816
  // network, and a failed start self-heals on the group's next activation (a `.catch` keeps the rejection
1546
1817
  // off the unhandled-rejection path).
1547
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
+ }
1548
1826
  const lazyTables = tables.filter((table) => lazyGuardIndex.lazyKeys.has(table)) as SyncTableName<TRegistry>[];
1549
1827
  if (lazyTables.length === 0) return;
1550
1828
  void ensureSynced(lazyTables).catch((error) => {
@@ -1555,8 +1833,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1555
1833
  // Per-table catch-up completion (ADR-0032 decision 6) — the body of `client.groupReady`, hoisted so the
1556
1834
  // live-rows seam can also await it when building a subscription's `hydrated` promise.
1557
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
+ }
1558
1841
  const activeSync = sync;
1559
- // 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".
1560
1843
  if (activeSync == null) return;
1561
1844
  const groupKey = activeSync.groupKeyForTable(table as string);
1562
1845
  if (groupKey == null) return;
@@ -1568,8 +1851,11 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1568
1851
  // referenced group is already ready at subscribe time, no `hydrated` promise is built (no extra refresh).
1569
1852
  const isGroupReadyForTable = (table: string): boolean => {
1570
1853
  const activeSync = sync;
1571
- // Sync disabled → local-only: reads hit whatever is local, so a group is trivially "ready".
1572
- 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
+ }
1573
1859
  const groupKey = activeSync.groupKeyForTable(table);
1574
1860
  // No consistency group (unknown/writeonly) → nothing to await; treat as ready.
1575
1861
  if (groupKey == null) return true;
@@ -1578,11 +1864,12 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1578
1864
 
1579
1865
  // The referenced synced tables whose consistency group is NOT YET caught up (ADR-0021/0032): scan the
1580
1866
  // compiled SQL for every synced relation the query reads (∪ the explicit `use`), then keep only those
1581
- // whose group is still catching up. Empty when sync is disabled OR every referenced group is already
1582
- // ready — the steady-state fast path, where the live-rows seam builds no `hydrated` promise. Eager and
1583
- // 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.
1584
1870
  const hydratingTablesFor = (query: { sql: string; use?: readonly string[] }): string[] => {
1585
- if (sync == null) return [];
1871
+ // Sync disabled → nothing hydrates. Sync pending → every referenced synced group is hydrating (below).
1872
+ if (sync == null && !isSyncPending()) return [];
1586
1873
  const referenced = new Set<string>(query.use ?? []);
1587
1874
  for (const key of findReferencedSyncedKeysInSql(query.sql, lazyGuardIndex)) referenced.add(key);
1588
1875
  return [...referenced].filter((table) => !isGroupReadyForTable(table));
@@ -1590,8 +1877,11 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1590
1877
 
1591
1878
  const isSynced: SyncClient<TRegistry>["isSynced"] = (key) => {
1592
1879
  const activeSync = sync;
1593
- // Sync disabled → local-only: reads hit whatever is in the local store, so nothing is "dormant".
1594
- 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
+ }
1595
1885
  return activeSync.isTableStarted(key);
1596
1886
  };
1597
1887
 
@@ -1653,6 +1943,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1653
1943
  };
1654
1944
 
1655
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;
1656
1950
  const entry = options.registry[key];
1657
1951
  if (entry == null) throw new Error(`desync: unknown table ${String(key)}`);
1658
1952
  if (entry.subscription !== "lazy") {
@@ -1663,42 +1957,49 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1663
1957
  await tearDownLazyGroup(key, entry, "desync");
1664
1958
  };
1665
1959
 
1666
- const discardEphemeral: SyncClient<TRegistry>["discardEphemeral"] = (key) =>
1667
- // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4): discardEphemeral
1668
- // clean-truncates an ephemeral group's local cache, so an export must never interleave it (nor it an
1669
- // export) — the slot's typed LifecycleBusyError fires in both directions. The existing lazy/ephemeral
1670
- // gates below stay EXACTLY as they were, now inside the slot run. (`desync` is deliberately NOT slotted:
1671
- // only the ADR-0035-named destructive ops — destroy/discardEphemeral/dropReadCache — serialise here.)
1672
- lifecycleSlot.run("discardEphemeral", async () => {
1673
- const entry = options.registry[key];
1674
- if (entry == null) throw new Error(`discardEphemeral: unknown table ${String(key)}`);
1675
- // Keep the lazy gate desync has: eager+ephemeral is NOT forbidden by the type system (retention and
1676
- // subscription are independent scalars on the entry — see contracts config.ts / registry.ts), and an
1677
- // eager relation would immediately re-stream, so the same refusal applies here.
1678
- if (entry.subscription !== "lazy") {
1679
- throw new Error(
1680
- `discardEphemeral('${String(key)}') refused: only a lazy relation can be discarded — an eager relation is always-on and would immediately re-sync.`,
1681
- );
1682
- }
1683
- // STRICTER gate than desync: every member of the consistency group must be ephemeral. Retention is read
1684
- // as `entry.retention ?? "persistent"` (absent → persistent, matching validateRegistryLifecycleGroups and
1685
- // the schema generator); a read PROJECTION surfaces its declared retention on the same `retention` field
1686
- // (withRetention/asEphemeral/defineReadProjection all set it), so this one read covers tables and
1687
- // projections alike. Refuse (naming the offender) if any member is persistent — discardEphemeral is the
1688
- // multi-tab-safe primitive for per-delivery-session windows, and truncating a persistent member's cache
1689
- // would drop durable local data; use desync for a persistent lazy relation.
1690
- for (const member of groupTableKeysFor(key, entry)) {
1691
- 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") {
1692
1976
  throw new Error(
1693
- `discardEphemeral('${String(key)}') refused: group member '${String(member)}' is persistent — ` +
1694
- `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.`,
1695
1978
  );
1696
1979
  }
1697
- }
1698
- await tearDownLazyGroup(key, entry, "discardEphemeral");
1699
- });
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
+ };
1700
1999
 
1701
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;
1702
2003
  // The block's table handles only COLLECT mutations; the whole set is enqueued atomically as one unit.
1703
2004
  const collected: MutationBatchItem<TRegistry>[] = [];
1704
2005
  const txTables = Object.fromEntries(
@@ -1772,6 +2073,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1772
2073
  build: GuardedQueryFn<TRegistry, TRows>,
1773
2074
  use?: readonly SyncTableName<TRegistry>[],
1774
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;
1775
2080
  const builder = build(client);
1776
2081
  await prepareQuery({ sql: builder.toSQL().sql, ...(use ? { use } : {}) });
1777
2082
  return builder;
@@ -1805,12 +2110,19 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1805
2110
  },
1806
2111
  ]),
1807
2112
  ) as SyncClient<TRegistry>["tables"],
2113
+ localReadReady,
2114
+ writeReady,
2115
+ bootSettled,
1808
2116
  ready,
1809
2117
  status,
1810
2118
  start: async () => {
1811
2119
  await ready;
1812
2120
  },
1813
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();
1814
2126
  // Await any in-flight convergence pass before closing PGlite, so a pass never queries a
1815
2127
  // closed handle.
1816
2128
  await convergenceDriver?.stop();
@@ -1832,6 +2144,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1832
2144
  // LifecycleBusyError fires in both directions. The refuse-if-owed guard stays EXACTLY as it was, now
1833
2145
  // inside the slot run.
1834
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();
1835
2150
  if (!destroyOptions?.force) {
1836
2151
  const stats = await mutationRuntime.readMutationStats();
1837
2152
  const owed =
@@ -1863,29 +2178,70 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1863
2178
  await liveManager.dispose();
1864
2179
  await pglite.close();
1865
2180
  }),
1866
- dropReadCache: () =>
1867
- // Under the SAME lifecycle slot as the exports (ADR-0035 decision 4). WHY dropReadCache is slotted and
1868
- // not just destroy/discardEphemeral: it DROPS and rebuilds the synced read-cache tables, so an export
1869
- // racing it would capture a half-rebuilt cache in the artefact (some tables dropped, some re-created,
1870
- // none re-streamed yet). The slot makes the drop+rebuild atomic against any concurrent export.
1871
- lifecycleSlot.run("dropReadCache", async () => {
1872
- await pglite.exec(buildDropReadCacheSql(options.registry));
1873
- await pglite.exec(generateLocalSchemaSql(options.registry));
1874
- // Reset the Electric subscriptions so the rebuilt synced tables re-stream from scratch
1875
- // rather than the bookkeeping believing they are already caught up (ADR-0006).
1876
- await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
1877
- }),
1878
- flush: (table) => mutationRuntime.flush(table),
1879
- reconcile: (table) => mutationRuntime.reconcile(table),
1880
- retryFailed: (table) => mutationRuntime.retryFailed(table),
1881
- 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.
1882
2228
  readMutationDetails: (table) => mutationRuntime.readMutationDetails(table),
1883
2229
  mutate,
1884
- discardConflict: (table, entityKey) => mutationRuntime.discardConflict(table, entityKey),
1885
- 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.
1886
2239
  diagnostics: async (table) => ({
1887
2240
  mutation: await mutationRuntime.readMutationStats(table),
1888
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>,
1889
2245
  // Inspection surface (see the interface doc): straight through to the underlying store, no journal /
1890
2246
  // overlay involvement. The worker facade runs the identical call inside the worker's own client.
1891
2247
  rawQuery: (sql, params, options) => pglite.query(sql, params as unknown[] | undefined, options),
@@ -1917,6 +2273,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1917
2273
  // identity across diffs (a bonus the raw `results.rows` path did not give). Keyless (no `pkColumns`)
1918
2274
  // exactly as the inline seam was: PGlite's `live.query` + the manager's value-identity diff.
1919
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;
1920
2279
  // Render the query safe to materialise: a JOIN with same-named columns fails `live.query`'s
1921
2280
  // temp-view creation (`column "title" specified more than once`) unless every output column has a
1922
2281
  // unique alias. No `fields` → SQL unchanged (backward-compatible name-keyed rows). The wrap stays
@@ -2042,6 +2401,66 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2042
2401
  },
2043
2402
  };
2044
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
+
2045
2464
  return client;
2046
2465
  }
2047
2466