@pgxsinkit/client 0.1.48 → 0.1.50

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 (40) hide show
  1. package/dist/boot-report.d.ts +76 -0
  2. package/dist/boot-report.d.ts.map +1 -1
  3. package/dist/index.d.ts +84 -3
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1549 -333
  6. package/dist/index.js.map +15 -12
  7. package/dist/local-store.d.ts +58 -0
  8. package/dist/local-store.d.ts.map +1 -1
  9. package/dist/local-tables.d.ts +340 -0
  10. package/dist/local-tables.d.ts.map +1 -1
  11. package/dist/mutation.d.ts +36 -0
  12. package/dist/mutation.d.ts.map +1 -1
  13. package/dist/mutations-api.d.ts +82 -0
  14. package/dist/mutations-api.d.ts.map +1 -0
  15. package/dist/schema.d.ts +62 -0
  16. package/dist/schema.d.ts.map +1 -1
  17. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  18. package/dist/worker/define-sync-worker.d.ts +17 -0
  19. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  20. package/dist/worker/live-query-fingerprint.d.ts +14 -0
  21. package/dist/worker/live-query-fingerprint.d.ts.map +1 -0
  22. package/dist/worker/live-query-manager.d.ts +130 -0
  23. package/dist/worker/live-query-manager.d.ts.map +1 -0
  24. package/dist/worker/protocol.d.ts +53 -2
  25. package/dist/worker/protocol.d.ts.map +1 -1
  26. package/package.json +2 -2
  27. package/skills/core/SKILL.md +1 -1
  28. package/skills/operating/SKILL.md +29 -1
  29. package/src/boot-report.ts +108 -0
  30. package/src/index.ts +648 -152
  31. package/src/local-store.ts +150 -3
  32. package/src/local-tables.ts +49 -1
  33. package/src/mutation.ts +256 -15
  34. package/src/mutations-api.ts +310 -0
  35. package/src/schema.ts +406 -193
  36. package/src/worker/attach-sync-client.ts +193 -15
  37. package/src/worker/define-sync-worker.ts +267 -53
  38. package/src/worker/live-query-fingerprint.ts +128 -0
  39. package/src/worker/live-query-manager.ts +591 -0
  40. package/src/worker/protocol.ts +49 -1
@@ -1,11 +1,18 @@
1
- import { eq, like } from "drizzle-orm";
1
+ import { and, eq, like, notExists, sql } from "drizzle-orm";
2
2
  import { drizzle } from "drizzle-orm/pglite";
3
3
 
4
4
  import { type MutationDiagnostics, type SyncTableRegistry } from "@pgxsinkit/contracts";
5
5
 
6
- import { getLocalMetaTable } from "./local-tables";
6
+ import { syncDebug } from "./debug";
7
+ import { getJournalTable, getLocalMetaTable } from "./local-tables";
7
8
  import type { MutationDb } from "./mutation";
8
- import { buildWipeLocalStoreSql, generateLocalSchemaSql, REGISTRY_FINGERPRINT_KEY } from "./schema";
9
+ import {
10
+ buildWipeLocalStoreSql,
11
+ computeLocalSchemaFingerprint,
12
+ generateLocalSchemaSql,
13
+ LOCAL_SCHEMA_FINGERPRINT_KEY,
14
+ REGISTRY_FINGERPRINT_KEY,
15
+ } from "./schema";
9
16
 
10
17
  // Statements are AUTHORED as Drizzle builders over the meta-table object (rename-safe, typed,
11
18
  // schema-qualification handled by the table object) and rendered to text+params here, because they
@@ -115,6 +122,143 @@ export async function writeStoredRegistryFingerprint(
115
122
  await upsertMetaValue(db, registry, REGISTRY_FINGERPRINT_KEY, fingerprint);
116
123
  }
117
124
 
125
+ /**
126
+ * The durable-schema fingerprint the local store was last provisioned under (slice 3 / proposal §3), or null
127
+ * when unstamped (a legacy store, or a store whose durable schema was never executed under this feature).
128
+ * Follows the raw-seam read shape of {@link readStoredRegistryFingerprint}.
129
+ */
130
+ export async function readStoredLocalSchemaFingerprint(
131
+ db: MutationDb,
132
+ registry: SyncTableRegistry,
133
+ ): Promise<string | null> {
134
+ const meta = getLocalMetaTable(registry);
135
+ const query = metaQueryBuilder
136
+ .select({ value: meta.value })
137
+ .from(meta)
138
+ .where(eq(meta.key, LOCAL_SCHEMA_FINGERPRINT_KEY))
139
+ .limit(1)
140
+ .toSQL();
141
+ const result = await db.query<{ value: string }>(query.sql, query.params as unknown[]);
142
+
143
+ return result.rows[0]?.value ?? null;
144
+ }
145
+
146
+ /**
147
+ * Stamp the durable-schema fingerprint the store is now provisioned under (slice 3). Called ONLY after a
148
+ * successful durable-schema exec — every full durable exec (boot fast-path miss, reconcile rebuild,
149
+ * `dropReadCache`) and its stamp travel together, so the fingerprint never claims a schema that was not run.
150
+ */
151
+ export async function writeStoredLocalSchemaFingerprint(
152
+ db: MutationDb,
153
+ registry: SyncTableRegistry,
154
+ fingerprint: string,
155
+ ): Promise<void> {
156
+ await upsertMetaValue(db, registry, LOCAL_SCHEMA_FINGERPRINT_KEY, fingerprint);
157
+ }
158
+
159
+ /**
160
+ * The durable recovery-required marker (warm-persisted-store-startup slice 2 / proposal §1). Its
161
+ * `pgxsinkit_local_meta` value is `"true"` while a `sending` journal row MAY have been committed since the
162
+ * last clean settle, and `"false"` once pgxsinkit has PROVEN no `sending` row remains. Absent = a
163
+ * pre-feature (legacy) store: run one conservative legacy recovery pass, then initialize the marker.
164
+ *
165
+ * The invariant the whole slice protects: **the marker is never `"false"` while a committed `sending`
166
+ * journal row exists.** It is upheld by marker-first ordering — {@link writeMutationRecoveryRequired}(true)
167
+ * is awaited (and auto-commits) strictly BEFORE the first pending→sending transition of a dirty epoch — and
168
+ * by the self-verifying clear ({@link clearMutationRecoveryMarkerIfSettled}), which only writes `"false"`
169
+ * when NOT EXISTS any `sending` row across every writable journal.
170
+ */
171
+ export const MUTATION_RECOVERY_REQUIRED_KEY = "mutation_recovery_required";
172
+
173
+ /**
174
+ * Read the durable recovery-required marker: `true`/`false` for the stored value, or `null` when the key is
175
+ * absent (a legacy/pre-feature store). Follows the raw-seam read shape of
176
+ * {@link readStoredRegistryFingerprint}.
177
+ *
178
+ * FIX 4 (fail closed): the marker is a SAFETY marker — `false` is the ONLY value that skips recovery, so any
179
+ * present value that is not exactly `"true"` or `"false"` (corruption, a future encoding, stray whitespace, a
180
+ * partial/manual edit) must NOT be decoded as clean. It is logged on the debug rail and treated as `true`
181
+ * (recovery required); the recovery pass then rewrites a well-formed value.
182
+ */
183
+ export async function readMutationRecoveryRequired(
184
+ db: MutationDb,
185
+ registry: SyncTableRegistry,
186
+ ): Promise<boolean | null> {
187
+ const meta = getLocalMetaTable(registry);
188
+ const query = metaQueryBuilder
189
+ .select({ value: meta.value })
190
+ .from(meta)
191
+ .where(eq(meta.key, MUTATION_RECOVERY_REQUIRED_KEY))
192
+ .limit(1)
193
+ .toSQL();
194
+ const result = await db.query<{ value: string }>(query.sql, query.params as unknown[]);
195
+ const value = result.rows[0]?.value;
196
+ if (value == null) {
197
+ return null;
198
+ }
199
+ if (value === "true") return true;
200
+ if (value === "false") return false;
201
+ // Unexpected durable value → fail CLOSED: run recovery (which rewrites a well-formed marker afterward).
202
+ syncDebug("mutation recovery marker has an unexpected value — treating as recovery-required (fail closed)", {
203
+ value,
204
+ });
205
+ return true;
206
+ }
207
+
208
+ /**
209
+ * Upsert the durable recovery-required marker to `"true"`/`"false"` unconditionally. The `true` write is the
210
+ * marker-first SET (awaited before the first `sending` transition of a dirty epoch); the `false` write
211
+ * initializes an absent (legacy) marker AFTER a legacy recovery pass has guaranteed no `sending` row remains.
212
+ */
213
+ export async function writeMutationRecoveryRequired(
214
+ db: MutationDb,
215
+ registry: SyncTableRegistry,
216
+ required: boolean,
217
+ ): Promise<void> {
218
+ await upsertMetaValue(db, registry, MUTATION_RECOVERY_REQUIRED_KEY, required ? "true" : "false");
219
+ }
220
+
221
+ /** The writable (non-`readonly`) table keys of a registry — the journals a recovery/clear pass spans. */
222
+ function writableTableKeys(registry: SyncTableRegistry): string[] {
223
+ return Object.keys(registry).filter((key) => registry[key]?.mode !== "readonly");
224
+ }
225
+
226
+ /**
227
+ * Self-verifying clear (proposal §1 rule 2): set the marker to `"false"` in ONE guarded, Drizzle-composed
228
+ * statement — but only where NOT EXISTS any `sending` row in ANY writable journal (the EXISTS-union is built
229
+ * from the registry's journal Drizzle objects via {@link getJournalTable}). Correct regardless of JS
230
+ * bookkeeping: a concurrent enqueue that committed a `sending` row makes the guard fail, so the marker stays
231
+ * `"true"`. Returns `{ cleared }` from the statement's affected-row count (PGlite reports `affectedRows`) —
232
+ * `true` when the guard passed (an existing marker row flipped/held at `"false"`), `false` when a `sending`
233
+ * row blocked it OR no marker row exists yet. Off the boot path AND at the end of a boot recovery pass.
234
+ *
235
+ * The marker row must already exist for this UPDATE to take effect; the absent-store INIT is a distinct
236
+ * unconditional {@link writeMutationRecoveryRequired}(false) after the legacy pass (a pure guarded UPDATE
237
+ * cannot create the row, and drizzle-rc.4 cannot render a from-less guarded insert-select).
238
+ */
239
+ export async function clearMutationRecoveryMarkerIfSettled(
240
+ db: MutationDb,
241
+ registry: SyncTableRegistry,
242
+ ): Promise<{ cleared: boolean }> {
243
+ const meta = getLocalMetaTable(registry);
244
+ const noSendingConditions = writableTableKeys(registry).map((key) => {
245
+ const journal = getJournalTable(registry, key);
246
+ return notExists(
247
+ metaQueryBuilder
248
+ .select({ one: sql`1` })
249
+ .from(journal)
250
+ .where(eq(journal.status, "sending")),
251
+ );
252
+ });
253
+ const query = metaQueryBuilder
254
+ .update(meta)
255
+ .set({ value: "false" })
256
+ .where(and(eq(meta.key, MUTATION_RECOVERY_REQUIRED_KEY), ...noSendingConditions))
257
+ .toSQL();
258
+ const result = (await db.query(query.sql, query.params as unknown[])) as { affectedRows?: number };
259
+ return { cleared: (result.affectedRows ?? 0) > 0 };
260
+ }
261
+
118
262
  /**
119
263
  * Reconcile the local store against the current registry fingerprint (ADR-0006). A fresh
120
264
  * (unstamped) store is stamped; an unchanged fingerprint is a no-op. On a change, the read
@@ -182,6 +326,9 @@ async function rebuildReadCacheOrDefer<TRegistry extends SyncTableRegistry>(
182
326
  await db.exec(buildWipeLocalStoreSql(registry));
183
327
  await db.exec(generateLocalSchemaSql(registry));
184
328
  await writeStoredRegistryFingerprint(db, registry, current);
329
+ // This is a full durable-schema exec, so re-stamp the durable-schema fingerprint alongside the registry
330
+ // fingerprint (slice 3): exec and stamp travel together, so the next boot's fast path can trust the skip.
331
+ await writeStoredLocalSchemaFingerprint(db, registry, computeLocalSchemaFingerprint(registry));
185
332
  const event: LocalStoreVersionEvent = {
186
333
  status: "rebuilt",
187
334
  previousFingerprint,
@@ -27,7 +27,7 @@ import {
27
27
  type SyncTableRegistry,
28
28
  } from "@pgxsinkit/contracts";
29
29
 
30
- import { LOCAL_META_TABLE } from "./schema";
30
+ import { ALL_MUTATIONS_VIEW, LOCAL_META_TABLE } from "./schema";
31
31
 
32
32
  /**
33
33
  * Runtime Drizzle objects for the GENERATED local-store relations (ADR-0004): the per-writable-table
@@ -530,6 +530,54 @@ export function resolveApplyTarget<TRegistry extends SyncTableRegistry, TKey ext
530
530
  };
531
531
  }
532
532
 
533
+ /**
534
+ * The fixed columns of the registry-wide `pgxsinkit_all_mutations` view (ADR-0021/slice 4): a `table_key`
535
+ * literal per branch plus the shared fixed journal columns ({@link ALL_MUTATIONS_JOURNAL_COLUMNS} in
536
+ * schema.ts) — MINUS `payload_json` and the per-table PK columns. The `_us` bigints are the same
537
+ * `bigintText` passthrough the journal object uses (read back through the raw seam / the live-rows seam,
538
+ * which return rows UNMAPPED — no drizzle result mapping), so the runtime reads them as strings.
539
+ */
540
+ function buildAllMutationsViewColumns() {
541
+ return {
542
+ tableKey: text("table_key").notNull(),
543
+ mutationId: uuid("mutation_id").notNull(),
544
+ entityKeyJson: text("entity_key_json").notNull(),
545
+ mutationSeq: integer("mutation_seq").notNull(),
546
+ mutationKind: varchar("mutation_kind", { length: 24 }).notNull(),
547
+ status: varchar("status", { length: 24 }).notNull(),
548
+ registryVersion: text("registry_version"),
549
+ baseServerVersion: bigintText("base_server_version"),
550
+ writeUnit: text("write_unit"),
551
+ writeMode: varchar("write_mode", { length: 24 }),
552
+ attemptCount: integer("attempt_count").notNull(),
553
+ lastError: text("last_error"),
554
+ lastHttpStatus: integer("last_http_status"),
555
+ conflictReason: text("conflict_reason"),
556
+ serverUpdatedAtUs: bigintText("server_updated_at_us"),
557
+ enqueuedAtUs: bigintText("enqueued_at_us").notNull(),
558
+ nextRetryAtUs: bigintText("next_retry_at_us"),
559
+ sentAtUs: bigintText("sent_at_us"),
560
+ ackedAtUs: bigintText("acked_at_us"),
561
+ updatedAtUs: bigintText("updated_at_us").notNull(),
562
+ };
563
+ }
564
+
565
+ const allMutationsShape = pgView(ALL_MUTATIONS_VIEW, buildAllMutationsViewColumns()).existing();
566
+
567
+ /**
568
+ * The registry-wide `pgxsinkit_all_mutations` cross-journal view (slice 4) as a runtime Drizzle object. Its
569
+ * columns are the fixed journal columns (typed) plus the `table_key` registry-key literal — no per-table PK
570
+ * columns, no payload. Unlike the other view factories this is schema-INDEPENDENT: the view is always emitted
571
+ * `TEMP` (it may reference `pg_temp` ephemeral journals), so it resolves bare via `pg_temp`/search_path
572
+ * regardless of the registry's local schema — hence one memoized instance for every registry. The
573
+ * `client.mutations.*` API authors its summary/detail queries over THIS object (tier ①).
574
+ */
575
+ export type AllMutationsView = typeof allMutationsShape;
576
+
577
+ export function getAllMutationsView(_registry: SyncTableRegistry): AllMutationsView {
578
+ return allMutationsShape;
579
+ }
580
+
533
581
  /** The `pgxsinkit_local_meta` key/value table (ADR-0006) under the registry's local schema. */
534
582
  export function getLocalMetaTable(registry: SyncTableRegistry): LocalMetaTable {
535
583
  const localSchema = getSyncRegistrySchema(registry);
package/src/mutation.ts CHANGED
@@ -26,6 +26,11 @@ import {
26
26
  } from "drizzle-orm/pg-core";
27
27
  import { drizzle } from "drizzle-orm/pglite";
28
28
 
29
+ import {
30
+ clearMutationRecoveryMarkerIfSettled,
31
+ readMutationRecoveryRequired,
32
+ writeMutationRecoveryRequired,
33
+ } from "./local-store";
29
34
  import {
30
35
  getJournalTable,
31
36
  getOverlayTable,
@@ -185,6 +190,13 @@ export interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistr
185
190
  * `registry_version`, so a version-boundary crossing is known before sending (ADR-0006).
186
191
  */
187
192
  registryVersion?: string;
193
+ /**
194
+ * Whether pgxsinkit owns the local schema (and therefore the `pgxsinkit_local_meta` table the durable
195
+ * recovery-required marker lives in). Defaults to `true`. A caller-owned `pgliteInstance` boot sets this
196
+ * `false`: the meta table may not exist, so the marker is never read/written and boot recovery falls back
197
+ * to the legacy always-recover pass (proposal §1 caller-owned-PGlite constraint).
198
+ */
199
+ ownsMetaTable?: boolean;
188
200
  /**
189
201
  * Hard cap on send attempts before a still-failing mutation is quarantined
190
202
  * (ADR-0005 congestion policy). Defaults to {@link DEFAULT_MAX_MUTATION_ATTEMPTS}.
@@ -307,6 +319,19 @@ interface TableContext {
307
319
  reconcileIdleProbe?: { sql: string; params: unknown[] };
308
320
  }
309
321
 
322
+ /**
323
+ * The result of {@link MutationRuntime.runBootRecovery}, shaped to feed the `warmBoot` BootReport fields
324
+ * directly (ADR-0034): whether the per-table recovery loop was skipped, whether recovery was required this
325
+ * boot, how many writable journals were visited, and how many rows were lifted `sending → pending` (`null`
326
+ * when the pass was legacy/uncounted, a real count on the marker-`true` path).
327
+ */
328
+ export interface BootRecoveryOutcome {
329
+ skipped: boolean;
330
+ required: boolean;
331
+ tablesVisited: number;
332
+ rowsRecovered: number | null;
333
+ }
334
+
310
335
  export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
311
336
  /** The registry fingerprint (ADR-0004) this runtime stamps onto enqueued mutations. */
312
337
  registryVersion: string;
@@ -359,6 +384,20 @@ export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
359
384
  reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;
360
385
  retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
361
386
  recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;
387
+ /**
388
+ * Boot-time journal recovery driven by the durable recovery-required marker (proposal §1 / slice 2). The
389
+ * internal boot entry point that decides — from the marker and the boot mode — whether the per-table
390
+ * `sending → pending` recovery loop runs at all, and clears/initializes the marker afterwards. It NEVER
391
+ * runs from a consumer call ({@link recoverSending} keeps today's exact per-table semantics and never
392
+ * touches the marker); {@link BootRecoveryOutcome} feeds the `warmBoot` BootReport fields verbatim.
393
+ *
394
+ * - `ownsMetaTable: false` (caller-owned PGlite) → legacy always-recover, marker untouched.
395
+ * - `restore: true` → legacy recovery + {@link quarantineRecovered} + self-verifying clear (marker ignored).
396
+ * - marker `false` → skip the loop entirely.
397
+ * - marker absent (legacy store) → one legacy recovery pass, then initialize the marker.
398
+ * - marker `true` → the N per-table updates PLUS the self-verifying clear, wrapped in one transaction.
399
+ */
400
+ runBootRecovery: (opts: { ownsMetaTable: boolean; restore: boolean }) => Promise<BootRecoveryOutcome>;
362
401
  /**
363
402
  * Quarantine EVERY non-terminal journal row recovered from a backup (`pending`/`sending`/`failed` →
364
403
  * `quarantined`) — the restore-boot rule (ADR-0035 decision 6). Nothing recovered from a store backup
@@ -473,6 +512,109 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
473
512
  const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);
474
513
  let flushQueue = Promise.resolve();
475
514
 
515
+ // Whether pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` table the durable
516
+ // recovery-required marker lives in). A caller-owned PGlite boot sets this false, so the marker is never
517
+ // touched and the SET/clear seams below are no-ops (proposal §1 caller-owned-PGlite constraint).
518
+ const ownsMetaTable = options.ownsMetaTable ?? true;
519
+ // Cached "this epoch has already committed the marker `true`" flag (slice 2). Marker-first ordering:
520
+ // `ensureRecoveryMarker` awaits ONE marker upsert before the first `sending` transition of a dirty epoch,
521
+ // then flips this true, so steady-state flushing pays zero extra crossings. Reset to false only after the
522
+ // self-verifying clear proves no `sending` row remains (`settleRecoveryMarker` / boot recovery).
523
+ let recoveryMarkerDirty = false;
524
+
525
+ // In-flight mark-sending span counter (FIX 1 — the concurrent-`flushUnit` marker race). Bumped SYNCHRONOUSLY
526
+ // (before any await) whenever a status-update call transitions a row to `sending`, and dropped in a `finally`
527
+ // once that UPDATE has committed — so it brackets the span from "marker decision" to "committed `sending`
528
+ // row". `settleRecoveryMarker` refuses to clear while any such span is open, so a concurrent pessimistic
529
+ // sender (a `flushUnit` that does NOT ride `flushQueue`) that has passed the cached-dirty check but not yet
530
+ // committed its `sending` UPDATE can never have the marker cleared out from under it.
531
+ //
532
+ // Soundness: EVERY pending→sending transition in existence flows through THIS one runtime on a single JS
533
+ // thread (ADR-0002 single in-DB write path; one engine per store), so the counter fully orders every
534
+ // "marker-decision → commit" span against every clear attempt; the durable guarded clear still protects
535
+ // against already-committed rows. Why not the review's primary fix (BEGIN/COMMIT around marker + claim +
536
+ // `sending`): it adds 3 crossings to every flush's hot path, and a single-crossing data-modifying CTE is
537
+ // not expressible in drizzle-rc.4 — the counter costs ZERO crossings and is sound under the single-runtime
538
+ // invariant.
539
+ let markSendingInFlight = 0;
540
+ const markSendingScope: MarkSendingScope = {
541
+ enter: () => {
542
+ markSendingInFlight += 1;
543
+ },
544
+ exit: () => {
545
+ markSendingInFlight -= 1;
546
+ },
547
+ };
548
+
549
+ /**
550
+ * Marker-first SET (proposal §1 rule 1, corrected): commit the marker `true` BEFORE the first
551
+ * pending→sending transition of a dirty epoch. Invoked from the ONE choke point (`applyMutationStatusUpdates`,
552
+ * gated on a `sending` target) immediately before its UPDATE executes. The upsert auto-commits, so the
553
+ * marker is durable before any `sending` row can commit — the invariant the whole slice protects.
554
+ */
555
+ const ensureRecoveryMarker = async () => {
556
+ if (!ownsMetaTable || recoveryMarkerDirty) {
557
+ return;
558
+ }
559
+ await writeMutationRecoveryRequired(options.db, options.registry, true);
560
+ recoveryMarkerDirty = true;
561
+ };
562
+
563
+ /**
564
+ * Self-verifying clear at a post-ack seam (in-flight `sending` count has dropped to zero after a flush).
565
+ * Writes the marker `false` only when NOT EXISTS any `sending` row across every writable journal; on a
566
+ * successful clear the epoch-dirty flag resets so the next dirty epoch re-commits the marker.
567
+ */
568
+ const settleRecoveryMarker = async () => {
569
+ if (!ownsMetaTable) {
570
+ return;
571
+ }
572
+ // FIX 1: do NOT attempt the guarded clear while a concurrent mark-sending span is open (between its marker
573
+ // decision and its committed `sending` UPDATE). Clearing now could write `false` before that sender's
574
+ // `sending` row commits, stranding it on a crash. Each sender settles at its OWN end, so the last
575
+ // concurrent unit to close its span still performs the clear — a skipped clear just leaves the
576
+ // conservative `true` for the next settle (or boot recovery) to clear.
577
+ if (markSendingInFlight > 0) {
578
+ return;
579
+ }
580
+ // FIX 1b — reset the epoch-dirty flag SYNCHRONOUSLY here, in the SAME continuation as the counter check and
581
+ // BEFORE the clear's `db.query` is issued (nothing awaits between them: `clearMutationRecoveryMarkerIfSettled`
582
+ // builds the statement synchronously and its first await is `db.query`). Do NOT touch the flag AFTER the
583
+ // clear resolves — a sender that entered mid-clear may have legitimately re-set it `true`, and stomping it
584
+ // back to `false` would reopen the hole.
585
+ //
586
+ // Soundness against a sender racing an IN-FLIGHT clear: every sender's `enter()` + dirty-read is synchronous,
587
+ // so relative to this synchronous check-and-reset block it is either
588
+ // (i) BEFORE it → `markSendingInFlight > 0` here → no clear is issued at all (the FIX 1 gate); or
589
+ // (ii) AFTER it → the sender reads `recoveryMarkerDirty === false` → it awaits
590
+ // `writeMutationRecoveryRequired(true)`, and PGlite's single-connection queue serializes that upsert
591
+ // AFTER the already-issued clear → the marker is durably `true` again BEFORE the sender's `sending`
592
+ // UPDATE (only issued once the marker await resolves) can commit. A crash between the rewrite and the
593
+ // UPDATE leaves marker-`true`/no-row (conservative).
594
+ // On a guard-blocked clear (a committed `sending` row made the UPDATE a no-op) the flag stays pessimistically
595
+ // `false`, so the next sender writes a redundant `true` — one extra crossing on a rare path, harmless.
596
+ recoveryMarkerDirty = false;
597
+ await clearMutationRecoveryMarkerIfSettled(options.db, options.registry);
598
+ };
599
+
600
+ /** The `sending → pending` recovery UPDATE for one journal (shared by the public + boot recovery paths). */
601
+ const buildRecoverSendingQuery = (journal: JournalTable, nowUs: string) =>
602
+ queryBuilder
603
+ .update(journal)
604
+ .set({
605
+ status: "pending",
606
+ updatedAtUs: nowUs,
607
+ sentAtUs: null,
608
+ nextRetryAtUs: nowUs,
609
+ lastError: null,
610
+ lastHttpStatus: null,
611
+ conflictReason: null,
612
+ })
613
+ .where(eq(journal.status, "sending"))
614
+ .toSQL();
615
+
616
+ const readAffectedRows = (result: unknown): number => (result as { affectedRows?: number }).affectedRows ?? 0;
617
+
476
618
  const getTableContext = (table: SyncTableName<TRegistry>) => {
477
619
  const context = tableContexts[table];
478
620
 
@@ -855,6 +997,8 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
855
997
  table,
856
998
  resolveAuthToken,
857
999
  options.requestHeaders,
1000
+ ensureRecoveryMarker,
1001
+ markSendingScope,
858
1002
  );
859
1003
 
860
1004
  processedCount = batchResult.processedCount;
@@ -876,6 +1020,11 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
876
1020
  await reconcileTable(options.db, context);
877
1021
  }
878
1022
 
1023
+ // Post-ack seam (optimistic path): the drain loop above has settled every `sending` row this pass
1024
+ // produced (into acked/failed/quarantined/conflicted), so try the self-verifying clear — it writes the
1025
+ // marker `false` iff no `sending` row remains across any journal, resetting the epoch-dirty flag.
1026
+ await settleRecoveryMarker();
1027
+
879
1028
  // Surface newly-quarantined mutations after reconciliation so the app never has to
880
1029
  // poll for permanently-rejected writes (ADR-0006 decision 4). Never silent loss.
881
1030
  if (quarantinedMutationIds.size > 0 && options.onQuarantine) {
@@ -1035,6 +1184,8 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1035
1184
  lastHttpStatus: null,
1036
1185
  conflictReason: null,
1037
1186
  })),
1187
+ ensureRecoveryMarker,
1188
+ markSendingScope,
1038
1189
  );
1039
1190
  }
1040
1191
 
@@ -1220,6 +1371,10 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1220
1371
  }
1221
1372
  }
1222
1373
 
1374
+ // Post-ack seam (pessimistic path): every member of the unit has left `sending`, so try the
1375
+ // self-verifying clear — it settles the marker to `false` iff no `sending` row remains anywhere.
1376
+ await settleRecoveryMarker();
1377
+
1223
1378
  return { acks: [...acksByMutationId.values()] };
1224
1379
  },
1225
1380
  reconcile: async (table) => {
@@ -1250,23 +1405,63 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1250
1405
  const nowUs = nowMicroseconds();
1251
1406
 
1252
1407
  for (const context of contexts) {
1253
- const journal = context.tables.journal;
1254
- const query = queryBuilder
1255
- .update(journal)
1256
- .set({
1257
- status: "pending",
1258
- updatedAtUs: nowUs,
1259
- sentAtUs: null,
1260
- nextRetryAtUs: nowUs,
1261
- lastError: null,
1262
- lastHttpStatus: null,
1263
- conflictReason: null,
1264
- })
1265
- .where(eq(journal.status, "sending"))
1266
- .toSQL();
1408
+ const query = buildRecoverSendingQuery(context.tables.journal, nowUs);
1267
1409
  await options.db.query(query.sql, query.params as unknown[]);
1268
1410
  }
1269
1411
  },
1412
+ runBootRecovery: async ({ ownsMetaTable: bootOwnsMetaTable, restore }) => {
1413
+ assertValidMutationTransition("sending", "pending");
1414
+ const contexts = filterContexts(tableContexts, undefined);
1415
+ const tablesVisited = contexts.length;
1416
+
1417
+ // Caller-owned PGlite: the meta table may not exist, so never touch the marker — legacy always-recover.
1418
+ if (!bootOwnsMetaTable) {
1419
+ await runtime.recoverSending();
1420
+ return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
1421
+ }
1422
+
1423
+ // Restore boot ignores the marker entirely (proposal §1): legacy recovery lifts any `sending` back to
1424
+ // `pending`, quarantine parks every recovered non-terminal row, then the self-verifying clear settles
1425
+ // the marker (a clean marker in the backup must never bypass quarantine — quarantine ran first).
1426
+ if (restore) {
1427
+ await runtime.recoverSending();
1428
+ await runtime.quarantineRecovered();
1429
+ await settleRecoveryMarker();
1430
+ return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
1431
+ }
1432
+
1433
+ const marker = await readMutationRecoveryRequired(options.db, options.registry);
1434
+
1435
+ // Marker `false`: a clean prior settle proved no `sending` row remains — skip the per-table loop.
1436
+ if (marker === false) {
1437
+ return { skipped: true, required: false, tablesVisited: 0, rowsRecovered: 0 };
1438
+ }
1439
+
1440
+ // Marker absent (legacy/pre-feature store): one conservative recovery pass, then initialize the marker
1441
+ // (the pass just guaranteed no `sending` row remains, so an unconditional `false` is correct).
1442
+ if (marker === null) {
1443
+ await runtime.recoverSending();
1444
+ await writeMutationRecoveryRequired(options.db, options.registry, false);
1445
+ recoveryMarkerDirty = false;
1446
+ return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
1447
+ }
1448
+
1449
+ // Marker `true`: a crash may have left committed `sending` rows. Run the N per-table updates PLUS the
1450
+ // self-verifying clear atomically (a correctness upgrade over today's un-wrapped loop), counting the
1451
+ // rows lifted `sending → pending` from each UPDATE's affected-row count.
1452
+ const nowUs = nowMicroseconds();
1453
+ let rowsRecovered = 0;
1454
+ await runInTransaction(async () => {
1455
+ for (const context of contexts) {
1456
+ const query = buildRecoverSendingQuery(context.tables.journal, nowUs);
1457
+ const result = await options.db.query(query.sql, query.params as unknown[]);
1458
+ rowsRecovered += readAffectedRows(result);
1459
+ }
1460
+ await clearMutationRecoveryMarkerIfSettled(options.db, options.registry);
1461
+ });
1462
+ recoveryMarkerDirty = false;
1463
+ return { skipped: false, required: true, tablesVisited, rowsRecovered };
1464
+ },
1270
1465
  quarantineRecovered: async (table) => {
1271
1466
  // The restore-boot quarantine (ADR-0035 decision 6): every non-terminal recovered row is parked in the
1272
1467
  // terminal `quarantined` state so NOTHING recovered from a backup auto-flushes (no dedupe ledger →
@@ -1305,6 +1500,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1305
1500
  failedCount: 0,
1306
1501
  quarantinedCount: 0,
1307
1502
  conflictedCount: 0,
1503
+ rejectedCount: 0,
1308
1504
  ackedCount: 0,
1309
1505
  };
1310
1506
 
@@ -1322,6 +1518,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1322
1518
  failedCount: filteredCount("failed", "failedCount"),
1323
1519
  quarantinedCount: filteredCount("quarantined", "quarantinedCount"),
1324
1520
  conflictedCount: filteredCount("conflicted", "conflictedCount"),
1521
+ rejectedCount: filteredCount("rejected", "rejectedCount"),
1325
1522
  ackedCount: filteredCount("acked", "ackedCount"),
1326
1523
  })
1327
1524
  .from(journal)
@@ -1341,6 +1538,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1341
1538
  totals.failedCount += row.failedCount;
1342
1539
  totals.quarantinedCount += row.quarantinedCount;
1343
1540
  totals.conflictedCount += row.conflictedCount;
1541
+ totals.rejectedCount += row.rejectedCount;
1344
1542
  totals.ackedCount += row.ackedCount;
1345
1543
  }
1346
1544
 
@@ -2165,6 +2363,17 @@ interface FlushBatchResult {
2165
2363
  conflictedMutationIds: string[];
2166
2364
  }
2167
2365
 
2366
+ /**
2367
+ * Runtime-scoped enter/exit seam for the in-flight mark-sending span counter (FIX 1). Threaded into
2368
+ * `applyMutationStatusUpdates` so the free function can bracket a `sending` transition against the runtime's
2369
+ * `settleRecoveryMarker`, which the free function cannot otherwise see. `enter` is called synchronously before
2370
+ * the marker await; `exit` in a `finally` after the `sending` UPDATE commits.
2371
+ */
2372
+ interface MarkSendingScope {
2373
+ enter: () => void;
2374
+ exit: () => void;
2375
+ }
2376
+
2168
2377
  interface MutationStatusUpdate {
2169
2378
  mutationId: string;
2170
2379
  status: MutationStatus;
@@ -2340,6 +2549,8 @@ async function flushBatch(
2340
2549
  tableFilter?: string,
2341
2550
  getAuthToken?: () => Promise<string | undefined>,
2342
2551
  requestHeaders?: Record<string, string>,
2552
+ ensureRecoveryMarker?: () => Promise<void>,
2553
+ markSendingScope?: MarkSendingScope,
2343
2554
  ): Promise<FlushBatchResult> {
2344
2555
  const contexts = filterContexts(tableContexts, tableFilter);
2345
2556
  const nowUs = nowMicroseconds();
@@ -2427,6 +2638,8 @@ async function flushBatch(
2427
2638
  lastHttpStatus: null,
2428
2639
  conflictReason: null,
2429
2640
  })),
2641
+ ensureRecoveryMarker,
2642
+ markSendingScope,
2430
2643
  );
2431
2644
  }
2432
2645
 
@@ -3093,11 +3306,39 @@ function buildRequestHeaders(bearerToken?: string, requestHeaders?: Record<strin
3093
3306
  };
3094
3307
  }
3095
3308
 
3096
- async function applyMutationStatusUpdates(db: MutationDb, context: TableContext, updates: MutationStatusUpdate[]) {
3309
+ async function applyMutationStatusUpdates(
3310
+ db: MutationDb,
3311
+ context: TableContext,
3312
+ updates: MutationStatusUpdate[],
3313
+ onBeforeMarkSending?: () => Promise<void>,
3314
+ markSendingScope?: MarkSendingScope,
3315
+ ) {
3097
3316
  if (updates.length === 0) {
3098
3317
  return;
3099
3318
  }
3100
3319
 
3320
+ // Marker-first choke point (slice 2): this is the ONE code path every pending→sending transition flows
3321
+ // through (optimistic `flushBatch` + pessimistic `flushUnit`). When any update targets `sending`, commit
3322
+ // the durable recovery-required marker BEFORE the transition's UPDATE executes, so a committed `sending`
3323
+ // row can never coexist with a `false` marker. Non-`sending` transitions (ack/fail/quarantine) never fire it.
3324
+ const marksSending = updates.some((update) => update.status === "sending");
3325
+ // FIX 1: open the in-flight mark-sending span SYNCHRONOUSLY (before the marker await below), so a concurrent
3326
+ // `settleRecoveryMarker` cannot clear the marker between this call's marker decision and its committed
3327
+ // `sending` UPDATE. Closed in the `finally` once the UPDATE has committed.
3328
+ if (marksSending) markSendingScope?.enter();
3329
+ try {
3330
+ if (onBeforeMarkSending && marksSending) {
3331
+ await onBeforeMarkSending();
3332
+ }
3333
+ await execMutationStatusUpdates(db, context, updates);
3334
+ } finally {
3335
+ if (marksSending) markSendingScope?.exit();
3336
+ }
3337
+ }
3338
+
3339
+ /** The bare status-update UPDATE (no marker/counter concerns) — split so `applyMutationStatusUpdates` can
3340
+ * bracket it with the mark-sending span in a `finally` (FIX 1). */
3341
+ async function execMutationStatusUpdates(db: MutationDb, context: TableContext, updates: MutationStatusUpdate[]) {
3101
3342
  // Tier ②: `update().from(<VALUES>)`. Every value is a bound param with the same cast as before;
3102
3343
  // the `updates` alias and its column list are fixed by this function (not derived from data), so
3103
3344
  // the alias-qualified references in SET/WHERE are fixed template text, while the journal side of