@pgxsinkit/client 0.1.51 → 0.2.0

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 (96) 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/error-chain.d.ts +9 -0
  9. package/dist/error-chain.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts.map +1 -1
  11. package/dist/export-store.d.ts +1 -1
  12. package/dist/export-store.d.ts.map +1 -1
  13. package/dist/index.d.ts +309 -38
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +4628 -1489
  16. package/dist/index.js.map +36 -24
  17. package/dist/live-rows-sql.d.ts +1 -1
  18. package/dist/local-store.d.ts +16 -31
  19. package/dist/local-store.d.ts.map +1 -1
  20. package/dist/local-tables.d.ts +10 -4
  21. package/dist/local-tables.d.ts.map +1 -1
  22. package/dist/mutation.d.ts +12 -15
  23. package/dist/mutation.d.ts.map +1 -1
  24. package/dist/opfs-effects.d.ts +51 -0
  25. package/dist/opfs-effects.d.ts.map +1 -0
  26. package/dist/placement-probe.d.ts +75 -0
  27. package/dist/placement-probe.d.ts.map +1 -0
  28. package/dist/schema.d.ts +11 -16
  29. package/dist/schema.d.ts.map +1 -1
  30. package/dist/store-boot.d.ts +77 -0
  31. package/dist/store-boot.d.ts.map +1 -0
  32. package/dist/store-lifecycle.d.ts +153 -0
  33. package/dist/store-lifecycle.d.ts.map +1 -0
  34. package/dist/store-meta.d.ts +190 -0
  35. package/dist/store-meta.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +77 -7
  37. package/dist/store-path.d.ts.map +1 -1
  38. package/dist/sync/apply.d.ts +12 -1
  39. package/dist/sync/apply.d.ts.map +1 -1
  40. package/dist/sync/index.d.ts.map +1 -1
  41. package/dist/sync/shape-inbox.d.ts +1 -1
  42. package/dist/sync/types.d.ts +3 -3
  43. package/dist/testing.js.map +3 -3
  44. package/dist/worker/attach-sync-client.d.ts +239 -13
  45. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  46. package/dist/worker/define-sync-worker.d.ts +162 -5
  47. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  48. package/dist/worker/election-coordinator.d.ts +95 -0
  49. package/dist/worker/election-coordinator.d.ts.map +1 -0
  50. package/dist/worker/engine-control.d.ts +265 -0
  51. package/dist/worker/engine-control.d.ts.map +1 -0
  52. package/dist/worker/engine-router.d.ts +75 -0
  53. package/dist/worker/engine-router.d.ts.map +1 -0
  54. package/dist/worker/live-query-manager.d.ts.map +1 -1
  55. package/dist/worker/live-query-params-guard.d.ts +14 -0
  56. package/dist/worker/live-query-params-guard.d.ts.map +1 -0
  57. package/dist/worker/protocol.d.ts +32 -11
  58. package/dist/worker/protocol.d.ts.map +1 -1
  59. package/dist/worker/sw-placement.d.ts +37 -0
  60. package/dist/worker/sw-placement.d.ts.map +1 -0
  61. package/package.json +4 -3
  62. package/skills/core/SKILL.md +15 -8
  63. package/skills/operating/SKILL.md +114 -34
  64. package/src/adoption.ts +275 -0
  65. package/src/boot-report.ts +70 -17
  66. package/src/convergence.ts +2 -1
  67. package/src/error-chain.ts +26 -0
  68. package/src/export-dump.ts +5 -1
  69. package/src/export-store.ts +1 -1
  70. package/src/index.ts +1246 -118
  71. package/src/live-rows-sql.ts +1 -1
  72. package/src/local-store.ts +18 -40
  73. package/src/local-tables.ts +9 -2
  74. package/src/mutation.ts +67 -49
  75. package/src/mutations-api.ts +3 -3
  76. package/src/opfs-effects.ts +160 -0
  77. package/src/placement-probe.ts +168 -0
  78. package/src/schema.ts +17 -22
  79. package/src/store-boot.ts +343 -0
  80. package/src/store-lifecycle.ts +227 -0
  81. package/src/store-meta.ts +459 -0
  82. package/src/store-path.ts +197 -22
  83. package/src/sync/apply.ts +227 -89
  84. package/src/sync/index.ts +33 -9
  85. package/src/sync/shape-inbox.ts +1 -1
  86. package/src/sync/types.ts +3 -3
  87. package/src/testing.ts +2 -2
  88. package/src/worker/attach-sync-client.ts +1675 -117
  89. package/src/worker/define-sync-worker.ts +810 -50
  90. package/src/worker/election-coordinator.ts +462 -0
  91. package/src/worker/engine-control.ts +379 -0
  92. package/src/worker/engine-router.ts +355 -0
  93. package/src/worker/live-query-manager.ts +10 -1
  94. package/src/worker/live-query-params-guard.ts +57 -0
  95. package/src/worker/protocol.ts +41 -10
  96. 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 }),
@@ -492,6 +492,12 @@ export interface ApplyTarget {
492
492
  propertyKeyByName: Record<string, string>;
493
493
  /** Primary-key column NAMES, in order (from the entry, local-projection override honoured). */
494
494
  primaryKey: string[];
495
+ /**
496
+ * CDC insert-apply policy (ADR-0045), from the entry. `"insert"` (default) applies a CDC insert as a
497
+ * plain INSERT so a genuine PK collision surfaces; `"upsert"` applies it idempotently (ON CONFLICT DO
498
+ * UPDATE) because this table legitimately receives locally-derived provisional rows.
499
+ */
500
+ applyMode: "insert" | "upsert";
495
501
  /** Model-derived column types (`deriveSyncColumnTypes`), keyed by DB column name via `.name`. */
496
502
  columnTypes: SyncColumnType[];
497
503
  /**
@@ -525,6 +531,7 @@ export function resolveApplyTarget<TRegistry extends SyncTableRegistry, TKey ext
525
531
  columnByName,
526
532
  propertyKeyByName,
527
533
  primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry),
534
+ applyMode: entry.applyMode,
528
535
  columnTypes: deriveSyncColumnTypes(entry),
529
536
  insertRenderCache: new Map(),
530
537
  };
@@ -545,7 +552,7 @@ function buildAllMutationsViewColumns() {
545
552
  mutationSeq: integer("mutation_seq").notNull(),
546
553
  mutationKind: varchar("mutation_kind", { length: 24 }).notNull(),
547
554
  status: varchar("status", { length: 24 }).notNull(),
548
- registryVersion: text("registry_version"),
555
+ registryVersion: text("registry_version").notNull(),
549
556
  baseServerVersion: bigintText("base_server_version"),
550
557
  writeUnit: text("write_unit"),
551
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,
@@ -385,16 +382,16 @@ export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
385
382
  retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
386
383
  recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;
387
384
  /**
388
- * Boot-time journal recovery driven by the durable recovery-required marker (proposal §1 / slice 2). The
385
+ * Boot-time journal recovery driven by the durable recovery-required marker. The
389
386
  * internal boot entry point that decides — from the marker and the boot mode — whether the per-table
390
387
  * `sending → pending` recovery loop runs at all, and clears/initializes the marker afterwards. It NEVER
391
388
  * runs from a consumer call ({@link recoverSending} keeps today's exact per-table semantics and never
392
389
  * touches the marker); {@link BootRecoveryOutcome} feeds the `warmBoot` BootReport fields verbatim.
393
390
  *
394
- * - `ownsMetaTable: false` (caller-owned PGlite) → legacy always-recover, marker untouched.
395
- * - `restore: true` → legacy recovery + {@link quarantineRecovered} + self-verifying clear (marker ignored).
391
+ * - `ownsMetaTable: false` (caller-owned PGlite) → unconditional recovery, marker untouched.
392
+ * - `restore: true` → unconditional recovery + {@link quarantineRecovered} + self-verifying clear (marker ignored).
396
393
  * - marker `false` → skip the loop entirely.
397
- * - marker absent (legacy store) → one legacy recovery pass, then initialize the marker.
394
+ * - marker absent (not initialized) → one conservative recovery pass, then initialize the marker.
398
395
  * - marker `true` → the N per-table updates PLUS the self-verifying clear, wrapped in one transaction.
399
396
  */
400
397
  runBootRecovery: (opts: { ownsMetaTable: boolean; restore: boolean }) => Promise<BootRecoveryOutcome>;
@@ -488,6 +485,7 @@ export function computeNextRetryAtUs(nowUs: string, attemptCount: number, random
488
485
  export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
489
486
  options: CreateMutationRuntimeOptions<TRegistry>,
490
487
  ): MutationRuntime<TRegistry> {
488
+ const mutationUrls = resolveMutationUrls(options.batchWriteUrl);
491
489
  const resolveAuthToken = async () => {
492
490
  if (options.getAuthToken) {
493
491
  return await options.getAuthToken();
@@ -507,16 +505,14 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
507
505
  const tableContexts = buildTableContexts(options.registry);
508
506
  const maxMutationAttempts = options.maxMutationAttempts ?? DEFAULT_MAX_MUTATION_ATTEMPTS;
509
507
  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
508
  const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);
513
509
  let flushQueue = Promise.resolve();
514
510
 
515
511
  // Whether pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` table the durable
516
512
  // 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).
513
+ // touched and the SET/clear seams below are no-ops.
518
514
  const ownsMetaTable = options.ownsMetaTable ?? true;
519
- // Cached "this epoch has already committed the marker `true`" flag (slice 2). Marker-first ordering:
515
+ // Cached "this epoch has already committed the marker `true`" flag. Marker-first ordering:
520
516
  // `ensureRecoveryMarker` awaits ONE marker upsert before the first `sending` transition of a dirty epoch,
521
517
  // then flips this true, so steady-state flushing pays zero extra crossings. Reset to false only after the
522
518
  // self-verifying clear proves no `sending` row remains (`settleRecoveryMarker` / boot recovery).
@@ -547,7 +543,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
547
543
  };
548
544
 
549
545
  /**
550
- * Marker-first SET (proposal §1 rule 1, corrected): commit the marker `true` BEFORE the first
546
+ * Marker-first SET: commit the marker `true` BEFORE the first
551
547
  * pending→sending transition of a dirty epoch. Invoked from the ONE choke point (`applyMutationStatusUpdates`,
552
548
  * gated on a `sending` target) immediately before its UPDATE executes. The upsert auto-commits, so the
553
549
  * marker is durable before any `sending` row can commit — the invariant the whole slice protects.
@@ -991,7 +987,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
991
987
  const batchResult = await flushBatch(
992
988
  options.db,
993
989
  tableContexts as Record<string, TableContext>,
994
- options.writeUrl,
990
+ mutationUrls.batch,
995
991
  maxMutationAttempts,
996
992
  flushBatchSize,
997
993
  table,
@@ -1200,7 +1196,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1200
1196
  ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),
1201
1197
  }));
1202
1198
 
1203
- const url = resolveAuthoritativeMutationUrl(options.writeUrl);
1199
+ const url = mutationUrls.authoritative;
1204
1200
  let acksByMutationId: Map<string, BatchMutationAck["acks"][number]>;
1205
1201
 
1206
1202
  try {
@@ -1414,13 +1410,13 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1414
1410
  const contexts = filterContexts(tableContexts, undefined);
1415
1411
  const tablesVisited = contexts.length;
1416
1412
 
1417
- // Caller-owned PGlite: the meta table may not exist, so never touch the marker — legacy always-recover.
1413
+ // Caller-owned PGlite: the meta table may not exist, so never touch the marker and always recover.
1418
1414
  if (!bootOwnsMetaTable) {
1419
1415
  await runtime.recoverSending();
1420
1416
  return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
1421
1417
  }
1422
1418
 
1423
- // Restore boot ignores the marker entirely (proposal §1): legacy recovery lifts any `sending` back to
1419
+ // Restore boot ignores the marker entirely: unconditional recovery lifts any `sending` back to
1424
1420
  // `pending`, quarantine parks every recovered non-terminal row, then the self-verifying clear settles
1425
1421
  // the marker (a clean marker in the backup must never bypass quarantine — quarantine ran first).
1426
1422
  if (restore) {
@@ -1437,7 +1433,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1437
1433
  return { skipped: true, required: false, tablesVisited: 0, rowsRecovered: 0 };
1438
1434
  }
1439
1435
 
1440
- // Marker absent (legacy/pre-feature store): one conservative recovery pass, then initialize the marker
1436
+ // Marker absent (not initialized): one conservative recovery pass, then initialize the marker
1441
1437
  // (the pass just guaranteed no `sending` row remains, so an unconditional `false` is correct).
1442
1438
  if (marker === null) {
1443
1439
  await runtime.recoverSending();
@@ -1587,7 +1583,7 @@ async function readMutationDetailsForContexts(
1587
1583
  nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as("nextRetryAtUs"),
1588
1584
  serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
1589
1585
  updatedAtUs: sql<string>`${journal.updatedAtUs}::text`.as("updatedAtUs"),
1590
- registryVersion: sql<string | null>`${journal.registryVersion}`.as("registryVersion"),
1586
+ registryVersion: sql<string>`${journal.registryVersion}`.as("registryVersion"),
1591
1587
  })
1592
1588
  .from(journal)
1593
1589
  .orderBy(desc(journal.updatedAtUs), desc(journal.mutationSeq))
@@ -1634,7 +1630,7 @@ interface MutationRow extends Record<string, unknown> {
1634
1630
  conflictReason: string | null;
1635
1631
  nextRetryAtUs: string | null;
1636
1632
  serverUpdatedAtUs: string | null;
1637
- registryVersion: string | null;
1633
+ registryVersion: string;
1638
1634
  }
1639
1635
 
1640
1636
  interface MutationDetailRow extends Record<string, unknown> {
@@ -1650,7 +1646,7 @@ interface MutationDetailRow extends Record<string, unknown> {
1650
1646
  nextRetryAtUs: string | null;
1651
1647
  serverUpdatedAtUs: string | null;
1652
1648
  updatedAtUs: string;
1653
- registryVersion: string | null;
1649
+ registryVersion: string;
1654
1650
  }
1655
1651
 
1656
1652
  interface CurrentRecordStateRow extends Record<string, unknown> {
@@ -1821,10 +1817,10 @@ function buildTableContext<TRegistry extends SyncTableRegistry>(
1821
1817
  : null;
1822
1818
 
1823
1819
  // 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.
1820
+ // `field.column` is the canonical drizzle property key (registry validation rejects a column-name
1821
+ // declaration — ADR-0012), so match on the property key alone.
1825
1822
  const resolveManagedPropertyKey = (fieldColumn: string): string | undefined =>
1826
- columns.find((candidate) => candidate.propertyKey === fieldColumn || candidate.column.name === fieldColumn)
1827
- ?.propertyKey;
1823
+ columns.find((candidate) => candidate.propertyKey === fieldColumn)?.propertyKey;
1828
1824
  const nowMicrosecondsManagedFields = (entry.governance?.managedFields ?? []).filter(
1829
1825
  (field) => field.strategy === "nowMicroseconds",
1830
1826
  );
@@ -1972,6 +1968,15 @@ function createOptimisticRecordFromContext<TCreate, TRecord>(
1972
1968
  }
1973
1969
  }
1974
1970
 
1971
+ // Conventional audit-timestamp fill — distinct from the governance-driven fill below, not redundant
1972
+ // with it. The `createdAtUs`/`updatedAtUs` columns are conventionally NOT NULL with a SQL-expression
1973
+ // default (`pgxsinkit_clock_us()`, ADR-0004) the client cannot evaluate: `materializeColumnDefault`
1974
+ // leaves an unmaterialisable SQL default undefined, and the overlay INSERT then writes an explicit NULL
1975
+ // (overriding the table DEFAULT), violating the NOT NULL. This stamps them BY NAME regardless of
1976
+ // governance, so a table carrying `created_at_us` WITHOUT declaring it a `nowMicroseconds` managed field
1977
+ // (e.g. the `projects` fixture, whose only managed field is `updated_at_us`) still gets a valid
1978
+ // optimistic timestamp. The governance-driven fill below stamps only DECLARED managed fields, so it
1979
+ // cannot cover an undeclared-but-present conventional column — the two paths are complementary.
1975
1980
  if (hasProperty(context, "createdAtUs") && record["createdAtUs"] === undefined) {
1976
1981
  record["createdAtUs"] = nowUs;
1977
1982
  }
@@ -1980,9 +1985,10 @@ function createOptimisticRecordFromContext<TCreate, TRecord>(
1980
1985
  record["updatedAtUs"] = nowUs;
1981
1986
  }
1982
1987
 
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).
1988
+ // Governance-driven managed-timestamp fill: stamp every `nowMicroseconds` managed field the convention
1989
+ // above did not reach — a Server version column not named `updated_at_us` (ADR-0010), or any
1990
+ // custom-named nowMicroseconds field. Idempotent with the convention fill (a conventionally-named
1991
+ // managed field is already stamped, so the `undefined` guard skips the re-stamp).
1986
1992
  for (const propertyKey of context.managedNowMicrosecondsPropertyKeys) {
1987
1993
  if (record[propertyKey] === undefined) {
1988
1994
  record[propertyKey] = nowUs;
@@ -2179,7 +2185,7 @@ async function insertMutationsBulk(
2179
2185
  db: MutationDb,
2180
2186
  context: TableContext,
2181
2187
  rows: ReadonlyArray<PlannedMutationInsert>,
2182
- registryVersion: string | null,
2188
+ registryVersion: string,
2183
2189
  unit?: WriteUnit,
2184
2190
  ) {
2185
2191
  if (rows.length === 0) {
@@ -2343,7 +2349,7 @@ function buildEntityInputJoin(pkColumnNames: string[], pkColumns: PgColumn[]): S
2343
2349
  interface PendingBatchRow extends MutationRow {
2344
2350
  tableKey: string;
2345
2351
  enqueuedAtUs: string;
2346
- /** The resolved Base server version (ADR-0015), or null when the table predates the policy. */
2352
+ /** The resolved Base server version (ADR-0015), or null for a create or blind write. */
2347
2353
  baseServerVersion: string | null;
2348
2354
  }
2349
2355
 
@@ -2543,7 +2549,7 @@ async function readUnitPendingRows(
2543
2549
  async function flushBatch(
2544
2550
  db: MutationDb,
2545
2551
  tableContexts: Record<string, TableContext>,
2546
- batchWriteUrl: string,
2552
+ batchMutationUrl: string,
2547
2553
  maxAttempts: number,
2548
2554
  batchSize: number,
2549
2555
  tableFilter?: string,
@@ -2653,15 +2659,13 @@ async function flushBatch(
2653
2659
  payload: row.envelopePayload,
2654
2660
  clientTimestampUs: sentAtUs,
2655
2661
  // 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.
2662
+ // Omitted for a create or blind write (null) — then no stale check runs.
2657
2663
  ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),
2658
2664
  };
2659
2665
  });
2660
2666
 
2661
2667
  let responseOk = false;
2662
2668
  let acksByMutationId: Map<string, BatchMutationAck["acks"][number]> = new Map();
2663
- const batchMutationUrl = resolveBatchMutationUrl(batchWriteUrl);
2664
-
2665
2669
  try {
2666
2670
  // Resolve the auth token and the network round-trip separately: in the board, `getAuthToken` calls
2667
2671
  // `supabase.auth.getSession()` per send, which can itself stall (token refresh) and would otherwise
@@ -2929,19 +2933,33 @@ function resolveBatchFailureOutcome(
2929
2933
  return { status: "failed", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };
2930
2934
  }
2931
2935
 
2932
- function resolveBatchMutationUrl(batchWriteUrl: string): string {
2933
- const trimmed = batchWriteUrl.replace(/\/+$/, "");
2936
+ function invalidBatchWriteUrl(): Error {
2937
+ return new Error(
2938
+ '[pgxsinkit] batchWriteUrl must be "/api/mutations" or an absolute deployment URL ending in "/api/mutations"',
2939
+ );
2940
+ }
2941
+
2942
+ function resolveMutationUrls(batchWriteUrl: string): { batch: string; authoritative: string } {
2943
+ if (batchWriteUrl.trim() !== batchWriteUrl || batchWriteUrl.length === 0) {
2944
+ throw invalidBatchWriteUrl();
2945
+ }
2934
2946
 
2935
- if (trimmed.endsWith("/mutations")) {
2936
- return trimmed;
2947
+ const isRelative = batchWriteUrl.startsWith("/") && !batchWriteUrl.startsWith("//");
2948
+ let parsed: URL;
2949
+ try {
2950
+ parsed = isRelative ? new URL(batchWriteUrl, "https://pgxsinkit.invalid") : new URL(batchWriteUrl);
2951
+ } catch {
2952
+ throw invalidBatchWriteUrl();
2937
2953
  }
2938
2954
 
2939
- return `${trimmed}/mutations`;
2940
- }
2955
+ const hasCanonicalPath = isRelative
2956
+ ? parsed.pathname === "/api/mutations"
2957
+ : ["http:", "https:"].includes(parsed.protocol) && parsed.pathname.endsWith("/api/mutations");
2958
+ if (!hasCanonicalPath || parsed.search !== "" || parsed.hash !== "") {
2959
+ throw invalidBatchWriteUrl();
2960
+ }
2941
2961
 
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`;
2962
+ return { batch: batchWriteUrl, authoritative: `${batchWriteUrl}/unit` };
2945
2963
  }
2946
2964
 
2947
2965
  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)