Skip to content

Cache v4 on the scheduling dispatcher prototype - #30

Draft
ethanresnick wants to merge 11 commits into
11-06-cache-v4from
claude/cache-v4-dispatcher-37e688
Draft

ethanresnick wants to merge 11 commits into
11-06-cache-v4from
claude/cache-v4-dispatcher-37e688

Conversation

@ethanresnick

@ethanresnick ethanresnick commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Draft, for review only. This shows what cache PR 27 looks like when its Store-read and producer scheduling run on the unpublished @zingage/scheduling dispatcher prototype. Do not merge: the scheduling package is vendored as a tarball (see below).

Base is 11-06-cache-v4, so the diff is the delta from PR 27 (704aef9).

The commits

  1. a1ae315 agreed v4 API changes. The API changes agreed after PR 27, applied from a patch: autoBatch?: false on Cache.get / Cache.getMany (no getUnbatched), maxConcurrentStoreReads, maxConcurrentProducerCalls, per-call joinInFlight: false, producerScheduler.ts, and the per-client slot steps. It does not build on its own: it uses an experimental scheduling 1.3.0 that is being replaced.
  2. 59c311a temporary: vendor the unpublished scheduling prototype. vendor/zingage-scheduling-1.3.0-prototype.0.tgz (packed from scheduling commit 55a4099, the build without oneByOne()), a relative file: dependency, the lockfile, and a .gitignore exception. Still does not build.
  3. 111f812 the port. The cache's scheduling rebuilt on createDispatcher, fifoBatches, ConcurrencyLimit, Sharing and Item. From here the branch builds and every gate passes.
  4. 10bf4e3 re-vendor from scheduling commit 80aa8e8. The prototype was repacked after the branch was pushed, so this is a follow-up commit, not an amend: the new tarball and lockfile hash, concurrencyLimit(n) → new ConcurrencyLimit(n), and one test updated for the synchronous slot grant. 5. 4817ed8 re-vendor from scheduling commit 361aae3. The tarball and lockfile hash only. New in the prototype: submit / submitMany take { signal, expedite }, and with preserveAsyncContext, flush and close keep the first item's async context.
  5. 93d661b use the submit options, and simplify the Store signal rule. Store reads pass { signal, expedite } to the dispatcher; producer work that a call with autoBatch.producer: false starts is expedited from the start; the Store signal rule no longer looks at autoBatched.
  6. 2ea8e6d cancel a Store read call when every caller has aborted. The Store signal rule changes from "the same signal on every read" to "aborts when the signal of every read has aborted" (difference 8). The new src/utils/allAborted.ts makes the signal. Two follow-ups: 8920df2 finds signals that have all aborted without a Set, and 17fccb6 moves the rule for a read without a signal out of the helper into Cache.#readStore.

The branch head is built on scheduling commit 361aae3.

The vendored tarball must be replaced before any merge

A published @zingage/cache cannot depend on a file: path, and vendor/ is not in the package's files. Before merge: publish the scheduling package, point the dependency at that version, delete vendor/ and the .gitignore exception.

What the port does

  • src/wrapProducer/producerScheduler.ts (457 → 212 lines): one dispatcher (fifoBatches(producerBatching) for produceMany, no waiting set for produce, new ConcurrencyLimit(maxConcurrentProducerCalls) as admission when set) with a Sharing in front. One canJoin holds the whole sharing rule. The senders, StartedTask, and startOrRideDirect are gone.
  • src/wrapProducer/producerClient.ts (1497 → 1366): each slot requests its own producer work; for autoBatch.producer: false the scheduler expedites it (new work starts expedited, joined waiting work gets item.expedite()). The cohort starter, ProducerStarter and decideAll are gone. collapsedRequestCount comes from sharing.joinedCount(item) at publish time, and queueWaitTotalMs from item.startedAt - item.submittedAt.
  • src/cache/Cache.ts (1092 → 1147): one read dispatcher (fifoBatches({ maxBatchSize: 100, ...readBatching }) for a Store with getMany, no waiting set for a get-only Store, new ConcurrencyLimit(maxConcurrentStoreReads) when set) replaces the read Batcher, the limiter field and runLimited. Reads still never share work, so there is no Sharing here.
  • src/utils/utils.ts (524 → 482): runLimited, LimitStoreCall and assertResultCount are gone; queueWaitMs is new. Abort-to-cancel for waiting reads is the dispatcher's signal option.
  • wrapSingleProducer.ts (65 → 45) and wrapBulkProducer.ts (98 → 73) only say whether their producer batches.

Line counts at PR 27 (704aef9), for reference: producerClient.ts 1224, Cache.ts 1005, utils.ts 450, wrapSingleProducer.ts 135, wrapBulkProducer.ts 245; producerScheduler.ts did not exist.

Behaviour differences from PR 27 (all intended)

Decided before the port:

  1. "Never split" is dropped. autoBatch: false (Cache) and autoBatch.store: false / autoBatch.producer: false (clients) only skip the accumulation wait: the work is expedited. It is still split at maxBatchSize. A direct call is not guaranteed to be one Store or producer call.
  2. No whole-set wait. A wrapped getMany with autoBatch.producer: false no longer waits for all of its cache reads before it produces. Each slot expedites its own producer work when its own read settles. With autoBatch.store: false, each slot is its own expedited Cache.get.
  3. One sharing rule. A request joins work that still waits. It joins running work only if the call did not pass joinInFlight: false and the producer call started no more than collapseOverlappingRequestsTime seconds ago.
  4. Limits are an admission on the dispatcher, for Store reads and producer calls, single and bulk.

Consequences of the dispatcher model, which follow from the above but are worth a look:

  1. Callers' direct work can share a call. The dispatcher forms calls once per burst of microtasks, from everything that is ready. So expedited work of several callers that is ready in the same turn shares Store or producer calls. The old test "gives each direct caller one producer call with only its own misses" now asserts the opposite: 45 misses of two concurrent direct callers reach the producer as 20 + 20 + 5, mixing callers. A producer can no longer rely on autoBatch.producer: false to see one caller's misses alone.
  2. A call's own duplicates share work. A request also joins running work that its own public call started, in any state. Slots now request one at a time, so Sharing.requestMany's same-call guarantee does not apply; this clause in canJoin keeps the documented "requests of one call with the same key share" true for the realistic case (duplicate ids in one getMany with joinInFlight: false on a produce producer). This is my addition to decision 3.
  3. autoBatched in diagnostics is false only when every request of the call was expedited, and always false for a get-only Store and a produce producer. A call that mixes expedited and accumulated requests reports true.
  4. Signal forwarding to the Store. A Store call gets a signal that aborts when the signal of every read in it has aborted, so the call stops only when no caller wants its result any more. Whether the call is autoBatched does not matter. The usual cases add no listener and make no signal: when no read has a signal, or only some reads have one, the Store gets no signal and the call always completes; when every read carries the same signal (for example one wrapped getMany with a signal), the Store gets that signal itself. Reads with different signals get a new signal from allAborted, whose reason is the reason of the last abort, and the Store call removes its listeners when it is done. A cancelled call's read-store message reports cancelled. In PR 27 only a direct read forwarded its signal, and an automatic batch always completed.
  5. Batched calls start in a microtask after their work becomes ready, not synchronously inside the schedule callback or close(). Without batching (a produce producer, a get-only Store), a call starts inside the request when no limit holds it back, also when a limit is set and a slot is free.
  6. Queue waits are measured, so queueWaitTotalMs is close to zero, not exactly zero, for work that nothing held back.
  7. preserveAsyncContext. fifoBatches arms one schedule callback per accumulation, not one per batch. So every Store or producer call of one accumulation runs in the context of the request that opened the accumulation (before: each batch in the context of its own first request). Calls that close() or flush start early keep that context too, as of scheduling 361aae3.
  8. batchScheduleFn and expedited work. New work with autoBatch: false is submitted expedited, never accumulates, and does not call batchScheduleFn, as in PR 27. Waiting work that an expediting request joins has armed the schedule already; its callback then finds nothing to do.
  9. No "enqueue called after close" warning. The dispatcher has no closed state and no logger. Work submitted after close still runs.
  10. Order inside a mixed call is the order in which items became ready, not arrival order.

Unchanged: per-request Error slots, the read / read-store / fetch / produce messages, abort behaviour for waiting work, close() draining, the cap of 10 concurrent get calls for one known-set read on a get-only Store without maxConcurrentStoreReads, and that set's shared time-slice budget.

Verification

Run on the branch head (93d661b), on the tarball packed from scheduling commit 361aae3. Node v26.5.0, pnpm 10.26.1.

Command Result
pnpm install --frozen-lockfile up to date
pnpm run build exit 0
pnpm run test:types exit 0
NODE_OPTIONS="--max-old-space-size=8192" ./node_modules/.bin/oxlint --type-aware 0 warnings, 0 errors, 85 files, 110 rules
./node_modules/.bin/oxlint 0 warnings, 0 errors
./node_modules/.bin/prettier --check on every file changed since 704aef9 all formatted
pnpm run test:docker 594 tests: 592 pass, 0 fail, 2 skipped
pnpm run test:docker:down done

The type-aware lint did not crash, and it caught one real error during the work (an unbound method), which is fixed.

Tests: the patch state had 570 pass, 0 fail, 2 skipped. Tests that asserted the unsplit or synchronous behaviour now assert the new behaviour deliberately; none was dropped. The scheduler cases of wrapSingleProducer.test.ts and wrapBulkProducer.test.ts moved into producerScheduler.test.ts, because the per-wrapper scheduler functions no longer exist. New tests cover: mixed and all-expedited autoBatched; expediting joined work; the same-call join; a Store call whose callers have different signals (it completes while one still waits, and is cancelled when all have aborted); the allAborted helper; the per-set cap of 10 and its abort; and close() with an accepted getMany on a schedule that never fires.

A mutation check removed each guard that the port moved (the close order, the signal and expedite submit options of get and getMany, the same-call join, joinInFlight, the scheduler's start-expedited and join-expedite steps, the signal rule). Every mutation fails at least one test, with one exception that led to a decision: passing signal to submit on the capped path (a known set on a get-only Store without maxConcurrentStoreReads) changes nothing a test can observe, because each of those reads is its own Store call, gets the signal by the rule in difference 8, and fails before it reaches the Store. So that path does not pass it.

Benchmark (rough)

One machine, one run each, medians of 7 rounds, a wrapped client over a MemoryStore. Treat differences under about 10% as noise. Measured on the prototype build from scheduling commit 55a4099; not re-measured on 80aa8e8 or 361aae3.

Case PR 27 (704aef9) This branch
wrapped get hit, MemoryStore (get-only) 5.21 µs 4.25 µs
wrapped getMany([x]) hit, MemoryStore 4.97 µs 4.57 µs
getMany of 20 misses, produceMany, MemoryStore 202 µs 173 µs
wrapped get hit, getMany Store over a MemoryStore 4.18 µs 3.23 µs
wrapped getMany([x]) hit, getMany Store 4.01 µs 3.51 µs
getMany of 20 misses, produceMany, getMany Store 154 µs 129 µs

The last three rows are extra: a MemoryStore is get-only, so only they exercise fifoBatches for reads. On the first prototype build the port was level with PR 27 (4.7 / 5.0 / 208 µs for the first three rows); the gain appeared with the repacked prototype.

What the prototype made awkward

  • The signal is passed twice for a Store read. submit(input, { signal }) (since 361aae3) cancels a waiting read, which removed the cache's own helper. The read's input still repeats the signal, because invoke decides from the items of one call whether the Store gets a signal, and an item does not expose the signal it was submitted with.
  • close() resolves once and there is no closed state. A later submit is accepted silently, and a second close() returns the first, already resolved promise. The cache therefore flushes first, drains its own accepted operations, and only then closes the dispatcher. The after-close warning could not be kept.
  • Sharing.request has no expedite. submit has the option since 361aae3, so the scheduler passes it in Sharing's start callback, from a flag on the request, and still calls item.expedite() itself when the request joined waiting work.
  • Nothing says whether a call came from accumulation. The cache computes accumulates && items.some(item => !item.expedited) in two places, and has to know itself whether its waiting set accumulates.
  • Item.startedAt is optional inside invoke, where it is always set, so queueWaitMs and canJoin carry a fallback. Item times are plain numbers; the cache has a branded PerformanceNow.
  • Item is invariant in its input and result types, so a helper that takes "any item" needs a structural parameter type.
  • A limit of Infinity is rejected, so both owners map Infinity to "no admission" themselves.
  • No per-submitter limit. The cap of 10 get calls per known set on a get-only Store is a pLimit around submit in the cache, and that set's time-slice budget travels in each item's input.
  • preserveAsyncContext binds per accumulation, not per batch (difference 11).
  • Sharing.request and Sharing.requestMany differ for one public call whose requests arrive one at a time; the cache added the same-call clause to canJoin (difference 6).
  • BatchOptions and DEFAULT_MAX_BATCH_SIZE still live in batcher.ts, and its doc still says a direct dispatch is never split.

Review findings left for a decision

From the /simplify pass (seven review angles). Applied: the close order, a dead helper, a duplicated settle step, leftover seams of the cohort design, and old-mechanism names. Not applied, because they cross this PR's scope:

  • readSingleStore in utils.ts still handles a list, but production now always passes one request for a get-only Store. Only test fixtures use the list. A TODO marks it.
  • The Store-read cluster (readStoreObserved, cancelWaitingOnAbort, the read dispatcher) could move from utils.ts and Cache.ts into a src/cache/storeReads.ts, mirroring producerScheduler.ts.
  • ProducerScheduler.request still returns the prototype's SharedOutcome. The scheduler now expedites from a flag on the request's call, so the return type could shrink to { result, joined }; the scheduler tests read item and startReason.
  • The logger components "batcher" and "collapsed-task-creator" now log nothing. Removing them changes the public ComponentName type.
  • "ride" and "task" remain in diagnostics.ts and the README next to "join" and "work"; the client's local Item type and the word "call" each carry more than one meaning in producerClient.ts.

🤖 Generated with Claude Code

ethanresnick and others added 11 commits November 23, 2026 17:06
Applies the API changes agreed for v4 after PR 27:

- `Cache.get` and `Cache.getMany` take `autoBatch?: false`;
  `Cache.getUnbatched` is removed.
- `maxConcurrentStoreReads` (Cache option) and
  `maxConcurrentProducerCalls` (producer-client option).
- Per-call `joinInFlight?: false` on producer clients. The sharing window
  runs from the producer call's start, and waiting work is always joinable.
- `src/wrapProducer/producerScheduler.ts`: one sharing layer composed with
  an "immediate" or "batching" sender. `wrapSingleProducer.ts` and
  `wrapBulkProducer.ts` are thin compositions of it.
- `src/wrapProducer/producerClient.ts`: the slot pipeline is split into
  per-client steps, and `get` no longer goes through `getMany`.
- Tests, README, CHANGELOG and plan-doc updates for the above.

This commit does not build on its own. The code uses `ConcurrencyLimiter`,
the `Batcher` `limiter` option, and `invokedAt`/`rideInvoked` on
`CollapsedTaskCreator`, which were an experimental `@zingage/scheduling`
1.3.0 that is being replaced. `package.json` and `pnpm-lock.yaml` are
unchanged here; the next commits vendor the scheduling dispatcher
prototype and port the code to it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Points `@zingage/scheduling` at `vendor/zingage-scheduling-1.3.0-prototype.0.tgz`
with a relative `file:` reference, so the branch installs anywhere,
including CI. The tarball is the unpublished dispatcher prototype
(`Item`, waiting sets, `Admission`, `createDispatcher`, `Sharing`), version
`1.3.0-prototype.0`, packed from scheduling commit 55a4099. `.gitignore`
gets an exception for `vendor/*.tgz`.

THIS MUST BE REPLACED BY A PUBLISHED VERSION BEFORE ANY MERGE. A published
`@zingage/cache` cannot depend on a `file:` path: the `vendor/` folder is
not in the package's `files`. Before merge, publish the scheduling package,
point the dependency at that version, and delete `vendor/` and the
`.gitignore` exception.

The branch still does not build after this commit: the cache code from the
previous commit uses scheduling APIs that the prototype does not have. The
next commit ports it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…dispatcher

Rebuilds the cache's scheduling on the dispatcher prototype of
`@zingage/scheduling` (`createDispatcher`, `fifoBatches`,
`concurrencyLimit`, `Sharing`, `Item`), in place of `Batcher`,
`CollapsedTaskCreator` and the experimental `ConcurrencyLimiter`.

- `producerScheduler.ts`: a dispatcher (`fifoBatches(producerBatching)` for
  `produceMany`, no waiting set for `produce`, `concurrencyLimit` as
  admission when `maxConcurrentProducerCalls` is set) with a `Sharing` in
  front. One `canJoin` holds the sharing rule.
- `producerClient.ts`: each slot requests its own producer work, and a call
  with `autoBatch.producer: false` expedites it. The cohort starter and its
  whole-set wait are gone. Every slot reads with its own `Cache.get`.
- `Cache.ts`: one read dispatcher replaces the read `Batcher`, the limiter
  field and `runLimited`. `autoBatch: false` is submit-then-expedite.
- `utils.ts`: `runLimited` and the `limit` parameter are gone;
  `queueWaitMs` and `cancelWaitingOnAbort` are new.

Intended behaviour changes against PR 27 with the agreed API:

- `autoBatch: false` only skips the accumulation wait. The work is still
  split at `maxBatchSize`, and one Store or producer call can carry several
  callers' work that is ready in the same turn.
- A wrapped `getMany` with `autoBatch.producer: false` no longer waits for
  all of its cache reads before it produces.
- A request joins producer work that waits; it joins running work only
  without `joinInFlight: false` and inside the sharing window; and it joins
  work that its own public call started.
- `autoBatched` in diagnostics is false only when every request of the call
  was expedited. A Store call gets a caller's signal only when it is not
  automatic and all of its reads carry that signal.
- Batched calls start in a microtask after their work is ready. Queue waits
  are measured, so never exactly 0. `preserveAsyncContext` binds one
  context per accumulation, and a `close()` runs its calls in the closer's
  context. The "enqueue called after close" warning is gone.

Tests that asserted the old unsplit or synchronous behaviour now assert the
new behaviour. The scheduler tests of `wrapSingleProducer.test.ts` and
`wrapBulkProducer.test.ts` moved into `producerScheduler.test.ts`, because
the per-wrapper scheduler functions no longer exist.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Replaces the vendored tarball (same file name and version) with the build
from scheduling commit 80aa8e8, and adapts the cache to its API:

- `concurrencyLimit(n)` is now `new ConcurrencyLimit(n)`.

With no waiting set and an admission, the dispatcher now asks for the slot
inside `submit`. So a `produce` call or a `get`-only Store call under a
limit starts synchronously when a slot is free. The scheduler test that
asserted the microtask start now asserts the synchronous start.

The tarball is still temporary: it must be replaced by a published
`@zingage/scheduling` version before any merge.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Replaces the vendored tarball (same file name and version) with the build
from scheduling commit 361aae3. New in it: `submit` and `submitMany` take
`{ signal, expedite }`, and with `preserveAsyncContext`, `flush` and
`close` start their calls in the first item's async context.

The cache builds against it unchanged. One test still expects the closer's
context for a call that `close()` starts; the next commit updates it and
uses the new submit options.

The tarball is still temporary: it must be replaced by a published
`@zingage/scheduling` version before any merge.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…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>
A Store read call now gets a signal that aborts when the signal of every
read in the call has aborted. Before, the Store got a signal only when
every read carried the same signal, so a call that two callers with
different signals shared could never stop.

The new `allAborted` helper makes the signal. Its usual cases add no
listener and make no signal: no read has a signal (or only some have
one) gives no signal, and one signal on every read gives that signal.
Different signals get a new signal, and the Store call removes its
listeners when it is done.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
`allAborted` now checks in its first pass whether every signal has
aborted already, and returns the aborted signal from there. Only callers
with different signals of which one has not aborted make a Set.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…ps its Store call

`allAborted` now takes only signals, and answers for exactly the signals
that it gets. Before, an undefined element meant "this caller can never
cancel", and made the result have no signal. That rule belongs to the
code that shares the work, so `Cache.#readStore` now applies it: a Store
call with a read that has no signal asks for no signal at all.

The behaviour of the cache does not change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
`allAborted` now takes a `NonEmptyArray` of signals, so its result always
has a signal. For an empty list, "every signal has aborted" would be
true at once, although nothing asked for a cancel; the helper returned
no signal for that case. Now the types do not allow it, and
`Cache.#readStore` asks for a signal only when it has reads.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant