Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
refactor(cache): use the dispatcher's submit options, and simplify th…
…e Store signal rule

- Store reads pass `{ signal, expedite }` to `submit` / `submitMany`. The
  separate `read.expedite()` calls and the cache's `cancelWaitingOnAbort`
  helper are gone. A read with `autoBatch: false` never accumulates, so it
  no longer calls `batchScheduleFn`.
- Producer work: a request of a call with `autoBatch.producer: false`
  starts its work expedited, through `Sharing`'s `start`. The scheduler
  still calls `item.expedite()` for waiting work that such a request
  joins. Both now live in `producerScheduler.ts`, driven by
  `request.call.expedite`; the client only sets the flag. No signal goes
  to `submit` there: `Sharing` owns the cancellation of shared work.
- The Store signal rule no longer looks at `autoBatched`. A Store call
  gets a signal exactly when every read in it carries that same signal;
  reads without a signal count as different from reads with one. So an
  automatic batch whose reads all share one signal now gets it, and an
  abort can cancel that Store call for those callers only.
- With `preserveAsyncContext`, a Store call that `close()` starts now runs
  in the context of the read that opened the accumulation.

The capped path (a known set on a `get`-only Store without
`maxConcurrentStoreReads`) does not pass the signal to `submit`. Its reads
never wait in the dispatcher, and each is its own Store call, which gets
the signal by the rule above and fails before it reaches the Store. A
mutation check showed that passing the signal there changes nothing that
a test can observe.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
  • Loading branch information
ethanresnick and claude committed Nov 23, 2026
commit 93d661b64c08062d13c987ad98000269cd470b9c
17 changes: 11 additions & 6 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,17 @@ Dates below are npm publication dates (UTC). Version 4.0.0 is unreleased.
becomes ready, not synchronously inside the schedule callback or `close()`.
With `preserveAsyncContext`, every Store or producer call of one
accumulation runs in the async context of the request that opened the
accumulation, and a call that `close()` starts runs in the closer's
context. Queue waits in diagnostics are measured times, so a call that
nothing held back reports a wait close to zero, not exactly zero. Work
with `autoBatch: false` still calls `batchScheduleFn`, whose callback then
finds nothing to do, because the work is submitted before it is expedited.
Work that is submitted after `close()` no longer logs a warning.
accumulation, also when `close()` starts the call. Queue waits in
diagnostics are measured times, so a call that nothing held back reports
a wait close to zero, not exactly zero. Work that is submitted after
`close()` no longer logs a warning.
- A Store read call receives a caller's `AbortSignal` exactly when every
read in the call carries that same signal, also for an automatic batch.
Aborting it can then cancel the Store call, which only affects the callers
that cancelled, and the `read-store` message reports `cancelled`. A Store
call whose reads carry different signals, or that mixes reads with and
without a signal, gets no signal and always completes. Before, only a
read with `autoBatch: false` passed its signal to the Store.
- A package contract violation in one producer result slot, or in one
`bulkProducerByIdType` slice, rejects only the callers of the affected
requests. Automatic batching merges unrelated callers into one invocation,
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ const withoutTheWait = await cache.getMany(requests, { autoBatch: false });

- **Requests share one Store call, never one result.** Each `get()` still classifies its own id, evaluates freshness at its own `now`, selects its own entry, and publishes its own `read` message. So a batched `get()` that succeeds returns what an unbatched one returns. Accumulation never caches or shares results, even for identical requests.
- **Scheduling is configurable.** `batchScheduleFn` receives a dispatch callback and must invoke it in the immediate future; for example, pass `setImmediate` to gather reads until the next check phase.
- **The Store call runs in one caller's async context.** With the default scheduler, the Store calls of one accumulation run in the async context (for example, `AsyncLocalStorage` stores and the active tracing span) of the `get()` that opened the accumulation. So the query's span appears in that caller's trace only. `preserveAsyncContext` does the same for a custom scheduler that runs its callback from an unrelated context. Reads that `close()` or `autoBatch: false` make ready go to the Store in the async context of the caller that made them ready, or of the first such caller when several do so in one turn.
- **The Store call runs in one caller's async context.** With the default scheduler, the Store calls of one accumulation run in the async context (for example, `AsyncLocalStorage` stores and the active tracing span) of the `get()` that opened the accumulation. So the query's span appears in that caller's trace only. `preserveAsyncContext` does the same for a custom scheduler that runs its callback from an unrelated context. It also keeps that context for a Store call that `close()` starts early. Reads with `autoBatch: false` go to the Store in the async context of the first such read of the turn.
- **One request's input can fail other requests.** For example, Postgres rejects a statement that binds an id with U+0000. When the whole Store call fails, every slot in it receives that Error, including other callers' requests.

`getMany(requests, { autoBatch: false })` makes the supplied known set ready for the Store's bulk primitive at once. It changes only the wait: the batch limit still splits a large set into several Store calls, and a Store call can also carry other callers' reads that are ready at the same time. It does not force individual reads. `get(request, { autoBatch: false })` does the same for one request.
Expand Down
5 changes: 3 additions & 2 deletions docs/plans/2026-11-06-cache-v4-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@ amendments above where they conflict.
every request of the call was expedited (and for every call of a
single-only capability). A call that mixes expedited and accumulated
requests reports true.
- A Store call receives a caller's signal only when the call is not
`autoBatched` and all of its requests carry that same signal.
- A Store call receives a caller's signal exactly when all of its requests
carry that same signal, whether or not the call is `autoBatched`. A call
that mixes signals, or requests with and without a signal, gets none.
- A batched call starts in a microtask after its work becomes ready. A call
of a single-only capability starts inside the request when no limit holds
it back. Queue waits in diagnostics are measured, so they are never
Expand Down
8 changes: 4 additions & 4 deletions src/cache/Cache.readBatching.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,12 +277,12 @@ describe("Cache read batching", suiteOptions, () => {
await Promise.all([a, b]);
assert.deepEqual(observed, ["reader-a", "reader-a"]);

// A close that makes waiting reads ready does not use that callback, so
// their Store call runs in the closer's context.
// A close that makes waiting reads ready also runs their Store call in
// the context of the read that opened the accumulation, not the closer's.
const c = context.run("reader-c", () => cache.get(lookup("c")));
await context.run("closer", () => cache.close());
await c;
assert.deepEqual(observed, ["reader-a", "reader-a", "closer"]);
assert.deepEqual(observed, ["reader-a", "reader-a", "reader-c"]);
// The scheduled callbacks still exist after a forced flush; neither a
// second close nor invoking those callbacks may execute a batch twice.
await cache.close();
Expand Down Expand Up @@ -593,7 +593,7 @@ describe(
assert.equal(schedule.mock.callCount(), 0);
});

it("does not cancel a dispatched shared operation when every caller aborts", async (t) => {
it("close() waits for a Store call that its only caller aborted", async (t) => {
const started = Promise.withResolvers<void>();
const release = Promise.withResolvers<void>();
const { store, getManyRequestCounts } = spiedStore({
Expand Down
96 changes: 43 additions & 53 deletions src/cache/Cache.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { noop, sumBy } from "es-toolkit";
import { sumBy } from "es-toolkit";
import { isNonEmptyArray, mapNonEmpty } from "type-party/runtime/nonempty.js";
import type { ReadonlyDeep } from "type-fest";
import type { PickEach } from "type-party";
Expand Down Expand Up @@ -69,7 +69,6 @@ import {
raceWithSignal,
asError,
assertUnreachable,
cancelWaitingOnAbort,
isContractError,
queueWaitMs,
defaultLoggersByComponent,
Expand Down Expand Up @@ -495,18 +494,15 @@ export default class Cache<
//
// Submitted synchronously, so a close() that starts later waits for the
// read: the dispatcher tracks it.
//
// The dispatcher takes a read that still waits out of its queue when the
// signal aborts. A read whose Store call has started keeps running, and
// `raceWithSignal` rejects this caller at once.
const signal = options?.signal;
const read = this.#readDispatcher.submit({
request: storeRequest,
signal,
budget: undefined,
});
if (options?.autoBatch === false) read.expedite();
// An abort takes a read that still waits out of the queue. A read whose
// Store call has started keeps running, and `raceWithSignal` rejects
// this caller at once.
const stopCancelling =
signal === undefined ? noop : cancelWaitingOnAbort([read], signal);
const read = this.#readDispatcher.submit(
{ request: storeRequest, signal, budget: undefined },
{ signal, expedite: options?.autoBatch === false },
);

let cacheEntries: Entry<SpecOf<RT>, Validators, Params>[];
try {
Expand All @@ -525,8 +521,6 @@ export default class Cache<
}

throw error;
} finally {
stopCancelling();
}

this.#logger("trace", "received entries from the store", {
Expand Down Expand Up @@ -741,38 +735,29 @@ export default class Cache<
(request): StoreRead<RT, Params> => ({ request, signal, budget }),
);

const { results, stopCancelling } = (() => {
if (this.#capsEachKnownSet) {
// These reads never wait in the dispatcher, so they need no
// cancellation there. A read that the limit still holds when the
// signal aborts fails before it reaches the Store: each read is its
// own Store call, which gets the signal (see `#readStore`).
const limit = pLimit(SINGLE_STORE_READS_PER_SET);
return {
results: inputs.map(async (input) =>
const results = this.#capsEachKnownSet
? (() => {
// These reads never wait in the dispatcher, so they need no
// cancellation there. A read that the limit still holds when the
// signal aborts fails before it reaches the Store: each read is
// its own Store call, which gets the signal (see `#readStore`).
const limit = pLimit(SINGLE_STORE_READS_PER_SET);
return inputs.map(async (input) =>
limit(async () => this.#readDispatcher.submit(input).result),
),
stopCancelling: noop,
};
}

const reads = this.#readDispatcher.submitMany(inputs);
if (options?.autoBatch === false) {
reads.forEach((read) => {
read.expedite();
});
}
return {
results: reads.map(({ result }) => result),
// An abort takes the reads that still wait out of the queue.
stopCancelling: cancelWaitingOnAbort(reads, signal),
};
})();
);
})()
: this.#readDispatcher
// With the signal, the dispatcher takes the reads that still wait
// out of its queue when the signal aborts.
.submitMany(inputs, {
signal,
expedite: options?.autoBatch === false,
})
.map(({ result }) => result);

// allSettled waits for every read, so a failure in one Store call does
// not hide the results of the others. It never rejects.
// not hide the results of the others.
const settled = await Promise.allSettled(results);
stopCancelling();
signal?.throwIfAborted();

return settled.map((read) => {
Expand Down Expand Up @@ -1023,11 +1008,12 @@ export default class Cache<
* with `getMany` accumulates reads, so no call to a Store without it is
* automatic.
*
* The Store gets a signal only for a call that is not automatic and whose
* reads all carry the same signal. Then only callers that cancelled can
* lose the call. An automatic call, or one whose reads carry different
* signals, gets no signal: it always completes, and each caller races its
* own signal.
* The Store gets a signal exactly when every read of the call carries that
* same signal. Then only callers that cancelled can lose the call. A call
* whose reads carry different signals, or that mixes reads with a signal
* and reads without one, gets no signal: it always completes, and each
* caller races its own signal. Whether the call is automatic does not
* matter.
*/
async #readStore(
reads: readonly Item<
Expand All @@ -1039,10 +1025,9 @@ export default class Cache<
this.#dataStore.getMany !== undefined &&
reads.some((read) => !read.expedited);
const first = reads[0]?.input;
const signal =
autoBatched || reads.some(({ input }) => input.signal !== first?.signal)
? undefined
: first?.signal;
const signal = reads.every(({ input }) => input.signal === first?.signal)
? first?.signal
: undefined;

return readStoreObserved(
this.#dataStore,
Expand Down Expand Up @@ -1119,7 +1104,12 @@ export default class Cache<
/** One Store read, as the read dispatcher holds it. */
type StoreRead<RT extends ResourceTypes, Params extends AnyParams> = {
readonly request: StoreGetManyRequest<SpecOf<RT>, Params>;
/** The signal of the call that made the read. See `Cache.#readStore`. */
/**
* The signal of the call that made the read. The dispatcher gets the same
* signal when the read is submitted, to cancel the read while it waits.
* It is repeated here because `Cache.#readStore` decides from the reads of
* one Store call whether the Store gets a signal.
*/
readonly signal: AbortSignal | undefined;
/**
* The time-slice budget of the known-set read that made this read, for a
Expand Down
4 changes: 2 additions & 2 deletions src/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -547,8 +547,8 @@ export type CacheReadStoreMessage = {
/**
* `failure` when any slot holds an Error or the whole call failed.
* `cancelled` when a Store call that got its caller's signal rejects after
* that caller cancels. A Store call gets a signal only when it is not
* `autoBatched` and all of its requests carry the same signal. Any other
* that caller cancels. A Store call gets a signal exactly when all of its
* requests carry that same signal, automatic or not. Any other
* Store call keeps the Store's eventual outcome after a cancellation.
*/
outcome: "success" | "failure" | "cancelled";
Expand Down
152 changes: 110 additions & 42 deletions src/readStoreDiagnostics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,54 +231,122 @@ describe("read-store channel", suiteOptions, () => {
});
}

for (const settlement of ["queued", "success", "failure"] as const) {
it(`preserves automatic Store accounting after ${settlement} cancellation`, async (t) => {
const scheduled = Promise.withResolvers<() => void>();
const started = Promise.withResolvers<void>();
const gate = Promise.withResolvers<void>();
const { store } = spiedStore({
beforeGetMany: async () => {
started.resolve();
await gate.promise;
if (settlement === "failure") {
throw new Error("Store failed after caller cancellation");
}
},
});
const cache = cacheOver(store, {
name: `automatic-cancel-${settlement}`,
readBatching: { batchScheduleFn: scheduled.resolve },
});
const capture = captureChannels(cache.name);
t.after(async () => {
capture.stop();
await cache.close();
});
/**
* A cache whose automatic reads wait for the returned `dispatch`, over a
* Store whose call stays open until `gate` resolves, and then fails if
* `fails` is set.
*/
const gatedAutomaticReads = (
t: { after: (fn: () => Promise<void>) => void },
name: string,
fails: boolean,
) => {
const scheduled = Promise.withResolvers<() => void>();
const started = Promise.withResolvers<void>();
const gate = Promise.withResolvers<void>();
const { store } = spiedStore({
beforeGetMany: async () => {
started.resolve();
await gate.promise;
if (fails) throw new Error("Store failed after caller cancellation");
},
});
const cache = cacheOver(store, {
name,
readBatching: { batchScheduleFn: scheduled.resolve },
});
const capture = captureChannels(cache.name);
t.after(async () => {
capture.stop();
await cache.close();
});
return { cache, capture, scheduled: scheduled.promise, started, gate };
};

it("emits nothing for an automatic read that is cancelled while it waits", async (t) => {
const { cache, capture, scheduled, gate } = gatedAutomaticReads(
t,
"automatic-cancel-queued",
false,
);
const controller = new AbortController();
const rejected = assert.rejects(
cache.get(lookup("a"), { signal: controller.signal }),
);
const dispatch = await scheduled;
controller.abort();
await rejected;
dispatch();
gate.resolve();
await cache.close();
assert.equal(capture.readStore.length, 0);
});

for (const fails of [false, true]) {
const settlement = fails ? "failure" : "success";

it(`cancels an automatic Store call whose reads all carry the aborted signal (Store ${settlement})`, async (t) => {
const { cache, capture, scheduled, started, gate } = gatedAutomaticReads(
t,
`automatic-cancel-own-${settlement}`,
fails,
);
const controller = new AbortController();
const read = cache.get(lookup("a"), { signal: controller.signal });
const rejected = assert.rejects(read);
const dispatch = await scheduled.promise;
if (settlement !== "queued") {
dispatch();
await started.promise;
}
// Two reads of one caller: every read of the Store call carries the
// same signal, so the Store call gets it.
const rejected = Promise.all(
["a", "b"].map(async (id) =>
assert.rejects(cache.get(lookup(id), { signal: controller.signal })),
),
);
(await scheduled)();
await started.promise;
controller.abort();
await rejected;
assert.equal(capture.readStore.length, 0);
dispatch();
gate.resolve();
await cache.close();
if (settlement === "queued") assert.equal(capture.readStore.length, 0);
else {
assert.equal(capture.readStore.length, 1);
const [message] = capture.readStore;
assert.equal(message?.operation, "getMany");
assert.equal(message?.outcome, settlement);
assert.equal(
message?.failedRequestCount,
settlement === "failure" ? 1 : 0,
);
}

assert.equal(capture.readStore.length, 1);
const [message] = capture.readStore;
assert.equal(message?.operation, "getMany");
assert.equal(message?.autoBatched, true);
assert.equal(message?.requestCount, 2);
// The Store call saw the abort, whatever the Store did after it.
assert.equal(message?.outcome, "cancelled");
assert.equal(message?.failedRequestCount, 0);
});

it(`preserves automatic Store accounting after ${settlement} cancellation when another caller shares the Store call`, async (t) => {
const { cache, capture, scheduled, started, gate } = gatedAutomaticReads(
t,
`automatic-cancel-shared-${settlement}`,
fails,
);
const controller = new AbortController();
const rejected = assert.rejects(
cache.get(lookup("a"), { signal: controller.signal }),
);
// This read has no signal, so the Store call gets none: the other
// caller must not lose the call.
const kept = cache.get(lookup("b")).then(
() => "fulfilled",
() => "rejected",
);
(await scheduled)();
await started.promise;
controller.abort();
await rejected;
assert.equal(capture.readStore.length, 0);
gate.resolve();
assert.equal(await kept, fails ? "rejected" : "fulfilled");
await cache.close();

assert.equal(capture.readStore.length, 1);
const [message] = capture.readStore;
assert.equal(message?.operation, "getMany");
assert.equal(message?.outcome, settlement);
assert.equal(message?.failedRequestCount, fails ? 2 : 0);
});
}

Expand Down
Loading
Loading