@pgxsinkit/client 0.1.32 → 0.1.40

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 (111) hide show
  1. package/README.md +11 -0
  2. package/dist/boot-report.d.ts +134 -0
  3. package/dist/boot-report.d.ts.map +1 -0
  4. package/dist/convergence.d.ts +76 -0
  5. package/dist/convergence.d.ts.map +1 -0
  6. package/dist/debug.d.ts +34 -0
  7. package/dist/debug.d.ts.map +1 -0
  8. package/dist/export-data.d.ts +100 -0
  9. package/dist/export-data.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts +92 -0
  11. package/dist/export-dump.d.ts.map +1 -0
  12. package/dist/export-store.d.ts +214 -0
  13. package/dist/export-store.d.ts.map +1 -0
  14. package/dist/index.d.ts +615 -8
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8083 -2286
  17. package/dist/index.js.map +81 -44
  18. package/dist/lazy-guard.d.ts +59 -0
  19. package/dist/lazy-guard.d.ts.map +1 -0
  20. package/dist/lifecycle-slot.d.ts +31 -0
  21. package/dist/lifecycle-slot.d.ts.map +1 -0
  22. package/dist/live-rows-sql.d.ts +21 -0
  23. package/dist/live-rows-sql.d.ts.map +1 -0
  24. package/dist/local-store.d.ts +56 -0
  25. package/dist/local-store.d.ts.map +1 -0
  26. package/dist/local-tables.d.ts +707 -0
  27. package/dist/local-tables.d.ts.map +1 -0
  28. package/dist/mutation-state.d.ts +69 -0
  29. package/dist/mutation-state.d.ts.map +1 -0
  30. package/dist/mutation.d.ts +129 -4
  31. package/dist/mutation.d.ts.map +1 -1
  32. package/dist/schema.d.ts +82 -0
  33. package/dist/schema.d.ts.map +1 -1
  34. package/dist/shape-sync.d.ts +190 -0
  35. package/dist/shape-sync.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +132 -0
  37. package/dist/store-path.d.ts.map +1 -0
  38. package/dist/sync/apply.d.ts +51 -0
  39. package/dist/sync/apply.d.ts.map +1 -0
  40. package/dist/sync/copy.d.ts +43 -0
  41. package/dist/sync/copy.d.ts.map +1 -0
  42. package/dist/sync/drizzle-executor.d.ts +5 -0
  43. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  44. package/dist/sync/index.d.ts +32 -0
  45. package/dist/sync/index.d.ts.map +1 -0
  46. package/dist/sync/metadata-tables.d.ts +131 -0
  47. package/dist/sync/metadata-tables.d.ts.map +1 -0
  48. package/dist/sync/nudge.d.ts +49 -0
  49. package/dist/sync/nudge.d.ts.map +1 -0
  50. package/dist/sync/shape-inbox.d.ts +215 -0
  51. package/dist/sync/shape-inbox.d.ts.map +1 -0
  52. package/dist/sync/subscription-state.d.ts +39 -0
  53. package/dist/sync/subscription-state.d.ts.map +1 -0
  54. package/dist/sync/tags.d.ts +130 -0
  55. package/dist/sync/tags.d.ts.map +1 -0
  56. package/dist/sync/types.d.ts +126 -0
  57. package/dist/sync/types.d.ts.map +1 -0
  58. package/dist/sync-auth.d.ts +53 -0
  59. package/dist/sync-auth.d.ts.map +1 -0
  60. package/dist/testing.d.ts +27 -0
  61. package/dist/testing.d.ts.map +1 -0
  62. package/dist/testing.js +17 -0
  63. package/dist/testing.js.map +11 -0
  64. package/dist/worker/attach-sync-client.d.ts +96 -0
  65. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  66. package/dist/worker/define-sync-worker.d.ts +76 -0
  67. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  68. package/dist/worker/live-diff.d.ts +44 -0
  69. package/dist/worker/live-diff.d.ts.map +1 -0
  70. package/dist/worker/protocol.d.ts +341 -0
  71. package/dist/worker/protocol.d.ts.map +1 -0
  72. package/dist/worker/token-cache.d.ts +26 -0
  73. package/dist/worker/token-cache.d.ts.map +1 -0
  74. package/oxlint-plugin.js +143 -0
  75. package/package.json +20 -7
  76. package/skills/core/SKILL.md +210 -0
  77. package/skills/operating/SKILL.md +303 -0
  78. package/src/boot-report.ts +287 -0
  79. package/src/convergence.ts +197 -0
  80. package/src/debug.ts +151 -0
  81. package/src/export-data.ts +300 -0
  82. package/src/export-dump.ts +239 -0
  83. package/src/export-store.ts +309 -0
  84. package/src/index.ts +1652 -51
  85. package/src/lazy-guard.ts +135 -0
  86. package/src/lifecycle-slot.ts +66 -0
  87. package/src/live-rows-sql.ts +45 -0
  88. package/src/local-store.ts +193 -0
  89. package/src/local-tables.ts +546 -0
  90. package/src/mutation-state.ts +99 -0
  91. package/src/mutation.ts +1910 -562
  92. package/src/schema.ts +472 -28
  93. package/src/shape-sync.ts +498 -0
  94. package/src/store-path.ts +249 -0
  95. package/src/sync/apply.ts +530 -0
  96. package/src/sync/copy.ts +206 -0
  97. package/src/sync/drizzle-executor.ts +48 -0
  98. package/src/sync/index.ts +1087 -0
  99. package/src/sync/metadata-tables.ts +67 -0
  100. package/src/sync/nudge.ts +110 -0
  101. package/src/sync/shape-inbox.ts +566 -0
  102. package/src/sync/subscription-state.ts +135 -0
  103. package/src/sync/tags.ts +365 -0
  104. package/src/sync/types.ts +141 -0
  105. package/src/sync-auth.ts +117 -0
  106. package/src/testing.ts +53 -0
  107. package/src/worker/attach-sync-client.ts +653 -0
  108. package/src/worker/define-sync-worker.ts +762 -0
  109. package/src/worker/live-diff.ts +140 -0
  110. package/src/worker/protocol.ts +425 -0
  111. package/src/worker/token-cache.ts +84 -0
package/src/mutation.ts CHANGED
@@ -1,5 +1,47 @@
1
- import { is, SQL } from "drizzle-orm";
2
- import { getTableConfig, getViewConfig, type AnyPgTable } from "drizzle-orm/pg-core";
1
+ import {
2
+ and,
3
+ desc,
4
+ eq,
5
+ exists,
6
+ getColumns,
7
+ gt,
8
+ inArray,
9
+ is,
10
+ isNotNull,
11
+ isNull,
12
+ lt,
13
+ ne,
14
+ notExists,
15
+ SQL,
16
+ sql,
17
+ } from "drizzle-orm";
18
+ import {
19
+ alias,
20
+ getTableConfig,
21
+ getViewConfig,
22
+ PgDialect,
23
+ type AnyPgTable,
24
+ type PgColumn,
25
+ type PgInsertValue,
26
+ } from "drizzle-orm/pg-core";
27
+ import { drizzle } from "drizzle-orm/pglite";
28
+
29
+ import {
30
+ getJournalTable,
31
+ getOverlayTable,
32
+ getSyncedLocalTable,
33
+ type JournalTable,
34
+ type OverlayTable,
35
+ } from "./local-tables";
36
+
37
+ // Statements are AUTHORED as Drizzle builders over the journal/overlay/synced table objects
38
+ // (rename-safe, typed, schema-qualification handled by the table objects) and rendered to
39
+ // text+params here, because they EXECUTE through the caller's raw `MutationDb` seam — the one
40
+ // connection the mutation runtime and its tests own (and mock). `drizzle.mock()` builds queries
41
+ // without a connection; `queryDialect` renders standalone `sql` fragments the builders cannot
42
+ // express (compound CTE shapes, derived-table wrappers).
43
+ const queryBuilder = drizzle.mock();
44
+ const queryDialect = new PgDialect();
3
45
 
4
46
  /**
5
47
  * Strip the two internal overlay columns that appear on _read_model views
@@ -32,19 +74,50 @@ function jsonStringifyPayload(value: unknown): string {
32
74
 
33
75
  import type {
34
76
  BatchMutationAck,
77
+ MutationAck,
35
78
  MutationDiagnostics,
79
+ MutationRejection,
36
80
  SyncTableCreateInput,
37
81
  SyncTableEntry,
38
82
  SyncTableName,
39
83
  SyncTableRecord,
40
84
  SyncTableRegistry,
41
85
  SyncTableUpdateInput,
86
+ WriteMode,
42
87
  } from "@pgxsinkit/contracts";
43
- import { getProjectedColumns as getProjectedTableColumns, getSyncRegistrySchema } from "@pgxsinkit/contracts";
88
+ import {
89
+ batchMutationErrorSchema,
90
+ buildOverlayResolutionBarrier,
91
+ fingerprintRegistry,
92
+ getProjectedColumns as getProjectedTableColumns,
93
+ getSyncRegistrySchema,
94
+ maybeQuoteIdentifier,
95
+ quoteIdentifier,
96
+ resolveServerVersionColumnName,
97
+ } from "@pgxsinkit/contracts";
98
+
99
+ import { syncDebug } from "./debug";
100
+ import {
101
+ assertValidMutationTransition,
102
+ classifyFailureStatus,
103
+ DEFAULT_MAX_MUTATION_ATTEMPTS,
104
+ type MutationStatus,
105
+ } from "./mutation-state";
44
106
 
45
- export type MutationStatus = "pending" | "sending" | "acked" | "failed";
107
+ export type { MutationStatus } from "./mutation-state";
46
108
  export type MutationKind = "create" | "update" | "delete";
47
109
 
110
+ /**
111
+ * The dynamic write-unit tag (ADR-0022 §2) a `transaction({ mode })` block stamps onto the mutations
112
+ * authored within it: a shared `id` grouping the co-committed mutations, and the unit's `mode`. Persisted
113
+ * on each journal row (`write_unit` / `write_mode`); absent for the default path, where the flusher derives
114
+ * mode + unit from the table's static consistency group.
115
+ */
116
+ export interface WriteUnit {
117
+ id: string;
118
+ mode: WriteMode;
119
+ }
120
+
48
121
  export type MutationBatchItem<TRegistry extends SyncTableRegistry> = {
49
122
  [TKey in SyncTableName<TRegistry>]:
50
123
  | {
@@ -57,6 +130,13 @@ export type MutationBatchItem<TRegistry extends SyncTableRegistry> = {
57
130
  kind: "update";
58
131
  entityKey: Record<string, string>;
59
132
  patch: SyncTableUpdateInput<TRegistry, TKey>;
133
+ /**
134
+ * A **blind** update (ADR-0022 addendum): plan a journal row ONLY — no local base row is required
135
+ * and no optimistic overlay is written. Set exclusively by the transaction handle's `updateBlind`;
136
+ * valid only when the write routes pessimistically (a `pessimistic` unit, or a statically-pessimistic
137
+ * table), and rejected at enqueue otherwise. Absent/false for an ordinary update.
138
+ */
139
+ blind?: boolean;
60
140
  }
61
141
  | {
62
142
  table: TKey;
@@ -81,6 +161,8 @@ export interface MutationDetail {
81
161
  nextRetryAtUs: string | null;
82
162
  serverUpdatedAtUs: string | null;
83
163
  updatedAtUs: string;
164
+ /** Registry fingerprint (ADR-0004) the mutation was authored under, or null if unstamped. */
165
+ registryVersion: string | null;
84
166
  }
85
167
 
86
168
  export interface MutationDb {
@@ -96,6 +178,46 @@ export interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistr
96
178
  registry: TRegistry;
97
179
  writeUrl: string;
98
180
  getAuthToken?: () => Promise<string | undefined>;
181
+ /** Static headers added to every write request (e.g. a Supabase Cloud `apikey`); see {@link CreateSyncClientOptions.requestHeaders}. */
182
+ requestHeaders?: Record<string, string>;
183
+ /**
184
+ * Registry fingerprint (ADR-0004) stamped onto each enqueued mutation as its
185
+ * `registry_version`, so a version-boundary crossing is known before sending (ADR-0006).
186
+ */
187
+ registryVersion?: string;
188
+ /**
189
+ * Hard cap on send attempts before a still-failing mutation is quarantined
190
+ * (ADR-0005 congestion policy). Defaults to {@link DEFAULT_MAX_MUTATION_ATTEMPTS}.
191
+ */
192
+ maxMutationAttempts?: number;
193
+ /**
194
+ * Max mutations drained per flush HTTP request; a flush loops slices until the journal is empty.
195
+ * Defaults to {@link DEFAULT_FLUSH_BATCH_SIZE}. Primarily a test seam (a small value exercises the
196
+ * multi-slice drain path without enqueueing hundreds of mutations).
197
+ */
198
+ flushBatchSize?: number;
199
+ /**
200
+ * Invoked after a flush whenever mutations transition to `quarantined` (terminal,
201
+ * permanently rejected). Receives the newly-quarantined details so the app can surface
202
+ * them, then either re-author + resubmit or roll back via {@link MutationRuntime.discardQuarantined}
203
+ * (clears the kept overlay + quarantined journal rows, so the entity accepts new mutations again).
204
+ * The library never silently drops these (ADR-0006 decision 4).
205
+ */
206
+ onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;
207
+ /**
208
+ * Invoked after a flush whenever mutations transition to `conflicted` — a stale write the
209
+ * server declined under the `reject-if-stale` Conflict policy (ADR-0015). Distinct from
210
+ * `onQuarantine` (structural rejection): the optimistic Overlay is KEPT, so the app surfaces a
211
+ * resolution/diff UI and resolves each as a new write (or `discardConflict`s it). Never silent.
212
+ */
213
+ onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;
214
+ /**
215
+ * Invoked after an authoritative (pessimistic) flush whenever a write-unit was `rejected` (ADR-0022) —
216
+ * a business decline the client could not evaluate locally (capacity/quota/uniqueness). The inverse of
217
+ * `onConflict`: the optimistic Overlay was **auto-discarded** for every member of the unit, so the app
218
+ * surfaces the typed reason (e.g. "full") rather than a resolve/diff UI. Never silent.
219
+ */
220
+ onReject?: (rejected: MutationDetail[]) => void | Promise<void>;
99
221
  }
100
222
 
101
223
  interface TableContext {
@@ -108,14 +230,76 @@ interface TableContext {
108
230
  journalSequence: string;
109
231
  pkColumnNames: string[];
110
232
  pkPropertyKeys: string[];
233
+ /**
234
+ * The Server version (ADR-0010) column name (e.g. `updated_at_us`) and its drizzle property key,
235
+ * resolved from the table's managed fields. Used to capture the Base server version (ADR-0015) at
236
+ * enqueue — the value the user's edit was authored against. `null` would mean no Server version,
237
+ * which registry validation already forbids for a writable table.
238
+ */
239
+ serverVersionColumnName: string | null;
240
+ serverVersionPropertyKey: string | null;
241
+ /**
242
+ * Property keys of the table's `nowMicroseconds` managed fields (governance), resolved generically
243
+ * rather than by the `createdAtUs`/`updatedAtUs` naming convention. The optimistic overlay stamps
244
+ * these client-side so a custom-named managed timestamp (e.g. a Server version not called
245
+ * `updated_at_us`) is materialised correctly — closing the split interpreter between the generic
246
+ * server applier (which reads governance) and the local path (ADR-0004).
247
+ *
248
+ * - `managedNowMicrosecondsPropertyKeys` — every `nowMicroseconds` field, stamped on create.
249
+ * - `updateManagedNowMicrosecondsPropertyKeys` — those that apply on update, re-stamped each update.
250
+ *
251
+ * These augment, and never remove, the convention fill in `createOptimisticRecordFromContext`,
252
+ * which remains the safety net for a `created_at_us`/`updated_at_us` column that carries a SQL
253
+ * `DEFAULT` (unmaterialisable client-side) yet is not declared a managed field.
254
+ */
255
+ managedNowMicrosecondsPropertyKeys: string[];
256
+ updateManagedNowMicrosecondsPropertyKeys: string[];
257
+ /**
258
+ * The table's `authClaim` managed fields that apply on create (governance), each with the JSON
259
+ * claimPath it stamps from. The server stamps these from the verified request claims, so they are
260
+ * stripped from the create input type and never sent in the flushed payload. But the optimistic
261
+ * overlay still needs a value — such a column is typically `NOT NULL` (an owner/author/created_by) —
262
+ * so the runtime fills it client-side from the decoded JWT claim at the same path (the same value the
263
+ * server will stamp), so the local row renders attributed immediately and never flips on convergence.
264
+ * (`auth.uid()` is just `claimPath: ["sub"]`, so this one path covers it.)
265
+ */
266
+ managedAuthClaimCreateFields: Array<{ propertyKey: string; claimPath: string[] }>;
111
267
  recordIncludesOverlayState: boolean;
112
268
  columns: Array<{
113
269
  propertyKey: string;
114
270
  column: ReturnType<typeof getProjectedTableColumns<AnyPgTable>>[number]["column"];
115
271
  }>;
272
+ /**
273
+ * The generated local relations as runtime Drizzle table objects (local-tables.ts), so the
274
+ * runtime's statements are AUTHORED as tier-① builders while still EXECUTING through the raw
275
+ * `MutationDb` seam. Journal fixed columns are camelCase-keyed; per-entry PK columns are keyed
276
+ * by DB column name; overlay/synced columns are keyed by drizzle property key.
277
+ */
278
+ tables: {
279
+ synced: AnyPgTable;
280
+ overlay: OverlayTable;
281
+ journal: JournalTable;
282
+ };
283
+ /** Overlay columns keyed by property key (`getColumns` memo — overlay keys are property keys, not DB names). */
284
+ overlayColumnsByPropertyKey: Record<string, PgColumn>;
285
+ /** Synced read-cache columns keyed by property key. */
286
+ syncedColumnsByPropertyKey: Record<string, PgColumn>;
287
+ /** The entry's PK columns ON THE OVERLAY, resolved by DB column name (ordered like `pkColumnNames`). */
288
+ overlayPkColumns: PgColumn[];
289
+ /** The entry's PK columns ON THE SYNCED table, resolved by DB column name (ordered like `pkColumnNames`). */
290
+ syncedPkColumns: PgColumn[];
291
+ /** The Server version column ON THE SYNCED table (ADR-0010), or null when the table declares none. */
292
+ syncedServerVersionColumn: PgColumn | null;
293
+ /**
294
+ * Memoized render of the reconcile idle probe (the per-tick hot statement): built once per
295
+ * context so every convergence tick pays only a plain `db.query` of a cached string.
296
+ */
297
+ reconcileIdleProbe?: { sql: string; params: unknown[] };
116
298
  }
117
299
 
118
300
  export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
301
+ /** The registry fingerprint (ADR-0004) this runtime stamps onto enqueued mutations. */
302
+ registryVersion: string;
119
303
  create: <TKey extends SyncTableName<TRegistry>>(
120
304
  table: TKey,
121
305
  input: SyncTableCreateInput<TRegistry, TKey>,
@@ -126,11 +310,57 @@ export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
126
310
  patch: SyncTableUpdateInput<TRegistry, TKey>,
127
311
  ) => Promise<void>;
128
312
  delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;
129
- batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => Promise<void>;
313
+ /**
314
+ * Enqueue an atomic batch of mutations. An optional {@link WriteUnit} tags every row of the batch as one
315
+ * dynamic write-unit (ADR-0022 §2) — the `transaction({ mode })` block passes it; the per-table
316
+ * `create`/`update`/`delete` helpers do not (their write-mode comes from the static group at flush).
317
+ */
318
+ batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>, unit?: WriteUnit) => Promise<void>;
319
+ /**
320
+ * Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entries and the kept
321
+ * optimistic Overlay, so the Read model falls back to the synced (server) value. Use when the user
322
+ * abandons their stale edit instead of resolving it as a new write. No-op for an entity with no
323
+ * conflicted entry.
324
+ */
325
+ discardConflict: <TKey extends SyncTableName<TRegistry>>(
326
+ table: TKey,
327
+ entityKey: Record<string, string>,
328
+ ) => Promise<void>;
329
+ /**
330
+ * Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entries and the kept
331
+ * optimistic Overlay, so the Read model falls back to the synced (server) value and the entity
332
+ * accepts new mutations again. The rollback path for a permanently-rejected write (e.g. an RLS
333
+ * policy denial routed to quarantine). Symmetric to {@link discardConflict}. No-op for an entity
334
+ * with no quarantined entry; the overlay is kept when another still-owed write depends on it.
335
+ */
336
+ discardQuarantined: <TKey extends SyncTableName<TRegistry>>(
337
+ table: TKey,
338
+ entityKey: Record<string, string>,
339
+ ) => Promise<void>;
130
340
  flush: (table?: SyncTableName<TRegistry>) => Promise<void>;
341
+ /**
342
+ * Flush one pessimistic write-unit (ADR-0022) to the authoritative endpoint and apply its per-mutation
343
+ * result inline: `acked` clears via the synced echo, `conflicted` keeps the overlay (surfaced), and
344
+ * `rejected` auto-discards the overlay for the whole unit (surfaced via `onReject`). A foreground
345
+ * operation — it resolves once the server has decided. Throws on transport failure (the overlay is kept
346
+ * for a retry). Returns the server acks. Used by the client `transaction({ mode: "pessimistic" })` block.
347
+ */
348
+ flushUnit: (unitId: string) => Promise<{ acks: MutationAck[] }>;
131
349
  reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;
132
350
  retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
133
351
  recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;
352
+ /**
353
+ * Quarantine EVERY non-terminal journal row recovered from a backup (`pending`/`sending`/`failed` →
354
+ * `quarantined`) — the restore-boot rule (ADR-0035 decision 6). Nothing recovered from a store backup
355
+ * may ever auto-flush: the write path keeps `mutationId` in `operations_log` but never consults it, so
356
+ * there is no dedupe ledger, and a replayed mutation would silently re-apply stale values over newer
357
+ * writes on a last-write-wins table (and a replayed create collides on its PK). Terminal states
358
+ * (`acked`/`conflicted`/`rejected`) are left untouched. Run ONCE, on the restore boot only, AFTER
359
+ * `recoverSending` (which first lifts any `sending` back to `pending`); the app then inspects
360
+ * `diagnostics()` and resolves each row via `discardQuarantined` (quarantine is terminal — "release"
361
+ * means discard and re-author as a new mutation) before going online. A no-op on a clean journal.
362
+ */
363
+ quarantineRecovered: (table?: SyncTableName<TRegistry>) => Promise<void>;
134
364
  readMutationStats: (table?: SyncTableName<TRegistry>) => Promise<MutationDiagnostics>;
135
365
  readMutationDetails: (table?: SyncTableName<TRegistry>) => Promise<MutationDetail[]>;
136
366
  createOptimisticRecord: <TKey extends SyncTableName<TRegistry>>(
@@ -143,13 +373,67 @@ export function nowMicroseconds(): string {
143
373
  return (BigInt(Date.now()) * 1000n).toString();
144
374
  }
145
375
 
376
+ /**
377
+ * Best-effort decode of a JWT's claims payload, for stamping `authClaim` managed fields into the
378
+ * optimistic overlay (the value the server will independently stamp from the same claim path). This is
379
+ * **not** a verification — the token is trusted only for a local, optimistic projection that the server
380
+ * re-stamps authoritatively on apply; a forged claim could never make the server attribute the row
381
+ * differently. Returns `undefined` for a malformed token.
382
+ */
383
+ export function decodeJwtClaims(token: string): Record<string, unknown> | undefined {
384
+ const segments = token.split(".");
385
+ if (segments.length < 2 || !segments[1]) {
386
+ return undefined;
387
+ }
388
+ try {
389
+ const normalized = segments[1].replace(/-/g, "+").replace(/_/g, "/");
390
+ const padded = normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), "=");
391
+ const binary = atob(padded);
392
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
393
+ const payload = JSON.parse(new TextDecoder().decode(bytes)) as unknown;
394
+ return typeof payload === "object" && payload !== null ? (payload as Record<string, unknown>) : undefined;
395
+ } catch {
396
+ return undefined;
397
+ }
398
+ }
399
+
400
+ /**
401
+ * Read a claim at a JSON path out of a decoded claims object, returning it as a string (the form the
402
+ * optimistic overlay column expects, mirroring the server's `jsonb #>>` text extraction). Returns
403
+ * `undefined` if the path is absent or the leaf is not a string/number.
404
+ */
405
+ export function readJwtClaimPath(claims: Record<string, unknown>, claimPath: string[]): string | undefined {
406
+ let cursor: unknown = claims;
407
+ for (const segment of claimPath) {
408
+ if (typeof cursor !== "object" || cursor === null) {
409
+ return undefined;
410
+ }
411
+ cursor = (cursor as Record<string, unknown>)[segment];
412
+ }
413
+ if (typeof cursor === "string") {
414
+ return cursor;
415
+ }
416
+ return typeof cursor === "number" ? String(cursor) : undefined;
417
+ }
418
+
146
419
  export function computeBackoffDelayMs(attemptCount: number) {
147
420
  const exponent = Math.max(attemptCount - 1, 0);
148
421
  return Math.min(1000 * 2 ** exponent, 30_000);
149
422
  }
150
423
 
151
- export function computeNextRetryAtUs(nowUs: string, attemptCount: number) {
152
- return (BigInt(nowUs) + BigInt(computeBackoffDelayMs(attemptCount)) * 1000n).toString();
424
+ /**
425
+ * Retry delay with equal jitter around the {@link computeBackoffDelayMs} ceiling: half
426
+ * the ceiling plus a random share of the other half. Spreads retries so a fleet of
427
+ * clients does not stampede the server in lockstep after an outage (ADR-0005 congestion
428
+ * policy). `random` is injectable for deterministic tests.
429
+ */
430
+ export function computeRetryDelayMs(attemptCount: number, random: () => number = Math.random) {
431
+ const ceiling = computeBackoffDelayMs(attemptCount);
432
+ return Math.round(ceiling / 2 + random() * (ceiling / 2));
433
+ }
434
+
435
+ export function computeNextRetryAtUs(nowUs: string, attemptCount: number, random: () => number = Math.random) {
436
+ return (BigInt(nowUs) + BigInt(computeRetryDelayMs(attemptCount, random)) * 1000n).toString();
153
437
  }
154
438
 
155
439
  export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
@@ -163,7 +447,20 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
163
447
  return undefined;
164
448
  };
165
449
 
450
+ // The decoded JWT claims for stamping `authClaim` create-managed fields into the optimistic overlay
451
+ // (the same value the server stamps from the same claim path). Resolved only when a create needs it
452
+ // (a table with such a field), so tokenless registries never pay a token lookup.
453
+ const resolveAuthClaims = async (): Promise<Record<string, unknown> | undefined> => {
454
+ const token = await resolveAuthToken();
455
+ return token ? decodeJwtClaims(token) : undefined;
456
+ };
457
+
166
458
  const tableContexts = buildTableContexts(options.registry);
459
+ const maxMutationAttempts = options.maxMutationAttempts ?? DEFAULT_MAX_MUTATION_ATTEMPTS;
460
+ const flushBatchSize = options.flushBatchSize ?? DEFAULT_FLUSH_BATCH_SIZE;
461
+ // The fingerprint (ADR-0004) stamped onto each enqueued mutation (ADR-0006). The runtime
462
+ // owns the registry, so it derives this itself; an explicit override is honoured for tests.
463
+ const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);
167
464
  let flushQueue = Promise.resolve();
168
465
 
169
466
  const getTableContext = (table: SyncTableName<TRegistry>) => {
@@ -188,7 +485,11 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
188
485
  }
189
486
  };
190
487
 
191
- const normalizeBatchItem = (item: MutationBatchItem<TRegistry>, order: number): NormalizedBatchItem => {
488
+ const normalizeBatchItem = (
489
+ item: MutationBatchItem<TRegistry>,
490
+ order: number,
491
+ claims: Record<string, unknown> | undefined,
492
+ ): NormalizedBatchItem => {
192
493
  const context = getTableContext(item.table as SyncTableName<TRegistry>);
193
494
  const mutationId = globalThis.crypto.randomUUID();
194
495
  const nowUs = nowMicroseconds();
@@ -196,7 +497,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
196
497
  switch (item.kind) {
197
498
  case "create": {
198
499
  const strippedInput = stripReadModelOverlayFields(item.input);
199
- const optimisticRecord = ensureRecord(createOptimisticRecordFromContext(context, strippedInput));
500
+ const optimisticRecord = ensureRecord(createOptimisticRecordFromContext(context, strippedInput, claims));
200
501
  const entityKey = buildEntityKeyFromRecord(context, optimisticRecord);
201
502
 
202
503
  return {
@@ -221,6 +522,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
221
522
  entityKey,
222
523
  entityKeyJson: serializeEntityKey(entityKey),
223
524
  patch,
525
+ blind: item.blind ?? false,
224
526
  mutationId,
225
527
  nowUs,
226
528
  order,
@@ -242,12 +544,28 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
242
544
  }
243
545
  };
244
546
 
245
- const enqueueBatch = async (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => {
547
+ const enqueueBatch = async (
548
+ items: ReadonlyArray<MutationBatchItem<TRegistry>>,
549
+ unit?: WriteUnit,
550
+ ): Promise<string[]> => {
246
551
  if (items.length === 0) {
247
- return;
552
+ return [];
248
553
  }
249
554
 
250
- const normalizedItems = items.map((item, index) => normalizeBatchItem(item, index));
555
+ // The distinct pessimistic write-unit ids this enqueue tagged — returned so the caller can
556
+ // foreground-route them to the authoritative endpoint (ADR-0022). Empty for a purely optimistic batch.
557
+ const pessimisticUnitIds = new Set<string>();
558
+
559
+ // Resolve the decoded claims once per batch, but only if a create actually needs them (a target
560
+ // table with an `authClaim` create-managed field). Avoids a token lookup for every other write.
561
+ const needsAuthClaims = items.some(
562
+ (item) =>
563
+ item.kind === "create" &&
564
+ getTableContext(item.table as SyncTableName<TRegistry>).managedAuthClaimCreateFields.length > 0,
565
+ );
566
+ const claims = needsAuthClaims ? await resolveAuthClaims() : undefined;
567
+
568
+ const normalizedItems = items.map((item, index) => normalizeBatchItem(item, index, claims));
251
569
  const batchGroups = new Map<string, { context: TableContext; items: NormalizedBatchItem[] }>();
252
570
 
253
571
  for (const item of normalizedItems) {
@@ -313,6 +631,9 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
313
631
  value: item.input,
314
632
  }),
315
633
  nowUs: item.nowUs,
634
+ // A create has no Base server version (ADR-0015): its conflict is a PK collision, a
635
+ // separate concern from the stale-write check.
636
+ baseServerVersion: null,
316
637
  });
317
638
 
318
639
  entityState.record = item.optimisticRecord;
@@ -330,6 +651,51 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
330
651
  break;
331
652
  }
332
653
  case "update": {
654
+ if (item.blind) {
655
+ // ADR-0022 addendum — a BLIND update: the write target is excluded from the actor's read
656
+ // shape (its rows never stream here), so there is no local base row to seed and no optimistic
657
+ // state to show. It is meaningful ONLY when the write routes to the authoritative endpoint (the
658
+ // /unit expander is authoritative): an optimistic-routed blind write has nothing to converge, so
659
+ // it is rejected at enqueue. The `unit` fixes the route inside a `transaction` block; a plain
660
+ // enqueue on a statically-pessimistic table earns its own pessimistic unit downstream.
661
+ const routesPessimistic = unit ? unit.mode === "pessimistic" : context.entry.writeMode === "pessimistic";
662
+ if (!routesPessimistic) {
663
+ throw new Error(
664
+ `${context.key}: updateBlind requires a pessimistic write unit — use transaction({ mode: "pessimistic" }) (an optimistic blind write has nothing to show and no base to converge)`,
665
+ );
666
+ }
667
+
668
+ // KEEP the already-queued-for-deletion guard (journal-derived; needs no local record).
669
+ if (entityState.latestMutationKind === "delete" && entityState.latestMutationStatus !== "acked") {
670
+ throw new Error(`${context.key} is already queued for deletion`);
671
+ }
672
+
673
+ // Plan a journal row ONLY — no overlay, so nothing enters the read model and nothing can linger
674
+ // there. `baseServerVersion: null`: the /unit expander is authoritative, there is no base to
675
+ // capture. The `pessimistic-blind` marker keeps the row off the optimistic flusher and lets
676
+ // reconcile retire it after ack WITHOUT a synced echo (there is no visible row to converge).
677
+ plannedMutations.push({
678
+ mutationId: item.mutationId,
679
+ entityKey: item.entityKey,
680
+ entityKeyJson: item.entityKeyJson,
681
+ mutationKind: "update",
682
+ payloadJson: jsonStringifyPayload({
683
+ kind: "update",
684
+ patch: item.patch,
685
+ }),
686
+ nowUs: item.nowUs,
687
+ baseServerVersion: null,
688
+ writeMode: "pessimistic-blind",
689
+ });
690
+
691
+ // Advance only the journal-derived tracking (no record/overlay): so a later same-batch item on
692
+ // this entity chains in author order and sees the pending blind write.
693
+ entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;
694
+ entityState.latestMutationKind = "update";
695
+ entityState.latestMutationStatus = "pending";
696
+ break;
697
+ }
698
+
333
699
  if (!entityState.record) {
334
700
  throw new Error(`${context.key} not found in local read model`);
335
701
  }
@@ -338,6 +704,9 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
338
704
  throw new Error(`${context.key} is already queued for deletion`);
339
705
  }
340
706
 
707
+ // ADR-0015: capture the Base server version BEFORE the record is replaced by the
708
+ // optimistic value below (which overwrites the Server version with the client clock).
709
+ const updateBaseServerVersion = captureChainHeadBase(context, entityState);
341
710
  const overlayKind = entityState.overlayKind === "pending_create" ? "pending_create" : "pending_update";
342
711
  const optimisticRecord = ensureRecord(
343
712
  buildOptimisticRecord(
@@ -345,7 +714,10 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
345
714
  {
346
715
  ...entityState.record,
347
716
  ...item.patch,
348
- updatedAtUs: item.nowUs,
717
+ // Re-stamp the on-update managed timestamp(s) generically (governance-driven) — for a
718
+ // convention table this is exactly `updatedAtUs`, for a custom-named Server version
719
+ // it is that column, so the optimistic row never carries a stale managed value.
720
+ ...buildUpdateManagedNowStamp(context, item.nowUs),
349
721
  },
350
722
  {
351
723
  overlayKind,
@@ -363,6 +735,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
363
735
  patch: item.patch,
364
736
  }),
365
737
  nowUs: item.nowUs,
738
+ baseServerVersion: updateBaseServerVersion,
366
739
  });
367
740
 
368
741
  entityState.record = optimisticRecord;
@@ -388,6 +761,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
388
761
  throw new Error(`${context.key} is already queued for deletion`);
389
762
  }
390
763
 
764
+ const deleteBaseServerVersion = captureChainHeadBase(context, entityState);
391
765
  plannedMutations.push({
392
766
  mutationId: item.mutationId,
393
767
  entityKey: item.entityKey,
@@ -398,6 +772,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
398
772
  entityKey: item.entityKey,
399
773
  }),
400
774
  nowUs: item.nowUs,
775
+ baseServerVersion: deleteBaseServerVersion,
401
776
  });
402
777
 
403
778
  entityState.overlayKind = "pending_delete";
@@ -416,13 +791,28 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
416
791
  }
417
792
  }
418
793
 
419
- await insertMutationsBulk(options.db, context, plannedMutations);
794
+ // ADR-0022: an explicit unit (from a `transaction` block) tags the whole batch; otherwise a
795
+ // statically-`pessimistic` table earns its own per-enqueue unit, so its writes route to the
796
+ // authoritative endpoint too. An optimistic table with no explicit unit stays untagged.
797
+ const effectiveUnit: WriteUnit | undefined =
798
+ unit ??
799
+ (context.entry.writeMode === "pessimistic"
800
+ ? { id: globalThis.crypto.randomUUID(), mode: "pessimistic" }
801
+ : undefined);
802
+ if (effectiveUnit?.mode === "pessimistic") {
803
+ pessimisticUnitIds.add(effectiveUnit.id);
804
+ }
805
+ await insertMutationsBulk(options.db, context, plannedMutations, registryVersion, effectiveUnit);
420
806
  await upsertOverlayRecordsBulk(options.db, context, [...plannedOverlays.values()]);
421
807
  }
808
+
809
+ return [...pessimisticUnitIds];
422
810
  };
423
811
 
424
812
  const runFlush = async (table?: SyncTableName<TRegistry>) => {
425
813
  const affectedContexts = new Map<string, TableContext>();
814
+ const quarantinedMutationIds = new Set<string>();
815
+ const conflictedMutationIds = new Set<string>();
426
816
  let processedCount = 0;
427
817
 
428
818
  do {
@@ -430,8 +820,11 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
430
820
  options.db,
431
821
  tableContexts as Record<string, TableContext>,
432
822
  options.writeUrl,
823
+ maxMutationAttempts,
824
+ flushBatchSize,
433
825
  table,
434
826
  resolveAuthToken,
827
+ options.requestHeaders,
435
828
  );
436
829
 
437
830
  processedCount = batchResult.processedCount;
@@ -439,58 +832,366 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
439
832
  for (const context of batchResult.affectedContexts) {
440
833
  affectedContexts.set(context.key, context);
441
834
  }
835
+
836
+ for (const mutationId of batchResult.quarantinedMutationIds) {
837
+ quarantinedMutationIds.add(mutationId);
838
+ }
839
+
840
+ for (const mutationId of batchResult.conflictedMutationIds) {
841
+ conflictedMutationIds.add(mutationId);
842
+ }
442
843
  } while (processedCount > 0);
443
844
 
444
845
  for (const context of affectedContexts.values()) {
445
846
  await reconcileTable(options.db, context);
446
847
  }
848
+
849
+ // Surface newly-quarantined mutations after reconciliation so the app never has to
850
+ // poll for permanently-rejected writes (ADR-0006 decision 4). Never silent loss.
851
+ if (quarantinedMutationIds.size > 0 && options.onQuarantine) {
852
+ const details = await readMutationDetailsForContexts(
853
+ options.db,
854
+ [...affectedContexts.values()],
855
+ quarantinedMutationIds,
856
+ );
857
+
858
+ if (details.length > 0) {
859
+ await options.onQuarantine(details);
860
+ }
861
+ }
862
+
863
+ // Surface newly-conflicted (stale) writes (ADR-0015). The optimistic Overlay is kept, so the app
864
+ // can show a resolution/diff UI and resolve each as a new write (or discard it). Never silent.
865
+ if (conflictedMutationIds.size > 0 && options.onConflict) {
866
+ const details = await readMutationDetailsForContexts(
867
+ options.db,
868
+ [...affectedContexts.values()],
869
+ conflictedMutationIds,
870
+ );
871
+
872
+ if (details.length > 0) {
873
+ await options.onConflict(details);
874
+ }
875
+ }
447
876
  };
448
877
 
449
- return {
878
+ const runtime: MutationRuntime<TRegistry> = {
879
+ registryVersion,
450
880
  create: async (table, input) => {
881
+ let unitIds: string[] = [];
451
882
  await runInTransaction(async () => {
452
- await enqueueBatch([
453
- {
454
- table,
455
- kind: "create",
456
- input,
457
- },
458
- ]);
883
+ unitIds = await enqueueBatch([{ table, kind: "create", input }]);
459
884
  });
885
+ // A statically-`pessimistic` table foreground-routes its write to the authoritative endpoint
886
+ // (ADR-0022) — the write is server-authoritative, so it is sent immediately, not left for the
887
+ // optimistic convergence loop (which skips pessimistic rows).
888
+ for (const unitId of unitIds) {
889
+ await runtime.flushUnit(unitId);
890
+ }
460
891
  },
461
892
  update: async (table, entityKeyInput, patch) => {
893
+ let unitIds: string[] = [];
462
894
  await runInTransaction(async () => {
463
- await enqueueBatch([
464
- {
465
- table,
466
- kind: "update",
467
- entityKey: entityKeyInput,
468
- patch,
469
- },
470
- ]);
895
+ unitIds = await enqueueBatch([{ table, kind: "update", entityKey: entityKeyInput, patch }]);
471
896
  });
897
+ for (const unitId of unitIds) {
898
+ await runtime.flushUnit(unitId);
899
+ }
472
900
  },
473
901
  delete: async (table, entityKeyInput) => {
902
+ let unitIds: string[] = [];
474
903
  await runInTransaction(async () => {
475
- await enqueueBatch([
476
- {
477
- table,
478
- kind: "delete",
479
- entityKey: entityKeyInput,
480
- },
481
- ]);
904
+ unitIds = await enqueueBatch([{ table, kind: "delete", entityKey: entityKeyInput }]);
482
905
  });
906
+ for (const unitId of unitIds) {
907
+ await runtime.flushUnit(unitId);
908
+ }
483
909
  },
484
- batch: async (items) => {
910
+ batch: async (items, unit) => {
911
+ let unitIds: string[] = [];
485
912
  await runInTransaction(async () => {
486
- await enqueueBatch(items);
913
+ unitIds = await enqueueBatch(items, unit);
487
914
  });
915
+ // An explicit unit (from a `transaction` block) is flushed by the caller; only foreground-route the
916
+ // units a plain `batch()` generated for statically-pessimistic tables.
917
+ if (!unit) {
918
+ for (const unitId of unitIds) {
919
+ await runtime.flushUnit(unitId);
920
+ }
921
+ }
922
+ },
923
+ discardConflict: async (table, entityKeyInput) => {
924
+ const context = getTableContext(table);
925
+ const entityKey = normalizeEntityKey(context, entityKeyInput);
926
+ const entityKeyJson = serializeEntityKey(entityKey);
927
+
928
+ // discardTerminalEntity owns its own transaction (like reconcileTable), so it is not wrapped.
929
+ await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, "conflicted");
930
+ },
931
+ discardQuarantined: async (table, entityKeyInput) => {
932
+ const context = getTableContext(table);
933
+ const entityKey = normalizeEntityKey(context, entityKeyInput);
934
+ const entityKeyJson = serializeEntityKey(entityKey);
935
+
936
+ // Symmetric to discardConflict — retire the entity's `quarantined` journal rows and clear the
937
+ // kept overlay behind the same owed-guard, so a permanently-rejected write is a real rollback.
938
+ await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, "quarantined");
488
939
  },
489
940
  flush: async (table) => {
490
941
  const nextFlush = flushQueue.then(() => runFlush(table));
491
942
  flushQueue = nextFlush.catch(() => undefined);
492
943
  await nextFlush;
493
944
  },
945
+ flushUnit: async (unitId) => {
946
+ const contexts = Object.values(tableContexts).filter((context): context is TableContext => context != null);
947
+ const unitRows = await readUnitPendingRows(options.db, contexts, unitId);
948
+ if (unitRows.length === 0) {
949
+ return { acks: [] };
950
+ }
951
+
952
+ // Prepare the unit's rows (entity key + envelope payload) and group them by table.
953
+ const prepared: PreparedBatchRow[] = [];
954
+ const byContext = new Map<string, PreparedBatchRow[]>();
955
+ for (const row of unitRows) {
956
+ const context = tableContexts[row.tableKey];
957
+ if (!context) {
958
+ continue;
959
+ }
960
+ const entityKey = JSON.parse(row.entityKeyJson) as Record<string, string>;
961
+ const rawPayload = JSON.parse(row.payloadJson) as Record<string, unknown>;
962
+ const preparedRow: PreparedBatchRow = {
963
+ ...row,
964
+ context,
965
+ entityKey,
966
+ envelopePayload:
967
+ row.mutationKind === "delete"
968
+ ? entityKey
969
+ : toSqlColumnPayload(
970
+ context,
971
+ stripManagedFields(
972
+ context,
973
+ (rawPayload["value"] ?? rawPayload["patch"] ?? rawPayload) as Record<string, unknown>,
974
+ row.mutationKind as "create" | "update",
975
+ ),
976
+ ),
977
+ sqlTableName: context.entry.shape?.tableName ?? context.key,
978
+ };
979
+ prepared.push(preparedRow);
980
+ const list = byContext.get(context.key);
981
+ if (list) {
982
+ list.push(preparedRow);
983
+ } else {
984
+ byContext.set(context.key, [preparedRow]);
985
+ }
986
+ }
987
+
988
+ // Mark every member sending (persist the resolved Base server version, like the batch path).
989
+ const sentAtUs = nowMicroseconds();
990
+ for (const rows of byContext.values()) {
991
+ await applyMutationStatusUpdates(
992
+ options.db,
993
+ rows[0]!.context,
994
+ rows.map((row) => ({
995
+ mutationId: row.mutationId,
996
+ status: "sending" as const,
997
+ attemptCount: row.attemptCount + 1,
998
+ updatedAtUs: sentAtUs,
999
+ sentAtUs,
1000
+ replaceSentAtUs: true,
1001
+ baseServerVersion: row.baseServerVersion,
1002
+ replaceBaseServerVersion: true,
1003
+ lastError: null,
1004
+ nextRetryAtUs: null,
1005
+ lastHttpStatus: null,
1006
+ conflictReason: null,
1007
+ })),
1008
+ );
1009
+ }
1010
+
1011
+ const mutations = prepared.map((row) => ({
1012
+ tableName: row.sqlTableName,
1013
+ entityKey: row.entityKey,
1014
+ mutationId: row.mutationId,
1015
+ mutationSeq: row.mutationSeq,
1016
+ kind: row.mutationKind as "create" | "update" | "delete",
1017
+ payload: row.envelopePayload,
1018
+ clientTimestampUs: sentAtUs,
1019
+ ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),
1020
+ }));
1021
+
1022
+ const url = resolveAuthoritativeMutationUrl(options.writeUrl);
1023
+ let acksByMutationId: Map<string, BatchMutationAck["acks"][number]>;
1024
+
1025
+ try {
1026
+ const authToken = await options.getAuthToken?.();
1027
+ let response = await fetch(url, {
1028
+ method: "POST",
1029
+ headers: buildRequestHeaders(authToken, options.requestHeaders),
1030
+ body: jsonStringifyPayload({ writeUnit: unitId, mutations }),
1031
+ });
1032
+
1033
+ if ([401, 403].includes(response.status) && options.getAuthToken) {
1034
+ response = await fetch(url, {
1035
+ method: "POST",
1036
+ headers: buildRequestHeaders(await options.getAuthToken(), options.requestHeaders),
1037
+ body: jsonStringifyPayload({ writeUnit: unitId, mutations }),
1038
+ });
1039
+ }
1040
+
1041
+ if (!response.ok) {
1042
+ const text = await response.text();
1043
+ throw new MutationRequestError(
1044
+ text.length > 0 ? text : `Authoritative write responded with ${response.status}`,
1045
+ response.status,
1046
+ parseBatchRejections(text),
1047
+ );
1048
+ }
1049
+
1050
+ const responseJson = (await response.json()) as BatchMutationAck;
1051
+ acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));
1052
+ } catch (error) {
1053
+ // A pessimistic write is foreground: it never reached the server (transport / non-2xx), so the
1054
+ // unit did not happen. Mark it failed — KEEPING the optimistic overlay so a retry can resend — and
1055
+ // rethrow so the caller surfaces it. There is no background retry for pessimistic units.
1056
+ const failedAtUs = nowMicroseconds();
1057
+ const httpStatus = error instanceof MutationRequestError ? error.status : null;
1058
+ const errorMessage = error instanceof Error ? error.message : "Authoritative write failed";
1059
+ for (const rows of byContext.values()) {
1060
+ await applyMutationStatusUpdates(
1061
+ options.db,
1062
+ rows[0]!.context,
1063
+ rows.map((row) => {
1064
+ const attemptCount = row.attemptCount + 1;
1065
+ const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);
1066
+ return {
1067
+ mutationId: row.mutationId,
1068
+ status: outcome.status,
1069
+ attemptCount,
1070
+ updatedAtUs: failedAtUs,
1071
+ lastError: errorMessage,
1072
+ nextRetryAtUs: outcome.nextRetryAtUs,
1073
+ lastHttpStatus: httpStatus,
1074
+ conflictReason: null,
1075
+ };
1076
+ }),
1077
+ );
1078
+ }
1079
+ throw error;
1080
+ }
1081
+
1082
+ // Apply each member's ack.
1083
+ const ackedAtUs = nowMicroseconds();
1084
+ const failedAtUs = nowMicroseconds();
1085
+ const rejectedIds = new Set<string>();
1086
+ const conflictedIds = new Set<string>();
1087
+
1088
+ for (const rows of byContext.values()) {
1089
+ await applyMutationStatusUpdates(
1090
+ options.db,
1091
+ rows[0]!.context,
1092
+ rows.map((row) => {
1093
+ const ack = acksByMutationId.get(row.mutationId);
1094
+
1095
+ if (ack?.status === "rejected") {
1096
+ // ADR-0022 §4: a business rejection. Terminal `rejected`; the overlay is auto-discarded below.
1097
+ rejectedIds.add(row.mutationId);
1098
+ return {
1099
+ mutationId: row.mutationId,
1100
+ status: "rejected" as const,
1101
+ attemptCount: row.attemptCount + 1,
1102
+ updatedAtUs: failedAtUs,
1103
+ lastError: ack.rejectionReason ?? "Rejected by the authoritative endpoint",
1104
+ nextRetryAtUs: null,
1105
+ lastHttpStatus: ack.httpStatus ?? 409,
1106
+ conflictReason: ack.rejectionReason ?? "Rejected by the authoritative endpoint",
1107
+ };
1108
+ }
1109
+
1110
+ if (ack?.status === "conflicted") {
1111
+ // ADR-0015: a stale member — terminal `conflicted`, overlay KEPT (resolve as a new write).
1112
+ conflictedIds.add(row.mutationId);
1113
+ return {
1114
+ mutationId: row.mutationId,
1115
+ status: "conflicted" as const,
1116
+ attemptCount: row.attemptCount + 1,
1117
+ updatedAtUs: failedAtUs,
1118
+ serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
1119
+ replaceServerUpdatedAtUs: true,
1120
+ lastError: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
1121
+ nextRetryAtUs: null,
1122
+ lastHttpStatus: ack.httpStatus ?? 409,
1123
+ conflictReason: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
1124
+ };
1125
+ }
1126
+
1127
+ if (!ack || ack.status !== "acked") {
1128
+ const attemptCount = row.attemptCount + 1;
1129
+ const outcome = resolveFailureOutcome(
1130
+ ack?.httpStatus ?? null,
1131
+ attemptCount,
1132
+ maxMutationAttempts,
1133
+ failedAtUs,
1134
+ );
1135
+ return {
1136
+ mutationId: row.mutationId,
1137
+ status: outcome.status,
1138
+ attemptCount,
1139
+ updatedAtUs: failedAtUs,
1140
+ lastError: ack?.conflictReason ?? "Authoritative write not acknowledged",
1141
+ nextRetryAtUs: outcome.nextRetryAtUs,
1142
+ lastHttpStatus: ack?.httpStatus ?? null,
1143
+ conflictReason: null,
1144
+ };
1145
+ }
1146
+
1147
+ return {
1148
+ mutationId: row.mutationId,
1149
+ status: "acked" as const,
1150
+ attemptCount: row.attemptCount + 1,
1151
+ updatedAtUs: ackedAtUs,
1152
+ ackedAtUs,
1153
+ replaceAckedAtUs: true,
1154
+ serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
1155
+ replaceServerUpdatedAtUs: true,
1156
+ lastError: null,
1157
+ nextRetryAtUs: null,
1158
+ lastHttpStatus: row.mutationKind === "delete" ? 204 : 200,
1159
+ conflictReason: null,
1160
+ };
1161
+ }),
1162
+ );
1163
+ }
1164
+
1165
+ // ADR-0022 §4: auto-discard the optimistic overlay for every rejected entity (the whole unit was
1166
+ // declined). The terminal `rejected` journal row is kept for diagnostics + `onReject`.
1167
+ for (const row of prepared) {
1168
+ if (rejectedIds.has(row.mutationId)) {
1169
+ await discardOverlayForSettledEntity(options.db, row.context, row.entityKey, row.entityKeyJson);
1170
+ }
1171
+ }
1172
+
1173
+ const affectedContexts = [...byContext.keys()]
1174
+ .map((key) => tableContexts[key])
1175
+ .filter((context): context is TableContext => context != null);
1176
+ for (const context of affectedContexts) {
1177
+ await reconcileTable(options.db, context);
1178
+ }
1179
+
1180
+ if (rejectedIds.size > 0 && options.onReject) {
1181
+ const details = await readMutationDetailsForContexts(options.db, affectedContexts, rejectedIds);
1182
+ if (details.length > 0) {
1183
+ await options.onReject(details);
1184
+ }
1185
+ }
1186
+ if (conflictedIds.size > 0 && options.onConflict) {
1187
+ const details = await readMutationDetailsForContexts(options.db, affectedContexts, conflictedIds);
1188
+ if (details.length > 0) {
1189
+ await options.onConflict(details);
1190
+ }
1191
+ }
1192
+
1193
+ return { acks: [...acksByMutationId.values()] };
1194
+ },
494
1195
  reconcile: async (table) => {
495
1196
  const contexts = filterContexts(tableContexts, table);
496
1197
 
@@ -499,44 +1200,71 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
499
1200
  }
500
1201
  },
501
1202
  retryFailed: async (table) => {
1203
+ assertValidMutationTransition("failed", "pending");
502
1204
  const contexts = filterContexts(tableContexts, table);
503
1205
  const nowUs = nowMicroseconds();
504
1206
 
505
1207
  for (const context of contexts) {
506
- await options.db.query(
507
- `
508
- UPDATE ${context.journalTable}
509
- SET
510
- status = 'pending',
511
- next_retry_at_us = $1::bigint,
512
- updated_at_us = $1::bigint,
513
- conflict_reason = NULL
514
- WHERE status = 'failed'
515
- `,
516
- [nowUs],
517
- );
1208
+ const journal = context.tables.journal;
1209
+ const query = queryBuilder
1210
+ .update(journal)
1211
+ .set({ status: "pending", nextRetryAtUs: nowUs, updatedAtUs: nowUs, conflictReason: null })
1212
+ .where(eq(journal.status, "failed"))
1213
+ .toSQL();
1214
+ await options.db.query(query.sql, query.params as unknown[]);
518
1215
  }
519
1216
  },
520
1217
  recoverSending: async (table) => {
1218
+ assertValidMutationTransition("sending", "pending");
521
1219
  const contexts = filterContexts(tableContexts, table);
522
1220
  const nowUs = nowMicroseconds();
523
1221
 
524
1222
  for (const context of contexts) {
525
- await options.db.query(
526
- `
527
- UPDATE ${context.journalTable}
528
- SET
529
- status = 'pending',
530
- updated_at_us = $1::bigint,
531
- sent_at_us = NULL,
532
- next_retry_at_us = $1::bigint,
533
- last_error = NULL,
534
- last_http_status = NULL,
535
- conflict_reason = NULL
536
- WHERE status = 'sending'
537
- `,
538
- [nowUs],
539
- );
1223
+ const journal = context.tables.journal;
1224
+ const query = queryBuilder
1225
+ .update(journal)
1226
+ .set({
1227
+ status: "pending",
1228
+ updatedAtUs: nowUs,
1229
+ sentAtUs: null,
1230
+ nextRetryAtUs: nowUs,
1231
+ lastError: null,
1232
+ lastHttpStatus: null,
1233
+ conflictReason: null,
1234
+ })
1235
+ .where(eq(journal.status, "sending"))
1236
+ .toSQL();
1237
+ await options.db.query(query.sql, query.params as unknown[]);
1238
+ }
1239
+ },
1240
+ quarantineRecovered: async (table) => {
1241
+ // The restore-boot quarantine (ADR-0035 decision 6): every non-terminal recovered row is parked in the
1242
+ // terminal `quarantined` state so NOTHING recovered from a backup auto-flushes (no dedupe ledger →
1243
+ // unsafe replay). `pending -> quarantined` is a restore-only edge (see mutation-state.ts); `sending`
1244
+ // and `failed` already reach quarantine. Assert all three edges up front so a future transition-table
1245
+ // change that breaks restore fails loudly here rather than silently skipping the quarantine.
1246
+ assertValidMutationTransition("pending", "quarantined");
1247
+ assertValidMutationTransition("sending", "quarantined");
1248
+ assertValidMutationTransition("failed", "quarantined");
1249
+ const contexts = filterContexts(tableContexts, table);
1250
+ const nowUs = nowMicroseconds();
1251
+
1252
+ for (const context of contexts) {
1253
+ const journal = context.tables.journal;
1254
+ const query = queryBuilder
1255
+ .update(journal)
1256
+ .set({
1257
+ status: "quarantined",
1258
+ updatedAtUs: nowUs,
1259
+ // Terminal: never retried, so clear the retry cursor and name restore as the cause on the row so
1260
+ // an inspecting app can tell a restore-quarantined write from a server-rejected one.
1261
+ nextRetryAtUs: null,
1262
+ lastError: "Quarantined on restore: recovered from a store backup, not replayed (ADR-0035).",
1263
+ conflictReason: null,
1264
+ })
1265
+ .where(inArray(journal.status, ["pending", "sending", "failed"]))
1266
+ .toSQL();
1267
+ await options.db.query(query.sql, query.params as unknown[]);
540
1268
  }
541
1269
  },
542
1270
  readMutationStats: async (table) => {
@@ -545,18 +1273,33 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
545
1273
  pendingCount: 0,
546
1274
  sendingCount: 0,
547
1275
  failedCount: 0,
1276
+ quarantinedCount: 0,
1277
+ conflictedCount: 0,
548
1278
  ackedCount: 0,
549
1279
  };
550
1280
 
551
1281
  for (const context of contexts) {
552
- const result = await options.db.query<MutationDiagnostics & Record<string, unknown>>(`
553
- SELECT
554
- COUNT(*) FILTER (WHERE status = 'pending')::int AS "pendingCount",
555
- COUNT(*) FILTER (WHERE status = 'sending')::int AS "sendingCount",
556
- COUNT(*) FILTER (WHERE status = 'failed')::int AS "failedCount",
557
- COUNT(*) FILTER (WHERE status = 'acked')::int AS "ackedCount"
558
- FROM ${context.journalTable}
559
- `);
1282
+ const journal = context.tables.journal;
1283
+ // Drizzle has no `FILTER` operator (tier ②): each aggregate is a typed `sql` fragment over the
1284
+ // journal `status` column object with a bound status literal, aliased to the exact camelCase row
1285
+ // key the totals below read (the raw seam returns rows UNMAPPED, so aliases are load-bearing).
1286
+ const filteredCount = (status: MutationStatus, columnAlias: string) =>
1287
+ sql<number>`count(*) filter (where ${journal.status} = ${status})::int`.as(columnAlias);
1288
+ const query = queryBuilder
1289
+ .select({
1290
+ pendingCount: filteredCount("pending", "pendingCount"),
1291
+ sendingCount: filteredCount("sending", "sendingCount"),
1292
+ failedCount: filteredCount("failed", "failedCount"),
1293
+ quarantinedCount: filteredCount("quarantined", "quarantinedCount"),
1294
+ conflictedCount: filteredCount("conflicted", "conflictedCount"),
1295
+ ackedCount: filteredCount("acked", "ackedCount"),
1296
+ })
1297
+ .from(journal)
1298
+ .toSQL();
1299
+ const result = await options.db.query<MutationDiagnostics & Record<string, unknown>>(
1300
+ query.sql,
1301
+ query.params as unknown[],
1302
+ );
560
1303
 
561
1304
  const row = result.rows[0];
562
1305
  if (!row) {
@@ -566,6 +1309,8 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
566
1309
  totals.pendingCount += row.pendingCount;
567
1310
  totals.sendingCount += row.sendingCount;
568
1311
  totals.failedCount += row.failedCount;
1312
+ totals.quarantinedCount += row.quarantinedCount;
1313
+ totals.conflictedCount += row.conflictedCount;
569
1314
  totals.ackedCount += row.ackedCount;
570
1315
  }
571
1316
 
@@ -573,53 +1318,79 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
573
1318
  },
574
1319
  readMutationDetails: async (table) => {
575
1320
  const contexts = filterContexts(tableContexts, table);
576
- const rows: MutationDetail[] = [];
577
-
578
- for (const context of contexts) {
579
- const result = await options.db.query<MutationDetailRow>(`
580
- SELECT
581
- mutation_id AS "mutationId",
582
- entity_key_json AS "entityKeyJson",
583
- mutation_seq AS "mutationSeq",
584
- mutation_kind AS "mutationKind",
585
- status,
586
- attempt_count AS "attemptCount",
587
- last_http_status AS "lastHttpStatus",
588
- last_error AS "lastError",
589
- conflict_reason AS "conflictReason",
590
- next_retry_at_us::text AS "nextRetryAtUs",
591
- server_updated_at_us::text AS "serverUpdatedAtUs",
592
- updated_at_us::text AS "updatedAtUs"
593
- FROM ${context.journalTable}
594
- ORDER BY updated_at_us DESC, mutation_seq DESC
595
- `);
596
-
597
- rows.push(
598
- ...result.rows.map((row) => ({
599
- tableName: context.key,
600
- entityKey: JSON.parse(row.entityKeyJson) as Record<string, string>,
601
- mutationId: row.mutationId,
602
- mutationSeq: row.mutationSeq,
603
- mutationKind: row.mutationKind,
604
- status: row.status,
605
- attemptCount: row.attemptCount,
606
- lastHttpStatus: row.lastHttpStatus,
607
- lastError: row.lastError,
608
- conflictReason: row.conflictReason,
609
- nextRetryAtUs: row.nextRetryAtUs,
610
- serverUpdatedAtUs: row.serverUpdatedAtUs,
611
- updatedAtUs: row.updatedAtUs,
612
- })),
613
- );
614
- }
615
-
616
- return rows.sort((left, right) => Number(right.updatedAtUs) - Number(left.updatedAtUs));
1321
+ return readMutationDetailsForContexts(options.db, contexts);
617
1322
  },
618
1323
  createOptimisticRecord: (table, input) => {
619
1324
  const context = getTableContext(table);
620
1325
  return createOptimisticRecordFromContext(context, input);
621
1326
  },
622
1327
  };
1328
+
1329
+ return runtime;
1330
+ }
1331
+
1332
+ /**
1333
+ * Read journal entries across the given contexts as {@link MutationDetail}s, newest first.
1334
+ * Shared by the public `readMutationDetails` and the flush path's quarantine surfacing,
1335
+ * optionally narrowed to a set of mutation ids.
1336
+ */
1337
+ async function readMutationDetailsForContexts(
1338
+ db: MutationDb,
1339
+ contexts: TableContext[],
1340
+ mutationIds?: ReadonlySet<string>,
1341
+ ): Promise<MutationDetail[]> {
1342
+ const rows: MutationDetail[] = [];
1343
+
1344
+ for (const context of contexts) {
1345
+ const journal = context.tables.journal;
1346
+ // The raw seam returns rows UNMAPPED (no drizzle result mapping), so every field is aliased
1347
+ // explicitly to its camelCase row key, and the `_us` bigints keep their `::text` casts.
1348
+ const query = queryBuilder
1349
+ .select({
1350
+ mutationId: sql<string>`${journal.mutationId}`.as("mutationId"),
1351
+ entityKeyJson: sql<string>`${journal.entityKeyJson}`.as("entityKeyJson"),
1352
+ mutationSeq: sql<number>`${journal.mutationSeq}`.as("mutationSeq"),
1353
+ mutationKind: sql<MutationKind>`${journal.mutationKind}`.as("mutationKind"),
1354
+ status: journal.status,
1355
+ attemptCount: sql<number>`${journal.attemptCount}`.as("attemptCount"),
1356
+ lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as("lastHttpStatus"),
1357
+ lastError: sql<string | null>`${journal.lastError}`.as("lastError"),
1358
+ conflictReason: sql<string | null>`${journal.conflictReason}`.as("conflictReason"),
1359
+ nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as("nextRetryAtUs"),
1360
+ serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
1361
+ updatedAtUs: sql<string>`${journal.updatedAtUs}::text`.as("updatedAtUs"),
1362
+ registryVersion: sql<string | null>`${journal.registryVersion}`.as("registryVersion"),
1363
+ })
1364
+ .from(journal)
1365
+ .orderBy(desc(journal.updatedAtUs), desc(journal.mutationSeq))
1366
+ .toSQL();
1367
+ const result = await db.query<MutationDetailRow>(query.sql, query.params as unknown[]);
1368
+
1369
+ for (const row of result.rows) {
1370
+ if (mutationIds && !mutationIds.has(row.mutationId)) {
1371
+ continue;
1372
+ }
1373
+
1374
+ rows.push({
1375
+ tableName: context.key,
1376
+ entityKey: JSON.parse(row.entityKeyJson) as Record<string, string>,
1377
+ mutationId: row.mutationId,
1378
+ mutationSeq: row.mutationSeq,
1379
+ mutationKind: row.mutationKind,
1380
+ status: row.status,
1381
+ attemptCount: row.attemptCount,
1382
+ lastHttpStatus: row.lastHttpStatus,
1383
+ lastError: row.lastError,
1384
+ conflictReason: row.conflictReason,
1385
+ nextRetryAtUs: row.nextRetryAtUs,
1386
+ serverUpdatedAtUs: row.serverUpdatedAtUs,
1387
+ updatedAtUs: row.updatedAtUs,
1388
+ registryVersion: row.registryVersion,
1389
+ });
1390
+ }
1391
+ }
1392
+
1393
+ return rows.sort((left, right) => Number(right.updatedAtUs) - Number(left.updatedAtUs));
623
1394
  }
624
1395
 
625
1396
  interface MutationRow extends Record<string, unknown> {
@@ -635,6 +1406,7 @@ interface MutationRow extends Record<string, unknown> {
635
1406
  conflictReason: string | null;
636
1407
  nextRetryAtUs: string | null;
637
1408
  serverUpdatedAtUs: string | null;
1409
+ registryVersion: string | null;
638
1410
  }
639
1411
 
640
1412
  interface MutationDetailRow extends Record<string, unknown> {
@@ -650,6 +1422,7 @@ interface MutationDetailRow extends Record<string, unknown> {
650
1422
  nextRetryAtUs: string | null;
651
1423
  serverUpdatedAtUs: string | null;
652
1424
  updatedAtUs: string;
1425
+ registryVersion: string | null;
653
1426
  }
654
1427
 
655
1428
  interface CurrentRecordStateRow extends Record<string, unknown> {
@@ -685,6 +1458,19 @@ interface PlannedMutationInsert {
685
1458
  mutationKind: MutationKind;
686
1459
  payloadJson: string;
687
1460
  nowUs: string;
1461
+ /**
1462
+ * The Base server version (ADR-0015) stamped at enqueue: the synced Server version the user saw,
1463
+ * for a **chain head** (the first staged write on the entity). `null` for a `create` (no base) and
1464
+ * for a **chained** write — the latter resolves its base at flush from its acked predecessor
1465
+ * (readPendingBatchRows), by Per-entity flush serialization (ADR-0014).
1466
+ */
1467
+ baseServerVersion: string | null;
1468
+ /**
1469
+ * A per-row `write_mode` override (ADR-0022 addendum). Left unset for an ordinary row, which inherits the
1470
+ * unit's mode at insert. A blind update sets `"pessimistic-blind"` so the row is flushed only by its unit's
1471
+ * foreground path (never the optimistic batch) and retires from the journal without a synced echo.
1472
+ */
1473
+ writeMode?: string | null;
688
1474
  }
689
1475
 
690
1476
  interface PlannedOverlayUpsert {
@@ -723,6 +1509,8 @@ type NormalizedBatchItem =
723
1509
  entityKey: Record<string, string>;
724
1510
  entityKeyJson: string;
725
1511
  patch: Record<string, unknown>;
1512
+ /** A blind update (ADR-0022 addendum): journal-only, no base-row presence check, no overlay. */
1513
+ blind: boolean;
726
1514
  mutationId: string;
727
1515
  nowUs: string;
728
1516
  order: number;
@@ -737,17 +1525,49 @@ type NormalizedBatchItem =
737
1525
  order: number;
738
1526
  };
739
1527
 
1528
+ /**
1529
+ * The Base server version (ADR-0015) to stamp at enqueue for an update/delete. Only a **chain head**
1530
+ * — the first staged write on the entity (no earlier unresolved mutation) — captures an enqueue-time
1531
+ * base: the synced Server version the user's edit was authored against, so a genuine external write
1532
+ * between view and apply is caught. A **chained** write (an earlier same-entity mutation is still
1533
+ * owed) returns `null` here; it resolves its base at flush from its acked predecessor, so an entity's
1534
+ * own successive edits never self-conflict (decision 2).
1535
+ */
1536
+ function captureChainHeadBase(context: TableContext, entityState: BatchEntityState): string | null {
1537
+ if ((entityState.latestMutationSeq ?? 0) !== 0) {
1538
+ return null;
1539
+ }
1540
+
1541
+ if (!context.serverVersionPropertyKey || !entityState.record) {
1542
+ return null;
1543
+ }
1544
+
1545
+ // The Server version is a bigint count of microseconds, surfaced as a string/number/bigint
1546
+ // depending on the read path. Anything else (null/object) means no observable base.
1547
+ const raw = entityState.record[context.serverVersionPropertyKey];
1548
+ if (typeof raw === "string" || typeof raw === "number" || typeof raw === "bigint") {
1549
+ return String(raw);
1550
+ }
1551
+
1552
+ return null;
1553
+ }
1554
+
740
1555
  function buildTableContexts<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
741
1556
  const localSchema = getSyncRegistrySchema(registry);
742
1557
 
743
1558
  return Object.fromEntries(
744
1559
  Object.entries(registry)
745
1560
  .filter(([, entry]) => entry.mode !== "readonly")
746
- .map(([key, entry]) => [key, buildTableContext(key, entry, localSchema)]),
1561
+ .map(([key, entry]) => [key, buildTableContext(registry, key, entry, localSchema)]),
747
1562
  ) as Partial<Record<SyncTableName<TRegistry>, TableContext>>;
748
1563
  }
749
1564
 
750
- function buildTableContext(key: string, entry: SyncTableEntry<AnyPgTable>, localSchema: string): TableContext {
1565
+ function buildTableContext<TRegistry extends SyncTableRegistry>(
1566
+ registry: TRegistry,
1567
+ key: string,
1568
+ entry: SyncTableEntry<AnyPgTable>,
1569
+ localSchema: string,
1570
+ ): TableContext {
751
1571
  if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {
752
1572
  throw new Error(`overlay and journal tables are required for writable table ${key}`);
753
1573
  }
@@ -767,6 +1587,58 @@ function buildTableContext(key: string, entry: SyncTableEntry<AnyPgTable>, local
767
1587
  return column.propertyKey;
768
1588
  });
769
1589
 
1590
+ const serverVersionColumnName = resolveServerVersionColumnName(entry) ?? null;
1591
+ const serverVersionPropertyKey = serverVersionColumnName
1592
+ ? (columns.find((candidate) => candidate.column.name === serverVersionColumnName)?.propertyKey ?? null)
1593
+ : null;
1594
+
1595
+ // Resolve the `nowMicroseconds` managed fields generically from governance, not by property name.
1596
+ // `field.column` is a drizzle property key, but tolerate a column-name declaration too.
1597
+ const resolveManagedPropertyKey = (fieldColumn: string): string | undefined =>
1598
+ columns.find((candidate) => candidate.propertyKey === fieldColumn || candidate.column.name === fieldColumn)
1599
+ ?.propertyKey;
1600
+ const nowMicrosecondsManagedFields = (entry.governance?.managedFields ?? []).filter(
1601
+ (field) => field.strategy === "nowMicroseconds",
1602
+ );
1603
+ const managedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields
1604
+ .map((field) => resolveManagedPropertyKey(field.column as string))
1605
+ .filter((propertyKey): propertyKey is string => propertyKey !== undefined);
1606
+ const updateManagedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields
1607
+ .filter((field) => field.applyOn.includes("update"))
1608
+ .map((field) => resolveManagedPropertyKey(field.column as string))
1609
+ .filter((propertyKey): propertyKey is string => propertyKey !== undefined);
1610
+
1611
+ const managedAuthClaimCreateFields = (entry.governance?.managedFields ?? [])
1612
+ .filter((field) => field.strategy === "authClaim" && field.applyOn.includes("create"))
1613
+ .flatMap((field) => {
1614
+ const propertyKey = resolveManagedPropertyKey(field.column as string);
1615
+ return propertyKey && field.claimPath ? [{ propertyKey, claimPath: field.claimPath }] : [];
1616
+ });
1617
+
1618
+ // The generated local relations as runtime Drizzle objects (memoized per registry+key in
1619
+ // local-tables.ts), plus name-resolved column handles the statement authors below need:
1620
+ // overlay/synced columns are keyed by PROPERTY key, so PK columns (a DB-column-name concept,
1621
+ // ADR-0012) are resolved once here by matching `.name`.
1622
+ const tables = {
1623
+ synced: getSyncedLocalTable(registry, key as string & keyof TRegistry),
1624
+ overlay: getOverlayTable(registry, key as string & keyof TRegistry),
1625
+ journal: getJournalTable(registry, key as string & keyof TRegistry),
1626
+ };
1627
+ const overlayColumnsByPropertyKey = getColumns(tables.overlay) as Record<string, PgColumn>;
1628
+ const syncedColumnsByPropertyKey = getColumns(tables.synced) as Record<string, PgColumn>;
1629
+ const resolvePkColumns = (columnsByKey: Record<string, PgColumn>, relation: string) =>
1630
+ entry.primaryKey.columns.map((columnName) => {
1631
+ const column = Object.values(columnsByKey).find((candidate) => candidate.name === columnName);
1632
+ if (!column) {
1633
+ throw new Error(`Primary key column ${columnName} was not found on the ${relation} table for ${key}`);
1634
+ }
1635
+ return column;
1636
+ });
1637
+ const syncedServerVersionColumn = serverVersionColumnName
1638
+ ? (Object.values(syncedColumnsByPropertyKey).find((candidate) => candidate.name === serverVersionColumnName) ??
1639
+ null)
1640
+ : null;
1641
+
770
1642
  return {
771
1643
  key,
772
1644
  entry,
@@ -785,8 +1657,19 @@ function buildTableContext(key: string, entry: SyncTableEntry<AnyPgTable>, local
785
1657
  journalSequence: qualifyLocalIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable)),
786
1658
  pkColumnNames: [...entry.primaryKey.columns],
787
1659
  pkPropertyKeys,
1660
+ serverVersionColumnName,
1661
+ serverVersionPropertyKey,
1662
+ managedNowMicrosecondsPropertyKeys,
1663
+ updateManagedNowMicrosecondsPropertyKeys,
1664
+ managedAuthClaimCreateFields,
788
1665
  recordIncludesOverlayState: "overlayTable" in (entry.clientProjection ?? {}),
789
1666
  columns,
1667
+ tables,
1668
+ overlayColumnsByPropertyKey,
1669
+ syncedColumnsByPropertyKey,
1670
+ overlayPkColumns: resolvePkColumns(overlayColumnsByPropertyKey, "overlay"),
1671
+ syncedPkColumns: resolvePkColumns(syncedColumnsByPropertyKey, "synced"),
1672
+ syncedServerVersionColumn,
790
1673
  };
791
1674
  }
792
1675
 
@@ -836,12 +1719,31 @@ function materializeColumnDefault(column: TableContext["columns"][number]["colum
836
1719
  return { ok: false };
837
1720
  }
838
1721
 
839
- function createOptimisticRecordFromContext<TCreate, TRecord>(context: TableContext, input: TCreate): TRecord {
1722
+ function createOptimisticRecordFromContext<TCreate, TRecord>(
1723
+ context: TableContext,
1724
+ input: TCreate,
1725
+ claims?: Record<string, unknown>,
1726
+ ): TRecord {
840
1727
  const record = {
841
1728
  ...(isRecord(input) ? input : {}),
842
1729
  };
843
1730
  const nowUs = nowMicroseconds();
844
1731
 
1732
+ // Stamp `authClaim` create-managed fields (owner/author/created_by) from the decoded claim at the
1733
+ // field's path, so the optimistic overlay row is attributed locally and satisfies the column's NOT
1734
+ // NULL — the server independently stamps the same claim on apply, so the value never flips on
1735
+ // convergence. (`auth.uid()` is just `claimPath: ["sub"]`.)
1736
+ if (claims != null) {
1737
+ for (const { propertyKey, claimPath } of context.managedAuthClaimCreateFields) {
1738
+ if (record[propertyKey] === undefined) {
1739
+ const value = readJwtClaimPath(claims, claimPath);
1740
+ if (value !== undefined) {
1741
+ record[propertyKey] = value;
1742
+ }
1743
+ }
1744
+ }
1745
+ }
1746
+
845
1747
  if (hasProperty(context, "createdAtUs") && record["createdAtUs"] === undefined) {
846
1748
  record["createdAtUs"] = nowUs;
847
1749
  }
@@ -850,6 +1752,15 @@ function createOptimisticRecordFromContext<TCreate, TRecord>(context: TableConte
850
1752
  record["updatedAtUs"] = nowUs;
851
1753
  }
852
1754
 
1755
+ // Generic managed-timestamp fill (governance-driven): stamp any `nowMicroseconds` managed field the
1756
+ // convention block above did not — e.g. a Server version column not named `updated_at_us`. Additive
1757
+ // and idempotent, so convention tables are unaffected (their fields are already filled).
1758
+ for (const propertyKey of context.managedNowMicrosecondsPropertyKeys) {
1759
+ if (record[propertyKey] === undefined) {
1760
+ record[propertyKey] = nowUs;
1761
+ }
1762
+ }
1763
+
853
1764
  for (const { propertyKey, column } of context.columns) {
854
1765
  if (record[propertyKey] !== undefined) {
855
1766
  continue;
@@ -867,6 +1778,18 @@ function createOptimisticRecordFromContext<TCreate, TRecord>(context: TableConte
867
1778
  }) as TRecord;
868
1779
  }
869
1780
 
1781
+ /**
1782
+ * Stamp every on-update `nowMicroseconds` managed field with `nowUs` (governance-driven, ADR-0004),
1783
+ * keyed by drizzle property key. For a convention table this is exactly `{ updatedAtUs: nowUs }`; for
1784
+ * a custom-named Server version it targets that column — so the local optimistic path never assumes
1785
+ * the demo naming the generic server applier does not.
1786
+ */
1787
+ function buildUpdateManagedNowStamp(context: TableContext, nowUs: string): Record<string, string> {
1788
+ return Object.fromEntries(
1789
+ context.updateManagedNowMicrosecondsPropertyKeys.map((propertyKey) => [propertyKey, nowUs]),
1790
+ );
1791
+ }
1792
+
870
1793
  function buildOptimisticRecord(
871
1794
  context: TableContext,
872
1795
  record: Record<string, unknown>,
@@ -895,15 +1818,19 @@ function buildEntityKeyFromRecord(context: TableContext, record: unknown) {
895
1818
  }
896
1819
 
897
1820
  function normalizeEntityKey(context: TableContext, input: Record<string, string>) {
1821
+ // The public API accepts the identity by drizzle property name (ergonomics); past this
1822
+ // boundary the canonical Entity identity is column-keyed (ADR-0012), matching the
1823
+ // journal/overlay PK columns, entity_key_json, and the applier's `v_entity_key->>'<column>'`.
1824
+ // pkPropertyKeys[i] ↔ pkColumnNames[i] by construction (buildTableContext), so we map once here.
898
1825
  return Object.fromEntries(
899
- context.pkPropertyKeys.map((propertyKey) => {
1826
+ context.pkPropertyKeys.map((propertyKey, index) => {
900
1827
  const value = input[propertyKey];
901
1828
 
902
1829
  if (value === undefined) {
903
1830
  throw new Error(`Missing entity key property ${propertyKey} for table ${context.key}`);
904
1831
  }
905
1832
 
906
- return [propertyKey, String(value)];
1833
+ return [context.pkColumnNames[index]!, String(value)];
907
1834
  }),
908
1835
  );
909
1836
  }
@@ -936,32 +1863,26 @@ async function readLatestMutationStates(
936
1863
  return new Map<string, BatchLatestMutationStateRow>();
937
1864
  }
938
1865
 
939
- const { cteSql, params } = buildBatchEntityInputCte(context, entities);
940
- const result = await db.query<BatchLatestMutationStateRow>(
941
- `
942
- WITH ${cteSql},
943
- latest_mutations AS (
944
- SELECT DISTINCT ON (journal.entity_key_json)
945
- journal.entity_key_json,
946
- journal.mutation_seq,
947
- journal.mutation_kind,
948
- journal.status
949
- FROM ${context.journalTable} AS journal
950
- JOIN input_entities AS input
951
- ON input.entity_key_json = journal.entity_key_json
952
- ORDER BY journal.entity_key_json, journal.mutation_seq DESC
953
- )
954
- SELECT
955
- input.entity_key_json AS "entityKeyJson",
956
- latest.mutation_seq AS "latestMutationSeq",
957
- latest.mutation_kind AS "latestMutationKind",
958
- latest.status AS "latestMutationStatus"
959
- FROM input_entities AS input
960
- LEFT JOIN latest_mutations AS latest
961
- ON latest.entity_key_json = input.entity_key_json
962
- `,
963
- params,
964
- );
1866
+ // The old VALUES-CTE + LEFT-JOIN-back-to-input existed only to emit null rows for entities with
1867
+ // no journal history; the caller reads via `map.get(...) ?? null`, so a missing key is equivalent.
1868
+ const journal = context.tables.journal;
1869
+ const query = queryBuilder
1870
+ .selectDistinctOn([journal.entityKeyJson], {
1871
+ entityKeyJson: sql<string>`${journal.entityKeyJson}`.as("entityKeyJson"),
1872
+ latestMutationSeq: sql<number>`${journal.mutationSeq}`.as("latestMutationSeq"),
1873
+ latestMutationKind: sql<MutationKind>`${journal.mutationKind}`.as("latestMutationKind"),
1874
+ latestMutationStatus: sql<MutationStatus>`${journal.status}`.as("latestMutationStatus"),
1875
+ })
1876
+ .from(journal)
1877
+ .where(
1878
+ inArray(
1879
+ journal.entityKeyJson,
1880
+ entities.map((entity) => entity.entityKeyJson),
1881
+ ),
1882
+ )
1883
+ .orderBy(journal.entityKeyJson, desc(journal.mutationSeq))
1884
+ .toSQL();
1885
+ const result = await db.query<BatchLatestMutationStateRow>(query.sql, query.params as unknown[]);
965
1886
 
966
1887
  return new Map(result.rows.map((row) => [row.entityKeyJson, row]));
967
1888
  }
@@ -971,40 +1892,47 @@ async function readCurrentRecordStates(db: MutationDb, context: TableContext, en
971
1892
  return new Map<string, BatchCurrentRecordStateRow>();
972
1893
  }
973
1894
 
974
- const { cteSql, params } = buildBatchEntityInputCte(context, entities);
975
- const overlaySelectColumns = buildContextSelectColumns(context, "overlay");
976
- const syncedSelectColumns = buildContextSelectColumns(context, "synced");
977
- const inputOverlayJoin = buildBatchEntityJoinClause(context, "overlay", "input");
978
- const inputSyncedJoin = buildBatchEntityJoinClause(context, "synced", "input");
979
- const syncedLocalUpdatedSql = hasProperty(context, "updatedAtUs")
980
- ? 'synced.updated_at_us::text AS "localUpdatedAtUs"'
981
- : `'0' AS "localUpdatedAtUs"`;
982
-
983
- const result = await db.query<BatchCurrentRecordStateRow>(
984
- `
985
- WITH ${cteSql},
1895
+ // Tier ②: the overlay-∪-synced shape over an input VALUES table. The input CTE carries each
1896
+ // entity's `entity_key_json` alongside its PK values (the caller maps rows back by that JSON), so
1897
+ // it cannot be a plain builder select; every identifier still comes from the table objects /
1898
+ // `sql.identifier`, and every value is a bound (cast-typed) param.
1899
+ const overlay = context.tables.overlay;
1900
+ const synced = context.tables.synced;
1901
+ const inputCte = buildEntityInputCte(context, entities);
1902
+ const overlaySelectColumns = buildProjectedSelectColumns(context, context.overlayColumnsByPropertyKey);
1903
+ const syncedSelectColumns = buildProjectedSelectColumns(context, context.syncedColumnsByPropertyKey);
1904
+ const inputOverlayJoin = buildEntityInputJoin(context.pkColumnNames, context.overlayPkColumns);
1905
+ const inputSyncedJoin = buildEntityInputJoin(context.pkColumnNames, context.syncedPkColumns);
1906
+ const syncedUpdatedAtColumn = context.syncedColumnsByPropertyKey["updatedAtUs"];
1907
+ const syncedLocalUpdated =
1908
+ hasProperty(context, "updatedAtUs") && syncedUpdatedAtColumn
1909
+ ? sql`${syncedUpdatedAtColumn}::text AS "localUpdatedAtUs"`
1910
+ : sql`'0' AS "localUpdatedAtUs"`;
1911
+
1912
+ const query = queryDialect.sqlToQuery(sql`
1913
+ WITH ${inputCte},
986
1914
  overlay_rows AS (
987
1915
  SELECT
988
1916
  input.entity_key_json AS "entityKeyJson",
989
- ${overlaySelectColumns.join(",\n ")},
990
- overlay.overlay_kind AS "overlayKind",
991
- overlay.local_updated_at_us::text AS "localUpdatedAtUs"
1917
+ ${overlaySelectColumns},
1918
+ ${overlay.overlayKind} AS "overlayKind",
1919
+ ${overlay.localUpdatedAtUs}::text AS "localUpdatedAtUs"
992
1920
  FROM input_entities AS input
993
- JOIN ${context.overlayTable} AS overlay
1921
+ JOIN ${overlay}
994
1922
  ON ${inputOverlayJoin}
995
1923
  ),
996
1924
  synced_rows AS (
997
1925
  SELECT
998
1926
  input.entity_key_json AS "entityKeyJson",
999
- ${syncedSelectColumns.join(",\n ")},
1000
- 'synced' AS "overlayKind",
1001
- ${syncedLocalUpdatedSql}
1927
+ ${syncedSelectColumns},
1928
+ ${"synced"} AS "overlayKind",
1929
+ ${syncedLocalUpdated}
1002
1930
  FROM input_entities AS input
1003
- JOIN ${context.syncedTable} AS synced
1931
+ JOIN ${synced}
1004
1932
  ON ${inputSyncedJoin}
1005
1933
  WHERE NOT EXISTS (
1006
1934
  SELECT 1
1007
- FROM ${context.overlayTable} AS overlay
1935
+ FROM ${overlay}
1008
1936
  WHERE ${inputOverlayJoin}
1009
1937
  )
1010
1938
  )
@@ -1013,72 +1941,58 @@ async function readCurrentRecordStates(db: MutationDb, context: TableContext, en
1013
1941
  UNION ALL
1014
1942
  SELECT *
1015
1943
  FROM synced_rows
1016
- `,
1017
- params,
1018
- );
1944
+ `);
1945
+ const result = await db.query<BatchCurrentRecordStateRow>(query.sql, query.params as unknown[]);
1019
1946
 
1020
1947
  return new Map(result.rows.map((row) => [row.entityKeyJson, row]));
1021
1948
  }
1022
1949
 
1023
- async function insertMutationsBulk(db: MutationDb, context: TableContext, rows: ReadonlyArray<PlannedMutationInsert>) {
1950
+ async function insertMutationsBulk(
1951
+ db: MutationDb,
1952
+ context: TableContext,
1953
+ rows: ReadonlyArray<PlannedMutationInsert>,
1954
+ registryVersion: string | null,
1955
+ unit?: WriteUnit,
1956
+ ) {
1024
1957
  if (rows.length === 0) {
1025
1958
  return;
1026
1959
  }
1027
1960
 
1028
- const insertColumnNames = [
1029
- "mutation_id",
1030
- ...context.pkColumnNames,
1031
- "entity_key_json",
1032
- "mutation_seq",
1033
- "mutation_kind",
1034
- "status",
1035
- "payload_json",
1036
- "enqueued_at_us",
1037
- "next_retry_at_us",
1038
- "updated_at_us",
1039
- ];
1040
- const params: unknown[] = [];
1041
- const tuples = rows.map((row) => {
1042
- const start = params.length;
1043
- const values = [
1044
- row.mutationId,
1045
- ...context.pkPropertyKeys.map((propertyKey) => row.entityKey[propertyKey]),
1046
- row.entityKeyJson,
1047
- row.mutationKind,
1048
- "pending",
1049
- row.payloadJson,
1050
- row.nowUs,
1051
- row.nowUs,
1052
- row.nowUs,
1053
- ];
1961
+ // ADR-0022: a dynamic write-unit tags every row of the batch with one shared unit id + mode; the
1962
+ // default path leaves both NULL (the flusher derives mode/unit from the static group). A blind row
1963
+ // carries its own `write_mode` override (`pessimistic-blind`), so the mode is resolved per row.
1964
+ const writeUnit = unit?.id ?? null;
1965
+ const journal = context.tables.journal;
1966
+ // `mutationSeq` is intentionally omitted: the generated journal DDL carries
1967
+ // `mutation_seq ... DEFAULT nextval(<journal sequence>)`, so the DB default assigns it — drizzle
1968
+ // renders `default` for every column a row does not provide.
1969
+ const values = rows.map((row) => ({
1970
+ mutationId: row.mutationId,
1971
+ ...Object.fromEntries(context.pkColumnNames.map((columnName) => [columnName, row.entityKey[columnName]])),
1972
+ entityKeyJson: row.entityKeyJson,
1973
+ mutationKind: row.mutationKind,
1974
+ status: "pending",
1975
+ registryVersion,
1976
+ baseServerVersion: row.baseServerVersion,
1977
+ payloadJson: row.payloadJson,
1978
+ enqueuedAtUs: row.nowUs,
1979
+ nextRetryAtUs: row.nowUs,
1980
+ updatedAtUs: row.nowUs,
1981
+ writeUnit,
1982
+ writeMode: row.writeMode ?? unit?.mode ?? null,
1983
+ }));
1054
1984
 
1055
- params.push(...values);
1056
-
1057
- const valuePlaceholders = [
1058
- formatSqlValuePlaceholder(start + 1, "mutation_id"),
1059
- ...context.pkColumnNames.map((columnName, index) => formatSqlValuePlaceholder(start + index + 2, columnName)),
1060
- formatSqlValuePlaceholder(start + context.pkColumnNames.length + 2, "entity_key_json"),
1061
- `nextval('${escapeSqlString(context.journalSequence)}')::integer`,
1062
- formatSqlValuePlaceholder(start + context.pkColumnNames.length + 3, "mutation_kind"),
1063
- formatSqlValuePlaceholder(start + context.pkColumnNames.length + 4, "status"),
1064
- formatSqlValuePlaceholder(start + context.pkColumnNames.length + 5, "payload_json"),
1065
- formatSqlValuePlaceholder(start + context.pkColumnNames.length + 6, "enqueued_at_us"),
1066
- formatSqlValuePlaceholder(start + context.pkColumnNames.length + 7, "next_retry_at_us"),
1067
- formatSqlValuePlaceholder(start + context.pkColumnNames.length + 8, "updated_at_us"),
1068
- ];
1985
+ const query = queryBuilder
1986
+ .insert(journal)
1987
+ .values(values as PgInsertValue<JournalTable>[])
1988
+ .toSQL();
1989
+ await db.query(query.sql, query.params as unknown[]);
1069
1990
 
1070
- return `(${valuePlaceholders.join(", ")})`;
1071
- });
1072
-
1073
- await db.query(
1074
- `
1075
- INSERT INTO ${context.journalTable} (
1076
- ${insertColumnNames.join(", ")}
1077
- )
1078
- VALUES ${tuples.join(",\n ")}
1079
- `,
1080
- params,
1081
- );
1991
+ // Lifecycle origin: the moment each mutation is first staged into the journal. Correlates by id with
1992
+ // the later "board-write sending"/"board-write acks" lines (staged → sent → acked, per id).
1993
+ for (const row of rows) {
1994
+ syncDebug("mutation staged", { mutationId: row.mutationId, table: context.key });
1995
+ }
1082
1996
  }
1083
1997
 
1084
1998
  async function upsertOverlayRecordsBulk(
@@ -1090,113 +2004,106 @@ async function upsertOverlayRecordsBulk(
1090
2004
  return;
1091
2005
  }
1092
2006
 
1093
- const overlayColumnNames = context.columns.map(({ column }) => column.name);
1094
- const insertColumns = [...overlayColumnNames, "overlay_kind", "local_updated_at_us"];
1095
- const updateColumns = [
1096
- ...overlayColumnNames.map((columnName) => `${columnName} = EXCLUDED.${columnName}`),
1097
- "overlay_kind = EXCLUDED.overlay_kind",
1098
- "local_updated_at_us = EXCLUDED.local_updated_at_us",
1099
- ];
1100
- const params: unknown[] = [];
1101
- const tuples = rows.map((row) => {
1102
- const start = params.length;
1103
- const values = [
1104
- ...context.columns.map(({ propertyKey }) => row.record[propertyKey] ?? null),
1105
- row.overlayKind,
1106
- row.localUpdatedAtUs,
1107
- ];
1108
-
1109
- params.push(...values);
1110
-
1111
- return `(${insertColumns
1112
- .map((columnName, index) => formatSqlValuePlaceholder(start + index + 1, columnName))
1113
- .join(", ")})`;
1114
- });
1115
-
1116
- await db.query(
1117
- `
1118
- INSERT INTO ${context.overlayTable} (
1119
- ${insertColumns.join(", ")}
1120
- )
1121
- VALUES ${tuples.join(",\n ")}
1122
- ON CONFLICT (${context.pkColumnNames.join(", ")})
1123
- DO UPDATE SET
1124
- ${updateColumns.join(",\n ")}
1125
- `,
1126
- params,
1127
- );
2007
+ const overlay = context.tables.overlay;
2008
+ const values = rows.map((row) => ({
2009
+ ...Object.fromEntries(context.columns.map(({ propertyKey }) => [propertyKey, row.record[propertyKey] ?? null])),
2010
+ overlayKind: row.overlayKind,
2011
+ localUpdatedAtUs: row.localUpdatedAtUs,
2012
+ }));
2013
+ // Every inserted column (the projection + the two overlay columns) takes its EXCLUDED value on
2014
+ // conflict — the fixed alias PostgreSQL defines for the proposed row; its column names are the
2015
+ // table's own, so they come from the column objects via `sql.identifier`.
2016
+ const excludedSet = Object.fromEntries([
2017
+ ...context.columns.map(({ propertyKey, column }) => [propertyKey, sql`excluded.${sql.identifier(column.name)}`]),
2018
+ ["overlayKind", sql`excluded.${sql.identifier(overlay.overlayKind.name)}`],
2019
+ ["localUpdatedAtUs", sql`excluded.${sql.identifier(overlay.localUpdatedAtUs.name)}`],
2020
+ ]) as Record<string, SQL>;
2021
+
2022
+ const query = queryBuilder
2023
+ .insert(overlay)
2024
+ .values(values as PgInsertValue<OverlayTable>[])
2025
+ .onConflictDoUpdate({ target: context.overlayPkColumns, set: excludedSet })
2026
+ .toSQL();
2027
+ await db.query(query.sql, query.params as unknown[]);
1128
2028
  }
1129
2029
 
1130
- function buildBatchEntityInputCte(context: TableContext, entities: ReadonlyArray<BatchEntityRef>) {
1131
- const columns = ["entity_key_json", ...context.pkColumnNames];
1132
- const params: unknown[] = [];
2030
+ /**
2031
+ * The batch-input CTE as a typed fragment: `input_entities (entity_key_json, <pks…>) AS (VALUES …)`
2032
+ * with every value a bound param, cast to its PK column's type (an untyped VALUES column would
2033
+ * otherwise default to text and break the join against a uuid/int PK).
2034
+ */
2035
+ function buildEntityInputCte(context: TableContext, entities: ReadonlyArray<BatchEntityRef>): SQL {
2036
+ const columnNames = ["entity_key_json", ...context.pkColumnNames];
1133
2037
  const tuples = entities.map((entity) => {
1134
- const start = params.length;
1135
2038
  const values = [
1136
- entity.entityKeyJson,
1137
- ...context.pkPropertyKeys.map((propertyKey) => entity.entityKey[propertyKey]),
2039
+ sql`${entity.entityKeyJson}`,
2040
+ ...context.pkColumnNames.map((columnName) => {
2041
+ const columnEntry = context.columns.find(({ column }) => column.name === columnName);
2042
+ const castSuffix = columnEntry ? resolveInputCastSuffix(columnEntry.column.columnType) : "";
2043
+ // The cast keyword is a FIXED type suffix selected from the closed switch below — never
2044
+ // derived from user data — so `sql.raw` is safe here; the value itself is a bound param.
2045
+ return castSuffix
2046
+ ? sql`${entity.entityKey[columnName]}${sql.raw(castSuffix)}`
2047
+ : sql`${entity.entityKey[columnName]}`;
2048
+ }),
1138
2049
  ];
1139
-
1140
- params.push(...values);
1141
-
1142
- return `(${columns
1143
- .map((columnName, index) => formatBatchEntityInputPlaceholder(context, start + index + 1, columnName))
1144
- .join(", ")})`;
2050
+ return sql`(${sql.join(values, sql`, `)})`;
1145
2051
  });
1146
2052
 
1147
- return {
1148
- cteSql: `input_entities (${columns.join(", ")}) AS (VALUES ${tuples.join(", ")})`,
1149
- params,
1150
- };
2053
+ return sql`input_entities (${sql.join(
2054
+ columnNames.map((columnName) => sql.identifier(columnName)),
2055
+ sql`, `,
2056
+ )}) AS (VALUES ${sql.join(tuples, sql`, `)})`;
1151
2057
  }
1152
2058
 
1153
- function formatBatchEntityInputPlaceholder(context: TableContext, position: number, columnName: string) {
1154
- if (columnName === "entity_key_json") {
1155
- return `$${position}`;
1156
- }
1157
-
1158
- const columnEntry = context.columns.find(({ column }) => column.name === columnName);
1159
-
1160
- if (!columnEntry) {
1161
- return `$${position}`;
1162
- }
1163
-
1164
- switch (columnEntry.column.columnType) {
2059
+ function resolveInputCastSuffix(columnType: string): string {
2060
+ switch (columnType) {
1165
2061
  case "PgUUID":
1166
- return `$${position}::uuid`;
2062
+ return "::uuid";
1167
2063
  case "PgBigInt64":
1168
2064
  case "PgBigInt53":
1169
- return `$${position}::bigint`;
2065
+ return "::bigint";
1170
2066
  case "PgInteger":
1171
2067
  case "PgSerial":
1172
2068
  case "PgSmallInt":
1173
- return `$${position}::int`;
2069
+ return "::int";
1174
2070
  case "PgBoolean":
1175
- return `$${position}::boolean`;
2071
+ return "::boolean";
1176
2072
  case "PgTimestamp":
1177
2073
  case "PgTimestampString":
1178
- return `$${position}::timestamp`;
2074
+ return "::timestamp";
1179
2075
  default:
1180
- return `$${position}`;
2076
+ return "";
1181
2077
  }
1182
2078
  }
1183
2079
 
1184
- function buildContextSelectColumns(context: TableContext, tableAlias: string) {
1185
- return context.columns.map(({ propertyKey, column }) => {
1186
- const qualifiedColumn = `${tableAlias}.${column.name}`;
1187
-
1188
- if (column.columnType === "PgBigInt64" || column.columnType === "PgBigInt53") {
1189
- return `${qualifiedColumn}::text AS "${propertyKey}"`;
1190
- }
1191
-
1192
- return `${qualifiedColumn} AS "${propertyKey}"`;
1193
- });
2080
+ /**
2081
+ * The projected columns of one branch (overlay or synced) as select-list fragments, aliased to
2082
+ * their camelCase property keys — the raw seam returns rows unmapped, so the aliases ARE the row
2083
+ * keys — with `::text` casts on the bigint columns (matching how the runtime reads them).
2084
+ */
2085
+ function buildProjectedSelectColumns(context: TableContext, columnsByPropertyKey: Record<string, PgColumn>): SQL {
2086
+ return sql.join(
2087
+ context.columns.map(({ propertyKey, column }) => {
2088
+ const target = columnsByPropertyKey[propertyKey];
2089
+ if (!target) {
2090
+ throw new Error(`Projected column ${propertyKey} was not found on the local tables for ${context.key}`);
2091
+ }
2092
+ if (column.columnType === "PgBigInt64" || column.columnType === "PgBigInt53") {
2093
+ return sql`${target}::text AS ${sql.identifier(propertyKey)}`;
2094
+ }
2095
+ return sql`${target} AS ${sql.identifier(propertyKey)}`;
2096
+ }),
2097
+ sql`, `,
2098
+ );
1194
2099
  }
1195
2100
 
1196
- function buildBatchEntityJoinClause(context: TableContext, tableAlias: string, inputAlias: string) {
1197
- return context.pkColumnNames
1198
- .map((columnName) => `${tableAlias}.${columnName} = ${inputAlias}.${columnName}`)
1199
- .join(" AND ");
2101
+ /** PK equality between a branch table's columns and the `input` CTE, as a typed fragment. */
2102
+ function buildEntityInputJoin(pkColumnNames: string[], pkColumns: PgColumn[]): SQL {
2103
+ return sql.join(
2104
+ pkColumnNames.map((columnName, index) => sql`${pkColumns[index]!} = input.${sql.identifier(columnName)}`),
2105
+ sql` AND `,
2106
+ );
1200
2107
  }
1201
2108
 
1202
2109
  // ---------------------------------------------------------------------------
@@ -1208,6 +2115,8 @@ function buildBatchEntityJoinClause(context: TableContext, tableAlias: string, i
1208
2115
  interface PendingBatchRow extends MutationRow {
1209
2116
  tableKey: string;
1210
2117
  enqueuedAtUs: string;
2118
+ /** The resolved Base server version (ADR-0015), or null when the table predates the policy. */
2119
+ baseServerVersion: string | null;
1211
2120
  }
1212
2121
 
1213
2122
  interface PreparedBatchRow extends PendingBatchRow {
@@ -1220,6 +2129,10 @@ interface PreparedBatchRow extends PendingBatchRow {
1220
2129
  interface FlushBatchResult {
1221
2130
  processedCount: number;
1222
2131
  affectedContexts: TableContext[];
2132
+ /** Mutation ids that transitioned to `quarantined` in this slice (ADR-0006), for surfacing. */
2133
+ quarantinedMutationIds: string[];
2134
+ /** Mutation ids that transitioned to `conflicted` in this slice (ADR-0015), for surfacing. */
2135
+ conflictedMutationIds: string[];
1223
2136
  }
1224
2137
 
1225
2138
  interface MutationStatusUpdate {
@@ -1233,60 +2146,157 @@ interface MutationStatusUpdate {
1233
2146
  replaceAckedAtUs?: boolean;
1234
2147
  serverUpdatedAtUs?: string | null;
1235
2148
  replaceServerUpdatedAtUs?: boolean;
2149
+ baseServerVersion?: string | null;
2150
+ replaceBaseServerVersion?: boolean;
1236
2151
  lastError?: string | null;
1237
2152
  nextRetryAtUs?: string | null;
1238
2153
  lastHttpStatus?: number | null;
1239
2154
  conflictReason?: string | null;
1240
2155
  }
1241
2156
 
1242
- async function readPendingBatchRows(db: MutationDb, contexts: TableContext[], nowUs: string) {
2157
+ /**
2158
+ * The resolved Base server version (ADR-0015) for a row at flush. A **chain head** already carries
2159
+ * `base_server_version` (stamped at enqueue), so COALESCE returns it untouched — keeping the
2160
+ * enqueue-time base means a genuine external write between view and apply is still caught. A
2161
+ * **chained** write has NULL there; it resolves to its **acked predecessor's** Server version (by
2162
+ * Per-entity flush serialization the predecessor is already acked when this row flushes), falling
2163
+ * back to the entity's current synced version once that predecessor has been reconciled away. Either
2164
+ * fallback yields the entity's own latest server state, so its own chain never self-conflicts.
2165
+ */
2166
+ function buildResolvedBaseServerVersion(context: TableContext): SQL {
2167
+ const journal = context.tables.journal;
2168
+ const synced = context.tables.synced;
2169
+ const pred = alias(journal, "pred");
2170
+ const predecessor = queryBuilder
2171
+ .select({ value: sql`MAX(${pred.serverUpdatedAtUs})` })
2172
+ .from(pred)
2173
+ .where(
2174
+ and(
2175
+ eq(pred.entityKeyJson, journal.entityKeyJson),
2176
+ lt(pred.mutationSeq, journal.mutationSeq),
2177
+ eq(pred.status, "acked"),
2178
+ ),
2179
+ );
2180
+
2181
+ if (!context.syncedServerVersionColumn) {
2182
+ return sql`COALESCE(${journal.baseServerVersion}, ${predecessor})::text`;
2183
+ }
2184
+
2185
+ const syncedFallback = queryBuilder
2186
+ .select({ value: sql`${context.syncedServerVersionColumn}` })
2187
+ .from(synced)
2188
+ .where(
2189
+ and(
2190
+ ...context.pkColumnNames.map((columnName, index) => eq(context.syncedPkColumns[index]!, journal[columnName]!)),
2191
+ ),
2192
+ );
2193
+
2194
+ return sql`COALESCE(${journal.baseServerVersion}, ${predecessor}, ${syncedFallback})::text`;
2195
+ }
2196
+
2197
+ /**
2198
+ * One table's send-eligible journal rows as a builder select with the shared {@link PendingBatchRow}
2199
+ * projection — the aliases ARE the row keys (raw seam), `tableKey` rides as a bound param, and the
2200
+ * resolved Base server version (ADR-0015) is the typed COALESCE fragment above.
2201
+ */
2202
+ function buildPendingRowsProjection(context: TableContext) {
2203
+ const journal = context.tables.journal;
2204
+ return {
2205
+ tableKey: sql<string>`${context.key}`.as("tableKey"),
2206
+ mutationId: sql<string>`${journal.mutationId}`.as("mutationId"),
2207
+ entityKeyJson: sql<string>`${journal.entityKeyJson}`.as("entityKeyJson"),
2208
+ mutationSeq: sql<number>`${journal.mutationSeq}`.as("mutationSeq"),
2209
+ mutationKind: sql<MutationKind>`${journal.mutationKind}`.as("mutationKind"),
2210
+ status: journal.status,
2211
+ payloadJson: sql<string>`${journal.payloadJson}`.as("payloadJson"),
2212
+ attemptCount: sql<number>`${journal.attemptCount}`.as("attemptCount"),
2213
+ lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as("lastHttpStatus"),
2214
+ lastError: sql<string | null>`${journal.lastError}`.as("lastError"),
2215
+ conflictReason: sql<string | null>`${journal.conflictReason}`.as("conflictReason"),
2216
+ nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as("nextRetryAtUs"),
2217
+ serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
2218
+ baseServerVersion: buildResolvedBaseServerVersion(context).as("baseServerVersion"),
2219
+ enqueuedAtUs: sql<string>`${journal.enqueuedAtUs}::text`.as("enqueuedAtUs"),
2220
+ };
2221
+ }
2222
+
2223
+ async function readPendingBatchRows(db: MutationDb, contexts: TableContext[], nowUs: string, batchSize: number) {
1243
2224
  if (contexts.length === 0) {
1244
2225
  return [] as PendingBatchRow[];
1245
2226
  }
1246
2227
 
1247
- const unionSql = contexts
1248
- .map(
1249
- (context) => `
1250
- SELECT
1251
- '${escapeSqlString(context.key)}' AS "tableKey",
1252
- mutation_id AS "mutationId",
1253
- entity_key_json AS "entityKeyJson",
1254
- mutation_seq AS "mutationSeq",
1255
- mutation_kind AS "mutationKind",
1256
- status,
1257
- payload_json AS "payloadJson",
1258
- attempt_count AS "attemptCount",
1259
- last_http_status AS "lastHttpStatus",
1260
- last_error AS "lastError",
1261
- conflict_reason AS "conflictReason",
1262
- next_retry_at_us::text AS "nextRetryAtUs",
1263
- server_updated_at_us::text AS "serverUpdatedAtUs",
1264
- enqueued_at_us::text AS "enqueuedAtUs"
1265
- FROM ${context.journalTable}
1266
- WHERE status IN ('pending', 'failed')
1267
- AND COALESCE(next_retry_at_us, 0) <= $1::bigint
1268
- AND NOT EXISTS (
1269
- SELECT 1
1270
- FROM ${context.journalTable} AS earlier
1271
- WHERE earlier.entity_key_json = ${context.journalTable}.entity_key_json
1272
- AND earlier.mutation_seq < ${context.journalTable}.mutation_seq
1273
- AND earlier.status IN ('pending', 'failed', 'sending')
1274
- )
1275
- `,
1276
- )
1277
- .join("\nUNION ALL\n");
2228
+ const branches = contexts.map((context) => {
2229
+ const journal = context.tables.journal;
2230
+ const earlier = alias(journal, "earlier");
2231
+ return queryBuilder
2232
+ .select(buildPendingRowsProjection(context))
2233
+ .from(journal)
2234
+ .where(
2235
+ and(
2236
+ inArray(journal.status, ["pending", "failed"]),
2237
+ // ADR-0022: pessimistic rows are flushed by the authoritative unit path (flushUnit), never the
2238
+ // optimistic batch — exclude them here so a tagged write is never optimistically sent. The
2239
+ // `NOT LIKE 'pessimistic%'` also excludes a `pessimistic-blind` row (ADR-0022 addendum), which
2240
+ // belongs to its unit's foreground flush too.
2241
+ sql`COALESCE(${journal.writeMode}, '') NOT LIKE 'pessimistic%'`,
2242
+ sql`COALESCE(${journal.nextRetryAtUs}, 0) <= ${nowUs}::bigint`,
2243
+ notExists(
2244
+ queryBuilder
2245
+ .select({ one: sql`1` })
2246
+ .from(earlier)
2247
+ .where(
2248
+ and(
2249
+ eq(earlier.entityKeyJson, journal.entityKeyJson),
2250
+ lt(earlier.mutationSeq, journal.mutationSeq),
2251
+ // A still-unresolved earlier mutation blocks later same-entity ones so the
2252
+ // server applies them in author order. The quarantined status is included: a
2253
+ // later mutation must not flush past a prerequisite the server permanently
2254
+ // rejected (it would itself fail); resolving the quarantine unblocks the queue.
2255
+ inArray(earlier.status, ["pending", "failed", "sending", "quarantined"]),
2256
+ ),
2257
+ ),
2258
+ ),
2259
+ ),
2260
+ );
2261
+ });
1278
2262
 
1279
- const result = await db.query<PendingBatchRow>(
1280
- `
1281
- SELECT *
1282
- FROM (
1283
- ${unionSql}
1284
- ) AS pending
1285
- ORDER BY pending."enqueuedAtUs"::bigint ASC, pending."mutationSeq" ASC
1286
- LIMIT ${DEFAULT_FLUSH_BATCH_SIZE}
1287
- `,
1288
- [nowUs],
2263
+ // The union rides inside a derived table because the outer ORDER BY casts the (text) output
2264
+ // columns — a set operation's own ORDER BY may only name plain output columns. The `pending`
2265
+ // alias and its two quoted output-column names are fixed by the projection above, not data.
2266
+ const query = queryDialect.sqlToQuery(
2267
+ sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS pending ORDER BY pending."enqueuedAtUs"::bigint ASC, pending."mutationSeq" ASC LIMIT ${batchSize}`,
1289
2268
  );
2269
+ const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);
2270
+
2271
+ return result.rows;
2272
+ }
2273
+
2274
+ /**
2275
+ * Read one pessimistic write-unit's send-eligible rows (ADR-0022) across every table, ordered by author
2276
+ * sequence. Unlike {@link readPendingBatchRows} it has no per-entity ordering gate: a unit is enqueued and
2277
+ * sent atomically, so its members go together.
2278
+ */
2279
+ async function readUnitPendingRows(
2280
+ db: MutationDb,
2281
+ contexts: TableContext[],
2282
+ unitId: string,
2283
+ ): Promise<PendingBatchRow[]> {
2284
+ if (contexts.length === 0) {
2285
+ return [];
2286
+ }
2287
+
2288
+ const branches = contexts.map((context) => {
2289
+ const journal = context.tables.journal;
2290
+ return queryBuilder
2291
+ .select(buildPendingRowsProjection(context))
2292
+ .from(journal)
2293
+ .where(and(eq(journal.writeUnit, unitId), inArray(journal.status, ["pending", "failed"])));
2294
+ });
2295
+
2296
+ const query = queryDialect.sqlToQuery(
2297
+ sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS unit ORDER BY unit."mutationSeq" ASC`,
2298
+ );
2299
+ const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);
1290
2300
 
1291
2301
  return result.rows;
1292
2302
  }
@@ -1295,14 +2305,19 @@ async function flushBatch(
1295
2305
  db: MutationDb,
1296
2306
  tableContexts: Record<string, TableContext>,
1297
2307
  batchWriteUrl: string,
2308
+ maxAttempts: number,
2309
+ batchSize: number,
1298
2310
  tableFilter?: string,
1299
2311
  getAuthToken?: () => Promise<string | undefined>,
2312
+ requestHeaders?: Record<string, string>,
1300
2313
  ): Promise<FlushBatchResult> {
1301
2314
  const contexts = filterContexts(tableContexts, tableFilter);
1302
2315
  const nowUs = nowMicroseconds();
2316
+ const quarantinedMutationIds: string[] = [];
2317
+ const conflictedMutationIds: string[] = [];
1303
2318
 
1304
2319
  // Collect send-eligible mutations across all target tables.
1305
- const pendingRows = await readPendingBatchRows(db, contexts, nowUs);
2320
+ const pendingRows = await readPendingBatchRows(db, contexts, nowUs, batchSize);
1306
2321
  const pending: PreparedBatchRow[] = [];
1307
2322
  const pendingByTable = new Map<string, PreparedBatchRow[]>();
1308
2323
 
@@ -1345,12 +2360,20 @@ async function flushBatch(
1345
2360
  }
1346
2361
 
1347
2362
  if (pending.length === 0) {
2363
+ // If a write just enqueued and requested a pass, but this flush sees nothing, the pass raced the
2364
+ // journal commit (or everything is already in-flight/backed-off) — the write then waits for a
2365
+ // later pass. Worth seeing explicitly when chasing flush latency.
2366
+ syncDebug("flushBatch: no send-eligible mutations this pass");
1348
2367
  return {
1349
2368
  processedCount: 0,
1350
2369
  affectedContexts: [],
2370
+ quarantinedMutationIds,
2371
+ conflictedMutationIds,
1351
2372
  };
1352
2373
  }
1353
2374
 
2375
+ syncDebug("flushBatch sending to board-write", { count: pending.length });
2376
+
1354
2377
  // Mark all as sending.
1355
2378
  const sentAtUs = nowMicroseconds();
1356
2379
 
@@ -1365,6 +2388,10 @@ async function flushBatch(
1365
2388
  updatedAtUs: sentAtUs,
1366
2389
  sentAtUs,
1367
2390
  replaceSentAtUs: true,
2391
+ // Persist the resolved Base server version (ADR-0015) so a chained write's flush-resolved
2392
+ // base is durable and matches exactly what the envelope carries to the server.
2393
+ baseServerVersion: row.baseServerVersion,
2394
+ replaceBaseServerVersion: true,
1368
2395
  lastError: null,
1369
2396
  nextRetryAtUs: null,
1370
2397
  lastHttpStatus: null,
@@ -1382,6 +2409,9 @@ async function flushBatch(
1382
2409
  kind: row.mutationKind as "create" | "update" | "delete",
1383
2410
  payload: row.envelopePayload,
1384
2411
  clientTimestampUs: sentAtUs,
2412
+ // ADR-0015: carry the resolved Base server version so the applier can detect a stale write.
2413
+ // Omitted for a create / a table that predates the policy (null) — then no stale check runs.
2414
+ ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),
1385
2415
  };
1386
2416
  });
1387
2417
 
@@ -1390,34 +2420,58 @@ async function flushBatch(
1390
2420
  const batchMutationUrl = resolveBatchMutationUrl(batchWriteUrl);
1391
2421
 
1392
2422
  try {
2423
+ // Resolve the auth token and the network round-trip separately: in the board, `getAuthToken` calls
2424
+ // `supabase.auth.getSession()` per send, which can itself stall (token refresh) and would otherwise
2425
+ // be invisibly folded into "the write was slow".
2426
+ const authStart = typeof performance !== "undefined" ? performance.now() : Date.now();
2427
+ const authToken = await getAuthToken?.();
2428
+ const fetchStart = typeof performance !== "undefined" ? performance.now() : Date.now();
2429
+ syncDebug("board-write auth token resolved", { ms: Math.round(fetchStart - authStart) });
2430
+
1393
2431
  let response = await fetch(batchMutationUrl, {
1394
2432
  method: "POST",
1395
- headers: buildRequestHeaders(await getAuthToken?.()),
2433
+ headers: buildRequestHeaders(authToken, requestHeaders),
1396
2434
  body: jsonStringifyPayload({ mutations }),
1397
2435
  });
1398
2436
 
1399
2437
  if ([401, 403].includes(response.status) && getAuthToken) {
1400
2438
  response = await fetch(batchMutationUrl, {
1401
2439
  method: "POST",
1402
- headers: buildRequestHeaders(await getAuthToken()),
2440
+ headers: buildRequestHeaders(await getAuthToken(), requestHeaders),
1403
2441
  body: jsonStringifyPayload({ mutations }),
1404
2442
  });
1405
2443
  }
1406
2444
 
2445
+ const fetchEnd = typeof performance !== "undefined" ? performance.now() : Date.now();
2446
+ syncDebug("board-write responded", { status: response.status, ms: Math.round(fetchEnd - fetchStart) });
2447
+
1407
2448
  if (response.ok) {
1408
2449
  const responseJson = (await response.json()) as BatchMutationAck;
1409
2450
  responseOk = true;
1410
2451
  acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));
2452
+ syncDebug("board-write acks", {
2453
+ acks: responseJson.acks.map((ack) => `${ack.mutationId.slice(0, 8)}:${ack.status}`),
2454
+ });
1411
2455
  } else {
1412
2456
  const text = await response.text();
1413
2457
  throw new MutationRequestError(
1414
2458
  text.length > 0 ? text : `Bulk write responded with ${response.status}`,
1415
2459
  response.status,
2460
+ parseBatchRejections(text),
1416
2461
  );
1417
2462
  }
1418
2463
  } catch (error) {
1419
- // All mutations in the batch fail together on a transport or server error.
1420
2464
  const failedAtUs = nowMicroseconds();
2465
+ const httpStatus = error instanceof MutationRequestError ? error.status : null;
2466
+ const errorMessage = error instanceof Error ? error.message : "Unknown batch write failure";
2467
+ // The server attributed the failure to specific mutations (a structural validation
2468
+ // rejection of an atomic batch). When present, we quarantine exactly those and leave the
2469
+ // innocent siblings immediately retryable; absent (transport / 5xx / auth / malformed
2470
+ // envelope), the whole batch stays retryable under the shared attempt cap.
2471
+ const rejectionById =
2472
+ error instanceof MutationRequestError && error.rejections
2473
+ ? new Map(error.rejections.map((rejection) => [rejection.mutationId, rejection]))
2474
+ : null;
1421
2475
 
1422
2476
  for (const rows of pendingByTable.values()) {
1423
2477
  await applyMutationStatusUpdates(
@@ -1426,14 +2480,57 @@ async function flushBatch(
1426
2480
  rows.map((row) => {
1427
2481
  const attemptCount = row.attemptCount + 1;
1428
2482
 
2483
+ if (rejectionById) {
2484
+ const rejection = rejectionById.get(row.mutationId);
2485
+
2486
+ if (rejection) {
2487
+ // Named as the cause: terminal quarantine (it will never succeed unchanged).
2488
+ quarantinedMutationIds.push(row.mutationId);
2489
+ return {
2490
+ mutationId: row.mutationId,
2491
+ status: "quarantined" as const,
2492
+ attemptCount,
2493
+ updatedAtUs: failedAtUs,
2494
+ lastError: rejection.reason,
2495
+ nextRetryAtUs: null,
2496
+ lastHttpStatus: httpStatus,
2497
+ conflictReason: rejection.reason,
2498
+ };
2499
+ }
2500
+
2501
+ // Innocent sibling: nothing was applied (atomic batch), so make it immediately
2502
+ // retryable — no backoff (the fault was the now-quarantined mutation, not
2503
+ // congestion) — and the next flush proceeds without the poison.
2504
+ return {
2505
+ mutationId: row.mutationId,
2506
+ status: "failed" as const,
2507
+ attemptCount,
2508
+ updatedAtUs: failedAtUs,
2509
+ lastError: "Batch rejected due to a sibling mutation; retrying without it",
2510
+ nextRetryAtUs: null,
2511
+ lastHttpStatus: httpStatus,
2512
+ conflictReason: null,
2513
+ };
2514
+ }
2515
+
2516
+ // Unattributed batch-level failure: stays retryable with jittered backoff; only the
2517
+ // hard attempt cap escalates to terminal quarantined. A structural 4xx is NOT
2518
+ // quarantined here (a stray 404/413/malformed envelope would otherwise permanently
2519
+ // kill unrelated valid writes).
2520
+ const outcome = resolveBatchFailureOutcome(attemptCount, maxAttempts, failedAtUs);
2521
+
2522
+ if (outcome.status === "quarantined") {
2523
+ quarantinedMutationIds.push(row.mutationId);
2524
+ }
2525
+
1429
2526
  return {
1430
2527
  mutationId: row.mutationId,
1431
- status: "failed",
2528
+ status: outcome.status,
1432
2529
  attemptCount,
1433
2530
  updatedAtUs: failedAtUs,
1434
- lastError: error instanceof Error ? error.message : "Unknown batch write failure",
1435
- nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount),
1436
- lastHttpStatus: error instanceof MutationRequestError ? error.status : null,
2531
+ lastError: errorMessage,
2532
+ nextRetryAtUs: outcome.nextRetryAtUs,
2533
+ lastHttpStatus: httpStatus,
1437
2534
  conflictReason: null,
1438
2535
  };
1439
2536
  }),
@@ -1443,6 +2540,8 @@ async function flushBatch(
1443
2540
  return {
1444
2541
  processedCount: pending.length,
1445
2542
  affectedContexts: [...new Set(pending.map((row) => row.context))],
2543
+ quarantinedMutationIds,
2544
+ conflictedMutationIds,
1446
2545
  };
1447
2546
  }
1448
2547
 
@@ -1450,6 +2549,8 @@ async function flushBatch(
1450
2549
  return {
1451
2550
  processedCount: pending.length,
1452
2551
  affectedContexts: [...new Set(pending.map((row) => row.context))],
2552
+ quarantinedMutationIds,
2553
+ conflictedMutationIds,
1453
2554
  };
1454
2555
  }
1455
2556
 
@@ -1464,15 +2565,43 @@ async function flushBatch(
1464
2565
  rows.map((row) => {
1465
2566
  const ack = acksByMutationId.get(row.mutationId);
1466
2567
 
1467
- if (!ack || ack.status !== "acked") {
2568
+ if (ack && ack.status === "conflicted") {
2569
+ // ADR-0015: a stale write the reject-if-stale policy declined. Move to the terminal
2570
+ // `conflicted` status — NOT a failure (never retried as-is, the base is still stale) — and
2571
+ // KEEP the optimistic Overlay (reconcile only clears acked rows, so the user's edit stays
2572
+ // visible). The server's current Server version rides on the journal row for the diff UI.
2573
+ conflictedMutationIds.push(row.mutationId);
1468
2574
  return {
1469
2575
  mutationId: row.mutationId,
1470
- status: "failed",
2576
+ status: "conflicted" as const,
1471
2577
  attemptCount: row.attemptCount + 1,
1472
2578
  updatedAtUs: failedAtUs,
2579
+ serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
2580
+ replaceServerUpdatedAtUs: true,
2581
+ lastError: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
2582
+ nextRetryAtUs: null,
2583
+ lastHttpStatus: ack.httpStatus ?? 409,
2584
+ conflictReason: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
2585
+ };
2586
+ }
2587
+
2588
+ if (!ack || ack.status !== "acked") {
2589
+ const attemptCount = row.attemptCount + 1;
2590
+ const httpStatus = ack?.httpStatus ?? null;
2591
+ const outcome = resolveFailureOutcome(httpStatus, attemptCount, maxAttempts, failedAtUs);
2592
+
2593
+ if (outcome.status === "quarantined") {
2594
+ quarantinedMutationIds.push(row.mutationId);
2595
+ }
2596
+
2597
+ return {
2598
+ mutationId: row.mutationId,
2599
+ status: outcome.status,
2600
+ attemptCount,
2601
+ updatedAtUs: failedAtUs,
1473
2602
  lastError: ack?.conflictReason ?? "Batch mutation not acknowledged",
1474
- nextRetryAtUs: computeNextRetryAtUs(failedAtUs, row.attemptCount + 1),
1475
- lastHttpStatus: ack?.httpStatus ?? null,
2603
+ nextRetryAtUs: outcome.nextRetryAtUs,
2604
+ lastHttpStatus: httpStatus,
1476
2605
  conflictReason: ack?.conflictReason ?? null,
1477
2606
  };
1478
2607
  }
@@ -1513,9 +2642,50 @@ async function flushBatch(
1513
2642
  return {
1514
2643
  processedCount: pending.length,
1515
2644
  affectedContexts: [...new Set(pending.map((row) => row.context))],
2645
+ quarantinedMutationIds,
2646
+ conflictedMutationIds,
1516
2647
  };
1517
2648
  }
1518
2649
 
2650
+ /**
2651
+ * Resolve a flush failure into the durable journal outcome (ADR-0006). A structural
2652
+ * rejection ({@link classifyFailureStatus}) or hitting the hard attempt cap ends the
2653
+ * retry loop with a terminal `quarantined` (no `next_retry_at_us`); otherwise the
2654
+ * mutation stays `failed` with a jittered backoff (ADR-0005 congestion policy).
2655
+ */
2656
+ function resolveFailureOutcome(
2657
+ httpStatus: number | null,
2658
+ attemptCount: number,
2659
+ maxAttempts: number,
2660
+ failedAtUs: string,
2661
+ ): { status: "failed" | "quarantined"; nextRetryAtUs: string | null } {
2662
+ if (classifyFailureStatus(httpStatus) === "quarantined" || attemptCount >= maxAttempts) {
2663
+ return { status: "quarantined", nextRetryAtUs: null };
2664
+ }
2665
+
2666
+ return { status: "failed", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };
2667
+ }
2668
+
2669
+ /**
2670
+ * Resolve a *batch-level* failure — the whole POST failed (transport error, 5xx, auth, or a
2671
+ * non-2xx the server did not attribute to a specific mutation). Unlike a per-mutation ack
2672
+ * rejection, the fault cannot be pinned on any one mutation, so a structural 4xx must NOT
2673
+ * quarantine the batch (a stray 404/413/malformed envelope would permanently kill unrelated
2674
+ * valid offline writes). These failures stay retryable `failed` with jittered backoff; only
2675
+ * the hard attempt cap escalates to terminal `quarantined`.
2676
+ */
2677
+ function resolveBatchFailureOutcome(
2678
+ attemptCount: number,
2679
+ maxAttempts: number,
2680
+ failedAtUs: string,
2681
+ ): { status: "failed" | "quarantined"; nextRetryAtUs: string | null } {
2682
+ if (attemptCount >= maxAttempts) {
2683
+ return { status: "quarantined", nextRetryAtUs: null };
2684
+ }
2685
+
2686
+ return { status: "failed", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };
2687
+ }
2688
+
1519
2689
  function resolveBatchMutationUrl(batchWriteUrl: string): string {
1520
2690
  const trimmed = batchWriteUrl.replace(/\/+$/, "");
1521
2691
 
@@ -1526,6 +2696,11 @@ function resolveBatchMutationUrl(batchWriteUrl: string): string {
1526
2696
  return `${trimmed}/mutations`;
1527
2697
  }
1528
2698
 
2699
+ /** The authoritative (pessimistic) write endpoint (ADR-0022): the batch URL with `/unit` appended. */
2700
+ function resolveAuthoritativeMutationUrl(batchWriteUrl: string): string {
2701
+ return `${resolveBatchMutationUrl(batchWriteUrl)}/unit`;
2702
+ }
2703
+
1529
2704
  function stripManagedFields(
1530
2705
  context: TableContext,
1531
2706
  payload: Record<string, unknown>,
@@ -1563,79 +2738,315 @@ function toSqlColumnPayload(context: TableContext, payload: Record<string, unkno
1563
2738
  return normalized;
1564
2739
  }
1565
2740
 
2741
+ /**
2742
+ * Discard a terminal-state entity: clear its journal rows in the given terminal status
2743
+ * (`conflicted` — ADR-0015; or `quarantined` — ADR-0006) and its kept optimistic Overlay row, so the
2744
+ * Read model falls back to the synced (server) value. The overlay is removed only when no OTHER journal
2745
+ * row still owes the entity (a pending/sending/failed/acked write), mirroring reconcileTable's
2746
+ * overlay-clear guard — so a discard never strips an overlay another un-resolved write still depends
2747
+ * on. Both public discards (`discardConflict`, `discardQuarantined`) are this one body parameterized by
2748
+ * the terminal status they retire; owning its own transaction (like reconcileTable), it is not wrapped.
2749
+ */
2750
+ async function discardTerminalEntity(
2751
+ db: MutationDb,
2752
+ context: TableContext,
2753
+ entityKey: Record<string, string>,
2754
+ entityKeyJson: string,
2755
+ terminalStatus: "conflicted" | "quarantined",
2756
+ ) {
2757
+ await db.exec("BEGIN");
2758
+
2759
+ try {
2760
+ const journal = context.tables.journal;
2761
+ const clearQuery = queryBuilder
2762
+ .delete(journal)
2763
+ .where(and(eq(journal.status, terminalStatus), eq(journal.entityKeyJson, entityKeyJson)))
2764
+ .toSQL();
2765
+ await db.query(clearQuery.sql, clearQuery.params as unknown[]);
2766
+
2767
+ // Clear the kept overlay only when no journal row still owes this entity — so a discard never
2768
+ // strips an overlay another un-resolved write (e.g. a resolution already enqueued) depends on.
2769
+ const overlayQuery = buildOverlayDiscardQuery(context, entityKey, entityKeyJson);
2770
+ await db.query(overlayQuery.sql, overlayQuery.params as unknown[]);
2771
+
2772
+ await db.exec("COMMIT");
2773
+ } catch (error) {
2774
+ await db.exec("ROLLBACK");
2775
+ throw error;
2776
+ }
2777
+ }
2778
+
2779
+ /**
2780
+ * The shared overlay-discard statement: delete the entity's overlay row unless a journal row still
2781
+ * owes the entity — `owedStatuses` narrows which journal rows count as "owed" (all of them for a
2782
+ * conflict discard; only the un-sent pending/sending/failed set for a settled-unit discard).
2783
+ */
2784
+ function buildOverlayDiscardQuery(
2785
+ context: TableContext,
2786
+ entityKey: Record<string, string>,
2787
+ entityKeyJson: string,
2788
+ owedStatuses?: MutationStatus[],
2789
+ ) {
2790
+ const overlay = context.tables.overlay;
2791
+ const journal = context.tables.journal;
2792
+ const owed = queryBuilder
2793
+ .select({ one: sql`1` })
2794
+ .from(journal)
2795
+ .where(
2796
+ owedStatuses
2797
+ ? and(eq(journal.entityKeyJson, entityKeyJson), inArray(journal.status, owedStatuses))
2798
+ : eq(journal.entityKeyJson, entityKeyJson),
2799
+ );
2800
+
2801
+ return queryBuilder
2802
+ .delete(overlay)
2803
+ .where(
2804
+ and(
2805
+ ...context.pkColumnNames.map((columnName, index) =>
2806
+ eq(context.overlayPkColumns[index]!, entityKey[columnName]),
2807
+ ),
2808
+ notExists(owed),
2809
+ ),
2810
+ )
2811
+ .toSQL();
2812
+ }
2813
+
2814
+ /**
2815
+ * Auto-discard the optimistic overlay for an entity whose pessimistic write-unit the authoritative endpoint
2816
+ * `rejected` (ADR-0022 §4). Unlike {@link discardTerminalEntity} this KEEPS the terminal `rejected` journal
2817
+ * row (for diagnostics + `onReject`); it only clears the overlay, and only when no still-owed
2818
+ * (`pending`/`sending`/`failed`) journal row depends on it — so a later un-sent write never loses its overlay.
2819
+ */
2820
+ async function discardOverlayForSettledEntity(
2821
+ db: MutationDb,
2822
+ context: TableContext,
2823
+ entityKey: Record<string, string>,
2824
+ entityKeyJson: string,
2825
+ ) {
2826
+ const query = buildOverlayDiscardQuery(context, entityKey, entityKeyJson, ["pending", "sending", "failed"]);
2827
+ await db.query(query.sql, query.params as unknown[]);
2828
+ }
2829
+
1566
2830
  async function reconcileTable(db: MutationDb, context: TableContext) {
1567
- // PK-match only — no timestamp gate. The trigger on the synced table
1568
- // handles real-time cleanup; this is a bulk recovery/fallback path.
2831
+ // Idle fast-path. Reconcile only retires/clears journal rows in a terminal-clearable state — 'acked'
2832
+ // (clear the overlay once the echo lands) or 'conflicted' (retire once a later write resolved it). When
2833
+ // none exist — the steady state of an idle entity set — all three statements below are no-ops, so skip
2834
+ // the whole transaction. This matters because the convergence driver runs reconcile for EVERY writable
2835
+ // table on its interval (default 1.5s), and each CTE pays full PGlite plan+execute cost even against an
2836
+ // empty journal: left unguarded it is the dominant idle-CPU cost. The real-time cleanup path is the
2837
+ // <table>_reconcile_on_sync trigger; this bulk pass is a fallback, so skipping it when there is nothing
2838
+ // to clear changes no outcome. The guard is a single existence probe over the (small, usually empty)
2839
+ // journal.
2840
+ const journal = context.tables.journal;
2841
+ const overlay = context.tables.overlay;
2842
+ const synced = context.tables.synced;
2843
+ // This is the idle-CPU hot statement (it runs for every writable table on every convergence
2844
+ // tick), so the rendered text+params are memoized per context — each tick pays only a plain
2845
+ // `db.query` of a cached string, and it stays OUTSIDE any transaction (no BEGIN on the idle path).
2846
+ let idleProbe = context.reconcileIdleProbe;
2847
+ if (!idleProbe) {
2848
+ const probeQuery = queryDialect.sqlToQuery(
2849
+ sql`SELECT ${exists(
2850
+ queryBuilder
2851
+ .select({ one: sql`1` })
2852
+ .from(journal)
2853
+ .where(inArray(journal.status, ["acked", "conflicted"])),
2854
+ )} AS "hasWork"`,
2855
+ );
2856
+ idleProbe = { sql: probeQuery.sql, params: probeQuery.params as unknown[] };
2857
+ context.reconcileIdleProbe = idleProbe;
2858
+ }
2859
+ const work = await db.query<{ hasWork: boolean }>(idleProbe.sql, idleProbe.params);
2860
+ if (work.rows[0]?.hasWork !== true) {
2861
+ return;
2862
+ }
2863
+
2864
+ // The Convergence barrier (ADR-0010) gates the acked-row clearing below; the synced-table trigger
2865
+ // handles real-time cleanup, and this is the bulk recovery/fallback path that runs after every flush.
1569
2866
  await db.exec("BEGIN");
1570
2867
 
1571
2868
  try {
1572
- // Clear acknowledged non-delete mutations + matching overlays
1573
- await db.query(
1574
- "WITH cleared_journal AS (" +
1575
- "DELETE FROM " +
1576
- context.journalTable +
1577
- " AS journal " +
1578
- "WHERE journal.status = 'acked' " +
1579
- "AND journal.server_updated_at_us IS NOT NULL " +
1580
- "AND journal.mutation_kind <> 'delete' " +
1581
- "RETURNING journal.entity_key_json, " +
1582
- context.pkColumnNames.map((cn) => "journal." + cn).join(", ") +
1583
- ") " +
1584
- "DELETE FROM " +
1585
- context.overlayTable +
1586
- " AS overlay " +
1587
- "USING cleared_journal AS cj " +
1588
- "WHERE " +
1589
- buildColumnEquality(context.pkColumnNames, "overlay", "cj") +
1590
- " " +
1591
- "AND NOT EXISTS (" +
1592
- "SELECT 1 FROM " +
1593
- context.journalTable +
1594
- " AS j " +
1595
- "WHERE j.entity_key_json = cj.entity_key_json " +
1596
- "AND j.status IN ('pending', 'sending', 'failed')" +
1597
- ")",
2869
+ // ADR-0015: retire a terminal `conflicted` row once the user has RESOLVED it — i.e. a LATER write
2870
+ // on the same entity has been acked (resolution is an ordinary new mutation). Without this, the old
2871
+ // conflicted row lingers forever: `<table>_sync_state.conflict_state` keeps surfacing the resolved
2872
+ // conflict and `diagnostics().conflictedCount` never drops. Run before the acked-clear below so the
2873
+ // resolving row is still present to supersede it. (`discardConflict` is the explicit throw-away path.)
2874
+ // Drizzle DELETE has no USING; the resolver leg is the equivalent EXISTS semi-join.
2875
+ const resolver = alias(journal, "resolver");
2876
+ const retireQuery = queryBuilder
2877
+ .delete(journal)
2878
+ .where(
2879
+ and(
2880
+ eq(journal.status, "conflicted"),
2881
+ exists(
2882
+ queryBuilder
2883
+ .select({ one: sql`1` })
2884
+ .from(resolver)
2885
+ .where(
2886
+ and(
2887
+ eq(resolver.entityKeyJson, journal.entityKeyJson),
2888
+ gt(resolver.mutationSeq, journal.mutationSeq),
2889
+ eq(resolver.status, "acked"),
2890
+ ),
2891
+ ),
2892
+ ),
2893
+ ),
2894
+ )
2895
+ .toSQL();
2896
+ await db.query(retireQuery.sql, retireQuery.params as unknown[]);
2897
+
2898
+ // ADR-0022 addendum — retire an acked `pessimistic-blind` row with NO echo barrier. A blind update's
2899
+ // write target is excluded from this actor's read shape, so no synced echo will ever land for it and no
2900
+ // overlay was ever planned: the standard acked-clear below (gated on a synced row reaching the acked
2901
+ // version) would keep it forever. Nothing local converges for these rows, so once the authoritative unit
2902
+ // acked them there is nothing left to do but drop the journal row. Crash-safe: any later reconcile tick
2903
+ // clears a blind row the foreground flushUnit didn't survive to reconcile.
2904
+ const blindRetireQuery = queryBuilder
2905
+ .delete(journal)
2906
+ .where(and(eq(journal.status, "acked"), eq(journal.writeMode, "pessimistic-blind")))
2907
+ .toSQL();
2908
+ await db.query(blindRetireQuery.sql, blindRetireQuery.params as unknown[]);
2909
+
2910
+ // Clear acknowledged non-delete mutations + matching overlays. ADR-0010: gated by the
2911
+ // Convergence barrier (same predicate as the trigger) — the acked write clears only once the
2912
+ // synced echo's Server version has reached its acked version. Joining the synced table makes
2913
+ // the comparison possible (and means an un-synced acked write is held until its echo lands).
2914
+ // Drizzle authoring: DELETE..USING becomes the equivalent EXISTS semi-join, chained through a
2915
+ // data-modifying CTE (both sub-statements see the same statement-start snapshot, exactly like
2916
+ // the USING form). The barrier predicate stays the shared contracts helper (single authority
2917
+ // with the trigger); it renders against the tables' own names, which is how drizzle references
2918
+ // their columns here (no aliases on a DELETE target).
2919
+ const barrier = sql.raw(
2920
+ buildOverlayResolutionBarrier(context.entry, {
2921
+ journalAlias: quoteIdentifier(getTableConfig(journal).name),
2922
+ syncedAlias: quoteIdentifier(getTableConfig(synced).name),
2923
+ }),
1598
2924
  );
2925
+ const clearedJournal = queryBuilder.$with("cleared_journal").as(
2926
+ queryBuilder
2927
+ .delete(journal)
2928
+ .where(
2929
+ and(
2930
+ eq(journal.status, "acked"),
2931
+ isNotNull(journal.serverUpdatedAtUs),
2932
+ ne(journal.mutationKind, "delete"),
2933
+ exists(
2934
+ queryBuilder
2935
+ .select({ one: sql`1` })
2936
+ .from(synced)
2937
+ .where(
2938
+ and(
2939
+ ...context.pkColumnNames.map((columnName, index) =>
2940
+ eq(context.syncedPkColumns[index]!, journal[columnName]!),
2941
+ ),
2942
+ barrier,
2943
+ ),
2944
+ ),
2945
+ ),
2946
+ ),
2947
+ )
2948
+ .returning(
2949
+ Object.fromEntries([
2950
+ ["entity_key_json", journal.entityKeyJson],
2951
+ ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),
2952
+ ]),
2953
+ ),
2954
+ );
2955
+ const clearedJournalColumns = clearedJournal as unknown as Record<string, PgColumn>;
2956
+ const ackedClearQuery = queryBuilder
2957
+ .with(clearedJournal)
2958
+ .delete(overlay)
2959
+ .where(
2960
+ exists(
2961
+ queryBuilder
2962
+ .select({ one: sql`1` })
2963
+ .from(clearedJournal)
2964
+ .where(
2965
+ and(
2966
+ ...context.pkColumnNames.map((columnName, index) =>
2967
+ eq(context.overlayPkColumns[index]!, clearedJournalColumns[columnName]!),
2968
+ ),
2969
+ notExists(
2970
+ queryBuilder
2971
+ .select({ one: sql`1` })
2972
+ .from(journal)
2973
+ .where(
2974
+ and(
2975
+ eq(journal.entityKeyJson, clearedJournalColumns["entity_key_json"]!),
2976
+ inArray(journal.status, ["pending", "sending", "failed"]),
2977
+ ),
2978
+ ),
2979
+ ),
2980
+ ),
2981
+ ),
2982
+ ),
2983
+ )
2984
+ .toSQL();
2985
+ await db.query(ackedClearQuery.sql, ackedClearQuery.params as unknown[]);
1599
2986
 
1600
2987
  // Clear acknowledged delete mutations where synced row is absent
1601
2988
  // Single compound CTE — PGlite does not support multi-statement query().
1602
- await db.query(
1603
- "WITH clearable_entities AS (" +
1604
- "SELECT DISTINCT journal.entity_key_json, " +
1605
- context.pkColumnNames.map((cn) => "journal." + cn).join(", ") +
1606
- " FROM " +
1607
- context.journalTable +
1608
- " AS journal " +
1609
- "LEFT JOIN " +
1610
- context.syncedTable +
1611
- " AS synced " +
1612
- "ON " +
1613
- buildColumnEquality(context.pkColumnNames, "journal", "synced") +
1614
- " " +
1615
- "WHERE journal.status = 'acked' " +
1616
- "AND journal.mutation_kind = 'delete' " +
1617
- "AND synced." +
1618
- context.pkColumnNames[0] +
1619
- " IS NULL" +
1620
- "), " +
1621
- "deleted_overlay AS (" +
1622
- "DELETE FROM " +
1623
- context.overlayTable +
1624
- " AS overlay " +
1625
- "USING clearable_entities AS ce " +
1626
- "WHERE " +
1627
- buildColumnEquality(context.pkColumnNames, "overlay", "ce") +
1628
- ") " +
1629
- "DELETE FROM " +
1630
- context.journalTable +
1631
- " AS journal " +
1632
- "USING clearable_entities AS ce " +
1633
- "WHERE " +
1634
- buildColumnEquality(context.pkColumnNames, "journal", "ce") +
1635
- " " +
1636
- "AND journal.status = 'acked' " +
1637
- "AND journal.mutation_kind = 'delete'",
2989
+ const clearableEntities = queryBuilder.$with("clearable_entities").as(
2990
+ queryBuilder
2991
+ .selectDistinct(
2992
+ Object.fromEntries([
2993
+ ["entity_key_json", journal.entityKeyJson],
2994
+ ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),
2995
+ ]),
2996
+ )
2997
+ .from(journal)
2998
+ .leftJoin(
2999
+ synced,
3000
+ and(
3001
+ ...context.pkColumnNames.map((columnName, index) =>
3002
+ eq(context.syncedPkColumns[index]!, journal[columnName]!),
3003
+ ),
3004
+ ),
3005
+ )
3006
+ .where(
3007
+ and(eq(journal.status, "acked"), eq(journal.mutationKind, "delete"), isNull(context.syncedPkColumns[0]!)),
3008
+ ),
1638
3009
  );
3010
+ const clearableEntityColumns = clearableEntities as unknown as Record<string, PgColumn>;
3011
+ const deletedOverlay = queryBuilder.$with("deleted_overlay").as(
3012
+ queryBuilder.delete(overlay).where(
3013
+ exists(
3014
+ queryBuilder
3015
+ .select({ one: sql`1` })
3016
+ .from(clearableEntities)
3017
+ .where(
3018
+ and(
3019
+ ...context.pkColumnNames.map((columnName, index) =>
3020
+ eq(context.overlayPkColumns[index]!, clearableEntityColumns[columnName]!),
3021
+ ),
3022
+ ),
3023
+ ),
3024
+ ),
3025
+ ),
3026
+ );
3027
+ const deleteClearQuery = queryBuilder
3028
+ .with(clearableEntities, deletedOverlay)
3029
+ .delete(journal)
3030
+ .where(
3031
+ and(
3032
+ eq(journal.status, "acked"),
3033
+ eq(journal.mutationKind, "delete"),
3034
+ exists(
3035
+ queryBuilder
3036
+ .select({ one: sql`1` })
3037
+ .from(clearableEntities)
3038
+ .where(
3039
+ and(
3040
+ ...context.pkColumnNames.map((columnName) =>
3041
+ eq(journal[columnName]!, clearableEntityColumns[columnName]!),
3042
+ ),
3043
+ ),
3044
+ ),
3045
+ ),
3046
+ ),
3047
+ )
3048
+ .toSQL();
3049
+ await db.query(deleteClearQuery.sql, deleteClearQuery.params as unknown[]);
1639
3050
  await db.exec("COMMIT");
1640
3051
  } catch (error) {
1641
3052
  await db.exec("ROLLBACK");
@@ -1643,16 +3054,12 @@ async function reconcileTable(db: MutationDb, context: TableContext) {
1643
3054
  }
1644
3055
  }
1645
3056
 
1646
- function buildRequestHeaders(bearerToken?: string): Record<string, string> {
1647
- if (!bearerToken) {
1648
- return {
1649
- "Content-Type": "application/json",
1650
- };
1651
- }
1652
-
3057
+ function buildRequestHeaders(bearerToken?: string, requestHeaders?: Record<string, string>): Record<string, string> {
3058
+ // Static headers first so the toolkit-owned Content-Type/Authorization always win.
1653
3059
  return {
3060
+ ...(requestHeaders ?? {}),
1654
3061
  "Content-Type": "application/json",
1655
- Authorization: `Bearer ${bearerToken}`,
3062
+ ...(bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}),
1656
3063
  };
1657
3064
  }
1658
3065
 
@@ -1661,149 +3068,64 @@ async function applyMutationStatusUpdates(db: MutationDb, context: TableContext,
1661
3068
  return;
1662
3069
  }
1663
3070
 
1664
- const columns = [
1665
- "mutation_id",
1666
- "status",
1667
- "attempt_count",
1668
- "updated_at_us",
1669
- "sent_at_us",
1670
- "replace_sent_at_us",
1671
- "acked_at_us",
1672
- "replace_acked_at_us",
1673
- "server_updated_at_us",
1674
- "replace_server_updated_at_us",
1675
- "last_error",
1676
- "next_retry_at_us",
1677
- "last_http_status",
1678
- "conflict_reason",
1679
- ] as const;
1680
- const params: unknown[] = [];
1681
- const tuples = updates.map((update) => {
1682
- const start = params.length;
1683
-
1684
- params.push(
1685
- update.mutationId,
1686
- update.status,
1687
- update.attemptCount,
1688
- update.updatedAtUs,
1689
- update.sentAtUs ?? null,
1690
- update.replaceSentAtUs ?? false,
1691
- update.ackedAtUs ?? null,
1692
- update.replaceAckedAtUs ?? false,
1693
- update.serverUpdatedAtUs ?? null,
1694
- update.replaceServerUpdatedAtUs ?? false,
1695
- update.lastError ?? null,
1696
- update.nextRetryAtUs ?? null,
1697
- update.lastHttpStatus ?? null,
1698
- update.conflictReason ?? null,
1699
- );
1700
-
1701
- return `(${columns
1702
- .map((columnName, index) => {
1703
- const position = start + index + 1;
1704
-
1705
- if (
1706
- columnName === "updated_at_us" ||
1707
- columnName === "sent_at_us" ||
1708
- columnName === "acked_at_us" ||
1709
- columnName === "server_updated_at_us" ||
1710
- columnName === "next_retry_at_us"
1711
- ) {
1712
- return `$${position}::bigint`;
1713
- }
1714
-
1715
- if (columnName === "attempt_count" || columnName === "last_http_status") {
1716
- return `$${position}::int`;
1717
- }
1718
-
1719
- if (
1720
- columnName === "replace_sent_at_us" ||
1721
- columnName === "replace_acked_at_us" ||
1722
- columnName === "replace_server_updated_at_us"
1723
- ) {
1724
- return `$${position}::boolean`;
1725
- }
1726
-
1727
- return `$${position}`;
1728
- })
1729
- .join(", ")})`;
1730
- });
1731
-
1732
- await db.query(
1733
- `
1734
- UPDATE ${context.journalTable} AS journal
1735
- SET
1736
- status = updates.status,
1737
- attempt_count = updates.attempt_count,
1738
- updated_at_us = updates.updated_at_us::bigint,
1739
- sent_at_us = CASE
1740
- WHEN updates.replace_sent_at_us THEN updates.sent_at_us::bigint
1741
- ELSE journal.sent_at_us
1742
- END,
1743
- acked_at_us = CASE
1744
- WHEN updates.replace_acked_at_us THEN updates.acked_at_us::bigint
1745
- ELSE journal.acked_at_us
1746
- END,
1747
- server_updated_at_us = CASE
1748
- WHEN updates.replace_server_updated_at_us THEN updates.server_updated_at_us::bigint
1749
- ELSE journal.server_updated_at_us
1750
- END,
1751
- last_error = updates.last_error,
1752
- next_retry_at_us = updates.next_retry_at_us::bigint,
1753
- last_http_status = updates.last_http_status,
1754
- conflict_reason = updates.conflict_reason
1755
- FROM (
1756
- VALUES ${tuples.join(",\n ")}
1757
- ) AS updates (
1758
- mutation_id,
1759
- status,
1760
- attempt_count,
1761
- updated_at_us,
1762
- sent_at_us,
1763
- replace_sent_at_us,
1764
- acked_at_us,
1765
- replace_acked_at_us,
1766
- server_updated_at_us,
1767
- replace_server_updated_at_us,
1768
- last_error,
1769
- next_retry_at_us,
1770
- last_http_status,
1771
- conflict_reason
1772
- )
1773
- WHERE journal.mutation_id = updates.mutation_id::uuid
1774
- `,
1775
- params,
3071
+ // Tier ②: `update().from(<VALUES>)`. Every value is a bound param with the same cast as before;
3072
+ // the `updates` alias and its column list are fixed by this function (not derived from data), so
3073
+ // the alias-qualified references in SET/WHERE are fixed template text, while the journal side of
3074
+ // each CASE interpolates the column objects.
3075
+ const journal = context.tables.journal;
3076
+ const tuples = updates.map(
3077
+ (update) =>
3078
+ sql`(${update.mutationId}, ${update.status}, ${update.attemptCount}::int, ${update.updatedAtUs}::bigint, ${
3079
+ update.sentAtUs ?? null
3080
+ }::bigint, ${update.replaceSentAtUs ?? false}::boolean, ${update.ackedAtUs ?? null}::bigint, ${
3081
+ update.replaceAckedAtUs ?? false
3082
+ }::boolean, ${update.serverUpdatedAtUs ?? null}::bigint, ${update.replaceServerUpdatedAtUs ?? false}::boolean, ${
3083
+ update.baseServerVersion ?? null
3084
+ }::bigint, ${update.replaceBaseServerVersion ?? false}::boolean, ${update.lastError ?? null}, ${
3085
+ update.nextRetryAtUs ?? null
3086
+ }::bigint, ${update.lastHttpStatus ?? null}::int, ${update.conflictReason ?? null})`,
1776
3087
  );
1777
- }
1778
-
1779
- function buildColumnEquality(columnNames: string[], leftAlias: string, rightAlias: string) {
1780
- return columnNames.map((columnName) => `${leftAlias}.${columnName} = ${rightAlias}.${columnName}`).join(" AND ");
3088
+ const updatesTable = sql`(VALUES ${sql.join(
3089
+ tuples,
3090
+ sql`, `,
3091
+ )}) AS updates (mutation_id, status, attempt_count, updated_at_us, sent_at_us, replace_sent_at_us, acked_at_us, replace_acked_at_us, server_updated_at_us, replace_server_updated_at_us, base_server_version, replace_base_server_version, last_error, next_retry_at_us, last_http_status, conflict_reason)`;
3092
+
3093
+ const query = queryBuilder
3094
+ .update(journal)
3095
+ .set({
3096
+ status: sql`updates.status`,
3097
+ attemptCount: sql`updates.attempt_count`,
3098
+ updatedAtUs: sql`updates.updated_at_us::bigint`,
3099
+ sentAtUs: sql`CASE WHEN updates.replace_sent_at_us THEN updates.sent_at_us::bigint ELSE ${journal.sentAtUs} END`,
3100
+ ackedAtUs: sql`CASE WHEN updates.replace_acked_at_us THEN updates.acked_at_us::bigint ELSE ${journal.ackedAtUs} END`,
3101
+ serverUpdatedAtUs: sql`CASE WHEN updates.replace_server_updated_at_us THEN updates.server_updated_at_us::bigint ELSE ${journal.serverUpdatedAtUs} END`,
3102
+ baseServerVersion: sql`CASE WHEN updates.replace_base_server_version THEN updates.base_server_version::bigint ELSE ${journal.baseServerVersion} END`,
3103
+ lastError: sql`updates.last_error`,
3104
+ nextRetryAtUs: sql`updates.next_retry_at_us::bigint`,
3105
+ lastHttpStatus: sql`updates.last_http_status`,
3106
+ conflictReason: sql`updates.conflict_reason`,
3107
+ })
3108
+ .from(updatesTable)
3109
+ .where(eq(journal.mutationId, sql`updates.mutation_id::uuid`))
3110
+ .toSQL();
3111
+ await db.query(query.sql, query.params as unknown[]);
1781
3112
  }
1782
3113
 
1783
3114
  function qualifyLocalIdentifier(schemaName: string, tableName: string) {
1784
3115
  if (schemaName === "public") {
1785
- return tableName;
3116
+ // Quote-when-needed: a reserved-word or mixed-case table name (e.g. `group`)
3117
+ // MUST be quoted or the generated SQL fails to parse (ADR-0004). Normal names
3118
+ // stay bare, so existing generated SQL is unchanged.
3119
+ return maybeQuoteIdentifier(tableName);
1786
3120
  }
1787
3121
 
1788
3122
  return `${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}`;
1789
3123
  }
1790
3124
 
1791
- function quoteIdentifier(value: string) {
1792
- return `"${value.replace(/"/g, '""')}"`;
1793
- }
1794
-
1795
3125
  function buildJournalSequenceName(journalTable: string) {
1796
3126
  return `${journalTable}_mutation_seq`;
1797
3127
  }
1798
3128
 
1799
- function escapeSqlString(value: string) {
1800
- return value.replace(/'/g, "''");
1801
- }
1802
-
1803
- function formatSqlValuePlaceholder(position: number, columnName: string) {
1804
- return /_at_us$/.test(columnName) ? `$${position}::bigint` : `$${position}`;
1805
- }
1806
-
1807
3129
  function hasProperty(context: TableContext, propertyKey: string) {
1808
3130
  return context.columns.some((column) => column.propertyKey === propertyKey);
1809
3131
  }
@@ -1826,10 +3148,36 @@ function isRecord(value: unknown): value is Record<string, unknown> {
1826
3148
 
1827
3149
  class MutationRequestError extends Error {
1828
3150
  readonly status: number;
3151
+ /** Per-mutation attribution the server returned for a structural rejection, or null. */
3152
+ readonly rejections: MutationRejection[] | null;
1829
3153
 
1830
- constructor(message: string, status: number) {
3154
+ constructor(message: string, status: number, rejections: MutationRejection[] | null = null) {
1831
3155
  super(message);
1832
3156
  this.name = "MutationRequestError";
1833
3157
  this.status = status;
3158
+ this.rejections = rejections;
3159
+ }
3160
+ }
3161
+
3162
+ /**
3163
+ * Extract per-mutation attribution from a non-2xx batch-write body. The server names the
3164
+ * offending mutations on a structural (validation) rejection; an absent, non-JSON, or
3165
+ * empty-`rejections` body yields null, so the failure is treated as non-attributable
3166
+ * (whole batch stays retryable).
3167
+ */
3168
+ function parseBatchRejections(body: string): MutationRejection[] | null {
3169
+ if (body.length === 0) {
3170
+ return null;
3171
+ }
3172
+
3173
+ let parsed: unknown;
3174
+ try {
3175
+ parsed = JSON.parse(body);
3176
+ } catch {
3177
+ return null;
1834
3178
  }
3179
+
3180
+ const result = batchMutationErrorSchema.safeParse(parsed);
3181
+ const rejections = result.success ? result.data.rejections : undefined;
3182
+ return rejections && rejections.length > 0 ? rejections : null;
1835
3183
  }