From 2303bb7bc1c1965073323142e8ce0eb82d6f2cb6 Mon Sep 17 00:00:00 2001 From: Effect Bot Date: Mon, 16 Nov 2026 11:35:32 +0000 Subject: [PATCH] Hand every fiber resumption to the captured async context The run loop no longer distinguishes native AsyncResource entry from a deferred hand-off. Each resumption goes through runInAsyncScope, and the context decides whether it runs synchronously or later. The race handling for in-flight resumptions moves out of the common path, so native Node resumption skips the re-entry into evaluate it used to make. --- packages/effect/src/Scheduler.ts | 13 ++-- packages/effect/src/internal/effect.ts | 104 +++++++++++++------------ packages/effect/test/Effect.test.ts | 59 ++++++++------ 3 files changed, 99 insertions(+), 77 deletions(-) diff --git a/packages/effect/src/Scheduler.ts b/packages/effect/src/Scheduler.ts index f356d00391..d9056a6d4a 100644 --- a/packages/effect/src/Scheduler.ts +++ b/packages/effect/src/Scheduler.ts @@ -61,11 +61,14 @@ export interface Scheduler { * * **Details** * - * Each captured context resumes its fiber once. `runInAsyncScope` either calls - * `fn` synchronously, or arranges to call it exactly once later and returns. - * A fiber whose resumption is still pending defers interrupts, and other - * resumptions, until it lands. A fiber interrupted before its start lands never - * runs. `emitDestroy` is called when `runInAsyncScope` returns. + * Each captured context resumes its fiber once. Fibers hand every resumption + * to `runInAsyncScope`, and the context decides where and when it runs: it + * either calls `fn` synchronously, as a `node:async_hooks` `AsyncResource` + * does, or arranges to call it exactly once later and returns. Fibers handle + * both the same way. Until `fn` is called, interrupts are deferred and a value + * that overtakes an interrupt is delivered first; a fiber interrupted before + * its start lands never runs. `emitDestroy` is called when `runInAsyncScope` + * returns. * * **Gotchas** * diff --git a/packages/effect/src/internal/effect.ts b/packages/effect/src/internal/effect.ts index 58720b9da6..146b14fdc5 100644 --- a/packages/effect/src/internal/effect.ts +++ b/packages/effect/src/internal/effect.ts @@ -632,21 +632,59 @@ export class FiberImpl implements Fiber.Fiber { // have overtaken an interrupt. It is delivered first, as if it had won. this._overtaken = effect return - } else if (this._asyncContext !== undefined) { - const asyncContext = this._asyncContext - this._asyncContext = undefined - try { - // Native resources always run the resumption synchronously, so only - // scheduler-provided contexts need the hand-off bookkeeping - return asyncContext.constructor === AsyncResource - ? asyncContext.runInAsyncScope(this.evaluate, this, effect) - : this.handOff(asyncContext, effect) - } finally { - // Each captured context is resumed once, so release it for async_hooks - // consumers like vitest's detectAsyncLeaks. - asyncContext.emitDestroy() - } - } else if (this._yielded !== undefined) { + } + const asyncContext = this._asyncContext + if (asyncContext === undefined) { + return this.run(effect) + } + // The captured context runs the resumption, now or later + this._asyncContext = undefined + this._resuming = true + try { + asyncContext.runInAsyncScope(this.resume, this, effect) + } catch (error) { + this._resuming = false + throw error + } finally { + // Each captured context is resumed once, so release it for async_hooks + // consumers like vitest's detectAsyncLeaks. + asyncContext.emitDestroy() + } + } + // Called by the captured context, synchronously or later. An interrupt + // requested meanwhile is deferred until the resumption has landed, so a value + // handed to the fiber is never dropped. + resume(effect: Primitive): void { + this._resuming = false + if (this._deferredInterrupt || this._overtaken !== undefined || this._pendingStart) { + return this.resumeRaced(effect) + } + this.run(effect) + } + // The resumption is a fork's start, or raced an interrupt + resumeRaced(effect: Primitive): void { + const overtaken = this._overtaken + this._overtaken = undefined + if (this._pendingStart) { + // A fiber interrupted before it starts never runs: an interrupt in flight + // drops the start that overtook it, and the run loop replaces a start + // with an interrupt deferred behind it. + this._pendingStart = false + return this.run(effect) + } + let interrupt = this._deferredInterrupt + this._deferredInterrupt = false + if (overtaken !== undefined) { + effect = overtaken + interrupt = true + } + this.run(effect) + if (interrupt && this._exit === undefined && this.interruptible && !this._running) { + this.evaluate(failCause(this._interruptedCause!) as any) + } + } + run(effect: Primitive): void { + if (this._yielded !== undefined) { const yielded = this._yielded as () => void this._yielded = undefined yielded() @@ -689,40 +727,6 @@ export class FiberImpl implements Fiber.Fiber { this.cache = { ...cache, span: undefined, stackFrame: undefined } } } - handOff(asyncContext: Scheduler.AsyncContext, effect: Primitive): void { - this._resuming = true - try { - asyncContext.runInAsyncScope(this.resume, this, effect) - } catch (error) { - this._resuming = false - throw error - } - } - // The captured async context can run the resumption later, in the context - // that owns the fiber. An interrupt requested meanwhile is delivered once the - // resumption suspends, so a value handed to the fiber is never dropped. - resume(effect: Primitive): void { - this._resuming = false - let interrupt = this._deferredInterrupt - this._deferredInterrupt = false - if (this._overtaken !== undefined) { - effect = this._overtaken - this._overtaken = undefined - interrupt = this._interruptedCause !== undefined - } - if (this._pendingStart) { - // A fiber interrupted before it starts never runs, whichever landed first - this._pendingStart = false - if (interrupt) { - interrupt = false - effect = failCause(this._interruptedCause!) as any - } - } - this.evaluate(effect) - if (interrupt && this._exit === undefined && this.interruptible && !this._running) { - this.evaluate(failCause(this._interruptedCause!) as any) - } - } runLoop(effect: Primitive): Exit.Exit | Yield { const prevFiber = (globalThis as any)[currentFiberTypeId] ;(globalThis as any)[currentFiberTypeId] = this @@ -5683,7 +5687,7 @@ export const forkUnsafe = ( } else { // Preserve the fork context rather than the dispatcher's context. child._asyncContext = captureAsyncContext(child.cache.scheduler) - child._pendingStart = child._asyncContext !== undefined && child._asyncContext.constructor !== AsyncResource + child._pendingStart = child._asyncContext !== undefined parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect as any), 0) } return child diff --git a/packages/effect/test/Effect.test.ts b/packages/effect/test/Effect.test.ts index 4bd95370cc..74394181f6 100644 --- a/packages/effect/test/Effect.test.ts +++ b/packages/effect/test/Effect.test.ts @@ -5484,29 +5484,44 @@ describe("Effect", () => { assert.deepStrictEqual(fiber.pollUnsafe(), Exit.succeed(["owner", "owner"])) }) - for (const interruptFirst of [false, true]) { - it(`delivers a value before an interrupt ${interruptFirst ? "it overtakes" : "requested while it lands"}`, async () => { - const { land, scheduler } = makeScheduler() - const seen: Array = [] - let wake!: () => void - const fiber = Effect.runFork( - Effect.uninterruptibleMask((restore) => - restore(Effect.callback((resume) => { - wake = () => resume(Effect.void) - })).pipe(Effect.andThen(Effect.sync(() => seen.push(current())))) - ).pipe(Effect.andThen(Effect.never)), - { scheduler } + for (const forked of [false, true]) { + for (const interruptFirst of [false, true]) { + it( + `delivers a value before an interrupt ${interruptFirst ? "it overtakes" : "requested while it lands"}${ + forked ? ", in a fork" : "" + }`, + async () => { + const { land, scheduler } = makeScheduler() + const seen: Array = [] + let wake!: () => void + const body = Effect.uninterruptibleMask((restore) => + restore(Effect.callback((resume) => { + wake = () => resume(Effect.void) + })).pipe(Effect.andThen(Effect.sync(() => seen.push(current())))) + ).pipe(Effect.andThen(Effect.never)) + let fiber!: Fiber.Fiber + if (forked) { + // A fork's start lands through the captured context too, so the + // race must still be handled after it has started + Effect.runFork( + Effect.forkDetach(body).pipe(Effect.tap((child) => Effect.sync(() => (fiber = child)))), + { scheduler } + ) + } else { + fiber = Effect.runFork(body, { scheduler }) + } + await land() + storage.run("waker", () => { + if (interruptFirst) fiber.interruptUnsafe() + wake() + if (!interruptFirst) fiber.interruptUnsafe() + }) + await land() + assert.deepStrictEqual(seen, ["owner"]) + assert.isTrue(Exit.hasInterrupts(fiber.pollUnsafe()!)) + } ) - await land() - storage.run("waker", () => { - if (interruptFirst) fiber.interruptUnsafe() - wake() - if (!interruptFirst) fiber.interruptUnsafe() - }) - await land() - assert.deepStrictEqual(seen, ["owner"]) - assert.isTrue(Exit.hasInterrupts(fiber.pollUnsafe()!)) - }) + } } for (const dispatched of [false, true]) { it(`interrupts a fork before it starts, ${dispatched ? "after" : "before"} its start is dispatched`, async () => {