@rindle/optimistic 0.1.6 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/backend.ts CHANGED
@@ -42,6 +42,7 @@ import { CLIENT_MUTATIONS_SCHEMA, LMID_QUERY_NAME, localTableNames, normalizedTa
42
42
  import type {
43
43
  Ast,
44
44
  Backend,
45
+ BackendDevObserver,
45
46
  ChangeEvent,
46
47
  ColsMap,
47
48
  Mutation,
@@ -65,6 +66,18 @@ import { AggOverlay, type ChildOp, collectAggDefs } from "./agg-overlay.ts";
65
66
  * against the schema at runtime, so a typo throws immediately with the valid names. */
66
67
  export type KeyedRow = Record<string, WireValue>;
67
68
 
69
+ /** What `MutationTx.query` accepts: a query handle whose `.ast()` lowers to the wire
70
+ * {@link Ast} — exactly what the typed query builder (`store.query.<table>…` or
71
+ * `newQueryBuilder(schema).<table>…`) produces (203-MUTATOR-READS-DESIGN.md §9.1). Typed
72
+ * structurally so the `MutationTx` surface need not carry the builder's heavy generics. */
73
+ export type QueryArg = { ast(): Ast };
74
+
75
+ /** A row returned by {@link MutationTx.query}: column name → cell, plus each materialized
76
+ * relationship name → its nested row(s) — an array (a plural relationship), or a single row /
77
+ * `null` (a `.one()` relationship). Recursive (nested rows share the shape). Presented
78
+ * identically to a `view.data` row of the same query (203-MUTATOR-READS-DESIGN.md §5.2). */
79
+ export type QueryResultRow = { [key: string]: WireValue | QueryResultRow | QueryResultRow[] };
80
+
68
81
  /** The write handle a client mutator runs against (the client `MutationTx`, §4.2):
69
82
  * reads see the current base + this transaction's own staged writes (§4.1).
70
83
  *
@@ -84,6 +97,14 @@ export interface MutationTx {
84
97
  upsert(table: string, row: KeyedRow): void;
85
98
  /** Delete the row identified by the pk columns. A missing row is a NO-OP. */
86
99
  delete(table: string, pk: KeyedRow): void;
100
+ /** Run a one-shot read query (`where`/`orderBy`/`limit`/join) over the state this
101
+ * mutator is mutating — it sees this transaction's own writes-so-far, the same
102
+ * read-your-writes contract as `get`/`row` (§4.1; 203-MUTATOR-READS-DESIGN.md §5.2).
103
+ * Synchronous; returns the matching rows in the query's order, each with its materialized
104
+ * relationship children nested by name (presented identically to a `view.data` row). Pass
105
+ * a query from the typed builder, e.g. `tx.query(q.issue.where("owner", "=", me))`.
106
+ * Refused inside a FOLDED mutator (a reading mutator is non-absorbing, §9.1). */
107
+ query(query: QueryArg): QueryResultRow[];
87
108
  // --- positional (the wire shape) ---
88
109
  get(table: string, pk: WireValue[]): WireValue[] | undefined;
89
110
  add(table: string, row: WireValue[]): void;
@@ -287,6 +308,12 @@ export class OptimisticBackend<S extends ColsMap> implements Backend {
287
308
  * pending delta `displayed = server_base ⊕ local_pending_delta` is applied from. */
288
309
  private readonly overlay = new AggOverlay();
289
310
  private handler: (qid: QueryId, ev: ChangeEvent) => void = () => {};
311
+ /** The Store's commit-boundary handler ({@link Backend.onCommitBoundary}), forwarded from the
312
+ * local engine's `dispatch` brackets so the Store folds every affected view before notifying any
313
+ * subscriber (cross-view-atomic notification). All this backend's data deltas originate from the
314
+ * local engine, so its commit brackets are this backend's commit brackets. */
315
+ private boundaryHandler: (phase: "begin" | "end") => void = () => {};
316
+ private readonly devObservers = new Set<BackendDevObserver>();
290
317
 
291
318
  private pendingMutations: PendingMutation[] = [];
292
319
  private nextMid = 1;
@@ -328,6 +355,9 @@ export class OptimisticBackend<S extends ColsMap> implements Backend {
328
355
  ) {
329
356
  this.local = new WasmBackend(schema);
330
357
  this.local.onEvent((qid, ev) => this.handler(qid, ev));
358
+ // Forward the local engine's commit brackets up to the Store (cross-view-atomic notification):
359
+ // every data delta this backend emits comes from `this.local`, so its commit boundaries are ours.
360
+ this.local.onCommitBoundary((phase) => this.boundaryHandler(phase));
331
361
  this.colCounts = colCountsFromSchema(schema);
332
362
  this.colIndex = colIndexFromSchema(schema);
333
363
  this.sync = new NormalizedSync(pkColsFromSchema(schema), this.colCounts);
@@ -479,12 +509,18 @@ export class OptimisticBackend<S extends ColsMap> implements Backend {
479
509
  // Store counter — re-materialize gets a fresh id, never this one again), so drop it on teardown.
480
510
  }
481
511
 
482
- retainRemoteQuery(qid: QueryId, remote: RemoteQuery, localQueryId?: QueryId): void {
512
+ retainRemoteQuery(qid: QueryId, remote: RemoteQuery, localQueryId?: QueryId, ast?: Ast): void {
513
+ if (ast) this.ensureSyntheticTables(qid, ast);
483
514
  this.retainRemote(qid, remote, localQueryId);
484
515
  }
485
516
 
486
517
  releaseRemoteQuery(qid: QueryId): void {
487
518
  const remoteQid = this.releaseRemote(qid);
519
+ this.releaseSyntheticTables(qid);
520
+ if (!this.queryTables.has(qid)) {
521
+ this.resultTypes.delete(qid);
522
+ this.hydrated.delete(qid);
523
+ }
488
524
  if (remoteQid === undefined) return;
489
525
  this.buffer = this.buffer.filter((f) => f.qid !== remoteQid);
490
526
  const gc = this.sync.dropQuery(remoteQid);
@@ -512,39 +548,65 @@ export class OptimisticBackend<S extends ColsMap> implements Backend {
512
548
  this.handler = handler;
513
549
  }
514
550
 
551
+ onCommitBoundary(handler: (phase: "begin" | "end") => void): void {
552
+ this.boundaryHandler = handler;
553
+ }
554
+
515
555
  // --- the named-mutator entry (§9) ----------------------------------------------
516
556
 
557
+ /** Bracket a multi-step optimistic apply as ONE notification commit (cross-view-atomic
558
+ * notification — {@link Backend.onCommitBoundary}). `invoke`/`invokeFolded` apply the prediction
559
+ * and then reconcile the `__agg` head in TWO `this.local` commits, but they are two halves of one
560
+ * logical mutation: a relationship-`count` view and the data view it counts must update together.
561
+ * The Store's `commitDepth` is a counter, so each inner commit's own `begin`/`end` nests under this
562
+ * outer pair and the Store flushes every affected view (data AND count) once, together, at the
563
+ * outer `end` — a subscriber re-reading a sibling view then sees post-commit data, never a torn
564
+ * half. Balanced on throw (the prediction mutator may reject) via the `finally`, so a thrown
565
+ * prediction never wedges the Store in deferred mode. */
566
+ private inOneCommit<T>(apply: () => T): T {
567
+ this.boundaryHandler("begin");
568
+ try {
569
+ return apply();
570
+ } finally {
571
+ this.boundaryHandler("end");
572
+ }
573
+ }
574
+
517
575
  /** Run the named client mutator optimistically: the prediction applies to the live
518
576
  * engine now (affected views update synchronously), `(mid, name, args)` joins the
519
577
  * pending stack, and the envelope ships upstream. Returns the assigned `mid`. */
520
578
  invoke(name: string, args: unknown): number {
521
579
  const mutator = this.registry[name];
522
580
  if (!mutator) throw new Error(`unknown client mutator: ${name}`);
523
- // Apply the prediction FIRST. If the mutator throws (client-side validation, a bad read),
524
- // the staged write is discarded (the wasm txn is a clean no-op until commit) and the throw
525
- // propagates with NO mid consumed — a burnt mid is a permanent server-side gap that
526
- // silently refuses every later mutation from this client (#10).
527
- const touched = new Set<string>();
528
- const ops: ChildOp[] = [];
529
- this.local.writeWith((tx) => {
530
- mutator(trackingTx(tx, touched, this.specs, this.localTables, this.opCollector(ops)), args as never);
581
+ // One commit boundary spans the prediction AND the `__agg`-head reconcile below, so their views
582
+ // (data + count) flush together rather than tearing across two engine commits.
583
+ return this.inOneCommit(() => {
584
+ // Apply the prediction FIRST. If the mutator throws (client-side validation, a bad read),
585
+ // the staged write is discarded (the wasm txn is a clean no-op until commit) and the throw
586
+ // propagates with NO mid consumed — a burnt mid is a permanent server-side gap that
587
+ // silently refuses every later mutation from this client (#10).
588
+ const touched = new Set<string>();
589
+ const ops: ChildOp[] = [];
590
+ this.local.writeWith((tx) => {
591
+ mutator(trackingTx(tx, touched, this.specs, this.localTables, this.opCollector(ops)), args as never);
592
+ });
593
+ // Flush-on-enqueue (§4.2): a fold whose tables overlap this write must take its mid NOW, BEFORE
594
+ // this write does, so wire order == local-apply order for any pair that can observe each other
595
+ // (a read-dependent write reading a folded cell sees the same value optimistically and on the
596
+ // wire — no snap). Drained folds ship with smaller mids; this write's mid is dealt after.
597
+ this.drainOverlapping(touched);
598
+ const mid = this.nextMid++;
599
+ this.pendingMutations.push({ mid, name, args, touched });
600
+ // The prediction stuck — fold its child ops into the optimistic agg delta and push it onto
601
+ // the `__agg` head rows (§4). No reset here (this is the §1.3 trivial case, no rewind): the
602
+ // delta accumulates on top of the prior pending set, and `reconcileAggHead` recomputes each
603
+ // touched group's head as the absolute `server_base ⊕ delta`.
604
+ for (const op of ops) this.overlay.observe(op);
605
+ this.reconcileAggHead();
606
+ this.refreshPending(); // §7.2: this write now touches its queries' pending axis (NOT ResultType).
607
+ void this.source.pushMutation({ clientID: this.clientID, mid, name, args });
608
+ return mid;
531
609
  });
532
- // Flush-on-enqueue (§4.2): a fold whose tables overlap this write must take its mid NOW, BEFORE
533
- // this write does, so wire order == local-apply order for any pair that can observe each other
534
- // (a read-dependent write reading a folded cell sees the same value optimistically and on the
535
- // wire — no snap). Drained folds ship with smaller mids; this write's mid is dealt after.
536
- this.drainOverlapping(touched);
537
- const mid = this.nextMid++;
538
- this.pendingMutations.push({ mid, name, args, touched });
539
- // The prediction stuck — fold its child ops into the optimistic agg delta and push it onto
540
- // the `__agg` head rows (§4). No reset here (this is the §1.3 trivial case, no rewind): the
541
- // delta accumulates on top of the prior pending set, and `reconcileAggHead` recomputes each
542
- // touched group's head as the absolute `server_base ⊕ delta`.
543
- for (const op of ops) this.overlay.observe(op);
544
- this.reconcileAggHead();
545
- this.refreshPending(); // §7.2: this write now touches its queries' pending axis (NOT ResultType).
546
- void this.source.pushMutation({ clientID: this.clientID, mid, name, args });
547
- return mid;
548
610
  }
549
611
 
550
612
  /** Run a FOLDED invoke (FOLDED-MUTATIONS-DESIGN §8): apply the prediction to the live engine now
@@ -555,64 +617,68 @@ export class OptimisticBackend<S extends ColsMap> implements Backend {
555
617
  const mutator = this.registry[name];
556
618
  if (!mutator) throw new Error(`unknown client mutator: ${name}`);
557
619
  const foldKey = `${name}\0${stableJson(opts.key)}`;
558
- // Apply the prediction with the read trap armed (§5): a folded mutator that reads state to
559
- // compute its write is non-absorbing and refused. A throw discards the staged write (clean
560
- // no-op) and consumes no mid — exactly `invoke`'s guarantee.
561
- const touched = new Set<string>();
562
- const ops: ChildOp[] = [];
563
- try {
564
- this.local.writeWith((tx) => {
565
- mutator(trackingTx(tx, touched, this.specs, this.localTables, this.opCollector(ops), true), args as never);
566
- });
567
- } catch (e) {
568
- if (e instanceof FoldReadError) {
569
- throw new Error(
570
- `cannot fold "${name}": it reads state via tx.get/tx.row, so it is not absorbing — folded mutators must be last-writer-wins (FOLDED-MUTATIONS-DESIGN §5)`,
571
- );
620
+ // One commit boundary spans the prediction AND the `__agg`-head reconcile (see {@link inOneCommit}),
621
+ // so a folded mutation's list view and count view flush together, never torn across two commits.
622
+ return this.inOneCommit(() => {
623
+ // Apply the prediction with the read trap armed (§5): a folded mutator that reads state to
624
+ // compute its write is non-absorbing and refused. A throw discards the staged write (clean
625
+ // no-op) and consumes no mid — exactly `invoke`'s guarantee.
626
+ const touched = new Set<string>();
627
+ const ops: ChildOp[] = [];
628
+ try {
629
+ this.local.writeWith((tx) => {
630
+ mutator(trackingTx(tx, touched, this.specs, this.localTables, this.opCollector(ops), true), args as never);
631
+ });
632
+ } catch (e) {
633
+ if (e instanceof FoldReadError) {
634
+ throw new Error(
635
+ `cannot fold "${name}": it reads state via tx.get/tx.row, so it is not absorbing — folded mutators must be last-writer-wins (FOLDED-MUTATIONS-DESIGN §5)`,
636
+ );
637
+ }
638
+ throw e;
572
639
  }
573
- throw e;
574
- }
575
- for (const op of ops) this.overlay.observe(op);
576
- this.reconcileAggHead();
577
-
578
- const now = this.clock.now();
579
- let f = this.folds.get(foldKey);
580
- if (f) {
581
- // Overwrite the single entry in place the pending stack does NOT grow (§1 #2). The head
582
- // already carries this new prediction (absorbing, last-wins on the cell); the entry holds
583
- // only the LATEST args, which is what a rebase re-derives from and what the flush ships.
584
- f.entry.args = args;
585
- f.entry.touched = touched;
586
- f.args = args;
587
- this.clock.clearTimeout(f.timer);
588
- } else {
589
- const entry: PendingMutation = { mid: null, name, args, touched };
590
- this.pendingMutations.push(entry);
591
- let resolveMid!: (mid: number) => void;
592
- const midPromise = new Promise<number>((res) => (resolveMid = res));
593
- f = {
594
- entry,
595
- args,
596
- timer: undefined,
597
- firstAt: now,
598
- debounceMs: opts.debounceMs ?? DEFAULT_FOLD_DEBOUNCE_MS,
599
- maxWaitMs: opts.maxWaitMs,
600
- deferAcrossWrites: opts.deferAcrossWrites ?? false,
601
- midPromise,
602
- resolveMid,
603
- };
604
- this.folds.set(foldKey, f);
605
- }
606
- // (Re)arm the trailing debounce unless the maxWaitMs cap is already due (a never-idle drag
607
- // still persists periodically, §3/#4), in which case flush now instead of re-arming.
608
- if (f.maxWaitMs !== undefined && now - f.firstAt >= f.maxWaitMs) {
609
- this.flushFold(foldKey);
610
- } else {
611
- f.timer = this.clock.setTimeout(() => this.flushFold(foldKey), f.debounceMs);
612
- }
613
- this.refreshPending();
614
- const handle: FoldHandle = { flush: () => this.flushFold(foldKey), mid: f.midPromise };
615
- return handle;
640
+ for (const op of ops) this.overlay.observe(op);
641
+ this.reconcileAggHead();
642
+
643
+ const now = this.clock.now();
644
+ let f = this.folds.get(foldKey);
645
+ if (f) {
646
+ // Overwrite the single entry in place — the pending stack does NOT grow (§1 #2). The head
647
+ // already carries this new prediction (absorbing, last-wins on the cell); the entry holds
648
+ // only the LATEST args, which is what a rebase re-derives from and what the flush ships.
649
+ f.entry.args = args;
650
+ f.entry.touched = touched;
651
+ f.args = args;
652
+ this.clock.clearTimeout(f.timer);
653
+ } else {
654
+ const entry: PendingMutation = { mid: null, name, args, touched };
655
+ this.pendingMutations.push(entry);
656
+ let resolveMid!: (mid: number) => void;
657
+ const midPromise = new Promise<number>((res) => (resolveMid = res));
658
+ f = {
659
+ entry,
660
+ args,
661
+ timer: undefined,
662
+ firstAt: now,
663
+ debounceMs: opts.debounceMs ?? DEFAULT_FOLD_DEBOUNCE_MS,
664
+ maxWaitMs: opts.maxWaitMs,
665
+ deferAcrossWrites: opts.deferAcrossWrites ?? false,
666
+ midPromise,
667
+ resolveMid,
668
+ };
669
+ this.folds.set(foldKey, f);
670
+ }
671
+ // (Re)arm the trailing debounce — unless the maxWaitMs cap is already due (a never-idle drag
672
+ // still persists periodically, §3/#4), in which case flush now instead of re-arming.
673
+ if (f.maxWaitMs !== undefined && now - f.firstAt >= f.maxWaitMs) {
674
+ this.flushFold(foldKey);
675
+ } else {
676
+ f.timer = this.clock.setTimeout(() => this.flushFold(foldKey), f.debounceMs);
677
+ }
678
+ this.refreshPending();
679
+ const handle: FoldHandle = { flush: () => this.flushFold(foldKey), mid: f.midPromise };
680
+ return handle;
681
+ });
616
682
  }
617
683
 
618
684
  /** Flush-on-enqueue (§4.2): for each outstanding fold whose touched tables overlap `tables`,
@@ -695,6 +761,13 @@ export class OptimisticBackend<S extends ColsMap> implements Backend {
695
761
  this.resultTypeHandler = handler;
696
762
  }
697
763
 
764
+ __attachDevtoolsServerDeltas(observer: BackendDevObserver): () => void {
765
+ this.devObservers.add(observer);
766
+ return () => {
767
+ this.devObservers.delete(observer);
768
+ };
769
+ }
770
+
698
771
  // --- the pending AXIS (§7.2): orthogonal to ResultType -------------------------------
699
772
 
700
773
  /** Whether any pending mutation (folded or not) touches this query's tables — "is a prediction
@@ -771,6 +844,7 @@ export class OptimisticBackend<S extends ColsMap> implements Backend {
771
844
  // --- the downstream stream (§8.5: buffer, then release coherently) ---------------
772
845
 
773
846
  private onNormalized(qid: QueryId, ev: NormalizedEvent): void {
847
+ if (qid !== LMID_QID) this.emitServerDelta(qid, ev);
774
848
  if (ev.type === "hello") {
775
849
  // A hello is a (re)subscribe = a NEW epoch. The column map below is mutated eagerly, but
776
850
  // data frames are cv-buffered and drained later (onProgress). So any frame still buffered
@@ -807,6 +881,21 @@ export class OptimisticBackend<S extends ColsMap> implements Backend {
807
881
  if (this.buffer.length > this.bufferCap) this.overflow();
808
882
  }
809
883
 
884
+ private emitServerDelta(sourceQid: QueryId, ev: NormalizedEvent): void {
885
+ if (!this.devObservers.size) return;
886
+ for (const qid of this.localQidsForSource(sourceQid)) {
887
+ for (const o of this.devObservers) o.onServerDelta?.(qid, { format: "normalized", event: ev });
888
+ }
889
+ }
890
+
891
+ private localQidsForSource(sourceQid: QueryId): QueryId[] {
892
+ const key = this.sourceToRemote.get(sourceQid);
893
+ const sub = key ? this.remoteSubs.get(key) : undefined;
894
+ if (!sub) return [sourceQid];
895
+ const localQids = [...sub.localQids.keys()];
896
+ return localQids.length ? localQids : [sourceQid];
897
+ }
898
+
810
899
  private onProgress(frame: ProgressFrame): void {
811
900
  // (1) Take every buffered frame at cv ≤ cvMin, in (cv, arrival) order, and fold it:
812
901
  // lmid system-query frames advance `confirmedLmid`; data frames fold through the
@@ -978,7 +1067,6 @@ export class OptimisticBackend<S extends ColsMap> implements Backend {
978
1067
  /** Recompute a query's server-channel state from hydration alone (§7): a pending mutation no
979
1068
  * longer affects it. Used when a remote sub attaches to or hydrates a local view. */
980
1069
  private recomputeResultType(qid: QueryId): void {
981
- if (!this.queryTables.has(qid)) return;
982
1070
  this.setResultType(qid, this.hydrated.has(qid) ? "complete" : "unknown");
983
1071
  }
984
1072
 
@@ -1220,8 +1308,20 @@ function trackingTx(
1220
1308
  throw new FoldReadError();
1221
1309
  };
1222
1310
 
1311
+ // One-shot query (203 §5.2): lower the builder to an AST, refuse any local-only table it
1312
+ // reads (M1 — same guard as `rawGet`), and run it over the engine's read-cache fork. The
1313
+ // wasm engine returns the rows already keyed by column name with their materialized
1314
+ // relationship children nested by name (`marshal::caught_node_to_js`), in the query's order —
1315
+ // identical in shape to `view.data` — so this is a pass-through.
1316
+ const runQuery = (q: QueryArg): QueryResultRow[] => {
1317
+ const ast = q.ast();
1318
+ for (const t of collectTables(ast)) assertNotLocal(t, "read");
1319
+ return tx.query(ast) as QueryResultRow[];
1320
+ };
1321
+
1223
1322
  return {
1224
1323
  get: trapReads ? trapped : rawGet,
1324
+ query: trapReads ? trapped : runQuery,
1225
1325
  add,
1226
1326
  remove,
1227
1327
  edit,
package/src/client-id.ts CHANGED
@@ -39,6 +39,22 @@ export function resetTabInstanceForTests(): void {
39
39
  tabInstance = 0;
40
40
  }
41
41
 
42
+ /** Clear the persisted client identity so the next page load starts a fresh mid/lmid stream.
43
+ * Intended for dev recovery after out-of-band server state loss, not for normal operation. */
44
+ export function resetStableClientID(): void {
45
+ try {
46
+ globalThis.localStorage?.removeItem(CLIENT_ID_KEY);
47
+ } catch {
48
+ // Storage can throw in private modes or test shims; best-effort reset.
49
+ }
50
+ try {
51
+ globalThis.sessionStorage?.removeItem(TAB_ID_KEY);
52
+ } catch {
53
+ // Storage can throw in private modes or test shims; best-effort reset.
54
+ }
55
+ tabInstance = 0;
56
+ }
57
+
42
58
  /** The connection's stable clientID. A per-origin base (localStorage) keeps one logical identity
43
59
  * across reloads; a per-tab suffix (sessionStorage) gives each tab its OWN mid/lmid stream; a
44
60
  * per-load instance suffix keeps two clients constructed in ONE tab from sharing that stream. Falls
package/src/client.ts CHANGED
@@ -20,7 +20,7 @@ import { initWasm } from "@rindle/wasm";
20
20
 
21
21
  import type { OptimisticBackend } from "./backend.ts";
22
22
  import type { ClientRegistry, MutationTx } from "./backend.ts";
23
- import { stableClientID } from "./client-id.ts";
23
+ import { resetStableClientID, stableClientID } from "./client-id.ts";
24
24
  import { createOptimisticStore, type MutateFn } from "./index.ts";
25
25
  import type { Store } from "@rindle/client";
26
26
 
@@ -58,6 +58,13 @@ export interface RindleClientOptions<S extends ColsMap, R extends ClientRegistry
58
58
  /** A policy rejection's reason (the prediction's snap-back rides the lmid release). */
59
59
  onRejected?: (envelope: MutationEnvelope, reason: string) => void;
60
60
  queue?: { maxBatch?: number; retryDelayMs?: (attempt: number) => number };
61
+ /** Development-only recovery knobs. Keep off in production: a mutation gap means state loss
62
+ * or two writers sharing a clientID, and should be investigated. */
63
+ dev?: {
64
+ /** On a mutation-gap response, clear the persisted clientID and hard reload the page. This
65
+ * recovers from dev DB wipes while making the reset visible to the developer. */
66
+ resetOnMutationGap?: boolean;
67
+ };
61
68
  }
62
69
 
63
70
  export interface RindleClient<S extends ColsMap, R extends ClientRegistry> {
@@ -90,8 +97,9 @@ export async function createRindleClient<S extends ColsMap, R extends ClientRegi
90
97
  headers: { "content-type": "application/json", ...extra },
91
98
  body: JSON.stringify(payload),
92
99
  });
93
- if (!res.ok) throw new Error(`rindle api ${path} failed: ${res.status} ${await res.text()}`);
94
- return res.json();
100
+ const text = await res.text();
101
+ if (!res.ok) throw new RindleApiHttpError(path, res.status, text);
102
+ return text ? JSON.parse(text) : undefined;
95
103
  };
96
104
 
97
105
  // Reads-leg connection: a fixed transport (tests/in-process) or a replaceable connection built
@@ -116,8 +124,15 @@ export async function createRindleClient<S extends ColsMap, R extends ClientRegi
116
124
  retryDelayMs: opts.queue?.retryDelayMs,
117
125
  onRejected: opts.onRejected,
118
126
  send: async (envelopes) => {
119
- const outcomes = (await post(routes.mutate, { envelopes })) as Array<{ accepted: boolean; reason?: string }>;
120
- return outcomes.map((o): PushOutcome => ({ accepted: o.accepted, reason: o.reason }));
127
+ try {
128
+ const outcomes = (await post(routes.mutate, { envelopes })) as Array<{ accepted: boolean; reason?: string }>;
129
+ return outcomes.map((o): PushOutcome => ({ accepted: o.accepted, reason: o.reason }));
130
+ } catch (err) {
131
+ if (opts.dev?.resetOnMutationGap && reloadAfterMutationGap(err)) {
132
+ return new Promise<never>(() => {});
133
+ }
134
+ throw err;
135
+ }
121
136
  },
122
137
  }),
123
138
  });
@@ -154,3 +169,41 @@ export async function createRindleClient<S extends ColsMap, R extends ClientRegi
154
169
 
155
170
  export type { ClientRegistry, MutationTx };
156
171
  export type { MutateFn } from "./index.ts";
172
+
173
+ class RindleApiHttpError extends Error {
174
+ readonly path: string;
175
+ readonly status: number;
176
+ readonly body: string;
177
+
178
+ constructor(path: string, status: number, body: string) {
179
+ super(`rindle api ${path} failed: ${status}${body ? ` ${body}` : ""}`);
180
+ this.name = "RindleApiHttpError";
181
+ this.path = path;
182
+ this.status = status;
183
+ this.body = body;
184
+ }
185
+ }
186
+
187
+ const MUTATION_GAP_RE = /\bmutation(?: id)? gap\b/i;
188
+
189
+ function reloadAfterMutationGap(err: unknown): boolean {
190
+ const text =
191
+ err instanceof RindleApiHttpError
192
+ ? `${err.status} ${err.body} ${err.message}`
193
+ : String((err as Error)?.message ?? err);
194
+ if (!MUTATION_GAP_RE.test(text)) return false;
195
+
196
+ resetStableClientID();
197
+ console.error(
198
+ "[rindle] mutation gap detected; cleared the dev client id and reloading so this tab starts a fresh mutation stream.",
199
+ err,
200
+ );
201
+ const loc = (globalThis as unknown as { location?: { reload?: () => void } }).location;
202
+ if (typeof loc?.reload !== "function") return false;
203
+ try {
204
+ loc.reload();
205
+ return true;
206
+ } catch {
207
+ return false;
208
+ }
209
+ }
package/src/index.ts CHANGED
@@ -34,6 +34,8 @@ export type {
34
34
  OptimisticBackendOptions,
35
35
  OptimisticInspect,
36
36
  PendingInspect,
37
+ QueryArg,
38
+ QueryResultRow,
37
39
  ResultType,
38
40
  } from "./backend.ts";
39
41
  export type { MutationEnvelope, OptimisticSource, ProgressFrame } from "@rindle/client";
@@ -41,7 +43,7 @@ export type { MutationEnvelope, OptimisticSource, ProgressFrame } from "@rindle/
41
43
  // The one-call client for the daemon/serverless topology (API server + daemon ws).
42
44
  export { createRindleClient } from "./client.ts";
43
45
  export type { RindleClient, RindleClientOptions } from "./client.ts";
44
- export { stableClientID } from "./client-id.ts";
46
+ export { resetStableClientID, stableClientID } from "./client-id.ts";
45
47
 
46
48
  /** A {@link Store} over an {@link OptimisticBackend}, plus the named-mutator entry
47
49
  * (`mutate.createIssue(args)` — the §9 dream shape) and the §6 lifecycle surface. */