Repository navigation
Cache v4 on the scheduling dispatcher prototype - #30
Draft
ethanresnick wants to merge 11 commits into
Draft
ethanresnick wants to merge 11 commits into
ethanresnick wants to merge 11 commits into
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Draft, for review only. This shows what cache PR 27 looks like when its Store-read and producer scheduling run on the unpublished
@zingage/schedulingdispatcher 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
a1ae315agreed v4 API changes. The API changes agreed after PR 27, applied from a patch:autoBatch?: falseonCache.get/Cache.getMany(nogetUnbatched),maxConcurrentStoreReads,maxConcurrentProducerCalls, per-calljoinInFlight: 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.59c311atemporary: vendor the unpublished scheduling prototype.vendor/zingage-scheduling-1.3.0-prototype.0.tgz(packed from scheduling commit55a4099, the build withoutoneByOne()), a relativefile:dependency, the lockfile, and a.gitignoreexception. Still does not build.111f812the port. The cache's scheduling rebuilt oncreateDispatcher,fifoBatches,ConcurrencyLimit,SharingandItem. From here the branch builds and every gate passes.10bf4e3re-vendor from scheduling commit80aa8e8. 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.4817ed8re-vendor from scheduling commit361aae3. The tarball and lockfile hash only. New in the prototype:submit/submitManytake{ signal, expedite }, and withpreserveAsyncContext,flushandclosekeep the first item's async context.93d661buse the submit options, and simplify the Store signal rule. Store reads pass{ signal, expedite }to the dispatcher; producer work that a call withautoBatch.producer: falsestarts is expedited from the start; the Store signal rule no longer looks atautoBatched.2ea8e6dcancel 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 newsrc/utils/allAborted.tsmakes the signal. Two follow-ups:8920df2finds signals that have all aborted without aSet, and17fccb6moves the rule for a read without a signal out of the helper intoCache.#readStore.The branch head is built on scheduling commit
361aae3.The vendored tarball must be replaced before any merge
A published
@zingage/cachecannot depend on afile:path, andvendor/is not in the package'sfiles. Before merge: publish the scheduling package, point the dependency at that version, deletevendor/and the.gitignoreexception.What the port does
src/wrapProducer/producerScheduler.ts(457 → 212 lines): one dispatcher (fifoBatches(producerBatching)forproduceMany, no waiting set forproduce,new ConcurrencyLimit(maxConcurrentProducerCalls)as admission when set) with aSharingin front. OnecanJoinholds the whole sharing rule. The senders,StartedTask, andstartOrRideDirectare gone.src/wrapProducer/producerClient.ts(1497 → 1366): each slot requests its own producer work; forautoBatch.producer: falsethe scheduler expedites it (new work starts expedited, joined waiting work getsitem.expedite()). The cohort starter,ProducerStarteranddecideAllare gone.collapsedRequestCountcomes fromsharing.joinedCount(item)at publish time, andqueueWaitTotalMsfromitem.startedAt - item.submittedAt.src/cache/Cache.ts(1092 → 1147): one read dispatcher (fifoBatches({ maxBatchSize: 100, ...readBatching })for a Store withgetMany, no waiting set for aget-only Store,new ConcurrencyLimit(maxConcurrentStoreReads)when set) replaces the readBatcher, the limiter field andrunLimited. Reads still never share work, so there is noSharinghere.src/utils/utils.ts(524 → 482):runLimited,LimitStoreCallandassertResultCountare gone;queueWaitMsis new. Abort-to-cancel for waiting reads is the dispatcher'ssignaloption.wrapSingleProducer.ts(65 → 45) andwrapBulkProducer.ts(98 → 73) only say whether their producer batches.Line counts at PR 27 (
704aef9), for reference:producerClient.ts1224,Cache.ts1005,utils.ts450,wrapSingleProducer.ts135,wrapBulkProducer.ts245;producerScheduler.tsdid not exist.Behaviour differences from PR 27 (all intended)
Decided before the port:
autoBatch: false(Cache) andautoBatch.store: false/autoBatch.producer: false(clients) only skip the accumulation wait: the work is expedited. It is still split atmaxBatchSize. A direct call is not guaranteed to be one Store or producer call.getManywithautoBatch.producer: falseno longer waits for all of its cache reads before it produces. Each slot expedites its own producer work when its own read settles. WithautoBatch.store: false, each slot is its own expeditedCache.get.joinInFlight: falseand the producer call started no more thancollapseOverlappingRequestsTimeseconds ago.Consequences of the dispatcher model, which follow from the above but are worth a look:
autoBatch.producer: falseto see one caller's misses alone.Sharing.requestMany's same-call guarantee does not apply; this clause incanJoinkeeps the documented "requests of one call with the same key share" true for the realistic case (duplicate ids in onegetManywithjoinInFlight: falseon aproduceproducer). This is my addition to decision 3.autoBatchedin diagnostics is false only when every request of the call was expedited, and always false for aget-only Store and aproduceproducer. A call that mixes expedited and accumulated requests reports true.autoBatcheddoes 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 wrappedgetManywith a signal), the Store gets that signal itself. Reads with different signals get a new signal fromallAborted, whose reason is the reason of the last abort, and the Store call removes its listeners when it is done. A cancelled call'sread-storemessage reportscancelled. In PR 27 only a direct read forwarded its signal, and an automatic batch always completed.close(). Without batching (aproduceproducer, aget-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.queueWaitTotalMsis close to zero, not exactly zero, for work that nothing held back.preserveAsyncContext.fifoBatchesarms 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 thatclose()orflushstart early keep that context too, as of scheduling361aae3.batchScheduleFnand expedited work. New work withautoBatch: falseis submitted expedited, never accumulates, and does not callbatchScheduleFn, as in PR 27. Waiting work that an expediting request joins has armed the schedule already; its callback then finds nothing to do.Unchanged: per-request Error slots, the
read/read-store/fetch/producemessages, abort behaviour for waiting work,close()draining, the cap of 10 concurrentgetcalls for one known-set read on aget-only Store withoutmaxConcurrentStoreReads, and that set's shared time-slice budget.Verification
Run on the branch head (
93d661b), on the tarball packed from scheduling commit361aae3. Node v26.5.0, pnpm 10.26.1.pnpm install --frozen-lockfilepnpm run buildpnpm run test:typesNODE_OPTIONS="--max-old-space-size=8192" ./node_modules/.bin/oxlint --type-aware./node_modules/.bin/oxlint./node_modules/.bin/prettier --checkon every file changed since704aef9pnpm run test:dockerpnpm run test:docker:downThe 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.tsandwrapBulkProducer.test.tsmoved intoproducerScheduler.test.ts, because the per-wrapper scheduler functions no longer exist. New tests cover: mixed and all-expeditedautoBatched; 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); theallAbortedhelper; the per-set cap of 10 and its abort; andclose()with an acceptedgetManyon a schedule that never fires.A mutation check removed each guard that the port moved (the close order, the
signalandexpeditesubmit options ofgetandgetMany, 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: passingsignaltosubmiton the capped path (a known set on aget-only Store withoutmaxConcurrentStoreReads) 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 commit55a4099; not re-measured on80aa8e8or361aae3.704aef9)gethit,MemoryStore(get-only)getMany([x])hit,MemoryStoregetManyof 20 misses,produceMany,MemoryStoregethit,getManyStore over aMemoryStoregetMany([x])hit,getManyStoregetManyof 20 misses,produceMany,getManyStoreThe last three rows are extra: a
MemoryStoreisget-only, so only they exercisefifoBatchesfor 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
submit(input, { signal })(since361aae3) cancels a waiting read, which removed the cache's own helper. The read's input still repeats the signal, becauseinvokedecides 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 latersubmitis accepted silently, and a secondclose()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.requesthas noexpedite.submithas the option since361aae3, so the scheduler passes it inSharing'sstartcallback, from a flag on the request, and still callsitem.expedite()itself when the request joined waiting work.accumulates && items.some(item => !item.expedited)in two places, and has to know itself whether its waiting set accumulates.Item.startedAtis optional insideinvoke, where it is always set, soqueueWaitMsandcanJoincarry a fallback. Item times are plain numbers; the cache has a brandedPerformanceNow.Itemis invariant in its input and result types, so a helper that takes "any item" needs a structural parameter type.Infinityis rejected, so both owners mapInfinityto "no admission" themselves.getcalls per known set on aget-only Store is apLimitaroundsubmitin the cache, and that set's time-slice budget travels in each item's input.preserveAsyncContextbinds per accumulation, not per batch (difference 11).Sharing.requestandSharing.requestManydiffer for one public call whose requests arrive one at a time; the cache added the same-call clause tocanJoin(difference 6).BatchOptionsandDEFAULT_MAX_BATCH_SIZEstill live inbatcher.ts, and its doc still says a direct dispatch is never split.Review findings left for a decision
From the
/simplifypass (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:readSingleStoreinutils.tsstill handles a list, but production now always passes one request for aget-only Store. Only test fixtures use the list. ATODOmarks it.readStoreObserved,cancelWaitingOnAbort, the read dispatcher) could move fromutils.tsandCache.tsinto asrc/cache/storeReads.ts, mirroringproducerScheduler.ts.ProducerScheduler.requeststill returns the prototype'sSharedOutcome. The scheduler now expedites from a flag on the request's call, so the return type could shrink to{ result, joined }; the scheduler tests readitemandstartReason."batcher"and"collapsed-task-creator"now log nothing. Removing them changes the publicComponentNametype.diagnostics.tsand the README next to "join" and "work"; the client's localItemtype and the word "call" each carry more than one meaning inproducerClient.ts.🤖 Generated with Claude Code