@pgxsinkit/client 0.1.53 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +22 -0
  2. package/dist/adoption.d.ts +118 -0
  3. package/dist/adoption.d.ts.map +1 -0
  4. package/dist/boot-report.d.ts +54 -15
  5. package/dist/boot-report.d.ts.map +1 -1
  6. package/dist/convergence.d.ts +2 -1
  7. package/dist/convergence.d.ts.map +1 -1
  8. package/dist/export-store.d.ts +1 -1
  9. package/dist/export-store.d.ts.map +1 -1
  10. package/dist/index.d.ts +286 -51
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +4795 -1519
  13. package/dist/index.js.map +34 -24
  14. package/dist/live-rows-sql.d.ts +1 -1
  15. package/dist/local-store.d.ts +16 -31
  16. package/dist/local-store.d.ts.map +1 -1
  17. package/dist/local-tables.d.ts +4 -4
  18. package/dist/mutation.d.ts +18 -15
  19. package/dist/mutation.d.ts.map +1 -1
  20. package/dist/opfs-effects.d.ts +51 -0
  21. package/dist/opfs-effects.d.ts.map +1 -0
  22. package/dist/placement-probe.d.ts +75 -0
  23. package/dist/placement-probe.d.ts.map +1 -0
  24. package/dist/schema.d.ts +11 -16
  25. package/dist/schema.d.ts.map +1 -1
  26. package/dist/store-boot.d.ts +77 -0
  27. package/dist/store-boot.d.ts.map +1 -0
  28. package/dist/store-lifecycle.d.ts +153 -0
  29. package/dist/store-lifecycle.d.ts.map +1 -0
  30. package/dist/store-meta.d.ts +190 -0
  31. package/dist/store-meta.d.ts.map +1 -0
  32. package/dist/store-path.d.ts +77 -7
  33. package/dist/store-path.d.ts.map +1 -1
  34. package/dist/sync/apply.d.ts.map +1 -1
  35. package/dist/sync/shape-inbox.d.ts +1 -1
  36. package/dist/sync/types.d.ts +3 -3
  37. package/dist/testing.js.map +3 -3
  38. package/dist/worker/attach-sync-client.d.ts +300 -16
  39. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  40. package/dist/worker/define-sync-worker.d.ts +164 -23
  41. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  42. package/dist/worker/election-coordinator.d.ts +95 -0
  43. package/dist/worker/election-coordinator.d.ts.map +1 -0
  44. package/dist/worker/engine-control.d.ts +266 -0
  45. package/dist/worker/engine-control.d.ts.map +1 -0
  46. package/dist/worker/engine-router.d.ts +75 -0
  47. package/dist/worker/engine-router.d.ts.map +1 -0
  48. package/dist/worker/live-query-manager.d.ts.map +1 -1
  49. package/dist/worker/protocol.d.ts +47 -31
  50. package/dist/worker/protocol.d.ts.map +1 -1
  51. package/dist/worker/sw-placement.d.ts +37 -0
  52. package/dist/worker/sw-placement.d.ts.map +1 -0
  53. package/package.json +4 -3
  54. package/skills/core/SKILL.md +15 -12
  55. package/skills/operating/SKILL.md +142 -46
  56. package/src/adoption.ts +275 -0
  57. package/src/boot-report.ts +70 -17
  58. package/src/convergence.ts +2 -1
  59. package/src/export-store.ts +1 -1
  60. package/src/index.ts +1157 -115
  61. package/src/live-rows-sql.ts +1 -1
  62. package/src/local-store.ts +18 -40
  63. package/src/local-tables.ts +2 -2
  64. package/src/mutation.ts +115 -53
  65. package/src/mutations-api.ts +3 -3
  66. package/src/opfs-effects.ts +160 -0
  67. package/src/placement-probe.ts +168 -0
  68. package/src/schema.ts +17 -22
  69. package/src/store-boot.ts +343 -0
  70. package/src/store-lifecycle.ts +227 -0
  71. package/src/store-meta.ts +459 -0
  72. package/src/store-path.ts +197 -22
  73. package/src/sync/apply.ts +63 -63
  74. package/src/sync/index.ts +2 -2
  75. package/src/sync/shape-inbox.ts +1 -1
  76. package/src/sync/types.ts +3 -3
  77. package/src/testing.ts +2 -2
  78. package/src/worker/attach-sync-client.ts +1753 -102
  79. package/src/worker/define-sync-worker.ts +1034 -71
  80. package/src/worker/election-coordinator.ts +462 -0
  81. package/src/worker/engine-control.ts +379 -0
  82. package/src/worker/engine-router.ts +355 -0
  83. package/src/worker/live-query-manager.ts +4 -1
  84. package/src/worker/protocol.ts +46 -16
  85. package/src/worker/sw-placement.ts +64 -0
@@ -32,7 +32,7 @@ const LIVE_QUERY_TABLE_ALIAS = "__pgx_live";
32
32
  * keep DISTINCT values). `SELECT *` from the aliased derived table is safe precisely because the alias
33
33
  * list has already made the names unique.
34
34
  *
35
- * Returns the SQL UNCHANGED when `fields` is absent or empty — the backward-compatible path for existing
35
+ * Returns the SQL UNCHANGED when `fields` is absent or empty — the default path for
36
36
  * callers (raw SQL strings, or non-colliding queries that pass no `fields`): they keep name-keyed rows
37
37
  * exactly as before. Only a caller that supplies `fields` opts into alias-keyed rows.
38
38
  */
@@ -20,13 +20,6 @@ import {
20
20
  // its tests own (and mock).
21
21
  const metaQueryBuilder = drizzle.mock();
22
22
 
23
- /**
24
- * The fingerprint-keyed local store (ADR-0006). The registry fingerprint the local PGlite
25
- * database was provisioned under is recorded in the local-meta table; comparing it to the
26
- * current fingerprint on boot is how a registry change is *detected* (rather than a
27
- * hand-bumped `idb://…-vN` suffix), which drives the drain-then-drop read-cache rebuild.
28
- */
29
-
30
23
  /** A boot-time registry-version reconciliation outcome (ADR-0006 drain-then-drop). */
31
24
  export interface LocalStoreVersionEvent {
32
25
  status: "rebuilt" | "deferred";
@@ -36,13 +29,13 @@ export interface LocalStoreVersionEvent {
36
29
  owedMutations: number;
37
30
  }
38
31
 
39
- /** The minimal mutation-runtime surface the version reconciliation needs. */
32
+ /** The mutation-runtime surface required by registry reconciliation. */
40
33
  interface VersionReconcileRuntime {
41
34
  registryVersion: string;
42
35
  readMutationStats: () => Promise<MutationDiagnostics>;
43
36
  }
44
37
 
45
- /** The registry fingerprint the local store was last provisioned under, or null if unstamped. */
38
+ /** The registry fingerprint under which the local store was provisioned, or null if unstamped. */
46
39
  export async function readStoredRegistryFingerprint(
47
40
  db: MutationDb,
48
41
  registry: SyncTableRegistry,
@@ -79,7 +72,7 @@ export async function readActivatedLazyGroups(db: MutationDb, registry: SyncTabl
79
72
  return new Set(result.rows.map((row) => row.key.slice(LAZY_ACTIVATION_PREFIX.length)));
80
73
  }
81
74
 
82
- /** Upsert one meta key — the shared write shape for activations and the fingerprint stamp. */
75
+ /** Upsert one meta key — the shared write shape for activations, schema identity, and safety markers. */
83
76
  async function upsertMetaValue(db: MutationDb, registry: SyncTableRegistry, key: string, value: string): Promise<void> {
84
77
  const meta = getLocalMetaTable(registry);
85
78
  const query = metaQueryBuilder
@@ -113,7 +106,7 @@ export async function clearLazyGroupActivation(
113
106
  await db.query(query.sql, query.params as unknown[]);
114
107
  }
115
108
 
116
- /** Stamp the local store with the fingerprint it is now provisioned under. */
109
+ /** Stamp the local store with the registry fingerprint it is provisioned under. */
117
110
  export async function writeStoredRegistryFingerprint(
118
111
  db: MutationDb,
119
112
  registry: SyncTableRegistry,
@@ -123,9 +116,8 @@ export async function writeStoredRegistryFingerprint(
123
116
  }
124
117
 
125
118
  /**
126
- * The durable-schema fingerprint the local store was last provisioned under (slice 3 / proposal §3), or null
127
- * when unstamped (a legacy store, or a store whose durable schema was never executed under this feature).
128
- * Follows the raw-seam read shape of {@link readStoredRegistryFingerprint}.
119
+ * The durable-schema fingerprint the local store was last provisioned under, or null
120
+ * when initial provisioning has not completed.
129
121
  */
130
122
  export async function readStoredLocalSchemaFingerprint(
131
123
  db: MutationDb,
@@ -145,7 +137,7 @@ export async function readStoredLocalSchemaFingerprint(
145
137
 
146
138
  /**
147
139
  * Stamp the durable-schema fingerprint the store is now provisioned under (slice 3). Called ONLY after a
148
- * successful durable-schema exec — every full durable exec (boot fast-path miss, reconcile rebuild,
140
+ * successful durable-schema exec — every full durable exec (initial provisioning,
149
141
  * `dropReadCache`) and its stamp travel together, so the fingerprint never claims a schema that was not run.
150
142
  */
151
143
  export async function writeStoredLocalSchemaFingerprint(
@@ -157,10 +149,10 @@ export async function writeStoredLocalSchemaFingerprint(
157
149
  }
158
150
 
159
151
  /**
160
- * The durable recovery-required marker (warm-persisted-store-startup slice 2 / proposal §1). Its
152
+ * The durable recovery-required marker. Its
161
153
  * `pgxsinkit_local_meta` value is `"true"` while a `sending` journal row MAY have been committed since the
162
- * last clean settle, and `"false"` once pgxsinkit has PROVEN no `sending` row remains. Absent = a
163
- * pre-feature (legacy) store: run one conservative legacy recovery pass, then initialize the marker.
154
+ * last clean settle, and `"false"` once pgxsinkit has PROVEN no `sending` row remains. Absent means the
155
+ * store has not initialized the marker yet: run one conservative recovery pass, then initialize it.
164
156
  *
165
157
  * The invariant the whole slice protects: **the marker is never `"false"` while a committed `sending`
166
158
  * journal row exists.** It is upheld by marker-first ordering — {@link writeMutationRecoveryRequired}(true)
@@ -172,8 +164,7 @@ export const MUTATION_RECOVERY_REQUIRED_KEY = "mutation_recovery_required";
172
164
 
173
165
  /**
174
166
  * Read the durable recovery-required marker: `true`/`false` for the stored value, or `null` when the key is
175
- * absent (a legacy/pre-feature store). Follows the raw-seam read shape of
176
- * {@link readStoredRegistryFingerprint}.
167
+ * absent (the marker has not been initialized).
177
168
  *
178
169
  * FIX 4 (fail closed): the marker is a SAFETY marker — `false` is the ONLY value that skips recovery, so any
179
170
  * present value that is not exactly `"true"` or `"false"` (corruption, a future encoding, stray whitespace, a
@@ -208,7 +199,7 @@ export async function readMutationRecoveryRequired(
208
199
  /**
209
200
  * Upsert the durable recovery-required marker to `"true"`/`"false"` unconditionally. The `true` write is the
210
201
  * marker-first SET (awaited before the first `sending` transition of a dirty epoch); the `false` write
211
- * initializes an absent (legacy) marker AFTER a legacy recovery pass has guaranteed no `sending` row remains.
202
+ * initializes an absent marker AFTER a conservative recovery pass has guaranteed no `sending` row remains.
212
203
  */
213
204
  export async function writeMutationRecoveryRequired(
214
205
  db: MutationDb,
@@ -224,7 +215,7 @@ function writableTableKeys(registry: SyncTableRegistry): string[] {
224
215
  }
225
216
 
226
217
  /**
227
- * Self-verifying clear (proposal §1 rule 2): set the marker to `"false"` in ONE guarded, Drizzle-composed
218
+ * Self-verifying clear: set the marker to `"false"` in ONE guarded, Drizzle-composed
228
219
  * statement — but only where NOT EXISTS any `sending` row in ANY writable journal (the EXISTS-union is built
229
220
  * from the registry's journal Drizzle objects via {@link getJournalTable}). Correct regardless of JS
230
221
  * bookkeeping: a concurrent enqueue that committed a `sending` row makes the guard fail, so the marker stays
@@ -233,7 +224,7 @@ function writableTableKeys(registry: SyncTableRegistry): string[] {
233
224
  * row blocked it OR no marker row exists yet. Off the boot path AND at the end of a boot recovery pass.
234
225
  *
235
226
  * The marker row must already exist for this UPDATE to take effect; the absent-store INIT is a distinct
236
- * unconditional {@link writeMutationRecoveryRequired}(false) after the legacy pass (a pure guarded UPDATE
227
+ * unconditional {@link writeMutationRecoveryRequired}(false) after the initialization pass (a pure guarded UPDATE
237
228
  * cannot create the row, and drizzle-rc.4 cannot render a from-less guarded insert-select).
238
229
  */
239
230
  export async function clearMutationRecoveryMarkerIfSettled(
@@ -260,16 +251,9 @@ export async function clearMutationRecoveryMarkerIfSettled(
260
251
  }
261
252
 
262
253
  /**
263
- * Reconcile the local store against the current registry fingerprint (ADR-0006). A fresh
264
- * (unstamped) store is stamped; an unchanged fingerprint is a no-op. On a change, the read
265
- * cache is dropped and rebuilt at the new shape **only when nothing is owed locally** —
266
- * otherwise the rebuild is deferred (and retried on a later boot) so un-flushed/quarantined
267
- * writes are never silently dropped. The drain happens across sessions: pending writes flush
268
- * and reconcile during normal use, and the rebuild completes once the journal is clear.
269
- *
270
- * An unstamped store is always treated as brand-new. There is no pre-fingerprint-store path:
271
- * the fingerprint mechanism shipped before launch, so every store in existence was
272
- * provisioned with it (and a stamped store's journal therefore always has `registry_version`).
254
+ * Reconcile a store created by a supported release against the current registry fingerprint. An unstamped
255
+ * store is stamped; an unchanged fingerprint is a no-op. On a change, the read cache is rebuilt only when
256
+ * no mutations are owed. Otherwise the rebuild is deferred until a later boot, preserving local writes.
273
257
  */
274
258
  export async function reconcileLocalStoreVersion<TRegistry extends SyncTableRegistry>(args: {
275
259
  db: MutationDb;
@@ -293,11 +277,7 @@ export async function reconcileLocalStoreVersion<TRegistry extends SyncTableRegi
293
277
  return rebuildReadCacheOrDefer(args, stored);
294
278
  }
295
279
 
296
- /**
297
- * The drain-then-drop core (ADR-0006): rebuild the read cache at the current shape when
298
- * nothing is owed locally, otherwise defer so un-flushed/quarantined writes are never
299
- * dropped (the drain completes on a later boot).
300
- */
280
+ /** Rebuild the read cache after a clean drain, or defer while mutations remain owed. */
301
281
  async function rebuildReadCacheOrDefer<TRegistry extends SyncTableRegistry>(
302
282
  args: {
303
283
  db: MutationDb;
@@ -326,8 +306,6 @@ async function rebuildReadCacheOrDefer<TRegistry extends SyncTableRegistry>(
326
306
  await db.exec(buildWipeLocalStoreSql(registry));
327
307
  await db.exec(generateLocalSchemaSql(registry));
328
308
  await writeStoredRegistryFingerprint(db, registry, current);
329
- // This is a full durable-schema exec, so re-stamp the durable-schema fingerprint alongside the registry
330
- // fingerprint (slice 3): exec and stamp travel together, so the next boot's fast path can trust the skip.
331
309
  await writeStoredLocalSchemaFingerprint(db, registry, computeLocalSchemaFingerprint(registry));
332
310
  const event: LocalStoreVersionEvent = {
333
311
  status: "rebuilt",
@@ -80,7 +80,7 @@ function buildJournalFixedColumns() {
80
80
  mutationSeq: integer("mutation_seq").notNull(),
81
81
  mutationKind: varchar("mutation_kind", { length: 24 }).notNull(),
82
82
  status: varchar("status", { length: 24 }).notNull(),
83
- registryVersion: text("registry_version"),
83
+ registryVersion: text("registry_version").notNull(),
84
84
  baseServerVersion: bigintText("base_server_version"),
85
85
  writeUnit: text("write_unit"),
86
86
  writeMode: varchar("write_mode", { length: 24 }),
@@ -552,7 +552,7 @@ function buildAllMutationsViewColumns() {
552
552
  mutationSeq: integer("mutation_seq").notNull(),
553
553
  mutationKind: varchar("mutation_kind", { length: 24 }).notNull(),
554
554
  status: varchar("status", { length: 24 }).notNull(),
555
- registryVersion: text("registry_version"),
555
+ registryVersion: text("registry_version").notNull(),
556
556
  baseServerVersion: bigintText("base_server_version"),
557
557
  writeUnit: text("write_unit"),
558
558
  writeMode: varchar("write_mode", { length: 24 }),
package/src/mutation.ts CHANGED
@@ -166,8 +166,8 @@ export interface MutationDetail {
166
166
  nextRetryAtUs: string | null;
167
167
  serverUpdatedAtUs: string | null;
168
168
  updatedAtUs: string;
169
- /** Registry fingerprint (ADR-0004) the mutation was authored under, or null if unstamped. */
170
- registryVersion: string | null;
169
+ /** Registry fingerprint under which the mutation was authored. */
170
+ registryVersion: string;
171
171
  }
172
172
 
173
173
  export interface MutationDb {
@@ -181,20 +181,17 @@ export interface MutationDb {
181
181
  export interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistry> {
182
182
  db: MutationDb;
183
183
  registry: TRegistry;
184
- writeUrl: string;
184
+ batchWriteUrl: string;
185
185
  getAuthToken?: () => Promise<string | undefined>;
186
186
  /** Static headers added to every write request (e.g. a Supabase Cloud `apikey`); see {@link CreateSyncClientOptions.requestHeaders}. */
187
187
  requestHeaders?: Record<string, string>;
188
- /**
189
- * Registry fingerprint (ADR-0004) stamped onto each enqueued mutation as its
190
- * `registry_version`, so a version-boundary crossing is known before sending (ADR-0006).
191
- */
188
+ /** Registry fingerprint stamped onto each enqueued mutation; normally derived from {@link registry}. */
192
189
  registryVersion?: string;
193
190
  /**
194
191
  * Whether pgxsinkit owns the local schema (and therefore the `pgxsinkit_local_meta` table the durable
195
192
  * recovery-required marker lives in). Defaults to `true`. A caller-owned `pgliteInstance` boot sets this
196
- * `false`: the meta table may not exist, so the marker is never read/written and boot recovery falls back
197
- * to the legacy always-recover pass (proposal §1 caller-owned-PGlite constraint).
193
+ * `false`: the meta table may not exist, so the marker is never read/written and boot recovery runs
194
+ * unconditionally.
198
195
  */
199
196
  ownsMetaTable?: boolean;
200
197
  /**
@@ -323,7 +320,7 @@ interface TableContext {
323
320
  * The result of {@link MutationRuntime.runBootRecovery}, shaped to feed the `warmBoot` BootReport fields
324
321
  * directly (ADR-0034): whether the per-table recovery loop was skipped, whether recovery was required this
325
322
  * boot, how many writable journals were visited, and how many rows were lifted `sending → pending` (`null`
326
- * when the pass was legacy/uncounted, a real count on the marker-`true` path).
323
+ * when the selected pass is uncounted, a real count on the marker-`true` path).
327
324
  */
328
325
  export interface BootRecoveryOutcome {
329
326
  skipped: boolean;
@@ -333,7 +330,7 @@ export interface BootRecoveryOutcome {
333
330
  }
334
331
 
335
332
  export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
336
- /** The registry fingerprint (ADR-0004) this runtime stamps onto enqueued mutations. */
333
+ /** Registry fingerprint stamped onto mutations authored by this runtime. */
337
334
  registryVersion: string;
338
335
  create: <TKey extends SyncTableName<TRegistry>>(
339
336
  table: TKey,
@@ -382,19 +379,25 @@ export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
382
379
  */
383
380
  flushUnit: (unitId: string) => Promise<{ acks: MutationAck[] }>;
384
381
  reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;
382
+ /**
383
+ * Fire the runtime's dispose signal: abort every in-flight write-path fetch AND unblock any await parked on
384
+ * a stalled getAuthToken(). Called FIRST by the client's stop()/destroy() so teardown halts all write-network
385
+ * activity before it awaits the convergence pass. Idempotent; a disposed runtime performs no further network.
386
+ */
387
+ abortInFlight: () => void;
385
388
  retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
386
389
  recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;
387
390
  /**
388
- * Boot-time journal recovery driven by the durable recovery-required marker (proposal §1 / slice 2). The
391
+ * Boot-time journal recovery driven by the durable recovery-required marker. The
389
392
  * internal boot entry point that decides — from the marker and the boot mode — whether the per-table
390
393
  * `sending → pending` recovery loop runs at all, and clears/initializes the marker afterwards. It NEVER
391
394
  * runs from a consumer call ({@link recoverSending} keeps today's exact per-table semantics and never
392
395
  * touches the marker); {@link BootRecoveryOutcome} feeds the `warmBoot` BootReport fields verbatim.
393
396
  *
394
- * - `ownsMetaTable: false` (caller-owned PGlite) → legacy always-recover, marker untouched.
395
- * - `restore: true` → legacy recovery + {@link quarantineRecovered} + self-verifying clear (marker ignored).
397
+ * - `ownsMetaTable: false` (caller-owned PGlite) → unconditional recovery, marker untouched.
398
+ * - `restore: true` → unconditional recovery + {@link quarantineRecovered} + self-verifying clear (marker ignored).
396
399
  * - marker `false` → skip the loop entirely.
397
- * - marker absent (legacy store) → one legacy recovery pass, then initialize the marker.
400
+ * - marker absent (not initialized) → one conservative recovery pass, then initialize the marker.
398
401
  * - marker `true` → the N per-table updates PLUS the self-verifying clear, wrapped in one transaction.
399
402
  */
400
403
  runBootRecovery: (opts: { ownsMetaTable: boolean; restore: boolean }) => Promise<BootRecoveryOutcome>;
@@ -488,6 +491,7 @@ export function computeNextRetryAtUs(nowUs: string, attemptCount: number, random
488
491
  export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
489
492
  options: CreateMutationRuntimeOptions<TRegistry>,
490
493
  ): MutationRuntime<TRegistry> {
494
+ const mutationUrls = resolveMutationUrls(options.batchWriteUrl);
491
495
  const resolveAuthToken = async () => {
492
496
  if (options.getAuthToken) {
493
497
  return await options.getAuthToken();
@@ -507,16 +511,32 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
507
511
  const tableContexts = buildTableContexts(options.registry);
508
512
  const maxMutationAttempts = options.maxMutationAttempts ?? DEFAULT_MAX_MUTATION_ATTEMPTS;
509
513
  const flushBatchSize = options.flushBatchSize ?? DEFAULT_FLUSH_BATCH_SIZE;
510
- // The fingerprint (ADR-0004) stamped onto each enqueued mutation (ADR-0006). The runtime
511
- // owns the registry, so it derives this itself; an explicit override is honoured for tests.
512
514
  const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);
513
515
  let flushQueue = Promise.resolve();
514
516
 
517
+ // Teardown halt (see stop()/destroy()): a disposed runtime stops ALL activity at once. The signal is
518
+ // fired once by abortInFlight() and never reset. Every write-path fetch rides it (aborting an in-flight
519
+ // POST), and every getAuthToken() await is raced against it — the board's getAuthToken calls
520
+ // supabase.auth.getSession(), which can stall on token refresh (see flushBatch), so a fetch signal alone
521
+ // would not release teardown. On abort, flush()/flushUnit() reject promptly and the convergence pass settles.
522
+ const disposeController = new AbortController();
523
+ // Reject a pending await the instant the runtime is disposed. Cleans up its listener so per-flush use never leaks.
524
+ const untilAborted = <T>(work: Promise<T>): Promise<T> => {
525
+ if (disposeController.signal.aborted) {
526
+ return Promise.reject(new DOMException("Mutation runtime disposed", "AbortError"));
527
+ }
528
+ return new Promise<T>((resolve, reject) => {
529
+ const onAbort = () => reject(new DOMException("Mutation runtime disposed", "AbortError"));
530
+ disposeController.signal.addEventListener("abort", onAbort, { once: true });
531
+ work.then(resolve, reject).finally(() => disposeController.signal.removeEventListener("abort", onAbort));
532
+ });
533
+ };
534
+
515
535
  // Whether pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` table the durable
516
536
  // recovery-required marker lives in). A caller-owned PGlite boot sets this false, so the marker is never
517
- // touched and the SET/clear seams below are no-ops (proposal §1 caller-owned-PGlite constraint).
537
+ // touched and the SET/clear seams below are no-ops.
518
538
  const ownsMetaTable = options.ownsMetaTable ?? true;
519
- // Cached "this epoch has already committed the marker `true`" flag (slice 2). Marker-first ordering:
539
+ // Cached "this epoch has already committed the marker `true`" flag. Marker-first ordering:
520
540
  // `ensureRecoveryMarker` awaits ONE marker upsert before the first `sending` transition of a dirty epoch,
521
541
  // then flips this true, so steady-state flushing pays zero extra crossings. Reset to false only after the
522
542
  // self-verifying clear proves no `sending` row remains (`settleRecoveryMarker` / boot recovery).
@@ -547,7 +567,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
547
567
  };
548
568
 
549
569
  /**
550
- * Marker-first SET (proposal §1 rule 1, corrected): commit the marker `true` BEFORE the first
570
+ * Marker-first SET: commit the marker `true` BEFORE the first
551
571
  * pending→sending transition of a dirty epoch. Invoked from the ONE choke point (`applyMutationStatusUpdates`,
552
572
  * gated on a `sending` target) immediately before its UPDATE executes. The upsert auto-commits, so the
553
573
  * marker is durable before any `sending` row can commit — the invariant the whole slice protects.
@@ -991,7 +1011,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
991
1011
  const batchResult = await flushBatch(
992
1012
  options.db,
993
1013
  tableContexts as Record<string, TableContext>,
994
- options.writeUrl,
1014
+ mutationUrls.batch,
995
1015
  maxMutationAttempts,
996
1016
  flushBatchSize,
997
1017
  table,
@@ -999,6 +1019,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
999
1019
  options.requestHeaders,
1000
1020
  ensureRecoveryMarker,
1001
1021
  markSendingScope,
1022
+ disposeController.signal,
1002
1023
  );
1003
1024
 
1004
1025
  processedCount = batchResult.processedCount;
@@ -1121,6 +1142,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1121
1142
  flushQueue = nextFlush.catch(() => undefined);
1122
1143
  await nextFlush;
1123
1144
  },
1145
+ abortInFlight: () => disposeController.abort(),
1124
1146
  flushUnit: async (unitId) => {
1125
1147
  const contexts = Object.values(tableContexts).filter((context): context is TableContext => context != null);
1126
1148
  const unitRows = await readUnitPendingRows(options.db, contexts, unitId);
@@ -1200,22 +1222,25 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1200
1222
  ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),
1201
1223
  }));
1202
1224
 
1203
- const url = resolveAuthoritativeMutationUrl(options.writeUrl);
1225
+ const url = mutationUrls.authoritative;
1204
1226
  let acksByMutationId: Map<string, BatchMutationAck["acks"][number]>;
1205
1227
 
1206
1228
  try {
1207
- const authToken = await options.getAuthToken?.();
1229
+ const authToken = await untilAborted(Promise.resolve(options.getAuthToken?.()));
1208
1230
  let response = await fetch(url, {
1209
1231
  method: "POST",
1210
1232
  headers: buildRequestHeaders(authToken, options.requestHeaders),
1211
1233
  body: jsonStringifyPayload({ writeUnit: unitId, mutations }),
1234
+ signal: disposeController.signal,
1212
1235
  });
1213
1236
 
1214
1237
  if ([401, 403].includes(response.status) && options.getAuthToken) {
1238
+ const retryToken = await untilAborted(Promise.resolve(options.getAuthToken()));
1215
1239
  response = await fetch(url, {
1216
1240
  method: "POST",
1217
- headers: buildRequestHeaders(await options.getAuthToken(), options.requestHeaders),
1241
+ headers: buildRequestHeaders(retryToken, options.requestHeaders),
1218
1242
  body: jsonStringifyPayload({ writeUnit: unitId, mutations }),
1243
+ signal: disposeController.signal,
1219
1244
  });
1220
1245
  }
1221
1246
 
@@ -1414,13 +1439,13 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1414
1439
  const contexts = filterContexts(tableContexts, undefined);
1415
1440
  const tablesVisited = contexts.length;
1416
1441
 
1417
- // Caller-owned PGlite: the meta table may not exist, so never touch the marker — legacy always-recover.
1442
+ // Caller-owned PGlite: the meta table may not exist, so never touch the marker and always recover.
1418
1443
  if (!bootOwnsMetaTable) {
1419
1444
  await runtime.recoverSending();
1420
1445
  return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
1421
1446
  }
1422
1447
 
1423
- // Restore boot ignores the marker entirely (proposal §1): legacy recovery lifts any `sending` back to
1448
+ // Restore boot ignores the marker entirely: unconditional recovery lifts any `sending` back to
1424
1449
  // `pending`, quarantine parks every recovered non-terminal row, then the self-verifying clear settles
1425
1450
  // the marker (a clean marker in the backup must never bypass quarantine — quarantine ran first).
1426
1451
  if (restore) {
@@ -1437,7 +1462,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1437
1462
  return { skipped: true, required: false, tablesVisited: 0, rowsRecovered: 0 };
1438
1463
  }
1439
1464
 
1440
- // Marker absent (legacy/pre-feature store): one conservative recovery pass, then initialize the marker
1465
+ // Marker absent (not initialized): one conservative recovery pass, then initialize the marker
1441
1466
  // (the pass just guaranteed no `sending` row remains, so an unconditional `false` is correct).
1442
1467
  if (marker === null) {
1443
1468
  await runtime.recoverSending();
@@ -1587,7 +1612,7 @@ async function readMutationDetailsForContexts(
1587
1612
  nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as("nextRetryAtUs"),
1588
1613
  serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
1589
1614
  updatedAtUs: sql<string>`${journal.updatedAtUs}::text`.as("updatedAtUs"),
1590
- registryVersion: sql<string | null>`${journal.registryVersion}`.as("registryVersion"),
1615
+ registryVersion: sql<string>`${journal.registryVersion}`.as("registryVersion"),
1591
1616
  })
1592
1617
  .from(journal)
1593
1618
  .orderBy(desc(journal.updatedAtUs), desc(journal.mutationSeq))
@@ -1634,7 +1659,7 @@ interface MutationRow extends Record<string, unknown> {
1634
1659
  conflictReason: string | null;
1635
1660
  nextRetryAtUs: string | null;
1636
1661
  serverUpdatedAtUs: string | null;
1637
- registryVersion: string | null;
1662
+ registryVersion: string;
1638
1663
  }
1639
1664
 
1640
1665
  interface MutationDetailRow extends Record<string, unknown> {
@@ -1650,7 +1675,7 @@ interface MutationDetailRow extends Record<string, unknown> {
1650
1675
  nextRetryAtUs: string | null;
1651
1676
  serverUpdatedAtUs: string | null;
1652
1677
  updatedAtUs: string;
1653
- registryVersion: string | null;
1678
+ registryVersion: string;
1654
1679
  }
1655
1680
 
1656
1681
  interface CurrentRecordStateRow extends Record<string, unknown> {
@@ -1821,10 +1846,10 @@ function buildTableContext<TRegistry extends SyncTableRegistry>(
1821
1846
  : null;
1822
1847
 
1823
1848
  // Resolve the `nowMicroseconds` managed fields generically from governance, not by property name.
1824
- // `field.column` is a drizzle property key, but tolerate a column-name declaration too.
1849
+ // `field.column` is the canonical drizzle property key (registry validation rejects a column-name
1850
+ // declaration — ADR-0012), so match on the property key alone.
1825
1851
  const resolveManagedPropertyKey = (fieldColumn: string): string | undefined =>
1826
- columns.find((candidate) => candidate.propertyKey === fieldColumn || candidate.column.name === fieldColumn)
1827
- ?.propertyKey;
1852
+ columns.find((candidate) => candidate.propertyKey === fieldColumn)?.propertyKey;
1828
1853
  const nowMicrosecondsManagedFields = (entry.governance?.managedFields ?? []).filter(
1829
1854
  (field) => field.strategy === "nowMicroseconds",
1830
1855
  );
@@ -1972,6 +1997,15 @@ function createOptimisticRecordFromContext<TCreate, TRecord>(
1972
1997
  }
1973
1998
  }
1974
1999
 
2000
+ // Conventional audit-timestamp fill — distinct from the governance-driven fill below, not redundant
2001
+ // with it. The `createdAtUs`/`updatedAtUs` columns are conventionally NOT NULL with a SQL-expression
2002
+ // default (`pgxsinkit_clock_us()`, ADR-0004) the client cannot evaluate: `materializeColumnDefault`
2003
+ // leaves an unmaterialisable SQL default undefined, and the overlay INSERT then writes an explicit NULL
2004
+ // (overriding the table DEFAULT), violating the NOT NULL. This stamps them BY NAME regardless of
2005
+ // governance, so a table carrying `created_at_us` WITHOUT declaring it a `nowMicroseconds` managed field
2006
+ // (e.g. the `projects` fixture, whose only managed field is `updated_at_us`) still gets a valid
2007
+ // optimistic timestamp. The governance-driven fill below stamps only DECLARED managed fields, so it
2008
+ // cannot cover an undeclared-but-present conventional column — the two paths are complementary.
1975
2009
  if (hasProperty(context, "createdAtUs") && record["createdAtUs"] === undefined) {
1976
2010
  record["createdAtUs"] = nowUs;
1977
2011
  }
@@ -1980,9 +2014,10 @@ function createOptimisticRecordFromContext<TCreate, TRecord>(
1980
2014
  record["updatedAtUs"] = nowUs;
1981
2015
  }
1982
2016
 
1983
- // Generic managed-timestamp fill (governance-driven): stamp any `nowMicroseconds` managed field the
1984
- // convention block above did not — e.g. a Server version column not named `updated_at_us`. Additive
1985
- // and idempotent, so convention tables are unaffected (their fields are already filled).
2017
+ // Governance-driven managed-timestamp fill: stamp every `nowMicroseconds` managed field the convention
2018
+ // above did not reach — a Server version column not named `updated_at_us` (ADR-0010), or any
2019
+ // custom-named nowMicroseconds field. Idempotent with the convention fill (a conventionally-named
2020
+ // managed field is already stamped, so the `undefined` guard skips the re-stamp).
1986
2021
  for (const propertyKey of context.managedNowMicrosecondsPropertyKeys) {
1987
2022
  if (record[propertyKey] === undefined) {
1988
2023
  record[propertyKey] = nowUs;
@@ -2179,7 +2214,7 @@ async function insertMutationsBulk(
2179
2214
  db: MutationDb,
2180
2215
  context: TableContext,
2181
2216
  rows: ReadonlyArray<PlannedMutationInsert>,
2182
- registryVersion: string | null,
2217
+ registryVersion: string,
2183
2218
  unit?: WriteUnit,
2184
2219
  ) {
2185
2220
  if (rows.length === 0) {
@@ -2343,7 +2378,7 @@ function buildEntityInputJoin(pkColumnNames: string[], pkColumns: PgColumn[]): S
2343
2378
  interface PendingBatchRow extends MutationRow {
2344
2379
  tableKey: string;
2345
2380
  enqueuedAtUs: string;
2346
- /** The resolved Base server version (ADR-0015), or null when the table predates the policy. */
2381
+ /** The resolved Base server version (ADR-0015), or null for a create or blind write. */
2347
2382
  baseServerVersion: string | null;
2348
2383
  }
2349
2384
 
@@ -2540,10 +2575,22 @@ async function readUnitPendingRows(
2540
2575
  return result.rows;
2541
2576
  }
2542
2577
 
2578
+ // Race a promise against an AbortSignal so a disposed runtime's teardown never parks on it (mirrors
2579
+ // createMutationRuntime's untilAborted; used by the module-level flushBatch). A missing signal is a passthrough.
2580
+ function raceAbort<T>(work: Promise<T>, signal?: AbortSignal): Promise<T> {
2581
+ if (!signal) return work;
2582
+ if (signal.aborted) return Promise.reject(new DOMException("Mutation runtime disposed", "AbortError"));
2583
+ return new Promise<T>((resolve, reject) => {
2584
+ const onAbort = () => reject(new DOMException("Mutation runtime disposed", "AbortError"));
2585
+ signal.addEventListener("abort", onAbort, { once: true });
2586
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
2587
+ });
2588
+ }
2589
+
2543
2590
  async function flushBatch(
2544
2591
  db: MutationDb,
2545
2592
  tableContexts: Record<string, TableContext>,
2546
- batchWriteUrl: string,
2593
+ batchMutationUrl: string,
2547
2594
  maxAttempts: number,
2548
2595
  batchSize: number,
2549
2596
  tableFilter?: string,
@@ -2551,6 +2598,7 @@ async function flushBatch(
2551
2598
  requestHeaders?: Record<string, string>,
2552
2599
  ensureRecoveryMarker?: () => Promise<void>,
2553
2600
  markSendingScope?: MarkSendingScope,
2601
+ signal?: AbortSignal,
2554
2602
  ): Promise<FlushBatchResult> {
2555
2603
  const contexts = filterContexts(tableContexts, tableFilter);
2556
2604
  const nowUs = nowMicroseconds();
@@ -2653,21 +2701,19 @@ async function flushBatch(
2653
2701
  payload: row.envelopePayload,
2654
2702
  clientTimestampUs: sentAtUs,
2655
2703
  // ADR-0015: carry the resolved Base server version so the applier can detect a stale write.
2656
- // Omitted for a create / a table that predates the policy (null) — then no stale check runs.
2704
+ // Omitted for a create or blind write (null) — then no stale check runs.
2657
2705
  ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),
2658
2706
  };
2659
2707
  });
2660
2708
 
2661
2709
  let responseOk = false;
2662
2710
  let acksByMutationId: Map<string, BatchMutationAck["acks"][number]> = new Map();
2663
- const batchMutationUrl = resolveBatchMutationUrl(batchWriteUrl);
2664
-
2665
2711
  try {
2666
2712
  // Resolve the auth token and the network round-trip separately: in the board, `getAuthToken` calls
2667
2713
  // `supabase.auth.getSession()` per send, which can itself stall (token refresh) and would otherwise
2668
2714
  // be invisibly folded into "the write was slow".
2669
2715
  const authStart = typeof performance !== "undefined" ? performance.now() : Date.now();
2670
- const authToken = await getAuthToken?.();
2716
+ const authToken = await raceAbort(getAuthToken?.() ?? Promise.resolve(undefined), signal);
2671
2717
  const fetchStart = typeof performance !== "undefined" ? performance.now() : Date.now();
2672
2718
  syncDebug("board-write auth token resolved", { ms: Math.round(fetchStart - authStart) });
2673
2719
 
@@ -2675,13 +2721,15 @@ async function flushBatch(
2675
2721
  method: "POST",
2676
2722
  headers: buildRequestHeaders(authToken, requestHeaders),
2677
2723
  body: jsonStringifyPayload({ mutations }),
2724
+ signal: signal ?? null,
2678
2725
  });
2679
2726
 
2680
2727
  if ([401, 403].includes(response.status) && getAuthToken) {
2681
2728
  response = await fetch(batchMutationUrl, {
2682
2729
  method: "POST",
2683
- headers: buildRequestHeaders(await getAuthToken(), requestHeaders),
2730
+ headers: buildRequestHeaders(await raceAbort(getAuthToken(), signal), requestHeaders),
2684
2731
  body: jsonStringifyPayload({ mutations }),
2732
+ signal: signal ?? null,
2685
2733
  });
2686
2734
  }
2687
2735
 
@@ -2929,19 +2977,33 @@ function resolveBatchFailureOutcome(
2929
2977
  return { status: "failed", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };
2930
2978
  }
2931
2979
 
2932
- function resolveBatchMutationUrl(batchWriteUrl: string): string {
2933
- const trimmed = batchWriteUrl.replace(/\/+$/, "");
2980
+ function invalidBatchWriteUrl(): Error {
2981
+ return new Error(
2982
+ '[pgxsinkit] batchWriteUrl must be "/api/mutations" or an absolute deployment URL ending in "/api/mutations"',
2983
+ );
2984
+ }
2934
2985
 
2935
- if (trimmed.endsWith("/mutations")) {
2936
- return trimmed;
2986
+ function resolveMutationUrls(batchWriteUrl: string): { batch: string; authoritative: string } {
2987
+ if (batchWriteUrl.trim() !== batchWriteUrl || batchWriteUrl.length === 0) {
2988
+ throw invalidBatchWriteUrl();
2937
2989
  }
2938
2990
 
2939
- return `${trimmed}/mutations`;
2940
- }
2991
+ const isRelative = batchWriteUrl.startsWith("/") && !batchWriteUrl.startsWith("//");
2992
+ let parsed: URL;
2993
+ try {
2994
+ parsed = isRelative ? new URL(batchWriteUrl, "https://pgxsinkit.invalid") : new URL(batchWriteUrl);
2995
+ } catch {
2996
+ throw invalidBatchWriteUrl();
2997
+ }
2998
+
2999
+ const hasCanonicalPath = isRelative
3000
+ ? parsed.pathname === "/api/mutations"
3001
+ : ["http:", "https:"].includes(parsed.protocol) && parsed.pathname.endsWith("/api/mutations");
3002
+ if (!hasCanonicalPath || parsed.search !== "" || parsed.hash !== "") {
3003
+ throw invalidBatchWriteUrl();
3004
+ }
2941
3005
 
2942
- /** The authoritative (pessimistic) write endpoint (ADR-0022): the batch URL with `/unit` appended. */
2943
- function resolveAuthoritativeMutationUrl(batchWriteUrl: string): string {
2944
- return `${resolveBatchMutationUrl(batchWriteUrl)}/unit`;
3006
+ return { batch: batchWriteUrl, authoritative: `${batchWriteUrl}/unit` };
2945
3007
  }
2946
3008
 
2947
3009
  function stripManagedFields(
@@ -1,4 +1,4 @@
1
- // The registry-wide reactive mutation-status API (warm-persisted-store-startup slice 4 / proposal §5,
1
+ // The registry-wide reactive mutation-status API (the current warm-store observability contract,
2
2
  // option 1). `client.mutations.*` lets a consumer render a global sync indicator or diagnostics screen with
3
3
  // ONE subscription over the `pgxsinkit_all_mutations` view (schema.ts) instead of one live query per writable
4
4
  // journal — the O(writable-table) fan-out the proposal set out to remove.
@@ -115,7 +115,7 @@ interface DetailRow extends Record<string, unknown> {
115
115
  nextRetryAtUs: string | null;
116
116
  serverUpdatedAtUs: string | null;
117
117
  updatedAtUs: string;
118
- registryVersion: string | null;
118
+ registryVersion: string;
119
119
  }
120
120
 
121
121
  /** The seams the factory needs — shared verbatim by both client modes (zero worker-protocol change). */
@@ -246,7 +246,7 @@ function buildDetailSql<TRegistry extends SyncTableRegistry>(
246
246
  nextRetryAtUs: sql<string | null>`${view.nextRetryAtUs}::text`.as("nextRetryAtUs"),
247
247
  serverUpdatedAtUs: sql<string | null>`${view.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
248
248
  updatedAtUs: sql<string>`${view.updatedAtUs}::text`.as("updatedAtUs"),
249
- registryVersion: sql<string | null>`${view.registryVersion}`.as("registryVersion"),
249
+ registryVersion: sql<string>`${view.registryVersion}`.as("registryVersion"),
250
250
  })
251
251
  .from(view)
252
252
  .where(conditions.length > 0 ? and(...conditions) : undefined)