@pgxsinkit/client 0.1.31 → 0.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +11 -0
  2. package/dist/convergence.d.ts +76 -0
  3. package/dist/convergence.d.ts.map +1 -0
  4. package/dist/debug.d.ts +34 -0
  5. package/dist/debug.d.ts.map +1 -0
  6. package/dist/index.d.ts +421 -7
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +7214 -2234
  9. package/dist/index.js.map +74 -44
  10. package/dist/lazy-guard.d.ts +58 -0
  11. package/dist/lazy-guard.d.ts.map +1 -0
  12. package/dist/local-store.d.ts +56 -0
  13. package/dist/local-store.d.ts.map +1 -0
  14. package/dist/local-tables.d.ts +707 -0
  15. package/dist/local-tables.d.ts.map +1 -0
  16. package/dist/mutation-state.d.ts +62 -0
  17. package/dist/mutation-state.d.ts.map +1 -0
  18. package/dist/mutation.d.ts +117 -4
  19. package/dist/mutation.d.ts.map +1 -1
  20. package/dist/schema.d.ts +49 -0
  21. package/dist/schema.d.ts.map +1 -1
  22. package/dist/shape-sync.d.ts +180 -0
  23. package/dist/shape-sync.d.ts.map +1 -0
  24. package/dist/sync/apply.d.ts +51 -0
  25. package/dist/sync/apply.d.ts.map +1 -0
  26. package/dist/sync/copy.d.ts +43 -0
  27. package/dist/sync/copy.d.ts.map +1 -0
  28. package/dist/sync/drizzle-executor.d.ts +5 -0
  29. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  30. package/dist/sync/index.d.ts +32 -0
  31. package/dist/sync/index.d.ts.map +1 -0
  32. package/dist/sync/metadata-tables.d.ts +131 -0
  33. package/dist/sync/metadata-tables.d.ts.map +1 -0
  34. package/dist/sync/nudge.d.ts +49 -0
  35. package/dist/sync/nudge.d.ts.map +1 -0
  36. package/dist/sync/shape-inbox.d.ts +215 -0
  37. package/dist/sync/shape-inbox.d.ts.map +1 -0
  38. package/dist/sync/subscription-state.d.ts +39 -0
  39. package/dist/sync/subscription-state.d.ts.map +1 -0
  40. package/dist/sync/tags.d.ts +130 -0
  41. package/dist/sync/tags.d.ts.map +1 -0
  42. package/dist/sync/types.d.ts +118 -0
  43. package/dist/sync/types.d.ts.map +1 -0
  44. package/dist/sync-auth.d.ts +53 -0
  45. package/dist/sync-auth.d.ts.map +1 -0
  46. package/dist/worker/attach-sync-client.d.ts +75 -0
  47. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  48. package/dist/worker/define-sync-worker.d.ts +75 -0
  49. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  50. package/dist/worker/live-diff.d.ts +44 -0
  51. package/dist/worker/live-diff.d.ts.map +1 -0
  52. package/dist/worker/protocol.d.ts +260 -0
  53. package/dist/worker/protocol.d.ts.map +1 -0
  54. package/dist/worker/token-cache.d.ts +26 -0
  55. package/dist/worker/token-cache.d.ts.map +1 -0
  56. package/oxlint-plugin.js +143 -0
  57. package/package.json +19 -7
  58. package/skills/core/SKILL.md +197 -0
  59. package/skills/operating/SKILL.md +243 -0
  60. package/src/convergence.ts +197 -0
  61. package/src/debug.ts +151 -0
  62. package/src/index.ts +1104 -44
  63. package/src/lazy-guard.ts +121 -0
  64. package/src/local-store.ts +193 -0
  65. package/src/local-tables.ts +546 -0
  66. package/src/mutation-state.ts +90 -0
  67. package/src/mutation.ts +1868 -562
  68. package/src/schema.ts +352 -27
  69. package/src/shape-sync.ts +477 -0
  70. package/src/sync/apply.ts +530 -0
  71. package/src/sync/copy.ts +206 -0
  72. package/src/sync/drizzle-executor.ts +48 -0
  73. package/src/sync/index.ts +1076 -0
  74. package/src/sync/metadata-tables.ts +67 -0
  75. package/src/sync/nudge.ts +110 -0
  76. package/src/sync/shape-inbox.ts +566 -0
  77. package/src/sync/subscription-state.ts +135 -0
  78. package/src/sync/tags.ts +365 -0
  79. package/src/sync/types.ts +132 -0
  80. package/src/sync-auth.ts +117 -0
  81. package/src/worker/attach-sync-client.ts +558 -0
  82. package/src/worker/define-sync-worker.ts +596 -0
  83. package/src/worker/live-diff.ts +140 -0
  84. package/src/worker/protocol.ts +325 -0
  85. 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,8 +310,42 @@ 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>;
@@ -143,13 +361,67 @@ export function nowMicroseconds(): string {
143
361
  return (BigInt(Date.now()) * 1000n).toString();
144
362
  }
145
363
 
364
+ /**
365
+ * Best-effort decode of a JWT's claims payload, for stamping `authClaim` managed fields into the
366
+ * optimistic overlay (the value the server will independently stamp from the same claim path). This is
367
+ * **not** a verification — the token is trusted only for a local, optimistic projection that the server
368
+ * re-stamps authoritatively on apply; a forged claim could never make the server attribute the row
369
+ * differently. Returns `undefined` for a malformed token.
370
+ */
371
+ export function decodeJwtClaims(token: string): Record<string, unknown> | undefined {
372
+ const segments = token.split(".");
373
+ if (segments.length < 2 || !segments[1]) {
374
+ return undefined;
375
+ }
376
+ try {
377
+ const normalized = segments[1].replace(/-/g, "+").replace(/_/g, "/");
378
+ const padded = normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), "=");
379
+ const binary = atob(padded);
380
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
381
+ const payload = JSON.parse(new TextDecoder().decode(bytes)) as unknown;
382
+ return typeof payload === "object" && payload !== null ? (payload as Record<string, unknown>) : undefined;
383
+ } catch {
384
+ return undefined;
385
+ }
386
+ }
387
+
388
+ /**
389
+ * Read a claim at a JSON path out of a decoded claims object, returning it as a string (the form the
390
+ * optimistic overlay column expects, mirroring the server's `jsonb #>>` text extraction). Returns
391
+ * `undefined` if the path is absent or the leaf is not a string/number.
392
+ */
393
+ export function readJwtClaimPath(claims: Record<string, unknown>, claimPath: string[]): string | undefined {
394
+ let cursor: unknown = claims;
395
+ for (const segment of claimPath) {
396
+ if (typeof cursor !== "object" || cursor === null) {
397
+ return undefined;
398
+ }
399
+ cursor = (cursor as Record<string, unknown>)[segment];
400
+ }
401
+ if (typeof cursor === "string") {
402
+ return cursor;
403
+ }
404
+ return typeof cursor === "number" ? String(cursor) : undefined;
405
+ }
406
+
146
407
  export function computeBackoffDelayMs(attemptCount: number) {
147
408
  const exponent = Math.max(attemptCount - 1, 0);
148
409
  return Math.min(1000 * 2 ** exponent, 30_000);
149
410
  }
150
411
 
151
- export function computeNextRetryAtUs(nowUs: string, attemptCount: number) {
152
- return (BigInt(nowUs) + BigInt(computeBackoffDelayMs(attemptCount)) * 1000n).toString();
412
+ /**
413
+ * Retry delay with equal jitter around the {@link computeBackoffDelayMs} ceiling: half
414
+ * the ceiling plus a random share of the other half. Spreads retries so a fleet of
415
+ * clients does not stampede the server in lockstep after an outage (ADR-0005 congestion
416
+ * policy). `random` is injectable for deterministic tests.
417
+ */
418
+ export function computeRetryDelayMs(attemptCount: number, random: () => number = Math.random) {
419
+ const ceiling = computeBackoffDelayMs(attemptCount);
420
+ return Math.round(ceiling / 2 + random() * (ceiling / 2));
421
+ }
422
+
423
+ export function computeNextRetryAtUs(nowUs: string, attemptCount: number, random: () => number = Math.random) {
424
+ return (BigInt(nowUs) + BigInt(computeRetryDelayMs(attemptCount, random)) * 1000n).toString();
153
425
  }
154
426
 
155
427
  export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
@@ -163,7 +435,20 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
163
435
  return undefined;
164
436
  };
165
437
 
438
+ // The decoded JWT claims for stamping `authClaim` create-managed fields into the optimistic overlay
439
+ // (the same value the server stamps from the same claim path). Resolved only when a create needs it
440
+ // (a table with such a field), so tokenless registries never pay a token lookup.
441
+ const resolveAuthClaims = async (): Promise<Record<string, unknown> | undefined> => {
442
+ const token = await resolveAuthToken();
443
+ return token ? decodeJwtClaims(token) : undefined;
444
+ };
445
+
166
446
  const tableContexts = buildTableContexts(options.registry);
447
+ const maxMutationAttempts = options.maxMutationAttempts ?? DEFAULT_MAX_MUTATION_ATTEMPTS;
448
+ const flushBatchSize = options.flushBatchSize ?? DEFAULT_FLUSH_BATCH_SIZE;
449
+ // The fingerprint (ADR-0004) stamped onto each enqueued mutation (ADR-0006). The runtime
450
+ // owns the registry, so it derives this itself; an explicit override is honoured for tests.
451
+ const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);
167
452
  let flushQueue = Promise.resolve();
168
453
 
169
454
  const getTableContext = (table: SyncTableName<TRegistry>) => {
@@ -188,7 +473,11 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
188
473
  }
189
474
  };
190
475
 
191
- const normalizeBatchItem = (item: MutationBatchItem<TRegistry>, order: number): NormalizedBatchItem => {
476
+ const normalizeBatchItem = (
477
+ item: MutationBatchItem<TRegistry>,
478
+ order: number,
479
+ claims: Record<string, unknown> | undefined,
480
+ ): NormalizedBatchItem => {
192
481
  const context = getTableContext(item.table as SyncTableName<TRegistry>);
193
482
  const mutationId = globalThis.crypto.randomUUID();
194
483
  const nowUs = nowMicroseconds();
@@ -196,7 +485,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
196
485
  switch (item.kind) {
197
486
  case "create": {
198
487
  const strippedInput = stripReadModelOverlayFields(item.input);
199
- const optimisticRecord = ensureRecord(createOptimisticRecordFromContext(context, strippedInput));
488
+ const optimisticRecord = ensureRecord(createOptimisticRecordFromContext(context, strippedInput, claims));
200
489
  const entityKey = buildEntityKeyFromRecord(context, optimisticRecord);
201
490
 
202
491
  return {
@@ -221,6 +510,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
221
510
  entityKey,
222
511
  entityKeyJson: serializeEntityKey(entityKey),
223
512
  patch,
513
+ blind: item.blind ?? false,
224
514
  mutationId,
225
515
  nowUs,
226
516
  order,
@@ -242,12 +532,28 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
242
532
  }
243
533
  };
244
534
 
245
- const enqueueBatch = async (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => {
535
+ const enqueueBatch = async (
536
+ items: ReadonlyArray<MutationBatchItem<TRegistry>>,
537
+ unit?: WriteUnit,
538
+ ): Promise<string[]> => {
246
539
  if (items.length === 0) {
247
- return;
540
+ return [];
248
541
  }
249
542
 
250
- const normalizedItems = items.map((item, index) => normalizeBatchItem(item, index));
543
+ // The distinct pessimistic write-unit ids this enqueue tagged — returned so the caller can
544
+ // foreground-route them to the authoritative endpoint (ADR-0022). Empty for a purely optimistic batch.
545
+ const pessimisticUnitIds = new Set<string>();
546
+
547
+ // Resolve the decoded claims once per batch, but only if a create actually needs them (a target
548
+ // table with an `authClaim` create-managed field). Avoids a token lookup for every other write.
549
+ const needsAuthClaims = items.some(
550
+ (item) =>
551
+ item.kind === "create" &&
552
+ getTableContext(item.table as SyncTableName<TRegistry>).managedAuthClaimCreateFields.length > 0,
553
+ );
554
+ const claims = needsAuthClaims ? await resolveAuthClaims() : undefined;
555
+
556
+ const normalizedItems = items.map((item, index) => normalizeBatchItem(item, index, claims));
251
557
  const batchGroups = new Map<string, { context: TableContext; items: NormalizedBatchItem[] }>();
252
558
 
253
559
  for (const item of normalizedItems) {
@@ -313,6 +619,9 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
313
619
  value: item.input,
314
620
  }),
315
621
  nowUs: item.nowUs,
622
+ // A create has no Base server version (ADR-0015): its conflict is a PK collision, a
623
+ // separate concern from the stale-write check.
624
+ baseServerVersion: null,
316
625
  });
317
626
 
318
627
  entityState.record = item.optimisticRecord;
@@ -330,6 +639,51 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
330
639
  break;
331
640
  }
332
641
  case "update": {
642
+ if (item.blind) {
643
+ // ADR-0022 addendum — a BLIND update: the write target is excluded from the actor's read
644
+ // shape (its rows never stream here), so there is no local base row to seed and no optimistic
645
+ // state to show. It is meaningful ONLY when the write routes to the authoritative endpoint (the
646
+ // /unit expander is authoritative): an optimistic-routed blind write has nothing to converge, so
647
+ // it is rejected at enqueue. The `unit` fixes the route inside a `transaction` block; a plain
648
+ // enqueue on a statically-pessimistic table earns its own pessimistic unit downstream.
649
+ const routesPessimistic = unit ? unit.mode === "pessimistic" : context.entry.writeMode === "pessimistic";
650
+ if (!routesPessimistic) {
651
+ throw new Error(
652
+ `${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)`,
653
+ );
654
+ }
655
+
656
+ // KEEP the already-queued-for-deletion guard (journal-derived; needs no local record).
657
+ if (entityState.latestMutationKind === "delete" && entityState.latestMutationStatus !== "acked") {
658
+ throw new Error(`${context.key} is already queued for deletion`);
659
+ }
660
+
661
+ // Plan a journal row ONLY — no overlay, so nothing enters the read model and nothing can linger
662
+ // there. `baseServerVersion: null`: the /unit expander is authoritative, there is no base to
663
+ // capture. The `pessimistic-blind` marker keeps the row off the optimistic flusher and lets
664
+ // reconcile retire it after ack WITHOUT a synced echo (there is no visible row to converge).
665
+ plannedMutations.push({
666
+ mutationId: item.mutationId,
667
+ entityKey: item.entityKey,
668
+ entityKeyJson: item.entityKeyJson,
669
+ mutationKind: "update",
670
+ payloadJson: jsonStringifyPayload({
671
+ kind: "update",
672
+ patch: item.patch,
673
+ }),
674
+ nowUs: item.nowUs,
675
+ baseServerVersion: null,
676
+ writeMode: "pessimistic-blind",
677
+ });
678
+
679
+ // Advance only the journal-derived tracking (no record/overlay): so a later same-batch item on
680
+ // this entity chains in author order and sees the pending blind write.
681
+ entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;
682
+ entityState.latestMutationKind = "update";
683
+ entityState.latestMutationStatus = "pending";
684
+ break;
685
+ }
686
+
333
687
  if (!entityState.record) {
334
688
  throw new Error(`${context.key} not found in local read model`);
335
689
  }
@@ -338,6 +692,9 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
338
692
  throw new Error(`${context.key} is already queued for deletion`);
339
693
  }
340
694
 
695
+ // ADR-0015: capture the Base server version BEFORE the record is replaced by the
696
+ // optimistic value below (which overwrites the Server version with the client clock).
697
+ const updateBaseServerVersion = captureChainHeadBase(context, entityState);
341
698
  const overlayKind = entityState.overlayKind === "pending_create" ? "pending_create" : "pending_update";
342
699
  const optimisticRecord = ensureRecord(
343
700
  buildOptimisticRecord(
@@ -345,7 +702,10 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
345
702
  {
346
703
  ...entityState.record,
347
704
  ...item.patch,
348
- updatedAtUs: item.nowUs,
705
+ // Re-stamp the on-update managed timestamp(s) generically (governance-driven) — for a
706
+ // convention table this is exactly `updatedAtUs`, for a custom-named Server version
707
+ // it is that column, so the optimistic row never carries a stale managed value.
708
+ ...buildUpdateManagedNowStamp(context, item.nowUs),
349
709
  },
350
710
  {
351
711
  overlayKind,
@@ -363,6 +723,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
363
723
  patch: item.patch,
364
724
  }),
365
725
  nowUs: item.nowUs,
726
+ baseServerVersion: updateBaseServerVersion,
366
727
  });
367
728
 
368
729
  entityState.record = optimisticRecord;
@@ -388,6 +749,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
388
749
  throw new Error(`${context.key} is already queued for deletion`);
389
750
  }
390
751
 
752
+ const deleteBaseServerVersion = captureChainHeadBase(context, entityState);
391
753
  plannedMutations.push({
392
754
  mutationId: item.mutationId,
393
755
  entityKey: item.entityKey,
@@ -398,6 +760,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
398
760
  entityKey: item.entityKey,
399
761
  }),
400
762
  nowUs: item.nowUs,
763
+ baseServerVersion: deleteBaseServerVersion,
401
764
  });
402
765
 
403
766
  entityState.overlayKind = "pending_delete";
@@ -416,13 +779,28 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
416
779
  }
417
780
  }
418
781
 
419
- await insertMutationsBulk(options.db, context, plannedMutations);
782
+ // ADR-0022: an explicit unit (from a `transaction` block) tags the whole batch; otherwise a
783
+ // statically-`pessimistic` table earns its own per-enqueue unit, so its writes route to the
784
+ // authoritative endpoint too. An optimistic table with no explicit unit stays untagged.
785
+ const effectiveUnit: WriteUnit | undefined =
786
+ unit ??
787
+ (context.entry.writeMode === "pessimistic"
788
+ ? { id: globalThis.crypto.randomUUID(), mode: "pessimistic" }
789
+ : undefined);
790
+ if (effectiveUnit?.mode === "pessimistic") {
791
+ pessimisticUnitIds.add(effectiveUnit.id);
792
+ }
793
+ await insertMutationsBulk(options.db, context, plannedMutations, registryVersion, effectiveUnit);
420
794
  await upsertOverlayRecordsBulk(options.db, context, [...plannedOverlays.values()]);
421
795
  }
796
+
797
+ return [...pessimisticUnitIds];
422
798
  };
423
799
 
424
800
  const runFlush = async (table?: SyncTableName<TRegistry>) => {
425
801
  const affectedContexts = new Map<string, TableContext>();
802
+ const quarantinedMutationIds = new Set<string>();
803
+ const conflictedMutationIds = new Set<string>();
426
804
  let processedCount = 0;
427
805
 
428
806
  do {
@@ -430,8 +808,11 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
430
808
  options.db,
431
809
  tableContexts as Record<string, TableContext>,
432
810
  options.writeUrl,
811
+ maxMutationAttempts,
812
+ flushBatchSize,
433
813
  table,
434
814
  resolveAuthToken,
815
+ options.requestHeaders,
435
816
  );
436
817
 
437
818
  processedCount = batchResult.processedCount;
@@ -439,58 +820,366 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
439
820
  for (const context of batchResult.affectedContexts) {
440
821
  affectedContexts.set(context.key, context);
441
822
  }
823
+
824
+ for (const mutationId of batchResult.quarantinedMutationIds) {
825
+ quarantinedMutationIds.add(mutationId);
826
+ }
827
+
828
+ for (const mutationId of batchResult.conflictedMutationIds) {
829
+ conflictedMutationIds.add(mutationId);
830
+ }
442
831
  } while (processedCount > 0);
443
832
 
444
833
  for (const context of affectedContexts.values()) {
445
834
  await reconcileTable(options.db, context);
446
835
  }
836
+
837
+ // Surface newly-quarantined mutations after reconciliation so the app never has to
838
+ // poll for permanently-rejected writes (ADR-0006 decision 4). Never silent loss.
839
+ if (quarantinedMutationIds.size > 0 && options.onQuarantine) {
840
+ const details = await readMutationDetailsForContexts(
841
+ options.db,
842
+ [...affectedContexts.values()],
843
+ quarantinedMutationIds,
844
+ );
845
+
846
+ if (details.length > 0) {
847
+ await options.onQuarantine(details);
848
+ }
849
+ }
850
+
851
+ // Surface newly-conflicted (stale) writes (ADR-0015). The optimistic Overlay is kept, so the app
852
+ // can show a resolution/diff UI and resolve each as a new write (or discard it). Never silent.
853
+ if (conflictedMutationIds.size > 0 && options.onConflict) {
854
+ const details = await readMutationDetailsForContexts(
855
+ options.db,
856
+ [...affectedContexts.values()],
857
+ conflictedMutationIds,
858
+ );
859
+
860
+ if (details.length > 0) {
861
+ await options.onConflict(details);
862
+ }
863
+ }
447
864
  };
448
865
 
449
- return {
866
+ const runtime: MutationRuntime<TRegistry> = {
867
+ registryVersion,
450
868
  create: async (table, input) => {
869
+ let unitIds: string[] = [];
451
870
  await runInTransaction(async () => {
452
- await enqueueBatch([
453
- {
454
- table,
455
- kind: "create",
456
- input,
457
- },
458
- ]);
871
+ unitIds = await enqueueBatch([{ table, kind: "create", input }]);
459
872
  });
873
+ // A statically-`pessimistic` table foreground-routes its write to the authoritative endpoint
874
+ // (ADR-0022) — the write is server-authoritative, so it is sent immediately, not left for the
875
+ // optimistic convergence loop (which skips pessimistic rows).
876
+ for (const unitId of unitIds) {
877
+ await runtime.flushUnit(unitId);
878
+ }
460
879
  },
461
880
  update: async (table, entityKeyInput, patch) => {
881
+ let unitIds: string[] = [];
462
882
  await runInTransaction(async () => {
463
- await enqueueBatch([
464
- {
465
- table,
466
- kind: "update",
467
- entityKey: entityKeyInput,
468
- patch,
469
- },
470
- ]);
883
+ unitIds = await enqueueBatch([{ table, kind: "update", entityKey: entityKeyInput, patch }]);
471
884
  });
885
+ for (const unitId of unitIds) {
886
+ await runtime.flushUnit(unitId);
887
+ }
472
888
  },
473
889
  delete: async (table, entityKeyInput) => {
890
+ let unitIds: string[] = [];
474
891
  await runInTransaction(async () => {
475
- await enqueueBatch([
476
- {
477
- table,
478
- kind: "delete",
479
- entityKey: entityKeyInput,
480
- },
481
- ]);
892
+ unitIds = await enqueueBatch([{ table, kind: "delete", entityKey: entityKeyInput }]);
482
893
  });
894
+ for (const unitId of unitIds) {
895
+ await runtime.flushUnit(unitId);
896
+ }
483
897
  },
484
- batch: async (items) => {
898
+ batch: async (items, unit) => {
899
+ let unitIds: string[] = [];
485
900
  await runInTransaction(async () => {
486
- await enqueueBatch(items);
901
+ unitIds = await enqueueBatch(items, unit);
487
902
  });
903
+ // An explicit unit (from a `transaction` block) is flushed by the caller; only foreground-route the
904
+ // units a plain `batch()` generated for statically-pessimistic tables.
905
+ if (!unit) {
906
+ for (const unitId of unitIds) {
907
+ await runtime.flushUnit(unitId);
908
+ }
909
+ }
910
+ },
911
+ discardConflict: async (table, entityKeyInput) => {
912
+ const context = getTableContext(table);
913
+ const entityKey = normalizeEntityKey(context, entityKeyInput);
914
+ const entityKeyJson = serializeEntityKey(entityKey);
915
+
916
+ // discardTerminalEntity owns its own transaction (like reconcileTable), so it is not wrapped.
917
+ await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, "conflicted");
918
+ },
919
+ discardQuarantined: async (table, entityKeyInput) => {
920
+ const context = getTableContext(table);
921
+ const entityKey = normalizeEntityKey(context, entityKeyInput);
922
+ const entityKeyJson = serializeEntityKey(entityKey);
923
+
924
+ // Symmetric to discardConflict — retire the entity's `quarantined` journal rows and clear the
925
+ // kept overlay behind the same owed-guard, so a permanently-rejected write is a real rollback.
926
+ await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, "quarantined");
488
927
  },
489
928
  flush: async (table) => {
490
929
  const nextFlush = flushQueue.then(() => runFlush(table));
491
930
  flushQueue = nextFlush.catch(() => undefined);
492
931
  await nextFlush;
493
932
  },
933
+ flushUnit: async (unitId) => {
934
+ const contexts = Object.values(tableContexts).filter((context): context is TableContext => context != null);
935
+ const unitRows = await readUnitPendingRows(options.db, contexts, unitId);
936
+ if (unitRows.length === 0) {
937
+ return { acks: [] };
938
+ }
939
+
940
+ // Prepare the unit's rows (entity key + envelope payload) and group them by table.
941
+ const prepared: PreparedBatchRow[] = [];
942
+ const byContext = new Map<string, PreparedBatchRow[]>();
943
+ for (const row of unitRows) {
944
+ const context = tableContexts[row.tableKey];
945
+ if (!context) {
946
+ continue;
947
+ }
948
+ const entityKey = JSON.parse(row.entityKeyJson) as Record<string, string>;
949
+ const rawPayload = JSON.parse(row.payloadJson) as Record<string, unknown>;
950
+ const preparedRow: PreparedBatchRow = {
951
+ ...row,
952
+ context,
953
+ entityKey,
954
+ envelopePayload:
955
+ row.mutationKind === "delete"
956
+ ? entityKey
957
+ : toSqlColumnPayload(
958
+ context,
959
+ stripManagedFields(
960
+ context,
961
+ (rawPayload["value"] ?? rawPayload["patch"] ?? rawPayload) as Record<string, unknown>,
962
+ row.mutationKind as "create" | "update",
963
+ ),
964
+ ),
965
+ sqlTableName: context.entry.shape?.tableName ?? context.key,
966
+ };
967
+ prepared.push(preparedRow);
968
+ const list = byContext.get(context.key);
969
+ if (list) {
970
+ list.push(preparedRow);
971
+ } else {
972
+ byContext.set(context.key, [preparedRow]);
973
+ }
974
+ }
975
+
976
+ // Mark every member sending (persist the resolved Base server version, like the batch path).
977
+ const sentAtUs = nowMicroseconds();
978
+ for (const rows of byContext.values()) {
979
+ await applyMutationStatusUpdates(
980
+ options.db,
981
+ rows[0]!.context,
982
+ rows.map((row) => ({
983
+ mutationId: row.mutationId,
984
+ status: "sending" as const,
985
+ attemptCount: row.attemptCount + 1,
986
+ updatedAtUs: sentAtUs,
987
+ sentAtUs,
988
+ replaceSentAtUs: true,
989
+ baseServerVersion: row.baseServerVersion,
990
+ replaceBaseServerVersion: true,
991
+ lastError: null,
992
+ nextRetryAtUs: null,
993
+ lastHttpStatus: null,
994
+ conflictReason: null,
995
+ })),
996
+ );
997
+ }
998
+
999
+ const mutations = prepared.map((row) => ({
1000
+ tableName: row.sqlTableName,
1001
+ entityKey: row.entityKey,
1002
+ mutationId: row.mutationId,
1003
+ mutationSeq: row.mutationSeq,
1004
+ kind: row.mutationKind as "create" | "update" | "delete",
1005
+ payload: row.envelopePayload,
1006
+ clientTimestampUs: sentAtUs,
1007
+ ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),
1008
+ }));
1009
+
1010
+ const url = resolveAuthoritativeMutationUrl(options.writeUrl);
1011
+ let acksByMutationId: Map<string, BatchMutationAck["acks"][number]>;
1012
+
1013
+ try {
1014
+ const authToken = await options.getAuthToken?.();
1015
+ let response = await fetch(url, {
1016
+ method: "POST",
1017
+ headers: buildRequestHeaders(authToken, options.requestHeaders),
1018
+ body: jsonStringifyPayload({ writeUnit: unitId, mutations }),
1019
+ });
1020
+
1021
+ if ([401, 403].includes(response.status) && options.getAuthToken) {
1022
+ response = await fetch(url, {
1023
+ method: "POST",
1024
+ headers: buildRequestHeaders(await options.getAuthToken(), options.requestHeaders),
1025
+ body: jsonStringifyPayload({ writeUnit: unitId, mutations }),
1026
+ });
1027
+ }
1028
+
1029
+ if (!response.ok) {
1030
+ const text = await response.text();
1031
+ throw new MutationRequestError(
1032
+ text.length > 0 ? text : `Authoritative write responded with ${response.status}`,
1033
+ response.status,
1034
+ parseBatchRejections(text),
1035
+ );
1036
+ }
1037
+
1038
+ const responseJson = (await response.json()) as BatchMutationAck;
1039
+ acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));
1040
+ } catch (error) {
1041
+ // A pessimistic write is foreground: it never reached the server (transport / non-2xx), so the
1042
+ // unit did not happen. Mark it failed — KEEPING the optimistic overlay so a retry can resend — and
1043
+ // rethrow so the caller surfaces it. There is no background retry for pessimistic units.
1044
+ const failedAtUs = nowMicroseconds();
1045
+ const httpStatus = error instanceof MutationRequestError ? error.status : null;
1046
+ const errorMessage = error instanceof Error ? error.message : "Authoritative write failed";
1047
+ for (const rows of byContext.values()) {
1048
+ await applyMutationStatusUpdates(
1049
+ options.db,
1050
+ rows[0]!.context,
1051
+ rows.map((row) => {
1052
+ const attemptCount = row.attemptCount + 1;
1053
+ const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);
1054
+ return {
1055
+ mutationId: row.mutationId,
1056
+ status: outcome.status,
1057
+ attemptCount,
1058
+ updatedAtUs: failedAtUs,
1059
+ lastError: errorMessage,
1060
+ nextRetryAtUs: outcome.nextRetryAtUs,
1061
+ lastHttpStatus: httpStatus,
1062
+ conflictReason: null,
1063
+ };
1064
+ }),
1065
+ );
1066
+ }
1067
+ throw error;
1068
+ }
1069
+
1070
+ // Apply each member's ack.
1071
+ const ackedAtUs = nowMicroseconds();
1072
+ const failedAtUs = nowMicroseconds();
1073
+ const rejectedIds = new Set<string>();
1074
+ const conflictedIds = new Set<string>();
1075
+
1076
+ for (const rows of byContext.values()) {
1077
+ await applyMutationStatusUpdates(
1078
+ options.db,
1079
+ rows[0]!.context,
1080
+ rows.map((row) => {
1081
+ const ack = acksByMutationId.get(row.mutationId);
1082
+
1083
+ if (ack?.status === "rejected") {
1084
+ // ADR-0022 §4: a business rejection. Terminal `rejected`; the overlay is auto-discarded below.
1085
+ rejectedIds.add(row.mutationId);
1086
+ return {
1087
+ mutationId: row.mutationId,
1088
+ status: "rejected" as const,
1089
+ attemptCount: row.attemptCount + 1,
1090
+ updatedAtUs: failedAtUs,
1091
+ lastError: ack.rejectionReason ?? "Rejected by the authoritative endpoint",
1092
+ nextRetryAtUs: null,
1093
+ lastHttpStatus: ack.httpStatus ?? 409,
1094
+ conflictReason: ack.rejectionReason ?? "Rejected by the authoritative endpoint",
1095
+ };
1096
+ }
1097
+
1098
+ if (ack?.status === "conflicted") {
1099
+ // ADR-0015: a stale member — terminal `conflicted`, overlay KEPT (resolve as a new write).
1100
+ conflictedIds.add(row.mutationId);
1101
+ return {
1102
+ mutationId: row.mutationId,
1103
+ status: "conflicted" as const,
1104
+ attemptCount: row.attemptCount + 1,
1105
+ updatedAtUs: failedAtUs,
1106
+ serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
1107
+ replaceServerUpdatedAtUs: true,
1108
+ lastError: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
1109
+ nextRetryAtUs: null,
1110
+ lastHttpStatus: ack.httpStatus ?? 409,
1111
+ conflictReason: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
1112
+ };
1113
+ }
1114
+
1115
+ if (!ack || ack.status !== "acked") {
1116
+ const attemptCount = row.attemptCount + 1;
1117
+ const outcome = resolveFailureOutcome(
1118
+ ack?.httpStatus ?? null,
1119
+ attemptCount,
1120
+ maxMutationAttempts,
1121
+ failedAtUs,
1122
+ );
1123
+ return {
1124
+ mutationId: row.mutationId,
1125
+ status: outcome.status,
1126
+ attemptCount,
1127
+ updatedAtUs: failedAtUs,
1128
+ lastError: ack?.conflictReason ?? "Authoritative write not acknowledged",
1129
+ nextRetryAtUs: outcome.nextRetryAtUs,
1130
+ lastHttpStatus: ack?.httpStatus ?? null,
1131
+ conflictReason: null,
1132
+ };
1133
+ }
1134
+
1135
+ return {
1136
+ mutationId: row.mutationId,
1137
+ status: "acked" as const,
1138
+ attemptCount: row.attemptCount + 1,
1139
+ updatedAtUs: ackedAtUs,
1140
+ ackedAtUs,
1141
+ replaceAckedAtUs: true,
1142
+ serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
1143
+ replaceServerUpdatedAtUs: true,
1144
+ lastError: null,
1145
+ nextRetryAtUs: null,
1146
+ lastHttpStatus: row.mutationKind === "delete" ? 204 : 200,
1147
+ conflictReason: null,
1148
+ };
1149
+ }),
1150
+ );
1151
+ }
1152
+
1153
+ // ADR-0022 §4: auto-discard the optimistic overlay for every rejected entity (the whole unit was
1154
+ // declined). The terminal `rejected` journal row is kept for diagnostics + `onReject`.
1155
+ for (const row of prepared) {
1156
+ if (rejectedIds.has(row.mutationId)) {
1157
+ await discardOverlayForSettledEntity(options.db, row.context, row.entityKey, row.entityKeyJson);
1158
+ }
1159
+ }
1160
+
1161
+ const affectedContexts = [...byContext.keys()]
1162
+ .map((key) => tableContexts[key])
1163
+ .filter((context): context is TableContext => context != null);
1164
+ for (const context of affectedContexts) {
1165
+ await reconcileTable(options.db, context);
1166
+ }
1167
+
1168
+ if (rejectedIds.size > 0 && options.onReject) {
1169
+ const details = await readMutationDetailsForContexts(options.db, affectedContexts, rejectedIds);
1170
+ if (details.length > 0) {
1171
+ await options.onReject(details);
1172
+ }
1173
+ }
1174
+ if (conflictedIds.size > 0 && options.onConflict) {
1175
+ const details = await readMutationDetailsForContexts(options.db, affectedContexts, conflictedIds);
1176
+ if (details.length > 0) {
1177
+ await options.onConflict(details);
1178
+ }
1179
+ }
1180
+
1181
+ return { acks: [...acksByMutationId.values()] };
1182
+ },
494
1183
  reconcile: async (table) => {
495
1184
  const contexts = filterContexts(tableContexts, table);
496
1185
 
@@ -499,44 +1188,41 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
499
1188
  }
500
1189
  },
501
1190
  retryFailed: async (table) => {
1191
+ assertValidMutationTransition("failed", "pending");
502
1192
  const contexts = filterContexts(tableContexts, table);
503
1193
  const nowUs = nowMicroseconds();
504
1194
 
505
1195
  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
- );
1196
+ const journal = context.tables.journal;
1197
+ const query = queryBuilder
1198
+ .update(journal)
1199
+ .set({ status: "pending", nextRetryAtUs: nowUs, updatedAtUs: nowUs, conflictReason: null })
1200
+ .where(eq(journal.status, "failed"))
1201
+ .toSQL();
1202
+ await options.db.query(query.sql, query.params as unknown[]);
518
1203
  }
519
1204
  },
520
1205
  recoverSending: async (table) => {
1206
+ assertValidMutationTransition("sending", "pending");
521
1207
  const contexts = filterContexts(tableContexts, table);
522
1208
  const nowUs = nowMicroseconds();
523
1209
 
524
1210
  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
- );
1211
+ const journal = context.tables.journal;
1212
+ const query = queryBuilder
1213
+ .update(journal)
1214
+ .set({
1215
+ status: "pending",
1216
+ updatedAtUs: nowUs,
1217
+ sentAtUs: null,
1218
+ nextRetryAtUs: nowUs,
1219
+ lastError: null,
1220
+ lastHttpStatus: null,
1221
+ conflictReason: null,
1222
+ })
1223
+ .where(eq(journal.status, "sending"))
1224
+ .toSQL();
1225
+ await options.db.query(query.sql, query.params as unknown[]);
540
1226
  }
541
1227
  },
542
1228
  readMutationStats: async (table) => {
@@ -545,18 +1231,33 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
545
1231
  pendingCount: 0,
546
1232
  sendingCount: 0,
547
1233
  failedCount: 0,
1234
+ quarantinedCount: 0,
1235
+ conflictedCount: 0,
548
1236
  ackedCount: 0,
549
1237
  };
550
1238
 
551
1239
  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
- `);
1240
+ const journal = context.tables.journal;
1241
+ // Drizzle has no `FILTER` operator (tier ②): each aggregate is a typed `sql` fragment over the
1242
+ // journal `status` column object with a bound status literal, aliased to the exact camelCase row
1243
+ // key the totals below read (the raw seam returns rows UNMAPPED, so aliases are load-bearing).
1244
+ const filteredCount = (status: MutationStatus, columnAlias: string) =>
1245
+ sql<number>`count(*) filter (where ${journal.status} = ${status})::int`.as(columnAlias);
1246
+ const query = queryBuilder
1247
+ .select({
1248
+ pendingCount: filteredCount("pending", "pendingCount"),
1249
+ sendingCount: filteredCount("sending", "sendingCount"),
1250
+ failedCount: filteredCount("failed", "failedCount"),
1251
+ quarantinedCount: filteredCount("quarantined", "quarantinedCount"),
1252
+ conflictedCount: filteredCount("conflicted", "conflictedCount"),
1253
+ ackedCount: filteredCount("acked", "ackedCount"),
1254
+ })
1255
+ .from(journal)
1256
+ .toSQL();
1257
+ const result = await options.db.query<MutationDiagnostics & Record<string, unknown>>(
1258
+ query.sql,
1259
+ query.params as unknown[],
1260
+ );
560
1261
 
561
1262
  const row = result.rows[0];
562
1263
  if (!row) {
@@ -566,6 +1267,8 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
566
1267
  totals.pendingCount += row.pendingCount;
567
1268
  totals.sendingCount += row.sendingCount;
568
1269
  totals.failedCount += row.failedCount;
1270
+ totals.quarantinedCount += row.quarantinedCount;
1271
+ totals.conflictedCount += row.conflictedCount;
569
1272
  totals.ackedCount += row.ackedCount;
570
1273
  }
571
1274
 
@@ -573,53 +1276,79 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
573
1276
  },
574
1277
  readMutationDetails: async (table) => {
575
1278
  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));
1279
+ return readMutationDetailsForContexts(options.db, contexts);
617
1280
  },
618
1281
  createOptimisticRecord: (table, input) => {
619
1282
  const context = getTableContext(table);
620
1283
  return createOptimisticRecordFromContext(context, input);
621
1284
  },
622
1285
  };
1286
+
1287
+ return runtime;
1288
+ }
1289
+
1290
+ /**
1291
+ * Read journal entries across the given contexts as {@link MutationDetail}s, newest first.
1292
+ * Shared by the public `readMutationDetails` and the flush path's quarantine surfacing,
1293
+ * optionally narrowed to a set of mutation ids.
1294
+ */
1295
+ async function readMutationDetailsForContexts(
1296
+ db: MutationDb,
1297
+ contexts: TableContext[],
1298
+ mutationIds?: ReadonlySet<string>,
1299
+ ): Promise<MutationDetail[]> {
1300
+ const rows: MutationDetail[] = [];
1301
+
1302
+ for (const context of contexts) {
1303
+ const journal = context.tables.journal;
1304
+ // The raw seam returns rows UNMAPPED (no drizzle result mapping), so every field is aliased
1305
+ // explicitly to its camelCase row key, and the `_us` bigints keep their `::text` casts.
1306
+ const query = queryBuilder
1307
+ .select({
1308
+ mutationId: sql<string>`${journal.mutationId}`.as("mutationId"),
1309
+ entityKeyJson: sql<string>`${journal.entityKeyJson}`.as("entityKeyJson"),
1310
+ mutationSeq: sql<number>`${journal.mutationSeq}`.as("mutationSeq"),
1311
+ mutationKind: sql<MutationKind>`${journal.mutationKind}`.as("mutationKind"),
1312
+ status: journal.status,
1313
+ attemptCount: sql<number>`${journal.attemptCount}`.as("attemptCount"),
1314
+ lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as("lastHttpStatus"),
1315
+ lastError: sql<string | null>`${journal.lastError}`.as("lastError"),
1316
+ conflictReason: sql<string | null>`${journal.conflictReason}`.as("conflictReason"),
1317
+ nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as("nextRetryAtUs"),
1318
+ serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
1319
+ updatedAtUs: sql<string>`${journal.updatedAtUs}::text`.as("updatedAtUs"),
1320
+ registryVersion: sql<string | null>`${journal.registryVersion}`.as("registryVersion"),
1321
+ })
1322
+ .from(journal)
1323
+ .orderBy(desc(journal.updatedAtUs), desc(journal.mutationSeq))
1324
+ .toSQL();
1325
+ const result = await db.query<MutationDetailRow>(query.sql, query.params as unknown[]);
1326
+
1327
+ for (const row of result.rows) {
1328
+ if (mutationIds && !mutationIds.has(row.mutationId)) {
1329
+ continue;
1330
+ }
1331
+
1332
+ rows.push({
1333
+ tableName: context.key,
1334
+ entityKey: JSON.parse(row.entityKeyJson) as Record<string, string>,
1335
+ mutationId: row.mutationId,
1336
+ mutationSeq: row.mutationSeq,
1337
+ mutationKind: row.mutationKind,
1338
+ status: row.status,
1339
+ attemptCount: row.attemptCount,
1340
+ lastHttpStatus: row.lastHttpStatus,
1341
+ lastError: row.lastError,
1342
+ conflictReason: row.conflictReason,
1343
+ nextRetryAtUs: row.nextRetryAtUs,
1344
+ serverUpdatedAtUs: row.serverUpdatedAtUs,
1345
+ updatedAtUs: row.updatedAtUs,
1346
+ registryVersion: row.registryVersion,
1347
+ });
1348
+ }
1349
+ }
1350
+
1351
+ return rows.sort((left, right) => Number(right.updatedAtUs) - Number(left.updatedAtUs));
623
1352
  }
624
1353
 
625
1354
  interface MutationRow extends Record<string, unknown> {
@@ -635,6 +1364,7 @@ interface MutationRow extends Record<string, unknown> {
635
1364
  conflictReason: string | null;
636
1365
  nextRetryAtUs: string | null;
637
1366
  serverUpdatedAtUs: string | null;
1367
+ registryVersion: string | null;
638
1368
  }
639
1369
 
640
1370
  interface MutationDetailRow extends Record<string, unknown> {
@@ -650,6 +1380,7 @@ interface MutationDetailRow extends Record<string, unknown> {
650
1380
  nextRetryAtUs: string | null;
651
1381
  serverUpdatedAtUs: string | null;
652
1382
  updatedAtUs: string;
1383
+ registryVersion: string | null;
653
1384
  }
654
1385
 
655
1386
  interface CurrentRecordStateRow extends Record<string, unknown> {
@@ -685,6 +1416,19 @@ interface PlannedMutationInsert {
685
1416
  mutationKind: MutationKind;
686
1417
  payloadJson: string;
687
1418
  nowUs: string;
1419
+ /**
1420
+ * The Base server version (ADR-0015) stamped at enqueue: the synced Server version the user saw,
1421
+ * for a **chain head** (the first staged write on the entity). `null` for a `create` (no base) and
1422
+ * for a **chained** write — the latter resolves its base at flush from its acked predecessor
1423
+ * (readPendingBatchRows), by Per-entity flush serialization (ADR-0014).
1424
+ */
1425
+ baseServerVersion: string | null;
1426
+ /**
1427
+ * A per-row `write_mode` override (ADR-0022 addendum). Left unset for an ordinary row, which inherits the
1428
+ * unit's mode at insert. A blind update sets `"pessimistic-blind"` so the row is flushed only by its unit's
1429
+ * foreground path (never the optimistic batch) and retires from the journal without a synced echo.
1430
+ */
1431
+ writeMode?: string | null;
688
1432
  }
689
1433
 
690
1434
  interface PlannedOverlayUpsert {
@@ -723,6 +1467,8 @@ type NormalizedBatchItem =
723
1467
  entityKey: Record<string, string>;
724
1468
  entityKeyJson: string;
725
1469
  patch: Record<string, unknown>;
1470
+ /** A blind update (ADR-0022 addendum): journal-only, no base-row presence check, no overlay. */
1471
+ blind: boolean;
726
1472
  mutationId: string;
727
1473
  nowUs: string;
728
1474
  order: number;
@@ -737,17 +1483,49 @@ type NormalizedBatchItem =
737
1483
  order: number;
738
1484
  };
739
1485
 
1486
+ /**
1487
+ * The Base server version (ADR-0015) to stamp at enqueue for an update/delete. Only a **chain head**
1488
+ * — the first staged write on the entity (no earlier unresolved mutation) — captures an enqueue-time
1489
+ * base: the synced Server version the user's edit was authored against, so a genuine external write
1490
+ * between view and apply is caught. A **chained** write (an earlier same-entity mutation is still
1491
+ * owed) returns `null` here; it resolves its base at flush from its acked predecessor, so an entity's
1492
+ * own successive edits never self-conflict (decision 2).
1493
+ */
1494
+ function captureChainHeadBase(context: TableContext, entityState: BatchEntityState): string | null {
1495
+ if ((entityState.latestMutationSeq ?? 0) !== 0) {
1496
+ return null;
1497
+ }
1498
+
1499
+ if (!context.serverVersionPropertyKey || !entityState.record) {
1500
+ return null;
1501
+ }
1502
+
1503
+ // The Server version is a bigint count of microseconds, surfaced as a string/number/bigint
1504
+ // depending on the read path. Anything else (null/object) means no observable base.
1505
+ const raw = entityState.record[context.serverVersionPropertyKey];
1506
+ if (typeof raw === "string" || typeof raw === "number" || typeof raw === "bigint") {
1507
+ return String(raw);
1508
+ }
1509
+
1510
+ return null;
1511
+ }
1512
+
740
1513
  function buildTableContexts<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
741
1514
  const localSchema = getSyncRegistrySchema(registry);
742
1515
 
743
1516
  return Object.fromEntries(
744
1517
  Object.entries(registry)
745
1518
  .filter(([, entry]) => entry.mode !== "readonly")
746
- .map(([key, entry]) => [key, buildTableContext(key, entry, localSchema)]),
1519
+ .map(([key, entry]) => [key, buildTableContext(registry, key, entry, localSchema)]),
747
1520
  ) as Partial<Record<SyncTableName<TRegistry>, TableContext>>;
748
1521
  }
749
1522
 
750
- function buildTableContext(key: string, entry: SyncTableEntry<AnyPgTable>, localSchema: string): TableContext {
1523
+ function buildTableContext<TRegistry extends SyncTableRegistry>(
1524
+ registry: TRegistry,
1525
+ key: string,
1526
+ entry: SyncTableEntry<AnyPgTable>,
1527
+ localSchema: string,
1528
+ ): TableContext {
751
1529
  if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {
752
1530
  throw new Error(`overlay and journal tables are required for writable table ${key}`);
753
1531
  }
@@ -767,6 +1545,58 @@ function buildTableContext(key: string, entry: SyncTableEntry<AnyPgTable>, local
767
1545
  return column.propertyKey;
768
1546
  });
769
1547
 
1548
+ const serverVersionColumnName = resolveServerVersionColumnName(entry) ?? null;
1549
+ const serverVersionPropertyKey = serverVersionColumnName
1550
+ ? (columns.find((candidate) => candidate.column.name === serverVersionColumnName)?.propertyKey ?? null)
1551
+ : null;
1552
+
1553
+ // Resolve the `nowMicroseconds` managed fields generically from governance, not by property name.
1554
+ // `field.column` is a drizzle property key, but tolerate a column-name declaration too.
1555
+ const resolveManagedPropertyKey = (fieldColumn: string): string | undefined =>
1556
+ columns.find((candidate) => candidate.propertyKey === fieldColumn || candidate.column.name === fieldColumn)
1557
+ ?.propertyKey;
1558
+ const nowMicrosecondsManagedFields = (entry.governance?.managedFields ?? []).filter(
1559
+ (field) => field.strategy === "nowMicroseconds",
1560
+ );
1561
+ const managedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields
1562
+ .map((field) => resolveManagedPropertyKey(field.column as string))
1563
+ .filter((propertyKey): propertyKey is string => propertyKey !== undefined);
1564
+ const updateManagedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields
1565
+ .filter((field) => field.applyOn.includes("update"))
1566
+ .map((field) => resolveManagedPropertyKey(field.column as string))
1567
+ .filter((propertyKey): propertyKey is string => propertyKey !== undefined);
1568
+
1569
+ const managedAuthClaimCreateFields = (entry.governance?.managedFields ?? [])
1570
+ .filter((field) => field.strategy === "authClaim" && field.applyOn.includes("create"))
1571
+ .flatMap((field) => {
1572
+ const propertyKey = resolveManagedPropertyKey(field.column as string);
1573
+ return propertyKey && field.claimPath ? [{ propertyKey, claimPath: field.claimPath }] : [];
1574
+ });
1575
+
1576
+ // The generated local relations as runtime Drizzle objects (memoized per registry+key in
1577
+ // local-tables.ts), plus name-resolved column handles the statement authors below need:
1578
+ // overlay/synced columns are keyed by PROPERTY key, so PK columns (a DB-column-name concept,
1579
+ // ADR-0012) are resolved once here by matching `.name`.
1580
+ const tables = {
1581
+ synced: getSyncedLocalTable(registry, key as string & keyof TRegistry),
1582
+ overlay: getOverlayTable(registry, key as string & keyof TRegistry),
1583
+ journal: getJournalTable(registry, key as string & keyof TRegistry),
1584
+ };
1585
+ const overlayColumnsByPropertyKey = getColumns(tables.overlay) as Record<string, PgColumn>;
1586
+ const syncedColumnsByPropertyKey = getColumns(tables.synced) as Record<string, PgColumn>;
1587
+ const resolvePkColumns = (columnsByKey: Record<string, PgColumn>, relation: string) =>
1588
+ entry.primaryKey.columns.map((columnName) => {
1589
+ const column = Object.values(columnsByKey).find((candidate) => candidate.name === columnName);
1590
+ if (!column) {
1591
+ throw new Error(`Primary key column ${columnName} was not found on the ${relation} table for ${key}`);
1592
+ }
1593
+ return column;
1594
+ });
1595
+ const syncedServerVersionColumn = serverVersionColumnName
1596
+ ? (Object.values(syncedColumnsByPropertyKey).find((candidate) => candidate.name === serverVersionColumnName) ??
1597
+ null)
1598
+ : null;
1599
+
770
1600
  return {
771
1601
  key,
772
1602
  entry,
@@ -785,8 +1615,19 @@ function buildTableContext(key: string, entry: SyncTableEntry<AnyPgTable>, local
785
1615
  journalSequence: qualifyLocalIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable)),
786
1616
  pkColumnNames: [...entry.primaryKey.columns],
787
1617
  pkPropertyKeys,
1618
+ serverVersionColumnName,
1619
+ serverVersionPropertyKey,
1620
+ managedNowMicrosecondsPropertyKeys,
1621
+ updateManagedNowMicrosecondsPropertyKeys,
1622
+ managedAuthClaimCreateFields,
788
1623
  recordIncludesOverlayState: "overlayTable" in (entry.clientProjection ?? {}),
789
1624
  columns,
1625
+ tables,
1626
+ overlayColumnsByPropertyKey,
1627
+ syncedColumnsByPropertyKey,
1628
+ overlayPkColumns: resolvePkColumns(overlayColumnsByPropertyKey, "overlay"),
1629
+ syncedPkColumns: resolvePkColumns(syncedColumnsByPropertyKey, "synced"),
1630
+ syncedServerVersionColumn,
790
1631
  };
791
1632
  }
792
1633
 
@@ -836,12 +1677,31 @@ function materializeColumnDefault(column: TableContext["columns"][number]["colum
836
1677
  return { ok: false };
837
1678
  }
838
1679
 
839
- function createOptimisticRecordFromContext<TCreate, TRecord>(context: TableContext, input: TCreate): TRecord {
1680
+ function createOptimisticRecordFromContext<TCreate, TRecord>(
1681
+ context: TableContext,
1682
+ input: TCreate,
1683
+ claims?: Record<string, unknown>,
1684
+ ): TRecord {
840
1685
  const record = {
841
1686
  ...(isRecord(input) ? input : {}),
842
1687
  };
843
1688
  const nowUs = nowMicroseconds();
844
1689
 
1690
+ // Stamp `authClaim` create-managed fields (owner/author/created_by) from the decoded claim at the
1691
+ // field's path, so the optimistic overlay row is attributed locally and satisfies the column's NOT
1692
+ // NULL — the server independently stamps the same claim on apply, so the value never flips on
1693
+ // convergence. (`auth.uid()` is just `claimPath: ["sub"]`.)
1694
+ if (claims != null) {
1695
+ for (const { propertyKey, claimPath } of context.managedAuthClaimCreateFields) {
1696
+ if (record[propertyKey] === undefined) {
1697
+ const value = readJwtClaimPath(claims, claimPath);
1698
+ if (value !== undefined) {
1699
+ record[propertyKey] = value;
1700
+ }
1701
+ }
1702
+ }
1703
+ }
1704
+
845
1705
  if (hasProperty(context, "createdAtUs") && record["createdAtUs"] === undefined) {
846
1706
  record["createdAtUs"] = nowUs;
847
1707
  }
@@ -850,6 +1710,15 @@ function createOptimisticRecordFromContext<TCreate, TRecord>(context: TableConte
850
1710
  record["updatedAtUs"] = nowUs;
851
1711
  }
852
1712
 
1713
+ // Generic managed-timestamp fill (governance-driven): stamp any `nowMicroseconds` managed field the
1714
+ // convention block above did not — e.g. a Server version column not named `updated_at_us`. Additive
1715
+ // and idempotent, so convention tables are unaffected (their fields are already filled).
1716
+ for (const propertyKey of context.managedNowMicrosecondsPropertyKeys) {
1717
+ if (record[propertyKey] === undefined) {
1718
+ record[propertyKey] = nowUs;
1719
+ }
1720
+ }
1721
+
853
1722
  for (const { propertyKey, column } of context.columns) {
854
1723
  if (record[propertyKey] !== undefined) {
855
1724
  continue;
@@ -867,6 +1736,18 @@ function createOptimisticRecordFromContext<TCreate, TRecord>(context: TableConte
867
1736
  }) as TRecord;
868
1737
  }
869
1738
 
1739
+ /**
1740
+ * Stamp every on-update `nowMicroseconds` managed field with `nowUs` (governance-driven, ADR-0004),
1741
+ * keyed by drizzle property key. For a convention table this is exactly `{ updatedAtUs: nowUs }`; for
1742
+ * a custom-named Server version it targets that column — so the local optimistic path never assumes
1743
+ * the demo naming the generic server applier does not.
1744
+ */
1745
+ function buildUpdateManagedNowStamp(context: TableContext, nowUs: string): Record<string, string> {
1746
+ return Object.fromEntries(
1747
+ context.updateManagedNowMicrosecondsPropertyKeys.map((propertyKey) => [propertyKey, nowUs]),
1748
+ );
1749
+ }
1750
+
870
1751
  function buildOptimisticRecord(
871
1752
  context: TableContext,
872
1753
  record: Record<string, unknown>,
@@ -895,15 +1776,19 @@ function buildEntityKeyFromRecord(context: TableContext, record: unknown) {
895
1776
  }
896
1777
 
897
1778
  function normalizeEntityKey(context: TableContext, input: Record<string, string>) {
1779
+ // The public API accepts the identity by drizzle property name (ergonomics); past this
1780
+ // boundary the canonical Entity identity is column-keyed (ADR-0012), matching the
1781
+ // journal/overlay PK columns, entity_key_json, and the applier's `v_entity_key->>'<column>'`.
1782
+ // pkPropertyKeys[i] ↔ pkColumnNames[i] by construction (buildTableContext), so we map once here.
898
1783
  return Object.fromEntries(
899
- context.pkPropertyKeys.map((propertyKey) => {
1784
+ context.pkPropertyKeys.map((propertyKey, index) => {
900
1785
  const value = input[propertyKey];
901
1786
 
902
1787
  if (value === undefined) {
903
1788
  throw new Error(`Missing entity key property ${propertyKey} for table ${context.key}`);
904
1789
  }
905
1790
 
906
- return [propertyKey, String(value)];
1791
+ return [context.pkColumnNames[index]!, String(value)];
907
1792
  }),
908
1793
  );
909
1794
  }
@@ -936,32 +1821,26 @@ async function readLatestMutationStates(
936
1821
  return new Map<string, BatchLatestMutationStateRow>();
937
1822
  }
938
1823
 
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
- );
1824
+ // The old VALUES-CTE + LEFT-JOIN-back-to-input existed only to emit null rows for entities with
1825
+ // no journal history; the caller reads via `map.get(...) ?? null`, so a missing key is equivalent.
1826
+ const journal = context.tables.journal;
1827
+ const query = queryBuilder
1828
+ .selectDistinctOn([journal.entityKeyJson], {
1829
+ entityKeyJson: sql<string>`${journal.entityKeyJson}`.as("entityKeyJson"),
1830
+ latestMutationSeq: sql<number>`${journal.mutationSeq}`.as("latestMutationSeq"),
1831
+ latestMutationKind: sql<MutationKind>`${journal.mutationKind}`.as("latestMutationKind"),
1832
+ latestMutationStatus: sql<MutationStatus>`${journal.status}`.as("latestMutationStatus"),
1833
+ })
1834
+ .from(journal)
1835
+ .where(
1836
+ inArray(
1837
+ journal.entityKeyJson,
1838
+ entities.map((entity) => entity.entityKeyJson),
1839
+ ),
1840
+ )
1841
+ .orderBy(journal.entityKeyJson, desc(journal.mutationSeq))
1842
+ .toSQL();
1843
+ const result = await db.query<BatchLatestMutationStateRow>(query.sql, query.params as unknown[]);
965
1844
 
966
1845
  return new Map(result.rows.map((row) => [row.entityKeyJson, row]));
967
1846
  }
@@ -971,40 +1850,47 @@ async function readCurrentRecordStates(db: MutationDb, context: TableContext, en
971
1850
  return new Map<string, BatchCurrentRecordStateRow>();
972
1851
  }
973
1852
 
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},
1853
+ // Tier ②: the overlay-∪-synced shape over an input VALUES table. The input CTE carries each
1854
+ // entity's `entity_key_json` alongside its PK values (the caller maps rows back by that JSON), so
1855
+ // it cannot be a plain builder select; every identifier still comes from the table objects /
1856
+ // `sql.identifier`, and every value is a bound (cast-typed) param.
1857
+ const overlay = context.tables.overlay;
1858
+ const synced = context.tables.synced;
1859
+ const inputCte = buildEntityInputCte(context, entities);
1860
+ const overlaySelectColumns = buildProjectedSelectColumns(context, context.overlayColumnsByPropertyKey);
1861
+ const syncedSelectColumns = buildProjectedSelectColumns(context, context.syncedColumnsByPropertyKey);
1862
+ const inputOverlayJoin = buildEntityInputJoin(context.pkColumnNames, context.overlayPkColumns);
1863
+ const inputSyncedJoin = buildEntityInputJoin(context.pkColumnNames, context.syncedPkColumns);
1864
+ const syncedUpdatedAtColumn = context.syncedColumnsByPropertyKey["updatedAtUs"];
1865
+ const syncedLocalUpdated =
1866
+ hasProperty(context, "updatedAtUs") && syncedUpdatedAtColumn
1867
+ ? sql`${syncedUpdatedAtColumn}::text AS "localUpdatedAtUs"`
1868
+ : sql`'0' AS "localUpdatedAtUs"`;
1869
+
1870
+ const query = queryDialect.sqlToQuery(sql`
1871
+ WITH ${inputCte},
986
1872
  overlay_rows AS (
987
1873
  SELECT
988
1874
  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"
1875
+ ${overlaySelectColumns},
1876
+ ${overlay.overlayKind} AS "overlayKind",
1877
+ ${overlay.localUpdatedAtUs}::text AS "localUpdatedAtUs"
992
1878
  FROM input_entities AS input
993
- JOIN ${context.overlayTable} AS overlay
1879
+ JOIN ${overlay}
994
1880
  ON ${inputOverlayJoin}
995
1881
  ),
996
1882
  synced_rows AS (
997
1883
  SELECT
998
1884
  input.entity_key_json AS "entityKeyJson",
999
- ${syncedSelectColumns.join(",\n ")},
1000
- 'synced' AS "overlayKind",
1001
- ${syncedLocalUpdatedSql}
1885
+ ${syncedSelectColumns},
1886
+ ${"synced"} AS "overlayKind",
1887
+ ${syncedLocalUpdated}
1002
1888
  FROM input_entities AS input
1003
- JOIN ${context.syncedTable} AS synced
1889
+ JOIN ${synced}
1004
1890
  ON ${inputSyncedJoin}
1005
1891
  WHERE NOT EXISTS (
1006
1892
  SELECT 1
1007
- FROM ${context.overlayTable} AS overlay
1893
+ FROM ${overlay}
1008
1894
  WHERE ${inputOverlayJoin}
1009
1895
  )
1010
1896
  )
@@ -1013,72 +1899,58 @@ async function readCurrentRecordStates(db: MutationDb, context: TableContext, en
1013
1899
  UNION ALL
1014
1900
  SELECT *
1015
1901
  FROM synced_rows
1016
- `,
1017
- params,
1018
- );
1902
+ `);
1903
+ const result = await db.query<BatchCurrentRecordStateRow>(query.sql, query.params as unknown[]);
1019
1904
 
1020
1905
  return new Map(result.rows.map((row) => [row.entityKeyJson, row]));
1021
1906
  }
1022
1907
 
1023
- async function insertMutationsBulk(db: MutationDb, context: TableContext, rows: ReadonlyArray<PlannedMutationInsert>) {
1908
+ async function insertMutationsBulk(
1909
+ db: MutationDb,
1910
+ context: TableContext,
1911
+ rows: ReadonlyArray<PlannedMutationInsert>,
1912
+ registryVersion: string | null,
1913
+ unit?: WriteUnit,
1914
+ ) {
1024
1915
  if (rows.length === 0) {
1025
1916
  return;
1026
1917
  }
1027
1918
 
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
- ];
1054
-
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
- ];
1919
+ // ADR-0022: a dynamic write-unit tags every row of the batch with one shared unit id + mode; the
1920
+ // default path leaves both NULL (the flusher derives mode/unit from the static group). A blind row
1921
+ // carries its own `write_mode` override (`pessimistic-blind`), so the mode is resolved per row.
1922
+ const writeUnit = unit?.id ?? null;
1923
+ const journal = context.tables.journal;
1924
+ // `mutationSeq` is intentionally omitted: the generated journal DDL carries
1925
+ // `mutation_seq ... DEFAULT nextval(<journal sequence>)`, so the DB default assigns it — drizzle
1926
+ // renders `default` for every column a row does not provide.
1927
+ const values = rows.map((row) => ({
1928
+ mutationId: row.mutationId,
1929
+ ...Object.fromEntries(context.pkColumnNames.map((columnName) => [columnName, row.entityKey[columnName]])),
1930
+ entityKeyJson: row.entityKeyJson,
1931
+ mutationKind: row.mutationKind,
1932
+ status: "pending",
1933
+ registryVersion,
1934
+ baseServerVersion: row.baseServerVersion,
1935
+ payloadJson: row.payloadJson,
1936
+ enqueuedAtUs: row.nowUs,
1937
+ nextRetryAtUs: row.nowUs,
1938
+ updatedAtUs: row.nowUs,
1939
+ writeUnit,
1940
+ writeMode: row.writeMode ?? unit?.mode ?? null,
1941
+ }));
1069
1942
 
1070
- return `(${valuePlaceholders.join(", ")})`;
1071
- });
1943
+ const query = queryBuilder
1944
+ .insert(journal)
1945
+ .values(values as PgInsertValue<JournalTable>[])
1946
+ .toSQL();
1947
+ await db.query(query.sql, query.params as unknown[]);
1072
1948
 
1073
- await db.query(
1074
- `
1075
- INSERT INTO ${context.journalTable} (
1076
- ${insertColumnNames.join(", ")}
1077
- )
1078
- VALUES ${tuples.join(",\n ")}
1079
- `,
1080
- params,
1081
- );
1949
+ // Lifecycle origin: the moment each mutation is first staged into the journal. Correlates by id with
1950
+ // the later "board-write sending"/"board-write acks" lines (staged → sent → acked, per id).
1951
+ for (const row of rows) {
1952
+ syncDebug("mutation staged", { mutationId: row.mutationId, table: context.key });
1953
+ }
1082
1954
  }
1083
1955
 
1084
1956
  async function upsertOverlayRecordsBulk(
@@ -1090,113 +1962,106 @@ async function upsertOverlayRecordsBulk(
1090
1962
  return;
1091
1963
  }
1092
1964
 
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
- );
1965
+ const overlay = context.tables.overlay;
1966
+ const values = rows.map((row) => ({
1967
+ ...Object.fromEntries(context.columns.map(({ propertyKey }) => [propertyKey, row.record[propertyKey] ?? null])),
1968
+ overlayKind: row.overlayKind,
1969
+ localUpdatedAtUs: row.localUpdatedAtUs,
1970
+ }));
1971
+ // Every inserted column (the projection + the two overlay columns) takes its EXCLUDED value on
1972
+ // conflict — the fixed alias PostgreSQL defines for the proposed row; its column names are the
1973
+ // table's own, so they come from the column objects via `sql.identifier`.
1974
+ const excludedSet = Object.fromEntries([
1975
+ ...context.columns.map(({ propertyKey, column }) => [propertyKey, sql`excluded.${sql.identifier(column.name)}`]),
1976
+ ["overlayKind", sql`excluded.${sql.identifier(overlay.overlayKind.name)}`],
1977
+ ["localUpdatedAtUs", sql`excluded.${sql.identifier(overlay.localUpdatedAtUs.name)}`],
1978
+ ]) as Record<string, SQL>;
1979
+
1980
+ const query = queryBuilder
1981
+ .insert(overlay)
1982
+ .values(values as PgInsertValue<OverlayTable>[])
1983
+ .onConflictDoUpdate({ target: context.overlayPkColumns, set: excludedSet })
1984
+ .toSQL();
1985
+ await db.query(query.sql, query.params as unknown[]);
1128
1986
  }
1129
1987
 
1130
- function buildBatchEntityInputCte(context: TableContext, entities: ReadonlyArray<BatchEntityRef>) {
1131
- const columns = ["entity_key_json", ...context.pkColumnNames];
1132
- const params: unknown[] = [];
1988
+ /**
1989
+ * The batch-input CTE as a typed fragment: `input_entities (entity_key_json, <pks…>) AS (VALUES …)`
1990
+ * with every value a bound param, cast to its PK column's type (an untyped VALUES column would
1991
+ * otherwise default to text and break the join against a uuid/int PK).
1992
+ */
1993
+ function buildEntityInputCte(context: TableContext, entities: ReadonlyArray<BatchEntityRef>): SQL {
1994
+ const columnNames = ["entity_key_json", ...context.pkColumnNames];
1133
1995
  const tuples = entities.map((entity) => {
1134
- const start = params.length;
1135
1996
  const values = [
1136
- entity.entityKeyJson,
1137
- ...context.pkPropertyKeys.map((propertyKey) => entity.entityKey[propertyKey]),
1997
+ sql`${entity.entityKeyJson}`,
1998
+ ...context.pkColumnNames.map((columnName) => {
1999
+ const columnEntry = context.columns.find(({ column }) => column.name === columnName);
2000
+ const castSuffix = columnEntry ? resolveInputCastSuffix(columnEntry.column.columnType) : "";
2001
+ // The cast keyword is a FIXED type suffix selected from the closed switch below — never
2002
+ // derived from user data — so `sql.raw` is safe here; the value itself is a bound param.
2003
+ return castSuffix
2004
+ ? sql`${entity.entityKey[columnName]}${sql.raw(castSuffix)}`
2005
+ : sql`${entity.entityKey[columnName]}`;
2006
+ }),
1138
2007
  ];
1139
-
1140
- params.push(...values);
1141
-
1142
- return `(${columns
1143
- .map((columnName, index) => formatBatchEntityInputPlaceholder(context, start + index + 1, columnName))
1144
- .join(", ")})`;
2008
+ return sql`(${sql.join(values, sql`, `)})`;
1145
2009
  });
1146
2010
 
1147
- return {
1148
- cteSql: `input_entities (${columns.join(", ")}) AS (VALUES ${tuples.join(", ")})`,
1149
- params,
1150
- };
2011
+ return sql`input_entities (${sql.join(
2012
+ columnNames.map((columnName) => sql.identifier(columnName)),
2013
+ sql`, `,
2014
+ )}) AS (VALUES ${sql.join(tuples, sql`, `)})`;
1151
2015
  }
1152
2016
 
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) {
2017
+ function resolveInputCastSuffix(columnType: string): string {
2018
+ switch (columnType) {
1165
2019
  case "PgUUID":
1166
- return `$${position}::uuid`;
2020
+ return "::uuid";
1167
2021
  case "PgBigInt64":
1168
2022
  case "PgBigInt53":
1169
- return `$${position}::bigint`;
2023
+ return "::bigint";
1170
2024
  case "PgInteger":
1171
2025
  case "PgSerial":
1172
2026
  case "PgSmallInt":
1173
- return `$${position}::int`;
2027
+ return "::int";
1174
2028
  case "PgBoolean":
1175
- return `$${position}::boolean`;
2029
+ return "::boolean";
1176
2030
  case "PgTimestamp":
1177
2031
  case "PgTimestampString":
1178
- return `$${position}::timestamp`;
2032
+ return "::timestamp";
1179
2033
  default:
1180
- return `$${position}`;
2034
+ return "";
1181
2035
  }
1182
2036
  }
1183
2037
 
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
- });
2038
+ /**
2039
+ * The projected columns of one branch (overlay or synced) as select-list fragments, aliased to
2040
+ * their camelCase property keys — the raw seam returns rows unmapped, so the aliases ARE the row
2041
+ * keys — with `::text` casts on the bigint columns (matching how the runtime reads them).
2042
+ */
2043
+ function buildProjectedSelectColumns(context: TableContext, columnsByPropertyKey: Record<string, PgColumn>): SQL {
2044
+ return sql.join(
2045
+ context.columns.map(({ propertyKey, column }) => {
2046
+ const target = columnsByPropertyKey[propertyKey];
2047
+ if (!target) {
2048
+ throw new Error(`Projected column ${propertyKey} was not found on the local tables for ${context.key}`);
2049
+ }
2050
+ if (column.columnType === "PgBigInt64" || column.columnType === "PgBigInt53") {
2051
+ return sql`${target}::text AS ${sql.identifier(propertyKey)}`;
2052
+ }
2053
+ return sql`${target} AS ${sql.identifier(propertyKey)}`;
2054
+ }),
2055
+ sql`, `,
2056
+ );
1194
2057
  }
1195
2058
 
1196
- function buildBatchEntityJoinClause(context: TableContext, tableAlias: string, inputAlias: string) {
1197
- return context.pkColumnNames
1198
- .map((columnName) => `${tableAlias}.${columnName} = ${inputAlias}.${columnName}`)
1199
- .join(" AND ");
2059
+ /** PK equality between a branch table's columns and the `input` CTE, as a typed fragment. */
2060
+ function buildEntityInputJoin(pkColumnNames: string[], pkColumns: PgColumn[]): SQL {
2061
+ return sql.join(
2062
+ pkColumnNames.map((columnName, index) => sql`${pkColumns[index]!} = input.${sql.identifier(columnName)}`),
2063
+ sql` AND `,
2064
+ );
1200
2065
  }
1201
2066
 
1202
2067
  // ---------------------------------------------------------------------------
@@ -1208,6 +2073,8 @@ function buildBatchEntityJoinClause(context: TableContext, tableAlias: string, i
1208
2073
  interface PendingBatchRow extends MutationRow {
1209
2074
  tableKey: string;
1210
2075
  enqueuedAtUs: string;
2076
+ /** The resolved Base server version (ADR-0015), or null when the table predates the policy. */
2077
+ baseServerVersion: string | null;
1211
2078
  }
1212
2079
 
1213
2080
  interface PreparedBatchRow extends PendingBatchRow {
@@ -1220,6 +2087,10 @@ interface PreparedBatchRow extends PendingBatchRow {
1220
2087
  interface FlushBatchResult {
1221
2088
  processedCount: number;
1222
2089
  affectedContexts: TableContext[];
2090
+ /** Mutation ids that transitioned to `quarantined` in this slice (ADR-0006), for surfacing. */
2091
+ quarantinedMutationIds: string[];
2092
+ /** Mutation ids that transitioned to `conflicted` in this slice (ADR-0015), for surfacing. */
2093
+ conflictedMutationIds: string[];
1223
2094
  }
1224
2095
 
1225
2096
  interface MutationStatusUpdate {
@@ -1233,60 +2104,157 @@ interface MutationStatusUpdate {
1233
2104
  replaceAckedAtUs?: boolean;
1234
2105
  serverUpdatedAtUs?: string | null;
1235
2106
  replaceServerUpdatedAtUs?: boolean;
2107
+ baseServerVersion?: string | null;
2108
+ replaceBaseServerVersion?: boolean;
1236
2109
  lastError?: string | null;
1237
2110
  nextRetryAtUs?: string | null;
1238
2111
  lastHttpStatus?: number | null;
1239
2112
  conflictReason?: string | null;
1240
2113
  }
1241
2114
 
1242
- async function readPendingBatchRows(db: MutationDb, contexts: TableContext[], nowUs: string) {
2115
+ /**
2116
+ * The resolved Base server version (ADR-0015) for a row at flush. A **chain head** already carries
2117
+ * `base_server_version` (stamped at enqueue), so COALESCE returns it untouched — keeping the
2118
+ * enqueue-time base means a genuine external write between view and apply is still caught. A
2119
+ * **chained** write has NULL there; it resolves to its **acked predecessor's** Server version (by
2120
+ * Per-entity flush serialization the predecessor is already acked when this row flushes), falling
2121
+ * back to the entity's current synced version once that predecessor has been reconciled away. Either
2122
+ * fallback yields the entity's own latest server state, so its own chain never self-conflicts.
2123
+ */
2124
+ function buildResolvedBaseServerVersion(context: TableContext): SQL {
2125
+ const journal = context.tables.journal;
2126
+ const synced = context.tables.synced;
2127
+ const pred = alias(journal, "pred");
2128
+ const predecessor = queryBuilder
2129
+ .select({ value: sql`MAX(${pred.serverUpdatedAtUs})` })
2130
+ .from(pred)
2131
+ .where(
2132
+ and(
2133
+ eq(pred.entityKeyJson, journal.entityKeyJson),
2134
+ lt(pred.mutationSeq, journal.mutationSeq),
2135
+ eq(pred.status, "acked"),
2136
+ ),
2137
+ );
2138
+
2139
+ if (!context.syncedServerVersionColumn) {
2140
+ return sql`COALESCE(${journal.baseServerVersion}, ${predecessor})::text`;
2141
+ }
2142
+
2143
+ const syncedFallback = queryBuilder
2144
+ .select({ value: sql`${context.syncedServerVersionColumn}` })
2145
+ .from(synced)
2146
+ .where(
2147
+ and(
2148
+ ...context.pkColumnNames.map((columnName, index) => eq(context.syncedPkColumns[index]!, journal[columnName]!)),
2149
+ ),
2150
+ );
2151
+
2152
+ return sql`COALESCE(${journal.baseServerVersion}, ${predecessor}, ${syncedFallback})::text`;
2153
+ }
2154
+
2155
+ /**
2156
+ * One table's send-eligible journal rows as a builder select with the shared {@link PendingBatchRow}
2157
+ * projection — the aliases ARE the row keys (raw seam), `tableKey` rides as a bound param, and the
2158
+ * resolved Base server version (ADR-0015) is the typed COALESCE fragment above.
2159
+ */
2160
+ function buildPendingRowsProjection(context: TableContext) {
2161
+ const journal = context.tables.journal;
2162
+ return {
2163
+ tableKey: sql<string>`${context.key}`.as("tableKey"),
2164
+ mutationId: sql<string>`${journal.mutationId}`.as("mutationId"),
2165
+ entityKeyJson: sql<string>`${journal.entityKeyJson}`.as("entityKeyJson"),
2166
+ mutationSeq: sql<number>`${journal.mutationSeq}`.as("mutationSeq"),
2167
+ mutationKind: sql<MutationKind>`${journal.mutationKind}`.as("mutationKind"),
2168
+ status: journal.status,
2169
+ payloadJson: sql<string>`${journal.payloadJson}`.as("payloadJson"),
2170
+ attemptCount: sql<number>`${journal.attemptCount}`.as("attemptCount"),
2171
+ lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as("lastHttpStatus"),
2172
+ lastError: sql<string | null>`${journal.lastError}`.as("lastError"),
2173
+ conflictReason: sql<string | null>`${journal.conflictReason}`.as("conflictReason"),
2174
+ nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as("nextRetryAtUs"),
2175
+ serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
2176
+ baseServerVersion: buildResolvedBaseServerVersion(context).as("baseServerVersion"),
2177
+ enqueuedAtUs: sql<string>`${journal.enqueuedAtUs}::text`.as("enqueuedAtUs"),
2178
+ };
2179
+ }
2180
+
2181
+ async function readPendingBatchRows(db: MutationDb, contexts: TableContext[], nowUs: string, batchSize: number) {
1243
2182
  if (contexts.length === 0) {
1244
2183
  return [] as PendingBatchRow[];
1245
2184
  }
1246
2185
 
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");
2186
+ const branches = contexts.map((context) => {
2187
+ const journal = context.tables.journal;
2188
+ const earlier = alias(journal, "earlier");
2189
+ return queryBuilder
2190
+ .select(buildPendingRowsProjection(context))
2191
+ .from(journal)
2192
+ .where(
2193
+ and(
2194
+ inArray(journal.status, ["pending", "failed"]),
2195
+ // ADR-0022: pessimistic rows are flushed by the authoritative unit path (flushUnit), never the
2196
+ // optimistic batch — exclude them here so a tagged write is never optimistically sent. The
2197
+ // `NOT LIKE 'pessimistic%'` also excludes a `pessimistic-blind` row (ADR-0022 addendum), which
2198
+ // belongs to its unit's foreground flush too.
2199
+ sql`COALESCE(${journal.writeMode}, '') NOT LIKE 'pessimistic%'`,
2200
+ sql`COALESCE(${journal.nextRetryAtUs}, 0) <= ${nowUs}::bigint`,
2201
+ notExists(
2202
+ queryBuilder
2203
+ .select({ one: sql`1` })
2204
+ .from(earlier)
2205
+ .where(
2206
+ and(
2207
+ eq(earlier.entityKeyJson, journal.entityKeyJson),
2208
+ lt(earlier.mutationSeq, journal.mutationSeq),
2209
+ // A still-unresolved earlier mutation blocks later same-entity ones so the
2210
+ // server applies them in author order. The quarantined status is included: a
2211
+ // later mutation must not flush past a prerequisite the server permanently
2212
+ // rejected (it would itself fail); resolving the quarantine unblocks the queue.
2213
+ inArray(earlier.status, ["pending", "failed", "sending", "quarantined"]),
2214
+ ),
2215
+ ),
2216
+ ),
2217
+ ),
2218
+ );
2219
+ });
1278
2220
 
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],
2221
+ // The union rides inside a derived table because the outer ORDER BY casts the (text) output
2222
+ // columns — a set operation's own ORDER BY may only name plain output columns. The `pending`
2223
+ // alias and its two quoted output-column names are fixed by the projection above, not data.
2224
+ const query = queryDialect.sqlToQuery(
2225
+ sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS pending ORDER BY pending."enqueuedAtUs"::bigint ASC, pending."mutationSeq" ASC LIMIT ${batchSize}`,
1289
2226
  );
2227
+ const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);
2228
+
2229
+ return result.rows;
2230
+ }
2231
+
2232
+ /**
2233
+ * Read one pessimistic write-unit's send-eligible rows (ADR-0022) across every table, ordered by author
2234
+ * sequence. Unlike {@link readPendingBatchRows} it has no per-entity ordering gate: a unit is enqueued and
2235
+ * sent atomically, so its members go together.
2236
+ */
2237
+ async function readUnitPendingRows(
2238
+ db: MutationDb,
2239
+ contexts: TableContext[],
2240
+ unitId: string,
2241
+ ): Promise<PendingBatchRow[]> {
2242
+ if (contexts.length === 0) {
2243
+ return [];
2244
+ }
2245
+
2246
+ const branches = contexts.map((context) => {
2247
+ const journal = context.tables.journal;
2248
+ return queryBuilder
2249
+ .select(buildPendingRowsProjection(context))
2250
+ .from(journal)
2251
+ .where(and(eq(journal.writeUnit, unitId), inArray(journal.status, ["pending", "failed"])));
2252
+ });
2253
+
2254
+ const query = queryDialect.sqlToQuery(
2255
+ sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS unit ORDER BY unit."mutationSeq" ASC`,
2256
+ );
2257
+ const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);
1290
2258
 
1291
2259
  return result.rows;
1292
2260
  }
@@ -1295,14 +2263,19 @@ async function flushBatch(
1295
2263
  db: MutationDb,
1296
2264
  tableContexts: Record<string, TableContext>,
1297
2265
  batchWriteUrl: string,
2266
+ maxAttempts: number,
2267
+ batchSize: number,
1298
2268
  tableFilter?: string,
1299
2269
  getAuthToken?: () => Promise<string | undefined>,
2270
+ requestHeaders?: Record<string, string>,
1300
2271
  ): Promise<FlushBatchResult> {
1301
2272
  const contexts = filterContexts(tableContexts, tableFilter);
1302
2273
  const nowUs = nowMicroseconds();
2274
+ const quarantinedMutationIds: string[] = [];
2275
+ const conflictedMutationIds: string[] = [];
1303
2276
 
1304
2277
  // Collect send-eligible mutations across all target tables.
1305
- const pendingRows = await readPendingBatchRows(db, contexts, nowUs);
2278
+ const pendingRows = await readPendingBatchRows(db, contexts, nowUs, batchSize);
1306
2279
  const pending: PreparedBatchRow[] = [];
1307
2280
  const pendingByTable = new Map<string, PreparedBatchRow[]>();
1308
2281
 
@@ -1345,12 +2318,20 @@ async function flushBatch(
1345
2318
  }
1346
2319
 
1347
2320
  if (pending.length === 0) {
2321
+ // If a write just enqueued and requested a pass, but this flush sees nothing, the pass raced the
2322
+ // journal commit (or everything is already in-flight/backed-off) — the write then waits for a
2323
+ // later pass. Worth seeing explicitly when chasing flush latency.
2324
+ syncDebug("flushBatch: no send-eligible mutations this pass");
1348
2325
  return {
1349
2326
  processedCount: 0,
1350
2327
  affectedContexts: [],
2328
+ quarantinedMutationIds,
2329
+ conflictedMutationIds,
1351
2330
  };
1352
2331
  }
1353
2332
 
2333
+ syncDebug("flushBatch sending to board-write", { count: pending.length });
2334
+
1354
2335
  // Mark all as sending.
1355
2336
  const sentAtUs = nowMicroseconds();
1356
2337
 
@@ -1365,6 +2346,10 @@ async function flushBatch(
1365
2346
  updatedAtUs: sentAtUs,
1366
2347
  sentAtUs,
1367
2348
  replaceSentAtUs: true,
2349
+ // Persist the resolved Base server version (ADR-0015) so a chained write's flush-resolved
2350
+ // base is durable and matches exactly what the envelope carries to the server.
2351
+ baseServerVersion: row.baseServerVersion,
2352
+ replaceBaseServerVersion: true,
1368
2353
  lastError: null,
1369
2354
  nextRetryAtUs: null,
1370
2355
  lastHttpStatus: null,
@@ -1382,6 +2367,9 @@ async function flushBatch(
1382
2367
  kind: row.mutationKind as "create" | "update" | "delete",
1383
2368
  payload: row.envelopePayload,
1384
2369
  clientTimestampUs: sentAtUs,
2370
+ // ADR-0015: carry the resolved Base server version so the applier can detect a stale write.
2371
+ // Omitted for a create / a table that predates the policy (null) — then no stale check runs.
2372
+ ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),
1385
2373
  };
1386
2374
  });
1387
2375
 
@@ -1390,34 +2378,58 @@ async function flushBatch(
1390
2378
  const batchMutationUrl = resolveBatchMutationUrl(batchWriteUrl);
1391
2379
 
1392
2380
  try {
2381
+ // Resolve the auth token and the network round-trip separately: in the board, `getAuthToken` calls
2382
+ // `supabase.auth.getSession()` per send, which can itself stall (token refresh) and would otherwise
2383
+ // be invisibly folded into "the write was slow".
2384
+ const authStart = typeof performance !== "undefined" ? performance.now() : Date.now();
2385
+ const authToken = await getAuthToken?.();
2386
+ const fetchStart = typeof performance !== "undefined" ? performance.now() : Date.now();
2387
+ syncDebug("board-write auth token resolved", { ms: Math.round(fetchStart - authStart) });
2388
+
1393
2389
  let response = await fetch(batchMutationUrl, {
1394
2390
  method: "POST",
1395
- headers: buildRequestHeaders(await getAuthToken?.()),
2391
+ headers: buildRequestHeaders(authToken, requestHeaders),
1396
2392
  body: jsonStringifyPayload({ mutations }),
1397
2393
  });
1398
2394
 
1399
2395
  if ([401, 403].includes(response.status) && getAuthToken) {
1400
2396
  response = await fetch(batchMutationUrl, {
1401
2397
  method: "POST",
1402
- headers: buildRequestHeaders(await getAuthToken()),
2398
+ headers: buildRequestHeaders(await getAuthToken(), requestHeaders),
1403
2399
  body: jsonStringifyPayload({ mutations }),
1404
2400
  });
1405
2401
  }
1406
2402
 
2403
+ const fetchEnd = typeof performance !== "undefined" ? performance.now() : Date.now();
2404
+ syncDebug("board-write responded", { status: response.status, ms: Math.round(fetchEnd - fetchStart) });
2405
+
1407
2406
  if (response.ok) {
1408
2407
  const responseJson = (await response.json()) as BatchMutationAck;
1409
2408
  responseOk = true;
1410
2409
  acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));
2410
+ syncDebug("board-write acks", {
2411
+ acks: responseJson.acks.map((ack) => `${ack.mutationId.slice(0, 8)}:${ack.status}`),
2412
+ });
1411
2413
  } else {
1412
2414
  const text = await response.text();
1413
2415
  throw new MutationRequestError(
1414
2416
  text.length > 0 ? text : `Bulk write responded with ${response.status}`,
1415
2417
  response.status,
2418
+ parseBatchRejections(text),
1416
2419
  );
1417
2420
  }
1418
2421
  } catch (error) {
1419
- // All mutations in the batch fail together on a transport or server error.
1420
2422
  const failedAtUs = nowMicroseconds();
2423
+ const httpStatus = error instanceof MutationRequestError ? error.status : null;
2424
+ const errorMessage = error instanceof Error ? error.message : "Unknown batch write failure";
2425
+ // The server attributed the failure to specific mutations (a structural validation
2426
+ // rejection of an atomic batch). When present, we quarantine exactly those and leave the
2427
+ // innocent siblings immediately retryable; absent (transport / 5xx / auth / malformed
2428
+ // envelope), the whole batch stays retryable under the shared attempt cap.
2429
+ const rejectionById =
2430
+ error instanceof MutationRequestError && error.rejections
2431
+ ? new Map(error.rejections.map((rejection) => [rejection.mutationId, rejection]))
2432
+ : null;
1421
2433
 
1422
2434
  for (const rows of pendingByTable.values()) {
1423
2435
  await applyMutationStatusUpdates(
@@ -1426,14 +2438,57 @@ async function flushBatch(
1426
2438
  rows.map((row) => {
1427
2439
  const attemptCount = row.attemptCount + 1;
1428
2440
 
2441
+ if (rejectionById) {
2442
+ const rejection = rejectionById.get(row.mutationId);
2443
+
2444
+ if (rejection) {
2445
+ // Named as the cause: terminal quarantine (it will never succeed unchanged).
2446
+ quarantinedMutationIds.push(row.mutationId);
2447
+ return {
2448
+ mutationId: row.mutationId,
2449
+ status: "quarantined" as const,
2450
+ attemptCount,
2451
+ updatedAtUs: failedAtUs,
2452
+ lastError: rejection.reason,
2453
+ nextRetryAtUs: null,
2454
+ lastHttpStatus: httpStatus,
2455
+ conflictReason: rejection.reason,
2456
+ };
2457
+ }
2458
+
2459
+ // Innocent sibling: nothing was applied (atomic batch), so make it immediately
2460
+ // retryable — no backoff (the fault was the now-quarantined mutation, not
2461
+ // congestion) — and the next flush proceeds without the poison.
2462
+ return {
2463
+ mutationId: row.mutationId,
2464
+ status: "failed" as const,
2465
+ attemptCount,
2466
+ updatedAtUs: failedAtUs,
2467
+ lastError: "Batch rejected due to a sibling mutation; retrying without it",
2468
+ nextRetryAtUs: null,
2469
+ lastHttpStatus: httpStatus,
2470
+ conflictReason: null,
2471
+ };
2472
+ }
2473
+
2474
+ // Unattributed batch-level failure: stays retryable with jittered backoff; only the
2475
+ // hard attempt cap escalates to terminal quarantined. A structural 4xx is NOT
2476
+ // quarantined here (a stray 404/413/malformed envelope would otherwise permanently
2477
+ // kill unrelated valid writes).
2478
+ const outcome = resolveBatchFailureOutcome(attemptCount, maxAttempts, failedAtUs);
2479
+
2480
+ if (outcome.status === "quarantined") {
2481
+ quarantinedMutationIds.push(row.mutationId);
2482
+ }
2483
+
1429
2484
  return {
1430
2485
  mutationId: row.mutationId,
1431
- status: "failed",
2486
+ status: outcome.status,
1432
2487
  attemptCount,
1433
2488
  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,
2489
+ lastError: errorMessage,
2490
+ nextRetryAtUs: outcome.nextRetryAtUs,
2491
+ lastHttpStatus: httpStatus,
1437
2492
  conflictReason: null,
1438
2493
  };
1439
2494
  }),
@@ -1443,6 +2498,8 @@ async function flushBatch(
1443
2498
  return {
1444
2499
  processedCount: pending.length,
1445
2500
  affectedContexts: [...new Set(pending.map((row) => row.context))],
2501
+ quarantinedMutationIds,
2502
+ conflictedMutationIds,
1446
2503
  };
1447
2504
  }
1448
2505
 
@@ -1450,6 +2507,8 @@ async function flushBatch(
1450
2507
  return {
1451
2508
  processedCount: pending.length,
1452
2509
  affectedContexts: [...new Set(pending.map((row) => row.context))],
2510
+ quarantinedMutationIds,
2511
+ conflictedMutationIds,
1453
2512
  };
1454
2513
  }
1455
2514
 
@@ -1464,15 +2523,43 @@ async function flushBatch(
1464
2523
  rows.map((row) => {
1465
2524
  const ack = acksByMutationId.get(row.mutationId);
1466
2525
 
1467
- if (!ack || ack.status !== "acked") {
2526
+ if (ack && ack.status === "conflicted") {
2527
+ // ADR-0015: a stale write the reject-if-stale policy declined. Move to the terminal
2528
+ // `conflicted` status — NOT a failure (never retried as-is, the base is still stale) — and
2529
+ // KEEP the optimistic Overlay (reconcile only clears acked rows, so the user's edit stays
2530
+ // visible). The server's current Server version rides on the journal row for the diff UI.
2531
+ conflictedMutationIds.push(row.mutationId);
1468
2532
  return {
1469
2533
  mutationId: row.mutationId,
1470
- status: "failed",
2534
+ status: "conflicted" as const,
1471
2535
  attemptCount: row.attemptCount + 1,
1472
2536
  updatedAtUs: failedAtUs,
2537
+ serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
2538
+ replaceServerUpdatedAtUs: true,
2539
+ lastError: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
2540
+ nextRetryAtUs: null,
2541
+ lastHttpStatus: ack.httpStatus ?? 409,
2542
+ conflictReason: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
2543
+ };
2544
+ }
2545
+
2546
+ if (!ack || ack.status !== "acked") {
2547
+ const attemptCount = row.attemptCount + 1;
2548
+ const httpStatus = ack?.httpStatus ?? null;
2549
+ const outcome = resolveFailureOutcome(httpStatus, attemptCount, maxAttempts, failedAtUs);
2550
+
2551
+ if (outcome.status === "quarantined") {
2552
+ quarantinedMutationIds.push(row.mutationId);
2553
+ }
2554
+
2555
+ return {
2556
+ mutationId: row.mutationId,
2557
+ status: outcome.status,
2558
+ attemptCount,
2559
+ updatedAtUs: failedAtUs,
1473
2560
  lastError: ack?.conflictReason ?? "Batch mutation not acknowledged",
1474
- nextRetryAtUs: computeNextRetryAtUs(failedAtUs, row.attemptCount + 1),
1475
- lastHttpStatus: ack?.httpStatus ?? null,
2561
+ nextRetryAtUs: outcome.nextRetryAtUs,
2562
+ lastHttpStatus: httpStatus,
1476
2563
  conflictReason: ack?.conflictReason ?? null,
1477
2564
  };
1478
2565
  }
@@ -1513,9 +2600,50 @@ async function flushBatch(
1513
2600
  return {
1514
2601
  processedCount: pending.length,
1515
2602
  affectedContexts: [...new Set(pending.map((row) => row.context))],
2603
+ quarantinedMutationIds,
2604
+ conflictedMutationIds,
1516
2605
  };
1517
2606
  }
1518
2607
 
2608
+ /**
2609
+ * Resolve a flush failure into the durable journal outcome (ADR-0006). A structural
2610
+ * rejection ({@link classifyFailureStatus}) or hitting the hard attempt cap ends the
2611
+ * retry loop with a terminal `quarantined` (no `next_retry_at_us`); otherwise the
2612
+ * mutation stays `failed` with a jittered backoff (ADR-0005 congestion policy).
2613
+ */
2614
+ function resolveFailureOutcome(
2615
+ httpStatus: number | null,
2616
+ attemptCount: number,
2617
+ maxAttempts: number,
2618
+ failedAtUs: string,
2619
+ ): { status: "failed" | "quarantined"; nextRetryAtUs: string | null } {
2620
+ if (classifyFailureStatus(httpStatus) === "quarantined" || attemptCount >= maxAttempts) {
2621
+ return { status: "quarantined", nextRetryAtUs: null };
2622
+ }
2623
+
2624
+ return { status: "failed", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };
2625
+ }
2626
+
2627
+ /**
2628
+ * Resolve a *batch-level* failure — the whole POST failed (transport error, 5xx, auth, or a
2629
+ * non-2xx the server did not attribute to a specific mutation). Unlike a per-mutation ack
2630
+ * rejection, the fault cannot be pinned on any one mutation, so a structural 4xx must NOT
2631
+ * quarantine the batch (a stray 404/413/malformed envelope would permanently kill unrelated
2632
+ * valid offline writes). These failures stay retryable `failed` with jittered backoff; only
2633
+ * the hard attempt cap escalates to terminal `quarantined`.
2634
+ */
2635
+ function resolveBatchFailureOutcome(
2636
+ attemptCount: number,
2637
+ maxAttempts: number,
2638
+ failedAtUs: string,
2639
+ ): { status: "failed" | "quarantined"; nextRetryAtUs: string | null } {
2640
+ if (attemptCount >= maxAttempts) {
2641
+ return { status: "quarantined", nextRetryAtUs: null };
2642
+ }
2643
+
2644
+ return { status: "failed", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };
2645
+ }
2646
+
1519
2647
  function resolveBatchMutationUrl(batchWriteUrl: string): string {
1520
2648
  const trimmed = batchWriteUrl.replace(/\/+$/, "");
1521
2649
 
@@ -1526,6 +2654,11 @@ function resolveBatchMutationUrl(batchWriteUrl: string): string {
1526
2654
  return `${trimmed}/mutations`;
1527
2655
  }
1528
2656
 
2657
+ /** The authoritative (pessimistic) write endpoint (ADR-0022): the batch URL with `/unit` appended. */
2658
+ function resolveAuthoritativeMutationUrl(batchWriteUrl: string): string {
2659
+ return `${resolveBatchMutationUrl(batchWriteUrl)}/unit`;
2660
+ }
2661
+
1529
2662
  function stripManagedFields(
1530
2663
  context: TableContext,
1531
2664
  payload: Record<string, unknown>,
@@ -1563,79 +2696,315 @@ function toSqlColumnPayload(context: TableContext, payload: Record<string, unkno
1563
2696
  return normalized;
1564
2697
  }
1565
2698
 
2699
+ /**
2700
+ * Discard a terminal-state entity: clear its journal rows in the given terminal status
2701
+ * (`conflicted` — ADR-0015; or `quarantined` — ADR-0006) and its kept optimistic Overlay row, so the
2702
+ * Read model falls back to the synced (server) value. The overlay is removed only when no OTHER journal
2703
+ * row still owes the entity (a pending/sending/failed/acked write), mirroring reconcileTable's
2704
+ * overlay-clear guard — so a discard never strips an overlay another un-resolved write still depends
2705
+ * on. Both public discards (`discardConflict`, `discardQuarantined`) are this one body parameterized by
2706
+ * the terminal status they retire; owning its own transaction (like reconcileTable), it is not wrapped.
2707
+ */
2708
+ async function discardTerminalEntity(
2709
+ db: MutationDb,
2710
+ context: TableContext,
2711
+ entityKey: Record<string, string>,
2712
+ entityKeyJson: string,
2713
+ terminalStatus: "conflicted" | "quarantined",
2714
+ ) {
2715
+ await db.exec("BEGIN");
2716
+
2717
+ try {
2718
+ const journal = context.tables.journal;
2719
+ const clearQuery = queryBuilder
2720
+ .delete(journal)
2721
+ .where(and(eq(journal.status, terminalStatus), eq(journal.entityKeyJson, entityKeyJson)))
2722
+ .toSQL();
2723
+ await db.query(clearQuery.sql, clearQuery.params as unknown[]);
2724
+
2725
+ // Clear the kept overlay only when no journal row still owes this entity — so a discard never
2726
+ // strips an overlay another un-resolved write (e.g. a resolution already enqueued) depends on.
2727
+ const overlayQuery = buildOverlayDiscardQuery(context, entityKey, entityKeyJson);
2728
+ await db.query(overlayQuery.sql, overlayQuery.params as unknown[]);
2729
+
2730
+ await db.exec("COMMIT");
2731
+ } catch (error) {
2732
+ await db.exec("ROLLBACK");
2733
+ throw error;
2734
+ }
2735
+ }
2736
+
2737
+ /**
2738
+ * The shared overlay-discard statement: delete the entity's overlay row unless a journal row still
2739
+ * owes the entity — `owedStatuses` narrows which journal rows count as "owed" (all of them for a
2740
+ * conflict discard; only the un-sent pending/sending/failed set for a settled-unit discard).
2741
+ */
2742
+ function buildOverlayDiscardQuery(
2743
+ context: TableContext,
2744
+ entityKey: Record<string, string>,
2745
+ entityKeyJson: string,
2746
+ owedStatuses?: MutationStatus[],
2747
+ ) {
2748
+ const overlay = context.tables.overlay;
2749
+ const journal = context.tables.journal;
2750
+ const owed = queryBuilder
2751
+ .select({ one: sql`1` })
2752
+ .from(journal)
2753
+ .where(
2754
+ owedStatuses
2755
+ ? and(eq(journal.entityKeyJson, entityKeyJson), inArray(journal.status, owedStatuses))
2756
+ : eq(journal.entityKeyJson, entityKeyJson),
2757
+ );
2758
+
2759
+ return queryBuilder
2760
+ .delete(overlay)
2761
+ .where(
2762
+ and(
2763
+ ...context.pkColumnNames.map((columnName, index) =>
2764
+ eq(context.overlayPkColumns[index]!, entityKey[columnName]),
2765
+ ),
2766
+ notExists(owed),
2767
+ ),
2768
+ )
2769
+ .toSQL();
2770
+ }
2771
+
2772
+ /**
2773
+ * Auto-discard the optimistic overlay for an entity whose pessimistic write-unit the authoritative endpoint
2774
+ * `rejected` (ADR-0022 §4). Unlike {@link discardTerminalEntity} this KEEPS the terminal `rejected` journal
2775
+ * row (for diagnostics + `onReject`); it only clears the overlay, and only when no still-owed
2776
+ * (`pending`/`sending`/`failed`) journal row depends on it — so a later un-sent write never loses its overlay.
2777
+ */
2778
+ async function discardOverlayForSettledEntity(
2779
+ db: MutationDb,
2780
+ context: TableContext,
2781
+ entityKey: Record<string, string>,
2782
+ entityKeyJson: string,
2783
+ ) {
2784
+ const query = buildOverlayDiscardQuery(context, entityKey, entityKeyJson, ["pending", "sending", "failed"]);
2785
+ await db.query(query.sql, query.params as unknown[]);
2786
+ }
2787
+
1566
2788
  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.
2789
+ // Idle fast-path. Reconcile only retires/clears journal rows in a terminal-clearable state — 'acked'
2790
+ // (clear the overlay once the echo lands) or 'conflicted' (retire once a later write resolved it). When
2791
+ // none exist — the steady state of an idle entity set — all three statements below are no-ops, so skip
2792
+ // the whole transaction. This matters because the convergence driver runs reconcile for EVERY writable
2793
+ // table on its interval (default 1.5s), and each CTE pays full PGlite plan+execute cost even against an
2794
+ // empty journal: left unguarded it is the dominant idle-CPU cost. The real-time cleanup path is the
2795
+ // <table>_reconcile_on_sync trigger; this bulk pass is a fallback, so skipping it when there is nothing
2796
+ // to clear changes no outcome. The guard is a single existence probe over the (small, usually empty)
2797
+ // journal.
2798
+ const journal = context.tables.journal;
2799
+ const overlay = context.tables.overlay;
2800
+ const synced = context.tables.synced;
2801
+ // This is the idle-CPU hot statement (it runs for every writable table on every convergence
2802
+ // tick), so the rendered text+params are memoized per context — each tick pays only a plain
2803
+ // `db.query` of a cached string, and it stays OUTSIDE any transaction (no BEGIN on the idle path).
2804
+ let idleProbe = context.reconcileIdleProbe;
2805
+ if (!idleProbe) {
2806
+ const probeQuery = queryDialect.sqlToQuery(
2807
+ sql`SELECT ${exists(
2808
+ queryBuilder
2809
+ .select({ one: sql`1` })
2810
+ .from(journal)
2811
+ .where(inArray(journal.status, ["acked", "conflicted"])),
2812
+ )} AS "hasWork"`,
2813
+ );
2814
+ idleProbe = { sql: probeQuery.sql, params: probeQuery.params as unknown[] };
2815
+ context.reconcileIdleProbe = idleProbe;
2816
+ }
2817
+ const work = await db.query<{ hasWork: boolean }>(idleProbe.sql, idleProbe.params);
2818
+ if (work.rows[0]?.hasWork !== true) {
2819
+ return;
2820
+ }
2821
+
2822
+ // The Convergence barrier (ADR-0010) gates the acked-row clearing below; the synced-table trigger
2823
+ // handles real-time cleanup, and this is the bulk recovery/fallback path that runs after every flush.
1569
2824
  await db.exec("BEGIN");
1570
2825
 
1571
2826
  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
- ")",
2827
+ // ADR-0015: retire a terminal `conflicted` row once the user has RESOLVED it — i.e. a LATER write
2828
+ // on the same entity has been acked (resolution is an ordinary new mutation). Without this, the old
2829
+ // conflicted row lingers forever: `<table>_sync_state.conflict_state` keeps surfacing the resolved
2830
+ // conflict and `diagnostics().conflictedCount` never drops. Run before the acked-clear below so the
2831
+ // resolving row is still present to supersede it. (`discardConflict` is the explicit throw-away path.)
2832
+ // Drizzle DELETE has no USING; the resolver leg is the equivalent EXISTS semi-join.
2833
+ const resolver = alias(journal, "resolver");
2834
+ const retireQuery = queryBuilder
2835
+ .delete(journal)
2836
+ .where(
2837
+ and(
2838
+ eq(journal.status, "conflicted"),
2839
+ exists(
2840
+ queryBuilder
2841
+ .select({ one: sql`1` })
2842
+ .from(resolver)
2843
+ .where(
2844
+ and(
2845
+ eq(resolver.entityKeyJson, journal.entityKeyJson),
2846
+ gt(resolver.mutationSeq, journal.mutationSeq),
2847
+ eq(resolver.status, "acked"),
2848
+ ),
2849
+ ),
2850
+ ),
2851
+ ),
2852
+ )
2853
+ .toSQL();
2854
+ await db.query(retireQuery.sql, retireQuery.params as unknown[]);
2855
+
2856
+ // ADR-0022 addendum — retire an acked `pessimistic-blind` row with NO echo barrier. A blind update's
2857
+ // write target is excluded from this actor's read shape, so no synced echo will ever land for it and no
2858
+ // overlay was ever planned: the standard acked-clear below (gated on a synced row reaching the acked
2859
+ // version) would keep it forever. Nothing local converges for these rows, so once the authoritative unit
2860
+ // acked them there is nothing left to do but drop the journal row. Crash-safe: any later reconcile tick
2861
+ // clears a blind row the foreground flushUnit didn't survive to reconcile.
2862
+ const blindRetireQuery = queryBuilder
2863
+ .delete(journal)
2864
+ .where(and(eq(journal.status, "acked"), eq(journal.writeMode, "pessimistic-blind")))
2865
+ .toSQL();
2866
+ await db.query(blindRetireQuery.sql, blindRetireQuery.params as unknown[]);
2867
+
2868
+ // Clear acknowledged non-delete mutations + matching overlays. ADR-0010: gated by the
2869
+ // Convergence barrier (same predicate as the trigger) — the acked write clears only once the
2870
+ // synced echo's Server version has reached its acked version. Joining the synced table makes
2871
+ // the comparison possible (and means an un-synced acked write is held until its echo lands).
2872
+ // Drizzle authoring: DELETE..USING becomes the equivalent EXISTS semi-join, chained through a
2873
+ // data-modifying CTE (both sub-statements see the same statement-start snapshot, exactly like
2874
+ // the USING form). The barrier predicate stays the shared contracts helper (single authority
2875
+ // with the trigger); it renders against the tables' own names, which is how drizzle references
2876
+ // their columns here (no aliases on a DELETE target).
2877
+ const barrier = sql.raw(
2878
+ buildOverlayResolutionBarrier(context.entry, {
2879
+ journalAlias: quoteIdentifier(getTableConfig(journal).name),
2880
+ syncedAlias: quoteIdentifier(getTableConfig(synced).name),
2881
+ }),
2882
+ );
2883
+ const clearedJournal = queryBuilder.$with("cleared_journal").as(
2884
+ queryBuilder
2885
+ .delete(journal)
2886
+ .where(
2887
+ and(
2888
+ eq(journal.status, "acked"),
2889
+ isNotNull(journal.serverUpdatedAtUs),
2890
+ ne(journal.mutationKind, "delete"),
2891
+ exists(
2892
+ queryBuilder
2893
+ .select({ one: sql`1` })
2894
+ .from(synced)
2895
+ .where(
2896
+ and(
2897
+ ...context.pkColumnNames.map((columnName, index) =>
2898
+ eq(context.syncedPkColumns[index]!, journal[columnName]!),
2899
+ ),
2900
+ barrier,
2901
+ ),
2902
+ ),
2903
+ ),
2904
+ ),
2905
+ )
2906
+ .returning(
2907
+ Object.fromEntries([
2908
+ ["entity_key_json", journal.entityKeyJson],
2909
+ ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),
2910
+ ]),
2911
+ ),
1598
2912
  );
2913
+ const clearedJournalColumns = clearedJournal as unknown as Record<string, PgColumn>;
2914
+ const ackedClearQuery = queryBuilder
2915
+ .with(clearedJournal)
2916
+ .delete(overlay)
2917
+ .where(
2918
+ exists(
2919
+ queryBuilder
2920
+ .select({ one: sql`1` })
2921
+ .from(clearedJournal)
2922
+ .where(
2923
+ and(
2924
+ ...context.pkColumnNames.map((columnName, index) =>
2925
+ eq(context.overlayPkColumns[index]!, clearedJournalColumns[columnName]!),
2926
+ ),
2927
+ notExists(
2928
+ queryBuilder
2929
+ .select({ one: sql`1` })
2930
+ .from(journal)
2931
+ .where(
2932
+ and(
2933
+ eq(journal.entityKeyJson, clearedJournalColumns["entity_key_json"]!),
2934
+ inArray(journal.status, ["pending", "sending", "failed"]),
2935
+ ),
2936
+ ),
2937
+ ),
2938
+ ),
2939
+ ),
2940
+ ),
2941
+ )
2942
+ .toSQL();
2943
+ await db.query(ackedClearQuery.sql, ackedClearQuery.params as unknown[]);
1599
2944
 
1600
2945
  // Clear acknowledged delete mutations where synced row is absent
1601
2946
  // 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'",
2947
+ const clearableEntities = queryBuilder.$with("clearable_entities").as(
2948
+ queryBuilder
2949
+ .selectDistinct(
2950
+ Object.fromEntries([
2951
+ ["entity_key_json", journal.entityKeyJson],
2952
+ ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),
2953
+ ]),
2954
+ )
2955
+ .from(journal)
2956
+ .leftJoin(
2957
+ synced,
2958
+ and(
2959
+ ...context.pkColumnNames.map((columnName, index) =>
2960
+ eq(context.syncedPkColumns[index]!, journal[columnName]!),
2961
+ ),
2962
+ ),
2963
+ )
2964
+ .where(
2965
+ and(eq(journal.status, "acked"), eq(journal.mutationKind, "delete"), isNull(context.syncedPkColumns[0]!)),
2966
+ ),
1638
2967
  );
2968
+ const clearableEntityColumns = clearableEntities as unknown as Record<string, PgColumn>;
2969
+ const deletedOverlay = queryBuilder.$with("deleted_overlay").as(
2970
+ queryBuilder.delete(overlay).where(
2971
+ exists(
2972
+ queryBuilder
2973
+ .select({ one: sql`1` })
2974
+ .from(clearableEntities)
2975
+ .where(
2976
+ and(
2977
+ ...context.pkColumnNames.map((columnName, index) =>
2978
+ eq(context.overlayPkColumns[index]!, clearableEntityColumns[columnName]!),
2979
+ ),
2980
+ ),
2981
+ ),
2982
+ ),
2983
+ ),
2984
+ );
2985
+ const deleteClearQuery = queryBuilder
2986
+ .with(clearableEntities, deletedOverlay)
2987
+ .delete(journal)
2988
+ .where(
2989
+ and(
2990
+ eq(journal.status, "acked"),
2991
+ eq(journal.mutationKind, "delete"),
2992
+ exists(
2993
+ queryBuilder
2994
+ .select({ one: sql`1` })
2995
+ .from(clearableEntities)
2996
+ .where(
2997
+ and(
2998
+ ...context.pkColumnNames.map((columnName) =>
2999
+ eq(journal[columnName]!, clearableEntityColumns[columnName]!),
3000
+ ),
3001
+ ),
3002
+ ),
3003
+ ),
3004
+ ),
3005
+ )
3006
+ .toSQL();
3007
+ await db.query(deleteClearQuery.sql, deleteClearQuery.params as unknown[]);
1639
3008
  await db.exec("COMMIT");
1640
3009
  } catch (error) {
1641
3010
  await db.exec("ROLLBACK");
@@ -1643,16 +3012,12 @@ async function reconcileTable(db: MutationDb, context: TableContext) {
1643
3012
  }
1644
3013
  }
1645
3014
 
1646
- function buildRequestHeaders(bearerToken?: string): Record<string, string> {
1647
- if (!bearerToken) {
1648
- return {
1649
- "Content-Type": "application/json",
1650
- };
1651
- }
1652
-
3015
+ function buildRequestHeaders(bearerToken?: string, requestHeaders?: Record<string, string>): Record<string, string> {
3016
+ // Static headers first so the toolkit-owned Content-Type/Authorization always win.
1653
3017
  return {
3018
+ ...(requestHeaders ?? {}),
1654
3019
  "Content-Type": "application/json",
1655
- Authorization: `Bearer ${bearerToken}`,
3020
+ ...(bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}),
1656
3021
  };
1657
3022
  }
1658
3023
 
@@ -1661,149 +3026,64 @@ async function applyMutationStatusUpdates(db: MutationDb, context: TableContext,
1661
3026
  return;
1662
3027
  }
1663
3028
 
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,
3029
+ // Tier ②: `update().from(<VALUES>)`. Every value is a bound param with the same cast as before;
3030
+ // the `updates` alias and its column list are fixed by this function (not derived from data), so
3031
+ // the alias-qualified references in SET/WHERE are fixed template text, while the journal side of
3032
+ // each CASE interpolates the column objects.
3033
+ const journal = context.tables.journal;
3034
+ const tuples = updates.map(
3035
+ (update) =>
3036
+ sql`(${update.mutationId}, ${update.status}, ${update.attemptCount}::int, ${update.updatedAtUs}::bigint, ${
3037
+ update.sentAtUs ?? null
3038
+ }::bigint, ${update.replaceSentAtUs ?? false}::boolean, ${update.ackedAtUs ?? null}::bigint, ${
3039
+ update.replaceAckedAtUs ?? false
3040
+ }::boolean, ${update.serverUpdatedAtUs ?? null}::bigint, ${update.replaceServerUpdatedAtUs ?? false}::boolean, ${
3041
+ update.baseServerVersion ?? null
3042
+ }::bigint, ${update.replaceBaseServerVersion ?? false}::boolean, ${update.lastError ?? null}, ${
3043
+ update.nextRetryAtUs ?? null
3044
+ }::bigint, ${update.lastHttpStatus ?? null}::int, ${update.conflictReason ?? null})`,
1776
3045
  );
1777
- }
1778
-
1779
- function buildColumnEquality(columnNames: string[], leftAlias: string, rightAlias: string) {
1780
- return columnNames.map((columnName) => `${leftAlias}.${columnName} = ${rightAlias}.${columnName}`).join(" AND ");
3046
+ const updatesTable = sql`(VALUES ${sql.join(
3047
+ tuples,
3048
+ sql`, `,
3049
+ )}) 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)`;
3050
+
3051
+ const query = queryBuilder
3052
+ .update(journal)
3053
+ .set({
3054
+ status: sql`updates.status`,
3055
+ attemptCount: sql`updates.attempt_count`,
3056
+ updatedAtUs: sql`updates.updated_at_us::bigint`,
3057
+ sentAtUs: sql`CASE WHEN updates.replace_sent_at_us THEN updates.sent_at_us::bigint ELSE ${journal.sentAtUs} END`,
3058
+ ackedAtUs: sql`CASE WHEN updates.replace_acked_at_us THEN updates.acked_at_us::bigint ELSE ${journal.ackedAtUs} END`,
3059
+ serverUpdatedAtUs: sql`CASE WHEN updates.replace_server_updated_at_us THEN updates.server_updated_at_us::bigint ELSE ${journal.serverUpdatedAtUs} END`,
3060
+ baseServerVersion: sql`CASE WHEN updates.replace_base_server_version THEN updates.base_server_version::bigint ELSE ${journal.baseServerVersion} END`,
3061
+ lastError: sql`updates.last_error`,
3062
+ nextRetryAtUs: sql`updates.next_retry_at_us::bigint`,
3063
+ lastHttpStatus: sql`updates.last_http_status`,
3064
+ conflictReason: sql`updates.conflict_reason`,
3065
+ })
3066
+ .from(updatesTable)
3067
+ .where(eq(journal.mutationId, sql`updates.mutation_id::uuid`))
3068
+ .toSQL();
3069
+ await db.query(query.sql, query.params as unknown[]);
1781
3070
  }
1782
3071
 
1783
3072
  function qualifyLocalIdentifier(schemaName: string, tableName: string) {
1784
3073
  if (schemaName === "public") {
1785
- return tableName;
3074
+ // Quote-when-needed: a reserved-word or mixed-case table name (e.g. `group`)
3075
+ // MUST be quoted or the generated SQL fails to parse (ADR-0004). Normal names
3076
+ // stay bare, so existing generated SQL is unchanged.
3077
+ return maybeQuoteIdentifier(tableName);
1786
3078
  }
1787
3079
 
1788
3080
  return `${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}`;
1789
3081
  }
1790
3082
 
1791
- function quoteIdentifier(value: string) {
1792
- return `"${value.replace(/"/g, '""')}"`;
1793
- }
1794
-
1795
3083
  function buildJournalSequenceName(journalTable: string) {
1796
3084
  return `${journalTable}_mutation_seq`;
1797
3085
  }
1798
3086
 
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
3087
  function hasProperty(context: TableContext, propertyKey: string) {
1808
3088
  return context.columns.some((column) => column.propertyKey === propertyKey);
1809
3089
  }
@@ -1826,10 +3106,36 @@ function isRecord(value: unknown): value is Record<string, unknown> {
1826
3106
 
1827
3107
  class MutationRequestError extends Error {
1828
3108
  readonly status: number;
3109
+ /** Per-mutation attribution the server returned for a structural rejection, or null. */
3110
+ readonly rejections: MutationRejection[] | null;
1829
3111
 
1830
- constructor(message: string, status: number) {
3112
+ constructor(message: string, status: number, rejections: MutationRejection[] | null = null) {
1831
3113
  super(message);
1832
3114
  this.name = "MutationRequestError";
1833
3115
  this.status = status;
3116
+ this.rejections = rejections;
3117
+ }
3118
+ }
3119
+
3120
+ /**
3121
+ * Extract per-mutation attribution from a non-2xx batch-write body. The server names the
3122
+ * offending mutations on a structural (validation) rejection; an absent, non-JSON, or
3123
+ * empty-`rejections` body yields null, so the failure is treated as non-attributable
3124
+ * (whole batch stays retryable).
3125
+ */
3126
+ function parseBatchRejections(body: string): MutationRejection[] | null {
3127
+ if (body.length === 0) {
3128
+ return null;
3129
+ }
3130
+
3131
+ let parsed: unknown;
3132
+ try {
3133
+ parsed = JSON.parse(body);
3134
+ } catch {
3135
+ return null;
1834
3136
  }
3137
+
3138
+ const result = batchMutationErrorSchema.safeParse(parsed);
3139
+ const rejections = result.success ? result.data.rejections : undefined;
3140
+ return rejections && rejections.length > 0 ? rejections : null;
1835
3141
  }