Repository navigation
Conversation
🦋 Changeset detectedLatest commit: 629d37e The changes in this PR will be included in the next version bump. This PR includes changesets to release 40 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Bundle Size AnalysisGenerated from PR build output; treat the content below as untrusted.
|
that sounds a bit crazy to me |
f6947b4 to
b920a0d
Compare
| } | ||
| evaluate(effect: Primitive): void { | ||
| const scheduler = this.cache.scheduler | ||
| if (Scheduler.isParkingScheduler(scheduler)) scheduler.resume(this, effect as any) |
There was a problem hiding this comment.
I think the fiber cache could just have a cache.schedulerIsParking flag instead of doing the typeof check every time? A type cast is fine here.
There was a problem hiding this comment.
Done in fbee5ed. The cache now has an internal schedulerIsParking flag, set once in makeFiberContextCache, and evaluate and park read it through a cast. The setContext path that keeps a suspended fiber's old scheduler sets the flag to true along with that scheduler.
| * @since 4.2.0 | ||
| */ | ||
| export const isParkingScheduler = (scheduler: Scheduler): scheduler is ParkingScheduler => | ||
| typeof (scheduler as Partial<ParkingScheduler>).park === "function" && |
There was a problem hiding this comment.
We could add a ParkingSchedulerTypeId instead?
There was a problem hiding this comment.
Done in fbee5ed. Scheduler.ParkingSchedulerTypeId is now part of the ParkingScheduler interface, and isParkingScheduler is ParkingSchedulerTypeId in scheduler. A scheduler with park and resume but no type id runs as before, and a test covers that. TestClock's wrapper sets the type id only when its parent has it.
| import * as Layer from "effect/Layer" | ||
| import * as Scheduler from "effect/Scheduler" | ||
|
|
||
| const compatibilityFlags: Record<string, boolean | undefined> | undefined = (globalThis as any).Cloudflare |
There was a problem hiding this comment.
move all the internals to the bottom of the file
There was a problem hiding this comment.
Done in fbee5ed. compatibilityFlags, waits and noop are now under an Internal section at the end of the file, after layer.
4931607 to
8fb0378
Compare
|
@tim-smart I think this is ready to go at least for testing, we should probably get some input from CF folks to see if we are correct in the assumptions |
ab80daa to
2d92861
Compare
Microtask dispatch kept yielding fibers off the event loop. A yield parks the fiber, so its owner stays open while the dispatcher's timer is pending.
…cases Scheduler.test.ts keeps three tests: a parked and a forked fiber run only when the scheduler resumes them, under TestClock; an interrupt after a wake wins; setContext moves a suspended fiber off its ParkingScheduler. The Worker suite keeps one test: a fiber woken by another request resumes in its owner, which stays open until then.
bf56e78 to
e38ab2d
Compare
80ed3d0 to
479fbaa
Compare
732f49a to
8434cb5
Compare
Summary
On Cloudflare Workers, a fiber that suspends in one request and is woken by another never completes, and the waking request fails with the request-bound
AsyncLocalStorageerror. workerd ties I/O objects, timers and async contexts to the request that created them. The only supported way to run code in another request is to settle a promise that request created, so workerd queues the reaction onto it.CloudflareSchedulerresumes each fiber in the request that owns it:parkcreates a promise in the current request and keeps its resolver for that fiber.resume, which settles the promise. The fiber runs in the reaction, in the owner, with the owner's store, I/O objects and timers. The waking request does not wait for it. workerd cannot tell which request is running, so a fiber woken by its own request takes the same path, a microtask later. Because a woken fiber never resumes inside the call that wakes it, the scheduler'sexecutionModeis"async". Queued work, such as a yield or a forked fiber's start, usesMixedScheduler's async dispatch, so a fiber that yields gives way to the event loop. A yield parks the fiber, so its owner stays open until the dispatch runs.waitUntiland sets a timer that is cleared when the fiber resumes. workerd cancels a request whose only pending work is a promise another request settles, and without the timer the Worker tests fail with "the creating request has already been completed or canceled". The timer never fires and never ends or interrupts the fiber.Core changes
The fiber calls its scheduler, and the scheduler owns everything else:
Scheduler.ParkingSchedulerTypeId, whichScheduler.isParkingSchedulerchecks. A scheduler without it is left alone, even if it hasparkandresumemethods. The fiber cache records the answer once per cache in an internalschedulerIsParkingflag, so parking and resuming read a flag instead of checking the scheduler.parkon such a scheduler.fiber.evaluate(effect)calls itsresume, and otherwise runs the fiber. The previous body ofevaluateisrun, which is also the entry aParkingSchedulercalls.SchedulerandMixedSchedulerare unchanged, so existing custom schedulers need no changes.AsyncResourcehandling is the code that was already there; the capture moved into the one helper called where a fiber stops, which also makes theparkcall.interruptUnsaferecords the interrupt in the existing_deferredInterruptflag for a fiber that is not running, because a parking scheduler may already hold the value the fiber was woken with and drops later effects.setContexton a fiber that is suspended or has not started updates the context at once and leaves the fiber'sParkingSchedulerin its cache, so the scheduler that may hold the fiber's wait still gets theresumecall. The fiber takes the cache of its context inrunLoop, after its async scope has been entered, so asetContextmade by anasync_hooksbeforehook on the way in is taken too. That is one comparison per run, for every fiber; when it differs,runLoopcallssetContextwith the fiber's own context, so replacement has one code path. The scheduler the fiber already stores is the only record.setContextno longer returns early for contexts that share a cache root. That return was a shortcut: the code after it resolves the same cache object and stores it. It would also stoprunLoop's call from taking the cache. The@internalContext.hasSameCachehad no other production use, and the repository'seffect/no-unused-internallint rule rejects an@internalexport in that state, so it is removed. It was in the JavaScript ofeffect4.1.0 to 4.1.4 and absent from the published declarations.TestClock's scheduler wrapper carries the type id, and forwardsparkandresume, whenisParkingScheduleraccepts the wrapped scheduler.Everything added is
@stability unstable.Compatibility
Fiber.setContextcan give another scheduler to a fiber that is suspended or has not started. The change is applied when the fiber next runs: itsParkingSchedulergets thatresumecall, and the fiber uses the new scheduler from that run on. Until thenfiber.contexthas the new scheduler whilefiber.cache.schedulerandfiber.currentDispatcherhave the old one. Other context entries, exited fibers, running fibers and fibers of other schedulers behave as before.CloudflareSchedulerthis way is in its owner, and that run clears the owner's timer. Its later waits follow the new scheduler. With a scheduler that does not park they are as unprotected as withoutCloudflareScheduler: finishing such a wait from another request completed with foreign I/O on compatibility date 2025-01-01, and failed with the request-boundAsyncLocalStorageerror on 2026-07-01, leaving the fiber pending.Effect.callbackthat resumes with a resource has to release it in its cancellation cleanup.handle_cross_request_promise_resolution(default from 2024-10-14), owner resumption is impossible, so the constructor throws.setTimeoutandwaitUntilthrow in a Worker's global scope and workerd has no way to ask whether a request is running, soparkcatches that. A fiber parked there has no owner and resumes in the request that wakes it.Platform limitations
This does not extend Cloudflare's request lifetime limits, such as the limit on
waitUntilwork after the response is sent or the client disconnects. A fiber whose owner has ended cannot resume: workerd drops the resumption with a warning. A fiber that is never woken keeps its owner running until those limits end it, and keeps a Durable Object from hibernating.Cost
Base is
3d13d1e84a. Node 26.13, fresh processes pinned to one CPU, ns per operation.Bundle
The repository's Rollup pipeline on built output, min + gzip-9 bytes:
Effect.runFork)Across the 31 fixtures that change, the PR adds 316 minified and 88 gzip bytes on average. The type id and the cache flag cost 6, 20 and 18 gzip bytes over
32b88e6b0c, which checked the two methods withtypeof. Most of that is the type id string and the flag's property name, which minification keeps.These figures are net of removing the base
setContextshortcut, which is worth about 34 gzip bytes. At32b88e6b0c, with the shortcut kept, the same code measured +105, +94 and +103.Run time
Measured at
32b88e6b0c, before the type id and cache flag, and not repeated. Built output, base and head processes run in rotating order. Each process reports the median of nine blocks (500,000 operations, 100,000 foryieldNow) after four warm-up blocks. The interval is a 95% bootstrap interval of the paired median.node:async_hooksyieldNow, withyieldNow, withoutprovideServiceround trip, withprovideServiceround trip, withoutThe promise wait is one fiber repeatedly awaiting
Effect.promise(() => Promise.resolve(1)). Its slowdown withoutnode:async_hooksis measurable and open; 60 pairs at5d32c99096gave +2.4% [+0.3%, +4.1%]. TheprovideServicerow provides a service that is not fiber cached aroundEffect.succeed, which is the path that used the removedsetContextshortcut twice per operation.runis 423 bytes of V8 bytecode (evaluateis 426 on base),evaluateis 46,runLoopis 453 (413 on base) andsetContextis 132 (104 on base). V8 does not inline a function above 460, and it still inlinesruninto the callbacks that resume a fiber.Measured from source at
5d32c99096and not repeated since, median of 11 interleaved processes, with and withoutnode:async_hooks:Validation
pnpm lint-fix,pnpm lint,pnpm checkandpnpm jsdocs --checkpass.pnpm vitest --run --project effect --project effect-isolated --project @effect/platform-cloudflare --project @effect/vitestpasses atbf56e78684, rebased onv4/next-minorcf6cce59d1: 470 files, 15,202 passed, 15 expected fail, 72 skipped.effect-isolatedholds the 13 schema compiler suites (289 tests) thatvitest.config.tskeeps out ofeffect.On Bun 1.4.2,
Effect.test.ts,Scheduler.test.tsandTestClock.test.tspassed (383 passed, 3 skipped) and@effect/platform-bunpassed (165) atfbee5ed5f1. At720ca865dc,Scheduler.test.tsandCloudflareScheduler.test.tspass on Bun.Scheduler.test.tshas three tests for the core change, using a testParkingSchedulerthat holds a woken fiber until it runs it:TestClock, a parked fiber and a forked fiber run only when the scheduler resumes them;setContextmoving a suspended fiber to aMixedScheduler: the parking scheduler resumes it once, and its next wait uses the new scheduler.Removing any of these makes a test fail: the
parkcall where a fiber stops, theparkcall in fork, the deferred interrupt, thesetContextkeep path or itsschedulerIsParking: true, therunLoopcache comparison, orTestClockforwarding the type id. AsetContextmade from anasync_hooksbeforehook takes the same path and has no separate test.CloudflareScheduler.test.tshas one Worker test, run on workerd through the package's existing Miniflare 4 dependency: a fiber woken by another request resumes in its owner, with the owner'sAsyncLocalStoragestore and I/O, after the owner has responded, and its timer is cleared. It fails if any of these is removed: the timer,waitUntil,clearTimeout, or resuming through the owner's promise.Not run: the pg integration suites, a deployed Cloudflare Worker (Miniflare only).
Closes EFF-3794