Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Seanaye/feat/combine mutation dispatch (#5500)

Sean Aye8480d356b56e
diff --git a/apps/web/docs/graphql-cache-optimistic-enqueue-claim-plan.md b/apps/web/docs/graphql-cache-optimistic-enqueue-claim-plan.md
new file mode 100644
index 0000000000..2fc7082b58
--- /dev/null
+++ b/apps/web/docs/graphql-cache-optimistic-enqueue-claim-plan.md
@@ -0,0 +1,440 @@
+# GraphQL Cache: Coupled Optimistic Enqueue and Initial Claim
+
+Status: **implementation plan**
+
+Base: implement after the reduced-inspection-cloning change (`wtomruqy`, currently described as `complete EntityKey Cow migration`).
+
+Related design: [`graphql-normalized-cache-plan.md`](./graphql-normalized-cache-plan.md)
+
+## 1. Problem
+
+Starting an optimistic cache update and starting its durable mutation runner are currently exposed as separate host operations:
+
+1. `beginOptimisticWrite` durably enqueues the mutation and publishes its optimistic layer.
+2. The cache worker/native plugin broadcasts `ops-affected`.
+3. Those pushes synchronously cause user-visible cache reads.
+4. The exchange later schedules `claimNextMutation` through `setTimeout(0)`.
+5. The single cache engine may therefore spend about 50 ms denormalizing an affected query before it can claim the mutation and let urql send the network request.
+
+The `Zen 2026-08-07 09.19` profile showed this sequence on a slow property change:
+
+```text
+click
+ inspect variants ~10 ms
+ membership read ~4 ms
+ begin optimistic write ~27 ms
+ affected active-query read ~52 ms
+ UI/DnD layout ~12 ms
+ mutation network request starts ~158 ms after click
+```
+
+The worker scheduler currently assigns:
+
+- cache writes: priority 2;
+- user-visible reads: priority 1;
+- `claim-next-mutation`: priority 0.
+
+Raising claim priority alone is insufficient because `begin-optimistic-write` fans out affected operations before returning. The affected read can already be running when the claim request is created.
+
+## 2. Decision
+
+Replace the public `beginOptimisticWrite` operation with one application-level operation:
+
+> **Durably enqueue an optimistic mutation and attempt to claim the strict queue head before publishing affected operations.**
+
+Use a name such as `enqueueOptimisticMutation` throughout the host/protocol surface. Keep standalone `claimNextMutation` for background queue draining, startup recovery, retries, and advancing after settlement.
+
+The initial implementation may use two storage transactions while holding the same serialized engine lock:
+
+1. enqueue mutation plus optimistic layer;
+2. attempt to claim the queue head.
+
+Do **not** add `enqueue_mutation_and_claim` to the storage trait in this change. A crash between the transactions is safe: the mutation remains durably queued and can be claimed later. Storage-level atomic enqueue-and-claim is a possible follow-up only if profiling shows a need.
+
+## 3. Required invariants
+
+The implementation must preserve all of these:
+
+1. The network mutation is never forwarded without a durable lease claim.
+2. The optimistic layer and mutation request remain atomically enqueued as they are today.
+3. The initial claim attempt completes before `ops-affected` or cache-change notifications are published.
+4. Strict queue order remains unchanged: a leased, deferred, or otherwise non-runnable head blocks every later mutation.
+5. If an older unclaimed mutation is at the head, the result may claim that older mutation; the newly enqueued operation is reported as queued.
+6. If the head is already leased or deferred, the new optimistic layer remains visible but the new operation is reported as queued.
+7. A failure during the claim step must **not** turn the already-enqueued mutation into an ordinary unqueued network request.
+8. Initial/continuation grouped-page patching, link-patch fallback, and post-success revalidation semantics remain unchanged.
+9. The browser SharedWorker and Tauri native host expose equivalent behavior.
+10. Standalone queue draining and retry/settlement behavior continue to work after the initial composite operation.
+
+## 4. Proposed result types
+
+Use an explicit tagged claim outcome instead of an optional claim. The caller must be able to distinguish “head is not runnable” from “the claim attempt failed after enqueue succeeded.”
+
+Conceptual TypeScript types:
+
+```ts
+export type InitialMutationClaim =
+ | { kind: 'claimed'; mutation: ClaimedMutation }
+ | { kind: 'not-runnable' }
+ | { kind: 'failed'; error: string };
+
+export type EnqueueOptimisticMutationResult = OptimisticWriteResult & {
+ initialClaim: InitialMutationClaim;
+};
+```
+
+The existing `OptimisticWriteResult` fields remain available:
+
+- `transactionId` identifies the newly enqueued mutation;
+- `changed` and `affectedOps` describe the newly visible composed cache view;
+- `revalidations` retains its current meaning.
+
+Interpretation:
+
+- `initialClaim.kind === 'claimed'` and claim id equals `transactionId`: forward the live operation immediately.
+- `initialClaim.kind === 'claimed'` and claim id differs: replay the older claimed head and return the new operation as queued.
+- `not-runnable`: return the new operation as queued and retain/schedule background draining.
+- `failed`: report the claim error diagnostically, return the new operation as queued, and schedule background draining. Never forward it outside the durable runner.
+
+## 5. Rust core design
+
+Primary files:
+
+- `crates/client/cache-core/src/engine.rs`
+- `crates/client/cache-core/src/queue.rs` if common result types belong there
+- `crates/client/cache-core/tests/optimistic.rs`
+- `crates/client/cache-core/tests/mutation_queue.rs`
+
+Add a composite engine method such as:
+
+```rust
+pub async fn enqueue_optimistic_mutation(
+ &mut self,
+ origin_op: Option<OpId>,
+ input: BeginOptimisticWrite<'_>,
+ claim: MutationClaimRequest,
+) -> Result<EnqueueOptimisticMutationResult<EngineError<S::Error>>, EngineError<S::Error>>;
+```
+
+A generic result shape can preserve the partial claim error without converting core errors to strings:
+
+```rust
+pub enum InitialClaimOutcome<E> {
+ Claimed(ClaimedMutation),
+ NotRunnable,
+ Failed(E),
+}
+
+pub struct EnqueueOptimisticMutationResult<E> {
+ pub transaction_id: OptimisticTransactionId,
+ pub write_result: WriteResult,
+ pub initial_claim: InitialClaimOutcome<E>,
+}
+```
+
+Implementation order:
+
+```text
+begin_optimistic_write(...).await? // top-level failure: no successful result
+claim_next_mutation(claim).await // nested outcome; do not discard begin result
+return enqueue result
+```
+
+Important error rule: once `begin_optimistic_write` succeeds, an error from `claim_next_mutation` becomes `InitialClaimOutcome::Failed`; it must not become the outer `Err`. Otherwise the exchange could incorrectly degrade to an ordinary network mutation even though durable user intent already exists.
+
+The existing low-level `begin_optimistic_write` and `claim_next_mutation` methods may remain available internally and for focused tests. The browser and Tauri host paths must use the composite method.
+
+Do not change the `Storage` trait or any IndexedDB/SQLite queue schema in this phase.
+
+## 6. WASM boundary
+
+Primary files:
+
+- `crates/client/cache-wasm/src/shell.rs`
+- `apps/web/src/lib/graphql-cache/worker/wasm-module.ts`
+
+Replace the generated-facing `beginOptimisticWrite` method with `enqueueOptimisticMutation`. Add claim inputs:
+
+- `leaseOwner`
+- `nowMs`
+- `leaseExpiresAtMs`
+
+The WASM shell must:
+
+1. parse mutation and claim inputs;
+2. hold the engine mutex across the composite engine method;
+3. convert the nested claim outcome to the tagged JavaScript wire shape;
+4. serialize a claim error as a diagnostic string while still resolving the enqueue request successfully.
+
+Keep `claimNextMutation` for background drains.
+
+Run the actual wasm32 build; native `cargo test -p cache-wasm` alone does not exercise the generated WASM interface.
+
+## 7. Browser protocol and worker
+
+Primary files:
+
+- `apps/web/src/lib/graphql-cache/protocol.ts`
+- `apps/web/src/lib/graphql-cache/worker/worker-core.ts`
+- `apps/web/src/lib/graphql-cache/worker/wasm-module.ts`
+- `apps/web/src/lib/graphql-cache/worker/worker-core.test.ts`
+
+Replace the worker request variant:
+
+```text
+begin-optimistic-write
+```
+
+with:
+
+```text
+enqueue-optimistic-mutation
+```
+
+Include the initial claim request fields in the same message.
+
+Worker dispatch must:
+
+1. await `engine.enqueueOptimisticMutation(...)`;
+2. only after that resolves, call `fanOut(result, true)`;
+3. return the composite result to the requesting port.
+
+Because the claim attempt is complete before `fanOut`, affected reads may start immediately without blocking mutation routing.
+
+Update `requestPriority`:
+
+- `enqueue-optimistic-mutation` is `CACHE_WRITE_PRIORITY`;
+- standalone `claim-next-mutation` is also `CACHE_WRITE_PRIORITY` because it mutates the durable lease and must outrank observational reads.
+
+Keep FIFO behavior among requests with equal write priority. Do not make claim a lifecycle barrier.
+
+## 8. CacheHost implementations
+
+Primary files:
+
+- `apps/web/src/lib/graphql-cache/host/types.ts`
+- `apps/web/src/lib/graphql-cache/host/worker-host.ts`
+- `apps/web/src/lib/graphql-cache/host/tauri-host.ts`
+- `apps/web/src/lib/graphql-cache/host/noop-host.ts`
+- corresponding host tests
+
+Replace:
+
+```ts
+beginOptimisticWrite(args)
+```
+
+with an API such as:
+
+```ts
+enqueueOptimisticMutation(
+ args: EnqueueOptimisticMutationArgs,
+ claim: {
+ owner: string;
+ nowMs: number;
+ leaseExpiresAtMs: number;
+ }
+): Promise<EnqueueOptimisticMutationResult>;
+```
+
+The exchange should compute `nowMs` once and derive both the enqueue timestamp and lease expiration consistently. It is acceptable for transport adapters to continue adding `createdAtMs`, but tests should use deterministic times rather than multiple independent `Date.now()` calls.
+
+The no-op host remains disabled and throws if this operation is called, matching current optimistic behavior.
+
+## 9. Tauri native path
+
+Primary files:
+
+- `apps/web/tauri/graphql_cache_plugin/src/engine.rs`
+- `apps/web/tauri/graphql_cache_plugin/src/commands.rs`
+- `apps/web/tauri/graphql_cache_plugin/src/lib.rs`
+- `apps/web/tauri/graphql_cache_plugin/src/engine/test.rs`
+- `apps/web/tauri/src-tauri/src/lib.rs`
+- `apps/web/src/lib/graphql-cache/host/tauri-host.ts`
+- `apps/web/src/lib/graphql-cache/host/tauri-host.test.ts`
+
+Add/rename the Tauri command to:
+
+```text
+graphql_cache_enqueue_optimistic_mutation
+```
+
+The `EngineHandle` must hold its existing async mutex across enqueue and initial claim by calling the composite core method.
+
+The command must emit `ops-affected` and `cache-changed` only after the composite method returns, meaning the claim attempt has completed. It may emit events before returning the IPC response; this is safe once the durable claim no longer depends on another engine request.
+
+Update command registration in `apps/web/tauri/src-tauri/src/lib.rs` and exports/documentation in the plugin crate. Keep the standalone claim command registered for background draining.
+
+## 10. Exchange routing refactor
+
+Primary files:
+
+- `apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts`
+- `apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts`
+
+Extract the existing “route a claimed queue head” block from `drainQueue()` into one helper used by both:
+
+- `drainQueue()` for background claims;
+- `prepareMutation()` for the initial claim returned by enqueue.
+
+The helper must preserve current behavior:
+
+1. set `attemptInFlight = true`;
+2. create the `QueueAttemptContext`;
+3. if the claim matches a live operation, forward that exact operation with the queue-attempt context;
+4. otherwise reconstruct and replay the durable mutation through `client.mutation`;
+5. resolve every other live operation as queued;
+6. roll back a claim if replay construction throws;
+7. let settlement schedule the next drain.
+
+Suggested `prepareMutation()` flow:
+
+```text
+build optimistic args
+compute now and lease expiration
+enqueueOptimisticMutation(...)
+register the returned transaction id in liveQueuedOps
+switch initialClaim:
+ claimed -> route the claim immediately
+ not-runnable -> resolve new/live operations as queued; retain background drain
+ failed -> call onCacheError; resolve as queued; schedule background drain
+await/return the routed result
+```
+
+Do not call `scheduleDrain()` after a successful initial claim. The network settlement path already schedules the next queue drain.
+
+If the claimed id differs from the newly enqueued transaction id, replay the older head and resolve the new operation as queued.
+
+### Link-patch fallback
+
+Preserve the existing retry that removes link patches when a cached bin/page disappears before enqueue. The distinction between outer enqueue failure and nested initial-claim failure is critical:
+
+- outer enqueue failure may take the existing no-link-patch fallback path;
+- `initialClaim.kind === 'failed'` means enqueue succeeded and must never enqueue a duplicate or bypass the queue.
+
+## 11. Tests
+
+### Cache core
+
+Add focused tests for:
+
+1. Empty queue: enqueue returns a claim whose id equals the new transaction id.
+2. Older unclaimed head: enqueueing a new mutation claims the older strict head, not the new entry.
+3. Actively leased head: new layer is visible but initial claim is `NotRunnable`.
+4. Deferred head: later mutation is not skipped.
+5. Claim storage error after successful enqueue: result is `Failed`, and the mutation/layer remain durably queued exactly once.
+6. Existing commit, rollback, retry, hydration, and strict ordering behavior remains unchanged.
+
+Use a fault-injecting test `Storage` wrapper for the partial claim failure case; do not weaken production error handling to make the test easier.
+
+### Worker core
+
+Add tests proving:
+
+1. affected pushes are not emitted until the composite engine promise resolves;
+2. a queued user-visible read cannot run between enqueue and initial claim;
+3. standalone claim has write priority over queued observational reads;
+4. claimed/not-runnable/failed outcomes pass through unchanged;
+5. write FIFO and lifecycle barriers remain unchanged.
+
+### Browser worker host
+
+Assert the new request contains:
+
+- mutation data;
+- `owner`;
+- `nowMs`;
+- `leaseExpiresAtMs`;
+- the new request kind.
+
+Keep timeout semantics for this mutating request: do not add a read-style timeout that could cause an uncertain durable operation to be retried.
+
+### Tauri host/plugin
+
+Test:
+
+1. command argument and result casing;
+2. claim outcome serialization;
+3. events are emitted after the claim attempt;
+4. standalone drain command remains available;
+5. old strict queue tests still pass.
+
+### Exchange
+
+Cover at least:
+
+1. New mutation claims itself and the original live operation is forwarded without a standalone claim call.
+2. Returned claim belongs to an older transaction: older durable mutation is replayed; new caller receives `queued`.
+3. No runnable claim: new caller receives `queued`, no raw network request is made.
+4. Claim failure after enqueue: error is reported, caller receives `queued`, no duplicate enqueue and no raw network request.
+5. Two concurrent optimistic mutations preserve strict order and only one network attempt runs.
+6. Retryable failure/defer still blocks later mutations until eligible.
+7. Commit/rollback still advances the queue through standalone draining.
+8. Startup recovery still uses standalone `claimNextMutation`.
+9. Missing grouped link targets still take the existing no-link-patch fallback and retain revalidations.
+10. Affected query re-execution still occurs; it is reordered after the initial claim, not removed.
+
+## 12. Verification commands
+
+Run from the repository root in the project development environment:
+
+```bash
+cargo fmt --check
+cargo test -p cache-core -p cache-idb -p cache-sqlite -p cache-wasm
+just build-cache-wasm
+bun type-check
+```
+
+Run the focused frontend tests for:
+
+- `normalized-cache-exchange.test.ts`
+- `worker-core.test.ts`
+- `worker-host.test.ts`
+- `tauri-host.test.ts`
+- grouped optimistic property tests
+
+Then run the Tauri plugin tests using the established JS-app shell:
+
+```bash
+nix develop .#js-app --command cargo test \
+ --manifest-path apps/web/tauri/graphql_cache_plugin/Cargo.toml
+```
+
+Use the repository-required targeted service/package test commands rather than running database migrations. This change requires no SQLx migration and no SQLx query-cache update.
+
+After successful verification, follow repository policy:
+
+```bash
+jj desc -m "perf(cache): claim optimistic mutations before affected reads"
+jj new
+```
+
+## 13. Profiling acceptance criteria
+
+Capture another Firefox profile using the same repeated grouped-property interaction.
+
+Required observations:
+
+1. The initial durable claim completes before the first `ops-affected` cache read begins.
+2. `SetEntityProperty` network dispatch does not wait for the approximately 50 ms affected active-query `read_query`.
+3. There is no standalone `claim-next-mutation` RPC for a freshly enqueued mutation that returned an initial claim.
+4. Every network mutation still carries a valid queue-attempt context.
+5. IndexedDB work before network dispatch remains bounded; no unrelated record reads return.
+6. Optimistic grouped movement remains visible and initial/continuation/revalidation semantics are unchanged.
+7. Target the former 158–171 ms slow interactions to approach the existing approximately 30 ms fast path; as an environment-tolerant criterion, require network dispatch before the affected read completes and preferably under 100 ms click-to-request.
+
+## 14. Non-goals
+
+Do not include these in this change:
+
+- storage-level atomic enqueue-and-claim;
+- removal of standalone queue draining;
+- compact Rust-side grouped membership inspection;
+- optimization of full active-query denormalization or Rust-to-JS serialization;
+- closing the property editor before network completion;
+- changes to grouped paging, link-patch applicability, or revalidation policy;
+- database migrations.
+
+## 15. Architectural boundary check
+
+This work is cache-engine and adapter orchestration, not application authorization or business policy. `cache-core` owns durable mutation queue invariants; WASM/Tauri and worker hosts adapt that operation to their transports; the urql exchange decides how a returned claim is routed to the network. No inbound/domain/outbound service authorization boundary is changed.
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
index 6b92dff8af..cc552ddb1b 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
@@ -20,8 +20,8 @@ import {
import type { CacheHost } from '../host/types';
import type {
ClaimedMutation,
+ EnqueueOptimisticMutationResult,
MutationClaim,
- OptimisticWriteResult,
ReadResult,
WriteResult,
} from '../protocol';
@@ -144,7 +144,9 @@ type FakeHost = CacheHost & {
cacheActions: Array<{ kind: 'write' | 'delete'; value: unknown }>;
teardowns: number[];
scriptRead: (result: ReadResult) => void;
- seedQueued: (args: Parameters<CacheHost['beginOptimisticWrite']>[0]) => void;
+ seedQueued: (
+ args: Parameters<CacheHost['enqueueOptimisticMutation']>[0]
+ ) => void;
pushAffected: (opKeys: number[]) => void;
};
@@ -153,11 +155,35 @@ function makeFakeHost(): FakeHost {
const subscribers = new Set<(opKeys: number[]) => void>();
const queue: Array<{
transactionId: string;
- args: Parameters<CacheHost['beginOptimisticWrite']>[0];
+ args: Parameters<CacheHost['enqueueOptimisticMutation']>[0];
attemptCount: number;
leased: boolean;
nextAttemptAtMs?: number;
}> = [];
+
+ function claimQueueHead(nowMs: number): ClaimedMutation | undefined {
+ const head = queue[0];
+ if (
+ !head ||
+ head.leased ||
+ (head.nextAttemptAtMs !== undefined && head.nextAttemptAtMs > nowMs)
+ ) {
+ return undefined;
+ }
+ head.leased = true;
+ head.nextAttemptAtMs = undefined;
+ head.attemptCount += 1;
+ host.claims.push(head.transactionId);
+ return {
+ transactionId: head.transactionId,
+ leaseGeneration: String(head.attemptCount),
+ query: head.args.query,
+ operationName: head.args.operationName,
+ variables: head.args.variables ?? {},
+ attemptCount: head.attemptCount,
+ };
+ }
+
const host: FakeHost = {
clientId: 'test-client',
reads: [],
@@ -205,7 +231,10 @@ function makeFakeHost(): FakeHost {
host.cacheActions.push({ kind: 'write', value: args.data });
return { changed: [], affectedOps: [], reset: false };
},
- async beginOptimisticWrite(args): Promise<OptimisticWriteResult> {
+ async enqueueOptimisticMutation(
+ args,
+ claim
+ ): Promise<EnqueueOptimisticMutationResult> {
host.begins.push({
query: args.query,
data: args.data,
@@ -213,11 +242,15 @@ function makeFakeHost(): FakeHost {
});
const transactionId = `txn-${host.begins.length}`;
queue.push({ transactionId, args, attemptCount: 0, leased: false });
+ const mutation = claimQueueHead(claim.nowMs);
return {
transactionId,
changed: [],
affectedOps: [],
reset: false,
+ initialClaim: mutation
+ ? { kind: 'claimed', mutation }
+ : { kind: 'not-runnable' },
};
},
async inspectQueryVariants() {
@@ -230,26 +263,7 @@ function makeFakeHost(): FakeHost {
_owner,
nowMs
): Promise<ClaimedMutation | undefined> {
- const head = queue[0];
- if (
- !head ||
- head.leased ||
- (head.nextAttemptAtMs !== undefined && head.nextAttemptAtMs > nowMs)
- ) {
- return undefined;
- }
- head.leased = true;
- head.nextAttemptAtMs = undefined;
- head.attemptCount += 1;
- host.claims.push(head.transactionId);
- return {
- transactionId: head.transactionId,
- leaseGeneration: String(head.attemptCount),
- query: head.args.query,
- operationName: head.args.operationName,
- variables: head.args.variables ?? {},
- attemptCount: head.attemptCount,
- };
+ return claimQueueHead(nowMs);
},
async deferOptimisticWrite(
transactionId,
@@ -401,7 +415,7 @@ function harness(
...context,
} as never)
);
- return Promise.resolve(undefined);
+ return Promise.resolve({ error: undefined });
},
})),
} as unknown as Client;
@@ -890,6 +904,28 @@ describe('normalizedCacheExchange', () => {
expect(host.commits[0]?.transactionId).toBe('restored-1');
});
+ it('rolls back when a persisted replay resolves with an urql error', async () => {
+ host.seedQueued({
+ query: stringifyDocument(MUTATION),
+ operationName: 'SetEntityProperty',
+ variables: { input: {} },
+ data: optimistic,
+ });
+ const error = new CombinedError({
+ networkError: new Error('offline'),
+ });
+ const { client } = harness(host);
+ vi.mocked(client.mutation).mockImplementation(
+ () =>
+ ({
+ toPromise: () => Promise.resolve({ error }),
+ }) as never
+ );
+ await tick();
+
+ expect(host.rollbacks).toEqual(['restored-1']);
+ });
+
it('forwards optimistic mutations without cache work when the host is disabled', async () => {
const disabledHost: CacheHost = { ...host, disabled: true };
const { ops, forwarded } = harness(disabledHost);
@@ -903,11 +939,11 @@ describe('normalizedCacheExchange', () => {
it('installs the optimistic layer before forwarding to the network', async () => {
const { ops, results, forwarded } = harness(host);
- const begin = host.beginOptimisticWrite.bind(host);
- host.beginOptimisticWrite = async (args) => {
+ const enqueue = host.enqueueOptimisticMutation.bind(host);
+ host.enqueueOptimisticMutation = async (args, claim) => {
// The mutation must not have hit the network yet.
expect(forwarded).toHaveLength(0);
- return begin(args);
+ return enqueue(args, claim);
};
ops.next(makeMutationOp(1, optimistic));
await tick();
@@ -919,6 +955,73 @@ describe('normalizedCacheExchange', () => {
expect(results[0]?.data).toEqual({ from: 'network' });
});
+ it('replays an older returned claim and reports the new caller as queued', async () => {
+ host.seedQueued({
+ query: stringifyDocument(MUTATION),
+ operationName: 'SetEntityProperty',
+ variables: { input: { restored: true } },
+ data: optimistic,
+ });
+ const { ops, results, forwarded } = harness(host);
+
+ ops.next(makeMutationOp(2, optimistic));
+ await tick();
+
+ expect(host.claims[0]).toBe('restored-1');
+ expect(forwarded[0]?.kind).toBe('mutation');
+ const liveResult = results.find((result) => result.operation.key === 2);
+ expect(liveResult).toBeDefined();
+ expect(optimisticMutationDispositionOf(liveResult!)).toEqual({
+ kind: 'queued',
+ transactionId: 'txn-1',
+ });
+ });
+
+ it('keeps the new mutation queued when the initial head is not runnable', async () => {
+ const enqueue = host.enqueueOptimisticMutation.bind(host);
+ host.enqueueOptimisticMutation = async (args, claim) => ({
+ ...(await enqueue(args, claim)),
+ initialClaim: { kind: 'not-runnable' },
+ });
+ const { ops, results, forwarded } = harness(host);
+
+ ops.next(makeMutationOp(1, optimistic));
+ await tick();
+
+ expect(host.begins).toHaveLength(1);
+ expect(forwarded).toHaveLength(0);
+ expect(optimisticMutationDispositionOf(results[0])).toEqual({
+ kind: 'queued',
+ transactionId: 'txn-1',
+ });
+ });
+
+ it('reports a nested initial claim failure without bypassing or duplicating enqueue', async () => {
+ const enqueue = host.enqueueOptimisticMutation.bind(host);
+ host.enqueueOptimisticMutation = async (args, claim) => ({
+ ...(await enqueue(args, claim)),
+ initialClaim: { kind: 'failed', error: 'claim storage failed' },
+ });
+ const onCacheError = vi.fn();
+ const { ops, results, forwarded } = harness(host, undefined, {
+ onCacheError,
+ });
+
+ ops.next(makeMutationOp(1, optimistic));
+ await tick();
+
+ expect(host.begins).toHaveLength(1);
+ expect(forwarded).toHaveLength(0);
+ expect(onCacheError).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'claim storage failed' }),
+ expect.objectContaining({ key: 1 })
+ );
+ expect(optimisticMutationDispositionOf(results[0])).toEqual({
+ kind: 'queued',
+ transactionId: 'txn-1',
+ });
+ });
+
it('passes declarative link patches into the durable begin call', async () => {
const base = makeMutationOp(1, optimistic);
const patch = {
@@ -977,10 +1080,10 @@ describe('normalizedCacheExchange', () => {
revalidations: [],
},
});
- const begin = host.beginOptimisticWrite.bind(host);
- host.beginOptimisticWrite = async (args) => {
+ const enqueue = host.enqueueOptimisticMutation.bind(host);
+ host.enqueueOptimisticMutation = async (args, claim) => {
if (args.linkPatches?.length) throw new Error('stale bin');
- return begin(args);
+ return enqueue(args, claim);
};
const onCacheError = vi.fn();
const { ops } = harness(host, undefined, { onCacheError });
@@ -1416,7 +1519,7 @@ describe('normalizedCacheExchange', () => {
});
it('degrades to a plain network mutation when the optimistic setup fails', async () => {
- host.beginOptimisticWrite = async () => {
+ host.enqueueOptimisticMutation = async () => {
throw new Error('idb exploded');
};
const onCacheError = vi.fn();
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
index d273f7dc1e..ed3a8711c6 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
@@ -43,6 +43,7 @@ import {
type OperationDefinitionNode,
parse,
} from 'graphql';
+import { match } from 'ts-pattern';
import {
empty,
filter,
@@ -57,7 +58,11 @@ import {
tap,
} from 'wonka';
import type { CacheHost } from '../host/types';
-import type { OptimisticWriteResult, QueryRevalidationWire } from '../protocol';
+import type {
+ ClaimedMutation,
+ EnqueueOptimisticMutationResult,
+ QueryRevalidationWire,
+} from '../protocol';
import {
normalizedEntityKey,
optimisticContextOf,
@@ -364,6 +369,67 @@ export function normalizedCacheExchange(
}
}
+ /** Routes one already-leased strict queue head to the network. */
+ async function routeClaimedMutation(
+ claimed: ClaimedMutation
+ ): Promise<void> {
+ deferredUntil = undefined;
+ attemptInFlight = true;
+ const attempt: QueueAttemptContext = {
+ transactionId: claimed.transactionId,
+ leaseOwner: queueOwner,
+ leaseGeneration: claimed.leaseGeneration,
+ attemptCount: claimed.attemptCount,
+ };
+ const live = liveQueuedOps.get(claimed.transactionId);
+ if (live) {
+ liveQueuedOps.delete(claimed.transactionId);
+ live.resolveRoute(undefined);
+ enqueueForward(
+ withQueueRequestTimeout(
+ makeOperation(live.operation.kind, live.operation, {
+ ...live.operation.context,
+ [QUEUE_ATTEMPT_CONTEXT_KEY]: attempt,
+ })
+ )
+ );
+ } else {
+ try {
+ const replay = client.mutation(
+ replayDocument(claimed.query, claimed.operationName),
+ claimed.variables,
+ {
+ requestPolicy: 'network-only',
+ [QUEUE_ATTEMPT_CONTEXT_KEY]: attempt,
+ }
+ );
+ await replay.toPromise().then((result) => {
+ // Normal exchange results settle the attempt in writeThrough
+ // before resolving. Reject only an otherwise-unhandled error.
+ if (result.error && attemptInFlight) {
+ return Promise.reject(result.error);
+ }
+ });
+ } catch (error) {
+ try {
+ await host.rollbackOptimisticWrite(
+ claimed.transactionId,
+ {
+ owner: queueOwner,
+ generation: claimed.leaseGeneration,
+ },
+ error instanceof Error ? error.message : String(error)
+ );
+ } finally {
+ attemptInFlight = false;
+ scheduleDrain();
+ }
+ }
+ }
+ // Any other live operation is ordered behind the claimed head.
+ resolveLiveOperationsAsQueued();
+ }
+
async function drainQueue(): Promise<void> {
if (attemptInFlight) {
// Every newly enqueued operation is behind the claimed head. Its
@@ -390,52 +456,7 @@ export function normalizedCacheExchange(
return;
}
- deferredUntil = undefined;
- attemptInFlight = true;
- const attempt: QueueAttemptContext = {
- transactionId: claimed.transactionId,
- leaseOwner: queueOwner,
- leaseGeneration: claimed.leaseGeneration,
- attemptCount: claimed.attemptCount,
- };
- const live = liveQueuedOps.get(claimed.transactionId);
- if (live) {
- liveQueuedOps.delete(claimed.transactionId);
- live.resolveRoute(undefined);
- enqueueForward(
- withQueueRequestTimeout(
- makeOperation(live.operation.kind, live.operation, {
- ...live.operation.context,
- [QUEUE_ATTEMPT_CONTEXT_KEY]: attempt,
- })
- )
- );
- } else {
- try {
- const replay = client.mutation(
- replayDocument(claimed.query, claimed.operationName),
- claimed.variables,
- {
- requestPolicy: 'network-only',
- [QUEUE_ATTEMPT_CONTEXT_KEY]: attempt,
- }
- );
- void replay.toPromise();
- } catch (error) {
- await host.rollbackOptimisticWrite(
- claimed.transactionId,
- {
- owner: queueOwner,
- generation: claimed.leaseGeneration,
- },
- error instanceof Error ? error.message : String(error)
- );
- attemptInFlight = false;
- scheduleDrain();
- }
- }
- // Any other live operation is ordered behind the claimed head.
- resolveLiveOperationsAsQueued();
+ await routeClaimedMutation(claimed);
} catch {
// Enqueue already succeeded, so callers must observe these as
// queued even if the runner cannot currently inspect the head.
@@ -536,50 +557,84 @@ export function normalizedCacheExchange(
enqueueForward(op);
return undefined;
}
+ const args = {
+ query: queryText(op),
+ operationName: operationName(op),
+ variables: op.variables as Record<string, unknown> | undefined,
+ data: optimistic.optimisticResponse,
+ linkPatches: optimistic.linkPatches,
+ revalidations: optimistic.revalidations,
+ };
+ const now = Date.now();
+ const claim = {
+ owner: queueOwner,
+ nowMs: now,
+ leaseExpiresAtMs: now + QUEUE_LEASE_MS,
+ };
+ let enqueue: EnqueueOptimisticMutationResult;
try {
- const args = {
- query: queryText(op),
- operationName: operationName(op),
- variables: op.variables as Record<string, unknown> | undefined,
- data: optimistic.optimisticResponse,
- linkPatches: optimistic.linkPatches,
- revalidations: optimistic.revalidations,
- };
- let begin: OptimisticWriteResult;
- try {
- begin = await host.beginOptimisticWrite(args);
- } catch (error) {
- // A cached bin/page may disappear between inspect and begin. Do
- // not expose a partial relation move: retain entity optimism and
- // the post-success revalidation descriptors instead.
- if (args.linkPatches.length === 0) throw error;
+ enqueue = await host.enqueueOptimisticMutation(args, claim);
+ } catch (error) {
+ // A cached bin/page may disappear between inspect and enqueue. Do
+ // not expose a partial relation move: retain entity optimism and
+ // the post-success revalidation descriptors instead.
+ if (args.linkPatches.length === 0) {
options.onCacheError?.(error, op);
- begin = await host.beginOptimisticWrite({
- ...args,
- linkPatches: [],
- revalidations: [
- ...args.revalidations,
- ...args.linkPatches.map((patch) => ({
- query: patch.query,
- operationName: patch.operationName,
- variablesJson: patch.variablesJson,
- })),
- ],
- });
+ enqueueForward(op);
+ return undefined;
}
- const routed = new Promise<OperationResult | undefined>((resolve) => {
- liveQueuedOps.set(begin.transactionId, {
- operation: op,
- resolveRoute: resolve,
- });
+ options.onCacheError?.(error, op);
+ try {
+ enqueue = await host.enqueueOptimisticMutation(
+ {
+ ...args,
+ linkPatches: [],
+ revalidations: [
+ ...args.revalidations,
+ ...args.linkPatches.map((patch) => ({
+ query: patch.query,
+ operationName: patch.operationName,
+ variablesJson: patch.variablesJson,
+ })),
+ ],
+ },
+ claim
+ );
+ } catch (fallbackError) {
+ options.onCacheError?.(fallbackError, op);
+ enqueueForward(op);
+ return undefined;
+ }
+ }
+ const routed = new Promise<OperationResult | undefined>((resolve) => {
+ liveQueuedOps.set(enqueue.transactionId, {
+ operation: op,
+ resolveRoute: resolve,
});
- scheduleDrain();
- return await routed;
+ });
+ try {
+ await match(enqueue.initialClaim)
+ .with({ kind: 'claimed' }, ({ mutation }) =>
+ routeClaimedMutation(mutation)
+ )
+ .with({ kind: 'not-runnable' }, () => {
+ resolveLiveOperationsAsQueued();
+ scheduleDrain();
+ })
+ .with({ kind: 'failed' }, ({ error }) => {
+ options.onCacheError?.(new Error(error), op);
+ resolveLiveOperationsAsQueued();
+ scheduleDrain(EMPTY_QUEUE_POLL_MS);
+ })
+ .exhaustive();
} catch (error) {
+ // Enqueue already succeeded. Preserve durable-runner ownership even
+ // if routing or claim rollback fails unexpectedly.
options.onCacheError?.(error, op);
- enqueueForward(op);
- return undefined;
+ resolveLiveOperationsAsQueued();
+ scheduleDrain(EMPTY_QUEUE_POLL_MS);
}
+ return await routed;
}
/** Applies operation cache effects serially and isolates every failure. */
diff --git a/apps/web/src/lib/graphql-cache/host/noop-host.ts b/apps/web/src/lib/graphql-cache/host/noop-host.ts
index 8f14c1ea5b..c2013c4a68 100644
--- a/apps/web/src/lib/graphql-cache/host/noop-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/noop-host.ts
@@ -1,5 +1,5 @@
import {
- type OptimisticWriteResult,
+ type EnqueueOptimisticMutationResult,
type ReadRecordsArgs,
type ReadResult,
validateRecordSelectionLimit,
@@ -34,7 +34,7 @@ export function createNoopCacheHost(reason: string): CacheHost {
async writeQuery(): Promise<WriteResult> {
return emptyWriteResult();
},
- async beginOptimisticWrite(): Promise<OptimisticWriteResult> {
+ async enqueueOptimisticMutation(): Promise<EnqueueOptimisticMutationResult> {
throw new Error('normalized GraphQL cache is unavailable');
},
async inspectQueryVariants() {
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
index a1fd1d3c44..424c5a1f9b 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
@@ -124,9 +124,10 @@ describe('createTauriCacheHost', () => {
changed: ['A:1'],
affectedOps: [],
reset: false,
+ initialClaim: { kind: 'not-runnable' as const },
};
invokeMock.mockImplementation((command: string) => {
- if (command === 'graphql_cache_begin_optimistic_write') {
+ if (command === 'graphql_cache_enqueue_optimistic_mutation') {
return Promise.resolve(optimistic);
}
if (
@@ -149,15 +150,28 @@ describe('createTauriCacheHost', () => {
],
operation: { kind: 'remove' as const, entityKey: 'Thing:1' },
};
- const begun = await host.beginOptimisticWrite({
- query: 'mutation { m }',
- data: { m: 1 },
- linkPatches: [patch],
- });
+ const begun = await host.enqueueOptimisticMutation(
+ {
+ query: 'mutation { m }',
+ data: { m: 1 },
+ linkPatches: [patch],
+ },
+ {
+ owner: 'runner',
+ nowMs: 123,
+ leaseExpiresAtMs: 1_123,
+ }
+ );
expect(begun).toEqual(optimistic);
expect(invokeMock).toHaveBeenCalledWith(
- 'graphql_cache_begin_optimistic_write',
- expect.objectContaining({ linkPatches: [patch] })
+ 'graphql_cache_enqueue_optimistic_mutation',
+ expect.objectContaining({
+ linkPatches: [patch],
+ createdAtMs: 123,
+ owner: 'runner',
+ nowMs: 123,
+ leaseExpiresAtMs: 1_123,
+ })
);
const claim = { owner: 'runner', generation: '2' };
@@ -321,6 +335,42 @@ describe('createTauriCacheHost', () => {
}
});
+ it('does not time out an uncertain durable enqueue', async () => {
+ vi.useFakeTimers();
+ try {
+ invokeMock.mockImplementation((command: string) =>
+ command === 'graphql_cache_init'
+ ? Promise.resolve(null)
+ : new Promise(() => {})
+ );
+ const host = createTauriCacheHost({
+ scope: 'scope-1',
+ requestTimeoutMs: 50,
+ });
+
+ let settled = false;
+ void host
+ .enqueueOptimisticMutation(
+ { query: 'mutation Rename { rename { id } }', data: {} },
+ { owner: 'runner', nowMs: 10, leaseExpiresAtMs: 1_010 }
+ )
+ .then(
+ () => {
+ settled = true;
+ },
+ () => {
+ settled = true;
+ }
+ );
+ await vi.advanceTimersByTimeAsync(60);
+
+ expect(settled).toBe(false);
+ host.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('tolerates a failed listener setup (no unhandled rejection)', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
index d121f0c833..2a1704a1fc 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
@@ -13,9 +13,9 @@ import {
type CachedQueryInstanceWire,
type CachedQueryVariantWire,
type ClaimedMutation,
+ type EnqueueOptimisticMutationResult,
type MutationClaim,
type MutationSettlement,
- type OptimisticWriteResult,
type ReadRecordsArgs,
type ReadResult,
type SelectedRecordPageWire,
@@ -23,10 +23,11 @@ import {
type WriteResult,
} from '../protocol';
import type {
- BeginOptimisticWriteArgs,
CacheHost,
CacheReadArgs,
CacheWriteArgs,
+ EnqueueOptimisticMutationArgs,
+ InitialMutationClaimArgs,
InspectQueryArgs,
InspectQueryVariantsArgs,
} from './types';
@@ -50,8 +51,9 @@ export interface TauriHostOptions {
scope: string;
hotCapacity?: number;
/**
- * Per-request timeout in ms (default 10s, matching worker-host). A hung
- * IPC call rejects; the exchange degrades rejected reads to the network.
+ * Request timeout in ms (default 10s, matching worker-host). Applies to all
+ * commands except optimistic enqueue, which remains pending because retrying
+ * an uncertain durable operation could duplicate user intent.
*/
requestTimeoutMs?: number;
/** Reports an asynchronous durable-storage initialization failure. */
@@ -72,19 +74,22 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
function request<T>(
command: string,
- args: Record<string, unknown>
+ args: Record<string, unknown>,
+ timeout = true
): Promise<T> {
return new Promise<T>((resolve, reject) => {
- const timer = setTimeout(() => {
- reject(new Error(`graphql cache ipc timeout: ${command}`));
- }, requestTimeoutMs);
+ const timer = timeout
+ ? setTimeout(() => {
+ reject(new Error(`graphql cache ipc timeout: ${command}`));
+ }, requestTimeoutMs)
+ : undefined;
invoke<T>(command, args).then(
(value) => {
- clearTimeout(timer);
+ if (timer !== undefined) clearTimeout(timer);
resolve(value);
},
(error) => {
- clearTimeout(timer);
+ if (timer !== undefined) clearTimeout(timer);
// Command errors cross the boundary as strings; normalize to
// Error for parity with worker-host rejections.
reject(error instanceof Error ? error : new Error(String(error)));
@@ -180,12 +185,13 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
});
},
- async beginOptimisticWrite(
- args: BeginOptimisticWriteArgs
- ): Promise<OptimisticWriteResult> {
+ async enqueueOptimisticMutation(
+ args: EnqueueOptimisticMutationArgs,
+ claim: InitialMutationClaimArgs
+ ): Promise<EnqueueOptimisticMutationResult> {
await ready;
- return await request<OptimisticWriteResult>(
- 'graphql_cache_begin_optimistic_write',
+ return await request<EnqueueOptimisticMutationResult>(
+ 'graphql_cache_enqueue_optimistic_mutation',
{
originOpId: args.opKey === undefined ? undefined : opId(args.opKey),
query: args.query,
@@ -194,8 +200,12 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
data: args.data,
linkPatches: args.linkPatches,
revalidations: args.revalidations,
- createdAtMs: Date.now(),
- }
+ createdAtMs: claim.nowMs,
+ owner: claim.owner,
+ nowMs: claim.nowMs,
+ leaseExpiresAtMs: claim.leaseExpiresAtMs,
+ },
+ false
);
},
diff --git a/apps/web/src/lib/graphql-cache/host/types.ts b/apps/web/src/lib/graphql-cache/host/types.ts
index 6b0f0bd1be..9b105fba2e 100644
--- a/apps/web/src/lib/graphql-cache/host/types.ts
+++ b/apps/web/src/lib/graphql-cache/host/types.ts
@@ -10,10 +10,10 @@ import type {
CachedQueryVariantWire,
CacheReadPriority,
ClaimedMutation,
+ EnqueueOptimisticMutationResult,
MutationClaim,
MutationSettlement,
OptimisticLinkPatchWire,
- OptimisticWriteResult,
QueryRevalidationWire,
QueryVariableFilter,
ReadRecordsArgs,
@@ -53,12 +53,19 @@ export interface CacheWriteArgs extends Omit<CacheReadArgs, 'priority'> {
identity?: string;
}
-export interface BeginOptimisticWriteArgs extends CacheWriteArgs {
+export interface EnqueueOptimisticMutationArgs extends CacheWriteArgs {
linkPatches?: OptimisticLinkPatchWire[];
/** Revalidations for relevant cached fields that could not be patched. */
revalidations?: QueryRevalidationWire[];
}
+/** Lease request used for the claim attempted immediately after enqueue. */
+export interface InitialMutationClaimArgs {
+ owner: string;
+ nowMs: number;
+ leaseExpiresAtMs: number;
+}
+
export interface CacheHost {
/** Stable id of this context; used to namespace operation ids. */
readonly clientId: string;
@@ -69,10 +76,11 @@ export interface CacheHost {
/** Projects normalized records through a named GraphQL fragment. */
readRecords(args: ReadRecordsArgs): Promise<SelectedRecordPageWire>;
writeQuery(args: CacheWriteArgs): Promise<WriteResult>;
- /** Durably queues a mutation and its optimistic response. */
- beginOptimisticWrite(
- args: BeginOptimisticWriteArgs
- ): Promise<OptimisticWriteResult>;
+ /** Durably queues an optimistic mutation and claims the strict head. */
+ enqueueOptimisticMutation(
+ args: EnqueueOptimisticMutationArgs,
+ claim: InitialMutationClaimArgs
+ ): Promise<EnqueueOptimisticMutationResult>;
/** Recovers variables for cached variants without materializing values. */
inspectQueryVariants(
args: InspectQueryVariantsArgs
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts b/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
index f7d9854067..214769a25d 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
@@ -230,10 +230,17 @@ describe('createWorkerCacheHost', () => {
const readResult = expect(
host.readQuery({ query: 'query Read { user { id } }' })
).rejects.toThrow('cache worker timeout: read');
- const mutationResult = host.beginOptimisticWrite({
- query: 'mutation Rename { rename { id } }',
- data: { rename: { id: 'doc-1' } },
- });
+ const mutationResult = host.enqueueOptimisticMutation(
+ {
+ query: 'mutation Rename { rename { id } }',
+ data: { rename: { id: 'doc-1' } },
+ },
+ {
+ owner: 'runner-1',
+ nowMs: 123,
+ leaseExpiresAtMs: 1_123,
+ }
+ );
let mutationSettled = false;
void mutationResult.then(
() => {
@@ -248,11 +255,21 @@ describe('createWorkerCacheHost', () => {
await readResult;
expect(mutationSettled).toBe(false);
expect(
- requests.filter((request) => request.kind === 'begin-optimistic-write')
+ requests.filter(
+ (request) => request.kind === 'enqueue-optimistic-mutation'
+ )
).toHaveLength(1);
const mutationRequest = requests.find(
- (request) => request.kind === 'begin-optimistic-write'
+ (request) => request.kind === 'enqueue-optimistic-mutation'
+ );
+ expect(mutationRequest).toEqual(
+ expect.objectContaining({
+ owner: 'runner-1',
+ nowMs: 123,
+ createdAtMs: 123,
+ leaseExpiresAtMs: 1_123,
+ })
);
expect(mutationRequest?.id).toBeTypeOf('number');
const result = {
@@ -260,6 +277,7 @@ describe('createWorkerCacheHost', () => {
changed: [],
affectedOps: [],
reset: false,
+ initialClaim: { kind: 'not-runnable' as const },
};
respond(mutationRequest?.id as number, result);
await expect(mutationResult).resolves.toEqual(result);
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.ts b/apps/web/src/lib/graphql-cache/host/worker-host.ts
index ae5ba711ce..5df05f832c 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.ts
@@ -9,10 +9,10 @@ import {
type CacheNotice,
type CacheRequest,
type ClaimedMutation,
+ type EnqueueOptimisticMutationResult,
isCachePush,
type MutationClaim,
type MutationSettlement,
- type OptimisticWriteResult,
type ReadRecordsArgs,
type ReadResult,
type SelectedRecordPageWire,
@@ -22,10 +22,11 @@ import {
} from '../protocol';
import { createNoopCacheHost } from './noop-host';
import type {
- BeginOptimisticWriteArgs,
CacheHost,
CacheReadArgs,
CacheWriteArgs,
+ EnqueueOptimisticMutationArgs,
+ InitialMutationClaimArgs,
InspectQueryArgs,
InspectQueryVariantsArgs,
} from './types';
@@ -213,12 +214,13 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
})) as WriteResult;
},
- async beginOptimisticWrite(
- args: BeginOptimisticWriteArgs
- ): Promise<OptimisticWriteResult> {
+ async enqueueOptimisticMutation(
+ args: EnqueueOptimisticMutationArgs,
+ claim: InitialMutationClaimArgs
+ ): Promise<EnqueueOptimisticMutationResult> {
await ready;
return (await request({
- kind: 'begin-optimistic-write',
+ kind: 'enqueue-optimistic-mutation',
originOpId: args.opKey === undefined ? undefined : opId(args.opKey),
query: args.query,
operationName: args.operationName,
@@ -226,8 +228,11 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
data: args.data,
linkPatches: args.linkPatches,
revalidations: args.revalidations,
- createdAtMs: Date.now(),
- })) as OptimisticWriteResult;
+ createdAtMs: claim.nowMs,
+ owner: claim.owner,
+ nowMs: claim.nowMs,
+ leaseExpiresAtMs: claim.leaseExpiresAtMs,
+ })) as EnqueueOptimisticMutationResult;
},
async inspectQueryVariants(
diff --git a/apps/web/src/lib/graphql-cache/index.ts b/apps/web/src/lib/graphql-cache/index.ts
index f86e3fbbf6..d55ff9132d 100644
--- a/apps/web/src/lib/graphql-cache/index.ts
+++ b/apps/web/src/lib/graphql-cache/index.ts
@@ -48,6 +48,8 @@ export type {
CacheReadPriority,
CacheRequest,
CacheResponse,
+ EnqueueOptimisticMutationResult,
+ InitialMutationClaim,
MutationSettlement,
OptimisticWriteResult,
QueryVariableFilter,
diff --git a/apps/web/src/lib/graphql-cache/protocol.ts b/apps/web/src/lib/graphql-cache/protocol.ts
index 96f38638b7..4bbb2ffd4b 100644
--- a/apps/web/src/lib/graphql-cache/protocol.ts
+++ b/apps/web/src/lib/graphql-cache/protocol.ts
@@ -126,6 +126,17 @@ export type ClaimedMutation = {
attemptCount: number;
};
+/** Outcome of the strict-head claim attempted immediately after enqueue. */
+export type InitialMutationClaim =
+ | { kind: 'claimed'; mutation: ClaimedMutation }
+ | { kind: 'not-runnable' }
+ | { kind: 'failed'; error: string };
+
+/** Result returned after enqueue and the initial claim attempt complete. */
+export type EnqueueOptimisticMutationResult = OptimisticWriteResult & {
+ initialClaim: InitialMutationClaim;
+};
+
/** Identifies the queue attempt allowed to settle a transaction. */
export type MutationClaim = {
owner: string;
@@ -166,9 +177,9 @@ export type CacheRequest = { id: number } & (
*/
identity?: string;
}
- /** Durably enqueue a mutation together with its optimistic response. */
+ /** Durably enqueue an optimistic mutation and claim the strict head. */
| {
- kind: 'begin-optimistic-write';
+ kind: 'enqueue-optimistic-mutation';
originOpId?: string;
query: string;
operationName?: string;
@@ -177,6 +188,9 @@ export type CacheRequest = { id: number } & (
linkPatches?: OptimisticLinkPatchWire[];
revalidations?: QueryRevalidationWire[];
createdAtMs: number;
+ owner: string;
+ nowMs: number;
+ leaseExpiresAtMs: number;
}
| {
kind: 'claim-next-mutation';
diff --git a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
index 5325df8fdb..9d5fe6c30e 100644
--- a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
+++ b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
@@ -12,8 +12,8 @@ import type {
CachedQueryInstanceWire,
CachedQueryVariantWire,
ClaimedMutation,
+ EnqueueOptimisticMutationResult,
OptimisticLinkPatchWire,
- OptimisticWriteResult,
QueryRevalidationWire,
ReadResult,
RecordCursor,
@@ -43,7 +43,7 @@ export interface CacheEngine {
data: unknown,
identity: string | undefined
): Promise<WriteResult>;
- beginOptimisticWrite(
+ enqueueOptimisticMutation(
originOpId: string | undefined,
query: string,
operationName: string | undefined,
@@ -51,8 +51,11 @@ export interface CacheEngine {
data: unknown,
linkPatches: OptimisticLinkPatchWire[] | undefined,
revalidations: QueryRevalidationWire[] | undefined,
- createdAtMs: number
- ): Promise<OptimisticWriteResult>;
+ createdAtMs: number,
+ leaseOwner: string,
+ nowMs: number,
+ leaseExpiresAtMs: number
+ ): Promise<EnqueueOptimisticMutationResult>;
inspectQueryVariants(
query: string,
operationName: string | undefined,
diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts
index 83bdfa6d3d..dc0e67c73e 100644
--- a/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts
+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts
@@ -48,6 +48,162 @@ describe('CacheWorkerCore', () => {
expect(messages.at(-1)).toEqual({ id: 2, ok: true, result: page });
});
+ it('finishes the initial claim before pushes or queued reads run', async () => {
+ const order: string[] = [];
+ let resolveEnqueue!: (result: {
+ transactionId: string;
+ changed: string[];
+ affectedOps: string[];
+ reset: false;
+ initialClaim: { kind: 'not-runnable' };
+ }) => void;
+ const enqueueOptimisticMutation = vi.fn(() => {
+ order.push('enqueue:start');
+ return new Promise<{
+ transactionId: string;
+ changed: string[];
+ affectedOps: string[];
+ reset: false;
+ initialClaim: { kind: 'not-runnable' };
+ }>((resolve) => {
+ resolveEnqueue = (result) => {
+ order.push('enqueue:resolved');
+ resolve(result);
+ };
+ });
+ });
+ const readQuery = vi.fn(async () => {
+ order.push('read');
+ return { kind: 'miss' as const };
+ });
+ loadCacheWasmMock.mockResolvedValue({
+ openCache: vi.fn().mockResolvedValue({
+ enqueueOptimisticMutation,
+ readQuery,
+ }),
+ });
+ const messages: unknown[] = [];
+ const port = { postMessage: (message: unknown) => messages.push(message) };
+ const core = new CacheWorkerCore();
+ core.addPort(port);
+ await core.handleRequest(port, {
+ id: 1,
+ kind: 'init',
+ scope: 'scope-1',
+ });
+ messages.length = 0;
+
+ const enqueue = core.handleRequest(port, {
+ id: 2,
+ kind: 'enqueue-optimistic-mutation',
+ query: 'mutation Update { update }',
+ data: { update: true },
+ createdAtMs: 10,
+ owner: 'runner',
+ nowMs: 10,
+ leaseExpiresAtMs: 1_010,
+ });
+ await vi.waitFor(() =>
+ expect(enqueueOptimisticMutation).toHaveBeenCalled()
+ );
+ const read = core.handleRequest(port, {
+ id: 3,
+ kind: 'read',
+ opId: 'client:query',
+ query: 'query Read { value }',
+ priority: 'user-visible',
+ });
+
+ expect(readQuery).not.toHaveBeenCalled();
+ expect(messages).not.toContainEqual(
+ expect.objectContaining({
+ kind: 'ops-affected',
+ })
+ );
+ resolveEnqueue({
+ transactionId: '1',
+ changed: ['Thing:1'],
+ affectedOps: ['client:query'],
+ reset: false,
+ initialClaim: { kind: 'not-runnable' },
+ });
+ await Promise.all([enqueue, read]);
+
+ expect(order).toEqual(['enqueue:start', 'enqueue:resolved', 'read']);
+ expect(messages).toContainEqual({
+ kind: 'ops-affected',
+ opIds: ['client:query'],
+ keys: ['Thing:1'],
+ });
+ });
+
+ it('runs standalone claims ahead of queued observational reads', async () => {
+ const order: string[] = [];
+ let releaseBlocker!: () => void;
+ let markBlockerStarted!: () => void;
+ const blocker = new Promise<void>((resolve) => {
+ releaseBlocker = resolve;
+ });
+ const blockerStarted = new Promise<void>((resolve) => {
+ markBlockerStarted = resolve;
+ });
+ const readQuery = vi.fn(async (opId: string | undefined) => {
+ order.push(`read:${opId}`);
+ if (opId === 'client:blocker') {
+ markBlockerStarted();
+ await blocker;
+ }
+ return { kind: 'miss' as const };
+ });
+ const claimNextMutation = vi.fn(async () => {
+ order.push('claim');
+ return undefined;
+ });
+ loadCacheWasmMock.mockResolvedValue({
+ openCache: vi.fn().mockResolvedValue({
+ readQuery,
+ claimNextMutation,
+ }),
+ });
+ const port = { postMessage: vi.fn() };
+ const core = new CacheWorkerCore();
+ await core.handleRequest(port, {
+ id: 1,
+ kind: 'init',
+ scope: 'scope-1',
+ });
+
+ const running = core.handleRequest(port, {
+ id: 2,
+ kind: 'read',
+ opId: 'client:blocker',
+ query: 'query Blocker { blocker }',
+ });
+ await blockerStarted;
+ const read = core.handleRequest(port, {
+ id: 3,
+ kind: 'read',
+ opId: 'client:visible',
+ query: 'query Visible { visible }',
+ priority: 'user-visible',
+ });
+ const claim = core.handleRequest(port, {
+ id: 4,
+ kind: 'claim-next-mutation',
+ owner: 'runner',
+ nowMs: 10,
+ leaseExpiresAtMs: 1_010,
+ });
+
+ releaseBlocker();
+ await Promise.all([running, read, claim]);
+ expect(order).toEqual([
+ 'read:client:blocker',
+ 'claim',
+ 'read:client:visible',
+ ]);
+ });
+
it('coalesces queued affected rereads and runs them ahead of incidental reads', async () => {
const order: string[] = [];
let releaseBlocker!: () => void;
@@ -66,21 +222,22 @@ describe('CacheWorkerCore', () => {
}
return { kind: 'hit' as const, data: { opId } };
});
- const beginOptimisticWrite = vi.fn(
+ const enqueueOptimisticMutation = vi.fn(
async (_originOpId: string | undefined, query: string) => {
- order.push(`begin:${query}`);
+ order.push(`enqueue:${query}`);
return {
transactionId: query,
changed: [],
affectedOps: [],
reset: false,
+ initialClaim: { kind: 'not-runnable' as const },
};
}
);
loadCacheWasmMock.mockResolvedValue({
openCache: vi.fn().mockResolvedValue({
readQuery,
- beginOptimisticWrite,
+ enqueueOptimisticMutation,
}),
});
const messages: unknown[] = [];
@@ -112,19 +269,25 @@ describe('CacheWorkerCore', () => {
opId: 'client:child',
query: 'query Child { child }',
});
- const firstBegin = core.handleRequest(port, {
+ const firstEnqueue = core.handleRequest(port, {
id: 5,
- kind: 'begin-optimistic-write',
+ kind: 'enqueue-optimistic-mutation',
query: 'mutation First { first }',
data: { first: true },
createdAtMs: 1,
+ owner: 'runner',
+ nowMs: 1,
+ leaseExpiresAtMs: 1_001,
});
- const secondBegin = core.handleRequest(port, {
+ const secondEnqueue = core.handleRequest(port, {
id: 6,
- kind: 'begin-optimistic-write',
+ kind: 'enqueue-optimistic-mutation',
query: 'mutation Second { second }',
data: { second: true },
createdAtMs: 2,
+ owner: 'runner',
+ nowMs: 2,
+ leaseExpiresAtMs: 1_002,
});
const affectedDuplicate = core.handleRequest(port, {
id: 7,
@@ -140,15 +303,15 @@ describe('CacheWorkerCore', () => {
running,
ordinaryDuplicate,
incidental,
- firstBegin,
- secondBegin,
+ firstEnqueue,
+ secondEnqueue,
affectedDuplicate,
]);
expect(order).toEqual([
'read:client:blocker',
- 'begin:mutation First { first }',
- 'begin:mutation Second { second }',
+ 'enqueue:mutation First { first }',
+ 'enqueue:mutation Second { second }',
'read:client:group-soup',
'read:client:child',
]);
@@ -196,20 +359,21 @@ describe('CacheWorkerCore', () => {
const teardownOperation = vi.fn(async (opId: string) => {
order.push(`teardown:${opId}`);
});
- const beginOptimisticWrite = vi.fn(async () => {
- order.push('begin');
+ const enqueueOptimisticMutation = vi.fn(async () => {
+ order.push('enqueue');
return {
transactionId: '1',
changed: [],
affectedOps: [],
reset: false,
+ initialClaim: { kind: 'not-runnable' as const },
};
});
loadCacheWasmMock.mockResolvedValue({
openCache: vi.fn().mockResolvedValue({
readQuery,
teardownOperation,
- beginOptimisticWrite,
+ enqueueOptimisticMutation,
}),
});
const port = { postMessage: vi.fn() };
@@ -238,12 +402,15 @@ describe('CacheWorkerCore', () => {
kind: 'teardown',
opId: 'client:group-soup',
});
- const begin = core.handleRequest(port, {
+ const enqueue = core.handleRequest(port, {
id: 5,
- kind: 'begin-optimistic-write',
+ kind: 'enqueue-optimistic-mutation',
query: 'mutation Update { update }',
data: { update: true },
createdAtMs: 1,
+ owner: 'runner',
+ nowMs: 1,
+ leaseExpiresAtMs: 1_001,
});
const readAfterTeardown = core.handleRequest(port, {
id: 6,
@@ -258,7 +425,7 @@ describe('CacheWorkerCore', () => {
running,
readBeforeTeardown,
teardown,
- begin,
+ enqueue,
readAfterTeardown,
]);
@@ -266,7 +433,7 @@ describe('CacheWorkerCore', () => {
'read:client:blocker',
'read:client:group-soup',
'teardown:client:group-soup',
- 'begin',
+ 'enqueue',
'read:client:group-soup',
]);
expect(
diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
index 057e402d58..382b16e2a3 100644
--- a/apps/web/src/lib/graphql-cache/worker/worker-core.ts
+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
@@ -8,7 +8,7 @@ import type {
CachePush,
CacheRequest,
CacheResponse,
- OptimisticWriteResult,
+ EnqueueOptimisticMutationResult,
ReadResult,
SelectedRecordPageWire,
WriteResult,
@@ -52,7 +52,8 @@ function requestPriority(request: CacheRequest): number {
}
if (
request.kind === 'write' ||
- request.kind === 'begin-optimistic-write' ||
+ request.kind === 'enqueue-optimistic-mutation' ||
+ request.kind === 'claim-next-mutation' ||
request.kind === 'commit-optimistic-write' ||
request.kind === 'rollback-optimistic-write' ||
request.kind === 'invalidate' ||
@@ -223,18 +224,22 @@ export class CacheWorkerCore {
this.fanOut(result, true);
return result;
})
- .with({ kind: 'begin-optimistic-write' }, async (request) => {
+ .with({ kind: 'enqueue-optimistic-mutation' }, async (request) => {
const engine = this.requireEngine();
- const result: OptimisticWriteResult = await engine.beginOptimisticWrite(
- request.originOpId,
- request.query,
- request.operationName,
- request.variables,
- request.data,
- request.linkPatches,
- request.revalidations,
- request.createdAtMs
- );
+ const result: EnqueueOptimisticMutationResult =
+ await engine.enqueueOptimisticMutation(
+ request.originOpId,
+ request.query,
+ request.operationName,
+ request.variables,
+ request.data,
+ request.linkPatches,
+ request.revalidations,
+ request.createdAtMs,
+ request.owner,
+ request.nowMs,
+ request.leaseExpiresAtMs
+ );
this.fanOut(result, true);
return result;
})
diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands.rs b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
index a43b83d276..8962ae2e46 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/commands.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
@@ -10,7 +10,8 @@
//! worker's `{ok: false, error}` responses.
use crate::engine::{
- ClaimedMutationWire, EngineHandle, OptimisticWriteResultWire, ReadResultWire, WriteResultWire,
+ ClaimedMutationWire, EngineHandle, EnqueueOptimisticMutationResultWire, ReadResultWire,
+ WriteResultWire,
};
use crate::{
CacheState, InitializedCache, emit_cache_changed, emit_mutation_settled, emit_ops_affected,
@@ -136,10 +137,11 @@ pub async fn graphql_cache_write<R: Runtime>(
Ok(result)
}
-/// Durably queues a mutation and its optimistic response. The one engine is
-/// shared by all webviews, so visible changes are broadcast too.
+/// Durably queues an optimistic mutation and attempts to claim the strict
+/// queue head before broadcasting visible changes to every webview.
#[tauri::command]
-pub async fn graphql_cache_begin_optimistic_write<R: Runtime>(
+#[allow(clippy::too_many_arguments)]
+pub async fn graphql_cache_enqueue_optimistic_mutation<R: Runtime>(
app: AppHandle<R>,
state: State<'_, CacheState>,
origin_op_id: Option<String>,
@@ -150,9 +152,12 @@ pub async fn graphql_cache_begin_optimistic_write<R: Runtime>(
link_patches: Option<Vec<OptimisticLinkPatch>>,
revalidations: Option<Vec<QueryRevalidation>>,
created_at_ms: i64,
-) -> Result<OptimisticWriteResultWire, String> {
+ owner: String,
+ now_ms: i64,
+ lease_expires_at_ms: i64,
+) -> Result<EnqueueOptimisticMutationResultWire, String> {
let result = engine_handle(&state)?
- .begin_optimistic_write(
+ .enqueue_optimistic_mutation(
origin_op_id,
query,
operation_name,
@@ -161,6 +166,9 @@ pub async fn graphql_cache_begin_optimistic_write<R: Runtime>(
link_patches.unwrap_or_default(),
revalidations.unwrap_or_default(),
created_at_ms,
+ owner,
+ now_ms,
+ lease_expires_at_ms,
)
.await?;
emit_ops_affected(&app, &result.result.affected_ops, &result.result.changed);
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine.rs b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
index 3ab36e63d8..2da2000171 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
@@ -12,7 +12,9 @@
//! internally — the same scheme as the `cache-wasm` shell.
use cache_core::deps::OpId;
-use cache_core::engine::{BeginOptimisticWrite, Engine, ReadResult, WriteResult};
+use cache_core::engine::{
+ BeginOptimisticWrite, Engine, InitialClaimOutcome, ReadResult, WriteResult,
+};
use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};
use cache_core::query_inspection::{CachedQueryInstance, CachedQueryVariant, QueryInspection};
use cache_core::queue::{ClaimedMutation, MutationClaimRequest, MutationClaimToken};
@@ -52,17 +54,37 @@ pub struct WriteResultWire {
pub revalidations: Vec<QueryRevalidation>,
}
-/// Mirrors `OptimisticWriteResult` in
-/// `apps/web/src/lib/graphql-cache/protocol.ts`.
+/// Result of durably enqueueing an optimistic mutation and attempting to
+/// claim the strict queue head.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct OptimisticWriteResultWire {
+pub struct EnqueueOptimisticMutationResultWire {
/// Engine-assigned id; settle with commit/rollback. A string because JS
/// numbers lose precision past 2^53 (same as the wasm shell).
pub transaction_id: String,
- /// Visible (composed-view) changes — nothing is durable until commit.
+ /// Visible composed-view changes caused by the new optimistic layer.
#[serde(flatten)]
pub result: WriteResultWire,
+ /// Claim outcome determined before cache-change events are emitted.
+ pub initial_claim: InitialMutationClaimWire,
+}
+
+/// Tagged outcome of the initial strict-head claim attempt.
+#[derive(Debug, Serialize)]
+#[serde(tag = "kind", rename_all = "kebab-case")]
+pub enum InitialMutationClaimWire {
+ /// The strict queue head was durably leased.
+ Claimed {
+ /// Mutation request and lease metadata for the claimed head.
+ mutation: ClaimedMutationWire,
+ },
+ /// The queue head is currently leased, deferred, or absent.
+ NotRunnable,
+ /// Enqueue succeeded, but the claim attempt failed.
+ Failed {
+ /// Diagnostic claim error.
+ error: String,
+ },
}
/// Claimed queue head returned to the JavaScript mutation runner.
@@ -300,8 +322,10 @@ impl EngineHandle {
.map_err(|e| e.to_string())
}
- /// Durably queues a mutation and its optimistic layer.
- pub async fn begin_optimistic_write(
+ /// Durably queues a mutation and its optimistic layer, then attempts to
+ /// claim the strict queue head while retaining the same engine lock.
+ #[allow(clippy::too_many_arguments)]
+ pub async fn enqueue_optimistic_mutation(
&self,
origin_op_id: Option<String>,
query: String,
@@ -311,12 +335,15 @@ impl EngineHandle {
link_patches: Vec<OptimisticLinkPatch>,
revalidations: Vec<QueryRevalidation>,
created_at_ms: i64,
- ) -> Result<OptimisticWriteResultWire, String> {
+ lease_owner: String,
+ now_ms: i64,
+ lease_expires_at_ms: i64,
+ ) -> Result<EnqueueOptimisticMutationResultWire, String> {
let mut state = self.inner.lock().await;
let EngineState { engine, ops } = &mut *state;
let origin = origin_op_id.map(|name| ops.intern(&name));
- engine
- .begin_optimistic_write(
+ let result = engine
+ .enqueue_optimistic_mutation(
origin,
BeginOptimisticWrite {
query: &query,
@@ -327,13 +354,28 @@ impl EngineHandle {
revalidations: &revalidations,
created_at_ms,
},
+ MutationClaimRequest {
+ owner: lease_owner,
+ now_ms,
+ lease_expires_at_ms,
+ },
)
.await
- .map(|(transaction, result)| OptimisticWriteResultWire {
- transaction_id: transaction.to_string(),
- result: wire_write_result(ops, result),
- })
- .map_err(|e| e.to_string())
+ .map_err(|error| error.to_string())?;
+ let initial_claim = match result.initial_claim {
+ InitialClaimOutcome::Claimed(claimed) => InitialMutationClaimWire::Claimed {
+ mutation: ClaimedMutationWire::try_from(*claimed)?,
+ },
+ InitialClaimOutcome::NotRunnable => InitialMutationClaimWire::NotRunnable,
+ InitialClaimOutcome::Failed(error) => InitialMutationClaimWire::Failed {
+ error: error.to_string(),
+ },
+ };
+ Ok(EnqueueOptimisticMutationResultWire {
+ transaction_id: result.transaction_id.to_string(),
+ result: wire_write_result(ops, result.write_result),
+ initial_claim,
+ })
}
/// Claims the strict mutation queue head when it is runnable.
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
index 5a2734eeda..f9674dd0b2 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
@@ -56,12 +56,6 @@ fn read(handle: &EngineHandle, op_id: Option<&str>) -> ReadResultWire {
.unwrap()
}
-fn claim(handle: &EngineHandle) -> ClaimedMutationWire {
- block_on(handle.claim_next_mutation("runner".to_string(), 10, 1_000))
- .unwrap()
- .expect("queue head")
-}
-
#[test]
fn write_then_read_round_trips() {
let handle = spawn_handle();
@@ -222,7 +216,7 @@ fn optimistic_layer_commits_durably() {
write(&handle, None, soup_data(false), None);
read(&handle, Some("client:1"));
- let optimistic = block_on(handle.begin_optimistic_write(
+ let optimistic = block_on(handle.enqueue_optimistic_mutation(
Some("client:2".to_string()),
QUERY.to_string(),
Some("Soup".to_string()),
@@ -231,9 +225,22 @@ fn optimistic_layer_commits_durably() {
vec![],
vec![],
0,
+ "runner".to_string(),
+ 10,
+ 1_000,
))
.unwrap();
assert_eq!(optimistic.result.affected_ops, vec!["client:1".to_string()]);
+ let serialized = serde_json::to_value(&optimistic).unwrap();
+ assert_eq!(serialized["initialClaim"]["kind"], "claimed");
+ assert_eq!(
+ serialized["initialClaim"]["mutation"]["transactionId"],
+ optimistic.transaction_id
+ );
+ let InitialMutationClaimWire::Claimed { mutation: claimed } = optimistic.initial_claim else {
+ panic!("new queue head should be claimed")
+ };
+ assert_eq!(claimed.transaction_id, optimistic.transaction_id);
// The optimistic view answers reads.
let ReadResultWire::Hit { data } = read(&handle, None) else {
@@ -241,7 +248,6 @@ fn optimistic_layer_commits_durably() {
};
assert_eq!(data, soup_data(true));
- let claimed = claim(&handle);
let committed = block_on(handle.commit_optimistic_write(
optimistic.transaction_id,
"runner".to_string(),
@@ -265,7 +271,7 @@ fn rollback_drops_optimistic_contribution() {
let handle = spawn_handle();
write(&handle, None, soup_data(false), None);
- let optimistic = block_on(handle.begin_optimistic_write(
+ let optimistic = block_on(handle.enqueue_optimistic_mutation(
None,
QUERY.to_string(),
Some("Soup".to_string()),
@@ -274,10 +280,15 @@ fn rollback_drops_optimistic_contribution() {
vec![],
vec![],
0,
+ "runner".to_string(),
+ 10,
+ 1_000,
))
.unwrap();
+ let InitialMutationClaimWire::Claimed { mutation: claimed } = optimistic.initial_claim else {
+ panic!("new queue head should be claimed")
+ };
- let claimed = claim(&handle);
block_on(handle.rollback_optimistic_write(
optimistic.transaction_id,
"runner".to_string(),
diff --git a/apps/web/tauri/graphql_cache_plugin/src/lib.rs b/apps/web/tauri/graphql_cache_plugin/src/lib.rs
index 36aff9f68c..953d265784 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/lib.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/lib.rs
@@ -23,7 +23,8 @@ pub mod commands;
mod engine;
pub use engine::{
- ClaimedMutationWire, EngineHandle, OptimisticWriteResultWire, ReadResultWire, WriteResultWire,
+ ClaimedMutationWire, EngineHandle, EnqueueOptimisticMutationResultWire,
+ InitialMutationClaimWire, ReadResultWire, WriteResultWire,
};
/// Broadcast event carrying [`OpsAffectedEvent`]: operations whose
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index 16bc5ed851..bb4ed1f7e9 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -246,7 +246,7 @@ pub fn run() {
graphql_cache_plugin::commands::graphql_cache_read,
graphql_cache_plugin::commands::graphql_cache_read_records,
graphql_cache_plugin::commands::graphql_cache_write,
- graphql_cache_plugin::commands::graphql_cache_begin_optimistic_write,
+ graphql_cache_plugin::commands::graphql_cache_enqueue_optimistic_mutation,
graphql_cache_plugin::commands::graphql_cache_inspect_query_variants,
graphql_cache_plugin::commands::graphql_cache_inspect_query,
graphql_cache_plugin::commands::graphql_cache_claim_next_mutation,
diff --git a/crates/client/cache-core/src/engine.rs b/crates/client/cache-core/src/engine.rs
index f42e6b3cda..1dce7dd423 100644
--- a/crates/client/cache-core/src/engine.rs
+++ b/crates/client/cache-core/src/engine.rs
@@ -87,6 +87,29 @@ pub struct WriteResult {
pub revalidations: Vec<QueryRevalidation>,
}
+/// Outcome of the initial strict-head claim attempted after enqueue.
+#[derive(Debug)]
+pub enum InitialClaimOutcome<E> {
+ /// The strict queue head was runnable and is now durably leased.
+ Claimed(Box<ClaimedMutation>),
+ /// The strict queue head is leased, deferred, or the queue is empty.
+ NotRunnable,
+ /// Enqueue succeeded, but attempting to claim the strict head failed.
+ Failed(E),
+}
+
+/// Result of durably enqueueing an optimistic mutation and attempting its
+/// initial strict-head claim.
+#[derive(Debug)]
+pub struct EnqueueOptimisticMutationResult<E> {
+ /// Engine-assigned id of the newly enqueued optimistic mutation.
+ pub transaction_id: OptimisticTransactionId,
+ /// Visible cache changes caused by the newly published optimistic layer.
+ pub write_result: WriteResult,
+ /// Outcome of the claim attempt made before hosts publish cache changes.
+ pub initial_claim: InitialClaimOutcome<E>,
+}
+
/// Borrowed inputs for atomically beginning one optimistic mutation.
pub struct BeginOptimisticWrite<'a> {
/// GraphQL mutation document.
@@ -877,6 +900,29 @@ impl<S: Storage> Engine<S> {
))
}
+ /// Durably enqueues a mutation and publishes its optimistic layer, then
+ /// attempts to claim the strict queue head before returning. A claim
+ /// failure is nested in the successful enqueue result so callers never
+ /// bypass or duplicate an already durable mutation.
+ pub async fn enqueue_optimistic_mutation(
+ &mut self,
+ origin_op: Option<OpId>,
+ input: BeginOptimisticWrite<'_>,
+ claim: MutationClaimRequest,
+ ) -> Result<EnqueueOptimisticMutationResult<EngineError<S::Error>>, EngineError<S::Error>> {
+ let (transaction_id, write_result) = self.begin_optimistic_write(origin_op, input).await?;
+ let initial_claim = match self.claim_next_mutation(claim).await {
+ Ok(Some(claimed)) => InitialClaimOutcome::Claimed(Box::new(claimed)),
+ Ok(None) => InitialClaimOutcome::NotRunnable,
+ Err(error) => InitialClaimOutcome::Failed(error),
+ };
+ Ok(EnqueueOptimisticMutationResult {
+ transaction_id,
+ write_result,
+ initial_claim,
+ })
+ }
+
/// Claims the oldest runnable mutation. A leased or backed-off head
/// blocks every later mutation.
pub async fn claim_next_mutation(
diff --git a/crates/client/cache-core/tests/optimistic.rs b/crates/client/cache-core/tests/optimistic.rs
index 65e538571b..0463f95371 100644
--- a/crates/client/cache-core/tests/optimistic.rs
+++ b/crates/client/cache-core/tests/optimistic.rs
@@ -1,10 +1,15 @@
//! Durable optimistic mutation tests: enqueue/read/claim/retry/commit/fail,
//! strict ordering, and lifecycle resets.
-use cache_core::engine::{BeginOptimisticWrite, Engine, EngineError, ReadResult};
-use cache_core::queue::{MutationClaimRequest, MutationClaimToken};
+use cache_core::engine::{
+ BeginOptimisticWrite, Engine, EngineError, InitialClaimOutcome, ReadResult,
+};
+use cache_core::queue::{
+ ClaimedMutation, MutationClaimRequest, MutationClaimToken, MutationId, NewQueuedMutation,
+ QueuedMutation,
+};
use cache_core::store::{InMemoryStorage, Storage};
-use cache_core::value::{CacheValue, EntityKey};
+use cache_core::value::{CacheValue, EntityKey, Record};
use pollster::block_on;
use serde_json::{Value as Json, json};
@@ -48,6 +53,119 @@ mutation SetEntityProperty($input: SetEntityPropertyInput!) {
const PROPERTY_KEY: &str = "GraphqlProperty:prop-1";
+#[derive(Debug, Default)]
+struct ClaimFailingStorage {
+ inner: InMemoryStorage,
+ fail_next_claim: bool,
+}
+
+impl ClaimFailingStorage {
+ fn new() -> Self {
+ Self {
+ inner: InMemoryStorage::new(),
+ fail_next_claim: true,
+ }
+ }
+}
+
+impl Storage for ClaimFailingStorage {
+ type Error = std::io::Error;
+
+ async fn get_batch(
+ &self,
+ keys: &[EntityKey<'static>],
+ ) -> Result<Vec<Option<Record>>, Self::Error> {
+ Ok(self.inner.get_batch(keys).await.unwrap())
+ }
+
+ async fn put_batch(
+ &mut self,
+ entries: Vec<(EntityKey<'static>, Record)>,
+ ) -> Result<(), Self::Error> {
+ self.inner.put_batch(entries).await.unwrap();
+ Ok(())
+ }
+
+ async fn delete_batch(&mut self, keys: &[EntityKey<'static>]) -> Result<(), Self::Error> {
+ self.inner.delete_batch(keys).await.unwrap();
+ Ok(())
+ }
+
+ async fn scan_records(
+ &self,
+ type_names: &[String],
+ after: Option<&EntityKey<'static>>,
+ limit: usize,
+ ) -> Result<Vec<(EntityKey<'static>, Record)>, Self::Error> {
+ Ok(self
+ .inner
+ .scan_records(type_names, after, limit)
+ .await
+ .unwrap())
+ }
+
+ async fn enqueue_mutation(
+ &mut self,
+ entry: NewQueuedMutation,
+ ) -> Result<MutationId, Self::Error> {
+ Ok(self.inner.enqueue_mutation(entry).await.unwrap())
+ }
+
+ async fn load_mutation_queue(&self) -> Result<Vec<QueuedMutation>, Self::Error> {
+ Ok(self.inner.load_mutation_queue().await.unwrap())
+ }
+
+ async fn claim_next_mutation(
+ &mut self,
+ request: MutationClaimRequest,
+ ) -> Result<Option<ClaimedMutation>, Self::Error> {
+ if std::mem::take(&mut self.fail_next_claim) {
+ return Err(std::io::Error::other("injected claim failure"));
+ }
+ Ok(self.inner.claim_next_mutation(request).await.unwrap())
+ }
+
+ async fn defer_mutation(
+ &mut self,
+ id: MutationId,
+ claim: MutationClaimToken,
+ next_attempt_at_ms: i64,
+ error: String,
+ ) -> Result<bool, Self::Error> {
+ Ok(self
+ .inner
+ .defer_mutation(id, claim, next_attempt_at_ms, error)
+ .await
+ .unwrap())
+ }
+
+ async fn complete_mutation(
+ &mut self,
+ id: MutationId,
+ claim: MutationClaimToken,
+ entries: Vec<(EntityKey<'static>, Record)>,
+ ) -> Result<bool, Self::Error> {
+ Ok(self
+ .inner
+ .complete_mutation(id, claim, entries)
+ .await
+ .unwrap())
+ }
+
+ async fn discard_mutation(
+ &mut self,
+ id: MutationId,
+ claim: MutationClaimToken,
+ ) -> Result<bool, Self::Error> {
+ Ok(self.inner.discard_mutation(id, claim).await.unwrap())
+ }
+
+ async fn clear(&mut self) -> Result<(), Self::Error> {
+ self.inner.clear().await.unwrap();
+ Ok(())
+ }
+}
+
fn query_vars() -> serde_json::Map<String, Json> {
let Json::Object(map) = json!({ "input": { "limit": 10 } }) else {
unreachable!()
@@ -213,6 +331,208 @@ fn begin_persists_mutation_and_optimistic_layer() {
});
}
+#[test]
+fn enqueue_claims_new_mutation_when_queue_was_empty() {
+ block_on(async {
+ let mut engine = engine_with_base("Status", "todo").await;
+ let result = engine
+ .enqueue_optimistic_mutation(
+ None,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("doing"),
+ data: &mutation_response("Status", "doing"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 123,
+ },
+ MutationClaimRequest {
+ owner: "runner".into(),
+ now_ms: 123,
+ lease_expires_at_ms: 1_123,
+ },
+ )
+ .await
+ .unwrap();
+
+ let InitialClaimOutcome::Claimed(claimed) = result.initial_claim else {
+ panic!("new strict queue head should be claimed")
+ };
+ assert_eq!(claimed.queued.id, result.transaction_id);
+ assert_eq!(claimed.queued.mutation.attempt_count, 1);
+ });
+}
+
+#[test]
+fn enqueue_claims_older_strict_head() {
+ block_on(async {
+ let mut engine = engine_with_base("Status", "todo").await;
+ let (older, _) = engine
+ .begin_optimistic_write(
+ None,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("older"),
+ data: &mutation_response("Status", "older"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 1,
+ },
+ )
+ .await
+ .unwrap();
+ let result = engine
+ .enqueue_optimistic_mutation(
+ None,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("new"),
+ data: &mutation_response("Status", "new"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 2,
+ },
+ MutationClaimRequest {
+ owner: "runner".into(),
+ now_ms: 10,
+ lease_expires_at_ms: 1_010,
+ },
+ )
+ .await
+ .unwrap();
+
+ assert!(older < result.transaction_id);
+ let InitialClaimOutcome::Claimed(claimed) = result.initial_claim else {
+ panic!("older strict queue head should be claimed")
+ };
+ assert_eq!(claimed.queued.id, older);
+ });
+}
+
+#[test]
+fn enqueue_does_not_skip_a_leased_or_deferred_head() {
+ block_on(async {
+ for deferred in [false, true] {
+ let mut engine = engine_with_base("Status", "todo").await;
+ let (older, _) = engine
+ .begin_optimistic_write(
+ None,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("older"),
+ data: &mutation_response("Status", "older"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 1,
+ },
+ )
+ .await
+ .unwrap();
+ let (_, claim) = claim_head(&mut engine, "first-runner", 10).await;
+ if deferred {
+ engine
+ .defer_optimistic_write(older, claim, 500, "offline".into())
+ .await
+ .unwrap();
+ }
+
+ let result = engine
+ .enqueue_optimistic_mutation(
+ None,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("new"),
+ data: &mutation_response("Status", "new"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 20,
+ },
+ MutationClaimRequest {
+ owner: "second-runner".into(),
+ now_ms: 20,
+ lease_expires_at_ms: 1_020,
+ },
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ result.initial_claim,
+ InitialClaimOutcome::NotRunnable
+ ));
+ assert_eq!(
+ engine.storage().load_mutation_queue().await.unwrap().len(),
+ 2
+ );
+ let data = read_hit(&mut engine, None).await;
+ assert_eq!(property_of(&data)["value"]["stringValue"], json!("new"));
+ }
+ });
+}
+
+#[test]
+fn claim_failure_after_enqueue_preserves_one_durable_visible_mutation() {
+ block_on(async {
+ let mut engine = Engine::new(ClaimFailingStorage::new());
+ engine
+ .write_query(
+ None,
+ QUERY,
+ Some("Soup"),
+ &query_vars(),
+ &soup_page("Status", "todo"),
+ None,
+ )
+ .await
+ .unwrap();
+
+ let result = engine
+ .enqueue_optimistic_mutation(
+ None,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("doing"),
+ data: &mutation_response("Status", "doing"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 123,
+ },
+ MutationClaimRequest {
+ owner: "runner".into(),
+ now_ms: 123,
+ lease_expires_at_ms: 1_123,
+ },
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ result.initial_claim,
+ InitialClaimOutcome::Failed(EngineError::Storage(ref error))
+ if error.to_string() == "injected claim failure"
+ ));
+ let queued = engine.storage().load_mutation_queue().await.unwrap();
+ assert_eq!(queued.len(), 1);
+ assert_eq!(queued[0].id, result.transaction_id);
+ assert_eq!(queued[0].mutation.attempt_count, 0);
+ let data = match engine
+ .read_query(None, QUERY, Some("Soup"), &query_vars())
+ .await
+ .unwrap()
+ {
+ ReadResult::Hit { data } => data,
+ ReadResult::Miss => panic!("expected optimistic hit"),
+ };
+ assert_eq!(property_of(&data)["value"]["stringValue"], json!("doing"));
+ });
+}
+
#[test]
fn claimed_success_atomically_commits_real_response() {
block_on(async {
diff --git a/crates/client/cache-wasm/src/shell.rs b/crates/client/cache-wasm/src/shell.rs
index d0b6b0af8e..d60463e810 100644
--- a/crates/client/cache-wasm/src/shell.rs
+++ b/crates/client/cache-wasm/src/shell.rs
@@ -1,6 +1,6 @@
use async_lock::Mutex;
use cache_core::deps::OpId;
-use cache_core::engine::{BeginOptimisticWrite, Engine, ReadResult};
+use cache_core::engine::{BeginOptimisticWrite, Engine, InitialClaimOutcome, ReadResult};
use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};
use cache_core::query_inspection::QueryInspection;
use cache_core::queue::{ClaimedMutation, MutationClaimRequest, MutationClaimToken};
@@ -70,12 +70,21 @@ struct JsInspectionPathSegment {
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
-struct JsOptimisticWriteResult {
+struct JsEnqueueOptimisticMutationResult {
transaction_id: String,
changed: Vec<String>,
affected_ops: Vec<String>,
reset: bool,
revalidations: Vec<QueryRevalidation>,
+ initial_claim: JsInitialMutationClaim,
+}
+
+#[derive(Serialize)]
+#[serde(tag = "kind", rename_all = "kebab-case")]
+enum JsInitialMutationClaim {
+ Claimed { mutation: JsClaimedMutation },
+ NotRunnable,
+ Failed { error: String },
}
#[derive(Serialize)]
@@ -339,11 +348,12 @@ impl CacheEngine {
})
}
- /// Durably queues a mutation and its optimistic response. Resolves to
- /// `{transactionId: string, changed: string[], affectedOps: string[],
- /// reset: false}` where changes reflect the composed view.
- #[wasm_bindgen(js_name = beginOptimisticWrite)]
- pub fn begin_optimistic_write(
+ /// Durably queues a mutation and its optimistic response, then attempts
+ /// to claim the strict queue head before resolving. Claim failures are
+ /// returned as a nested diagnostic outcome because enqueue succeeded.
+ #[wasm_bindgen(js_name = enqueueOptimisticMutation)]
+ #[allow(clippy::too_many_arguments)]
+ pub fn enqueue_optimistic_mutation(
&self,
origin_op_id: Option<String>,
query: String,
@@ -353,6 +363,9 @@ impl CacheEngine {
link_patches: JsValue,
revalidations: JsValue,
created_at_ms: f64,
+ lease_owner: String,
+ now_ms: f64,
+ lease_expires_at_ms: f64,
) -> js_sys::Promise {
let engine = self.engine.clone();
let ops = self.ops.clone();
@@ -362,10 +375,18 @@ impl CacheEngine {
let link_patches: Vec<OptimisticLinkPatch> = parse_vec(link_patches)?;
let revalidations: Vec<QueryRevalidation> = parse_vec(revalidations)?;
let created_at_ms = parse_timestamp(created_at_ms, "enqueue timestamp")?;
+ let claim = MutationClaimRequest {
+ owner: lease_owner,
+ now_ms: parse_timestamp(now_ms, "claim timestamp")?,
+ lease_expires_at_ms: parse_timestamp(
+ lease_expires_at_ms,
+ "lease expiration timestamp",
+ )?,
+ };
let origin = origin_op_id.map(|name| ops.borrow_mut().intern(&name));
let mut engine = engine.lock().await;
- let (transaction, result) = engine
- .begin_optimistic_write(
+ let result = engine
+ .enqueue_optimistic_mutation(
origin,
BeginOptimisticWrite {
query: &query,
@@ -376,19 +397,31 @@ impl CacheEngine {
revalidations: &revalidations,
created_at_ms,
},
+ claim,
)
.await
.map_err(err_js)?;
- to_js(&JsOptimisticWriteResult {
- transaction_id: transaction.to_string(),
+ let initial_claim = match result.initial_claim {
+ InitialClaimOutcome::Claimed(claimed) => JsInitialMutationClaim::Claimed {
+ mutation: JsClaimedMutation::try_from(*claimed)?,
+ },
+ InitialClaimOutcome::NotRunnable => JsInitialMutationClaim::NotRunnable,
+ InitialClaimOutcome::Failed(error) => JsInitialMutationClaim::Failed {
+ error: error.to_string(),
+ },
+ };
+ to_js(&JsEnqueueOptimisticMutationResult {
+ transaction_id: result.transaction_id.to_string(),
changed: result
+ .write_result
.changed
.into_iter()
.map(|key| key.0.into_owned())
.collect(),
- affected_ops: ops.borrow().names(result.affected_ops),
- reset: result.reset,
- revalidations: result.revalidations,
+ affected_ops: ops.borrow().names(result.write_result.affected_ops),
+ reset: result.write_result.reset,
+ revalidations: result.write_result.revalidations,
+ initial_claim,
})
})
}
diff --git a/crates/client/cache-wasm/tests/web.rs b/crates/client/cache-wasm/tests/web.rs
index b474cd3fd0..ad6848a44d 100644
--- a/crates/client/cache-wasm/tests/web.rs
+++ b/crates/client/cache-wasm/tests/web.rs
@@ -214,8 +214,8 @@ async fn optimistic_write_round_trip() {
"value": { "string": "x" }
}});
- // Begin: op 1 is affected, a string transaction id comes back.
- let begin = JsFuture::from(engine.begin_optimistic_write(
+ // Enqueue: op 1 is affected and the strict head is already claimed.
+ let enqueue = JsFuture::from(engine.enqueue_optimistic_mutation(
None,
PROPERTY_MUTATION.into(),
Some("SetEntityProperty".into()),
@@ -224,16 +224,21 @@ async fn optimistic_write_round_trip() {
JsValue::UNDEFINED,
JsValue::UNDEFINED,
123.0,
+ "runner".into(),
+ 10.0,
+ 1_000.0,
))
.await
.unwrap();
- let begin: serde_json::Value = serde_wasm_bindgen::from_value(begin).unwrap();
- let txn = begin["transactionId"].as_str().unwrap().to_string();
- assert_eq!(begin["affectedOps"], serde_json::json!(["tab1:1"]));
+ let enqueue: serde_json::Value = serde_wasm_bindgen::from_value(enqueue).unwrap();
+ let txn = enqueue["transactionId"].as_str().unwrap().to_string();
+ assert_eq!(enqueue["affectedOps"], serde_json::json!(["tab1:1"]));
assert_eq!(
- begin["changed"],
+ enqueue["changed"],
serde_json::json!(["GraphqlProperty:prop-1"])
);
+ assert_eq!(enqueue["initialClaim"]["kind"], "claimed");
+ assert_eq!(enqueue["initialClaim"]["mutation"]["transactionId"], txn);
// The optimistic layer is visible through reads.
let read = JsFuture::from(engine.read_query(
@@ -250,12 +255,10 @@ async fn optimistic_write_round_trip() {
serde_json::json!("Stage")
);
- let claimed = JsFuture::from(engine.claim_next_mutation("runner".into(), 10.0, 1_000.0))
- .await
- .unwrap();
- let claimed: serde_json::Value = serde_wasm_bindgen::from_value(claimed).unwrap();
- assert_eq!(claimed["transactionId"], txn);
- let generation = claimed["leaseGeneration"].as_str().unwrap().to_string();
+ let generation = enqueue["initialClaim"]["mutation"]["leaseGeneration"]
+ .as_str()
+ .unwrap()
+ .to_string();
// Commit with the real response; the layer flushes durably.
let commit = JsFuture::from(engine.commit_optimistic_write(