From 3b593dd5d27eeabf28be8db056178438b773e326 Mon Sep 17 00:00:00 2001 From: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> Date: Tue, 20 Oct 2026 11:19:00 -0700 Subject: [PATCH] fix(codemode): run each job to completion (#54276) Co-authored-by: Aiden Cline --- packages/codemode/interpreter-support.md | 3 + packages/codemode/src/interpreter/execute.ts | 25 +- .../codemode/src/interpreter/extensions.ts | 2 +- .../codemode/src/interpreter/interpreter.ts | 53 +++- packages/codemode/src/interpreter/promises.ts | 271 +++++++++++++++--- packages/codemode/test/promise.test.ts | 58 ++++ 6 files changed, 354 insertions(+), 58 deletions(-) diff --git a/packages/codemode/interpreter-support.md b/packages/codemode/interpreter-support.md index e02a1c4e0fc..0179ac1e2af 100644 --- a/packages/codemode/interpreter-support.md +++ b/packages/codemode/interpreter-support.md @@ -274,6 +274,9 @@ Math.floor)` is `"3"`). A detached method loses its receiver, as in JS: `values. unless its cleanup fails, and direct self-resolution rejects with a `TypeError`. - [x] Every `await` (including of plain values and already-settled promises) defers its continuation one reaction turn, so concurrent async functions interleave at await points as in JavaScript. +- [x] Each job runs to completion: code between two awaits, and an async function's body up to its first await, + finishes before another job runs, even when the scheduler preempts a long job. Tool calls still run + concurrently. - [x] Combinators settle one reaction turn after their deciding member (V8-observable ordering): reactions already attached to members run first, and an aggregate cannot beat a plain value settling in the same turn into a `Promise.race`. Exact microtask-count parity beyond this observable ordering is not a documented guarantee. diff --git a/packages/codemode/src/interpreter/execute.ts b/packages/codemode/src/interpreter/execute.ts index c1fdab13c6c..9643e9393ff 100644 --- a/packages/codemode/src/interpreter/execute.ts +++ b/packages/codemode/src/interpreter/execute.ts @@ -40,16 +40,21 @@ export const executeProgram = ( const program = parseProgram(code) const pending = new Pending(scope, builtins.Promise) const ctx = new Interpreter({ tools, pending, builtins, logs, globals }) - const result = (yield* toBoundary(ctx, yield* ctx.run(program))) ?? null - returned = { value: result, pending } - const warnings = yield* pending.interrupt() - return { - ok: true, - value: result, - ...(warnings.length > 0 ? { warnings } : {}), - ...logged(), - toolCalls: tools.calls, - } satisfies Result + // The main job holds the turn until leftover promise work is interrupted. + return yield* pending.turn.hold( + Effect.gen(function* () { + const result = (yield* toBoundary(ctx, yield* ctx.run(program))) ?? null + returned = { value: result, pending } + const warnings = yield* pending.interrupt() + return { + ok: true, + value: result, + ...(warnings.length > 0 ? { warnings } : {}), + ...logged(), + toolCalls: tools.calls, + } satisfies Result + }), + ) }), (scope, exit) => Scope.close(scope, exit), ) diff --git a/packages/codemode/src/interpreter/extensions.ts b/packages/codemode/src/interpreter/extensions.ts index 530b4575c86..a45a435d2b9 100644 --- a/packages/codemode/src/interpreter/extensions.ts +++ b/packages/codemode/src/interpreter/extensions.ts @@ -155,7 +155,7 @@ export const extensionGlobals = ( return settle(Effect.fail(reason)) } if (!(result instanceof Promise)) return settle(Effect.succeed(result)) - return ctx.pending.create(settle(Effect.tryPromise({ try: () => result, catch: (reason) => reason }))) + return ctx.pending.createHost(settle(Effect.tryPromise({ try: () => result, catch: (reason) => reason }))) }) return extensions.flatMap((extension) => diff --git a/packages/codemode/src/interpreter/interpreter.ts b/packages/codemode/src/interpreter/interpreter.ts index b60ab8404a9..4527078e634 100644 --- a/packages/codemode/src/interpreter/interpreter.ts +++ b/packages/codemode/src/interpreter/interpreter.ts @@ -419,9 +419,11 @@ class Frame { }).pipe(Effect.ensuring(Effect.sync(() => self.scopes.pop()))) } - // Fork at the call site so admission and hooks occur when the call is made. + // Fork at the call site so admission and hooks occur when the call is made. Arguments cross on the caller's turn, + // since `toJSON` is program code; the host call runs without it, so tool calls stay concurrent. private createToolCallPromise(path: ReadonlyArray, args: Array): Effect.Effect { - return this.ctx.pending.create(this.ctx.tool((json) => this.ctx.tools.execute(path, json), args)) + const pending = this.ctx.pending + return pending.create(this.ctx.tool((json) => pending.turn.leave(this.ctx.tools.execute(path, json)), args)) } // Fiber exits make settlement idempotent; yielding prevents inline continuation. @@ -429,10 +431,17 @@ class Frame { const pending = this.ctx.pending return Effect.suspend(() => { pending.markObserved(promise) - return Effect.flatMap(pending.await(promise), (exit) => Effect.andThen(Effect.yieldNow, exit)) + return Effect.flatten( + pending.turn.suspend(Effect.flatMap(pending.await(promise), (exit) => Effect.as(Effect.yieldNow, exit))), + ) }) } + // End this job; the program continues in a later one, after the jobs already waiting. + nextJob(): Effect.Effect { + return this.ctx.pending.turn.suspend(Effect.yieldNow) + } + private evaluateStatement(node: Statement | ModuleDeclaration): Effect.Effect { switch (node.type) { case "ExpressionStatement": @@ -730,7 +739,7 @@ class Frame { iterator ? self.closeIterator(iterator, node, awaiting) : awaiting - ? Effect.andThen(cursor?.close ?? Effect.void, Effect.yieldNow) + ? Effect.andThen(cursor?.close ?? Effect.void, self.nextJob()) : (cursor?.close ?? Effect.void) if (left.type === "RestElement" || left.type === "AssignmentPattern") { @@ -887,7 +896,7 @@ class Frame { const called = yield* Effect.exit(self.call(iterator.next, iterator.iterator, [], node)) if (!Exit.isSuccess(called)) { - if (awaiting) yield* Effect.yieldNow + if (awaiting) yield* self.nextJob() return yield* Effect.failCause(called.cause) } const captured = yield* Effect.exit( @@ -897,7 +906,7 @@ class Frame { }), ) if (!Exit.isSuccess(captured)) { - if (awaiting) yield* Effect.yieldNow + if (awaiting) yield* self.nextJob() return yield* Effect.failCause(captured.cause) } return { @@ -915,7 +924,9 @@ class Frame { awaiting = true, ): Effect.Effect { const close = get(iterator.iterator, "return") - if (close === undefined || close === null) return iterator.asynchronous || !awaiting ? Effect.void : Effect.yieldNow + if (close === undefined || close === null) { + return iterator.asynchronous || !awaiting ? Effect.void : this.nextJob() + } const self = this return Effect.gen(function* () { const method = self.requireIteratorMethod(close, "Iterator return", node) @@ -930,14 +941,14 @@ class Frame { const called = yield* Effect.exit(self.call(method, iterator.iterator, [], node)) if (!Exit.isSuccess(called)) { - if (awaiting) yield* Effect.yieldNow + if (awaiting) yield* self.nextJob() return yield* Effect.failCause(called.cause) } const captured = yield* Effect.exit( Effect.sync(() => get(self.requireIteratorObject(called.value, "Iterator return() result", node), "value")), ) if (!Exit.isSuccess(captured)) { - if (awaiting) yield* Effect.yieldNow + if (awaiting) yield* self.nextJob() return yield* Effect.failCause(captured.cause) } if (awaiting) yield* self.awaitValue(captured.value) @@ -1814,14 +1825,22 @@ class Frame { invocation.generatorAsync = asynchronous const builtins = this.ctx.builtins const result = (value: Value, done: boolean) => record(builtins.Object, { value, done }) + const turn = this.ctx.pending.turn const request = (kind: GeneratorRequestKind, value: Value) => { const request = { kind, value, response: Deferred.makeUnsafe() } + // A body that ran on the caller's turn has answered or suspended when it hands the turn back. An answer still + // pending can only be an async generator's: its promise settles when the body answers, without the turn. + const answer = Effect.suspend(() => + Deferred.isDoneUnsafe(request.response) + ? Deferred.await(request.response) + : turn.leave(Deferred.await(request.response)), + ) if (!asynchronous && state.active) return Effect.die(typeError("Generator is already running.")) if (asynchronous && (state.completed || (!state.started && kind !== "next"))) { state.started = true state.completed = true state.pending.push(request) - if (state.draining) return Deferred.await(request.response) + if (state.draining) return answer state.draining = true return Effect.andThen( this.ctx.pending.fork( @@ -1829,7 +1848,7 @@ class Frame { .completeGeneratorRequests(state, true) .pipe(Effect.ensuring(Effect.sync(() => (state.draining = false)))), ), - Deferred.await(request.response), + answer, ) } if (state.completed) { @@ -1844,9 +1863,13 @@ class Frame { state.pending.push(request) if (state.available) { + // The body is parked waiting for a request: it runs this step on the caller's turn. const available = state.available state.available = undefined - Deferred.doneUnsafe(available, Exit.succeed(undefined)) + return Effect.andThen( + turn.handOff(Effect.sync(() => Deferred.doneUnsafe(available, Exit.succeed(undefined)))), + answer, + ) } if (!state.started) { state.started = true @@ -1872,9 +1895,9 @@ class Frame { yield* invocation.completeGeneratorRequests(state, asynchronous) state.completed = true }) - return Effect.andThen(this.ctx.pending.fork(body), Deferred.await(request.response)) + return Effect.andThen(this.ctx.pending.fork(body), answer) } - return Deferred.await(request.response) + return answer } const proto = get(fn, "prototype") return new GeneratorObj(proto instanceof Obj ? proto : builtins.Generator, asynchronous, request) @@ -1912,7 +1935,7 @@ class Frame { if (next) return Effect.succeed(next) state.available = Deferred.makeUnsafe() return Effect.andThen( - Deferred.await(state.available), + this.ctx.pending.turn.park(Deferred.await(state.available)), Effect.sync(() => this.dequeueGeneratorRequest(state)!), ) } diff --git a/packages/codemode/src/interpreter/promises.ts b/packages/codemode/src/interpreter/promises.ts index 4a82667e076..fde5f60efcf 100644 --- a/packages/codemode/src/interpreter/promises.ts +++ b/packages/codemode/src/interpreter/promises.ts @@ -16,8 +16,189 @@ const capability = (ctx: Interpreter, name: string, settle: (value: Value) return undefined }) +type Waiter = { + readonly fiber: Fiber.Fiber + readonly resume: (effect: Effect.Effect) => void + next?: Waiter + removed: boolean +} + +// Program fibers that synchronous starts and handbacks may nest on the host stack. Deeper ones start and resume +// through the scheduler, so deep recursion through async calls cannot overflow the host stack. +const MAX_NESTING = 100 + +type Handback = { + readonly fiber: Fiber.Fiber + returned: boolean + resume?: (effect: Effect.Effect) => void +} + +/** + * The right to run program code. JavaScript runs one job at a time: code between two awaits finishes before another + * job starts. Effect preempts a busy fiber so timeouts and host work still run, so only the fiber holding the turn may + * run program code. A synchronous call into another fiber (an async function's body up to its first await, a + * generator step) lends that fiber the turn and gets it back when the callee suspends or ends. An await gives the turn + * to the next waiting job and queues to take it back. Work that only settles a promise or runs host code leaves + * without it, so tool calls stay concurrent and resolvers settle in the call, as in JavaScript. + */ +export class Turn { + private holder: Fiber.Fiber | undefined + // Callers waiting for a callee to hand the turn back, innermost last. + private readonly handbacks: Array = [] + // Jobs waiting to take the turn, in the order they became ready. + private first: Waiter | undefined + private last: Waiter | undefined + private nesting = 0 + + // Take the turn when it is free, after the jobs already waiting. + readonly take: Effect.Effect = Effect.withFiber((fiber) => { + if (this.holder === undefined) { + this.holder = fiber + return Effect.void + } + return Effect.callback((resume) => { + const waiter: Waiter = { fiber, resume, removed: false } + if (this.last === undefined) this.first = waiter + else this.last.next = waiter + this.last = waiter + // Interrupted while waiting, or after the turn was granted but before it ran. + return Effect.sync(() => { + if (this.holder === fiber) this.release(fiber) + else waiter.removed = true + }) + }) + }) + + // Run `effect` holding the turn, as the program's main job does. + hold(effect: Effect.Effect): Effect.Effect { + return Effect.withFiber((fiber) => + Effect.andThen(this.take, effect).pipe(Effect.ensuring(Effect.sync(() => this.release(fiber)))), + ) + } + + // Give up the turn, back to the innermost caller waiting for it or to the next waiting job. + release(fiber: Fiber.Fiber): void { + if (this.holder !== fiber) return + const back = this.handbacks.pop() + if (back !== undefined) { + this.holder = back.fiber + this.handBack(back) + return + } + let next = this.first + while (next !== undefined && next.removed) next = next.next + this.first = next?.next + if (this.first === undefined) this.last = undefined + this.holder = next?.fiber + // Resume in the scheduler, as a yield would: release can run inside another fiber's step. + if (next !== undefined) next.fiber.currentDispatcher.scheduleTask(() => next.resume(Effect.void), 0) + } + + // Wait without the turn, then queue for it like any job that became ready. An interrupted fiber stops without it. + suspend(wait: Effect.Effect): Effect.Effect { + return Effect.uninterruptibleMask((restore) => + Effect.withFiber((fiber) => { + this.release(fiber) + return Effect.flatMap(Effect.exit(restore(wait)), (exit) => + Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause) ? exit : Effect.andThen(restore(this.take), exit), + ) + }), + ) + } + + // Wait without the turn and finish without it, for work that only settles a promise or runs host code. + leave(wait: Effect.Effect): Effect.Effect { + return Effect.withFiber((fiber) => { + this.release(fiber) + return wait + }) + } + + // Run `start`, which wakes a fiber parked with `park`, and continue once it hands the turn back. + handOff(start: Effect.Effect): Effect.Effect { + return Effect.withFiber((fiber) => { + const back: Handback = { fiber, returned: false } + this.handbacks.push(back) + return Effect.andThen(this.nest(start), awaitHandback(back)) + }) + } + + // Wait without the turn for a caller to hand it over with `handOff`. + park(wait: Effect.Effect): Effect.Effect { + return Effect.uninterruptibleMask((restore) => + Effect.withFiber((fiber) => { + this.release(fiber) + // The wake runs inside the caller's step; when that is deep, yield so the body continues on its own stack. + return Effect.tap(restore(wait), () => { + this.holder = fiber + return this.nesting > MAX_NESTING ? Effect.yieldNow : Effect.void + }) + }), + ) + } + + // Fork a fiber that runs program code. It starts with the caller's turn, and the caller continues once the fiber + // suspends or ends; the fiber gives up the turn whenever it ends. + fork(effect: Effect.Effect, scope: Scope.Scope): Effect.Effect, never, R> { + return Effect.withFiber((caller) => { + const back: Handback = { fiber: caller, returned: false } + this.handbacks.push(back) + let started = false + const body = Effect.withFiber((fiber) => { + started = true + this.holder = fiber + return effect + }) + const forked = + this.nesting < MAX_NESTING + ? this.nest(Effect.forkIn(body, scope, { startImmediately: true })) + : Effect.forkIn(body, scope) + return Effect.flatMap(forked, (fiber) => { + fiber.addObserver(() => { + if (started) return this.release(fiber) + // Forked into a closing scope: it never took the turn, so the caller keeps it. + const index = this.handbacks.lastIndexOf(back) + if (index >= 0) this.handbacks.splice(index, 1) + this.handBack(back) + }) + // A callee that suspends without blocking hands the turn back before `forkIn` returns. + return back.returned ? Effect.succeed(fiber) : Effect.as(awaitHandback(back), fiber) + }) + }) + } + + // Resume a parked caller in the scheduler: resumed inline, it would run to its next await and queue before the callee + // that just suspended has queued its own continuation. + private handBack(back: Handback): void { + back.returned = true + const resume = back.resume + if (resume !== undefined) back.fiber.currentDispatcher.scheduleTask(() => resume(Effect.void), 0) + } + + // Run `effect`, which can run another program fiber inside the current step, counting the nesting. + private nest(effect: Effect.Effect): Effect.Effect { + return Effect.suspend(() => { + this.nesting++ + return Effect.ensuring( + effect, + Effect.sync(() => { + this.nesting-- + }), + ) + }) + } +} + +// The check runs when the caller suspends: it can be preempted after deciding to wait. +const awaitHandback = (back: Handback) => + Effect.callback((resume) => { + if (back.returned) resume(Effect.void) + else back.resume = resume + }) + // Observation only controls rejection reporting; program completion interrupts all promise work. export class Pending { + readonly turn = new Turn() private readonly active = new Set() private readonly ids = new WeakMap() private readonly observed = new WeakSet() @@ -40,7 +221,20 @@ export class Pending { }) } + // A promise whose work runs program code, on the turn. Host work that runs no program code uses `createHost`. create(effect: Effect.Effect): Effect.Effect { + return this.register(effect, (body) => this.turn.fork(body, this.scope)) + } + + // Starts now, without the turn, so host work stays concurrent and attaches to host promises at once. + createHost(effect: Effect.Effect): Effect.Effect { + return this.register(effect, (body) => Effect.forkIn(body, this.scope, { startImmediately: true })) + } + + private register( + effect: Effect.Effect, + fork: (body: Effect.Effect) => Effect.Effect, never, R>, + ): Effect.Effect { return Effect.flatMap(CallSite, (site) => { if (this.active.size >= MAX_PENDING_PROMISES) { throw rangeError( @@ -50,7 +244,7 @@ export class Pending { // Allocate before forking so reruns get distinct IDs and diagnostics retain creation order. const id = this.nextID++ const body = Effect.catchDefect(effect, (defect) => Effect.die(locate(defect, site.node))) - return Effect.map(Effect.forkIn(body, this.scope, { startImmediately: true }), (fiber) => { + return Effect.map(fork(body), (fiber) => { const promise = new PromiseObj(this.proto, fiber) this.active.add(promise) this.ids.set(promise, id) @@ -84,7 +278,7 @@ export class Pending { } fork(effect: Effect.Effect): Effect.Effect { - return Effect.asVoid(Effect.forkIn(effect, this.scope, { startImmediately: true })) + return Effect.asVoid(this.turn.fork(effect, this.scope)) } diagnostics(): Array { @@ -118,7 +312,7 @@ export const resolvePromiseValue = ( return Effect.gen(function* () { // Promise resolution invokes a thenable's method in a later job. - yield* Effect.yieldNow + yield* ctx.pending.turn.suspend(Effect.yieldNow) const deferred = Deferred.makeUnsafe() const resolve = capability(ctx, "resolve", (result) => Deferred.doneUnsafe(deferred, Exit.succeed(result))) const reject = capability(ctx, "reject", (reason) => Deferred.doneUnsafe(deferred, Exit.fail(new Throw(reason)))) @@ -127,7 +321,7 @@ export const resolvePromiseValue = ( if (Cause.hasInterruptsOnly(executed.cause)) return yield* Effect.failCause(executed.cause) Deferred.doneUnsafe(deferred, Exit.fail(Cause.squash(executed.cause))) } - return yield* resolvePromiseValue(ctx, yield* Deferred.await(deferred), own) + return yield* resolvePromiseValue(ctx, yield* ctx.pending.turn.leave(Deferred.await(deferred)), own) }) } @@ -184,6 +378,7 @@ const invokePromiseMethod = ( return new Arr( ctx.builtins.Array, yield* settleAfterTurn( + ctx, Effect.all( items.map((item) => Effect.flatten(ctx.pending.await(item))), { concurrency: "unbounded" }, @@ -192,29 +387,33 @@ const invokePromiseMethod = ( ) } if (name === "allSettled") { - const outcomes: Array = [] - for (const item of items) { - const exit = yield* ctx.pending.await(item) - if (Exit.isSuccess(exit)) { - outcomes.push(record(ctx.builtins.Object, { status: "fulfilled", value: exit.value })) - continue - } - if (Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause) - outcomes.push( - record(ctx.builtins.Object, { - status: "rejected", - reason: materialize(ctx, Cause.squash(exit.cause)), - }), - ) - } - yield* Effect.yieldNow - return new Arr(ctx.builtins.Array, outcomes) + return yield* ctx.pending.turn.suspend( + Effect.gen(function* () { + const outcomes: Array = [] + for (const item of items) { + const exit = yield* ctx.pending.await(item) + if (Exit.isSuccess(exit)) { + outcomes.push(record(ctx.builtins.Object, { status: "fulfilled", value: exit.value })) + continue + } + if (Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause) + outcomes.push( + record(ctx.builtins.Object, { + status: "rejected", + reason: materialize(ctx, Cause.squash(exit.cause)), + }), + ) + } + yield* Effect.yieldNow + return new Arr(ctx.builtins.Array, outcomes) + }), + ) } if (name === "race") { if (items.length === 0) { throw typeError("Promise.race([]) would never settle; provide at least one promise or value.") } - return yield* settleAfterTurn(Effect.flatten(Effect.raceAll(items.map((item) => ctx.pending.await(item))))) + return yield* settleAfterTurn(ctx, Effect.flatten(Effect.raceAll(items.map((item) => ctx.pending.await(item))))) } const flipped = items.map((item) => Effect.flatMap(ctx.pending.await(item), (exit) => { @@ -224,6 +423,7 @@ const invokePromiseMethod = ( }), ) return yield* settleAfterTurn( + ctx, Effect.all(flipped, { concurrency: "unbounded" }).pipe( Effect.flatMap((reasons) => Effect.fail(new Throw(createAggregateErrorValue(ctx, reasons, "All promises were rejected"))), @@ -259,7 +459,9 @@ const promiseCapability = (ctx: Interpreter) => Effect.gen(function* () { const deferred = Deferred.makeUnsafe() const promise = yield* ctx.pending.createWithSelf((self) => - Effect.flatMap(Deferred.await(deferred), (value) => resolvePromiseValue(ctx, value, self)), + Effect.flatMap(ctx.pending.turn.leave(Deferred.await(deferred)), (value) => + resolvePromiseValue(ctx, value, self), + ), ) const resolve = capability(ctx, "resolve", (value) => Deferred.doneUnsafe(deferred, Exit.succeed(value))) const reject = capability(ctx, "reject", (value) => Deferred.doneUnsafe(deferred, Exit.fail(new Throw(value)))) @@ -281,9 +483,12 @@ const constructPromise = (ctx: Interpreter, executor: Value): Effect.Effec }) } -// Settle one reaction turn after the deciding member, after its existing reactions. -const settleAfterTurn = (body: Effect.Effect): Effect.Effect => - Effect.flatMap(Effect.exit(body), (exit) => Effect.andThen(Effect.yieldNow, exit)) +// Settle one reaction turn after the deciding member, after its existing reactions. That reaction is a job: it queues +// for the turn behind the jobs ready before it and settles holding it. +const settleAfterTurn = (ctx: Interpreter, body: Effect.Effect): Effect.Effect => + Effect.flatten( + ctx.pending.turn.suspend(Effect.flatMap(Effect.exit(body), (exit) => Effect.as(Effect.yieldNow, exit))), + ) class PromiseAnyFulfilled { constructor(readonly value: Value) {} @@ -304,12 +509,14 @@ const reactionExit = ( ctx: Interpreter, source: PromiseObj, ): Effect.Effect, unknown, R> => - Effect.gen(function* () { - const exit = yield* ctx.pending.await(source) - if (!Exit.isSuccess(exit) && Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause) - yield* Effect.yieldNow - return exit - }) + ctx.pending.turn.suspend( + Effect.gen(function* () { + const exit = yield* ctx.pending.await(source) + if (!Exit.isSuccess(exit) && Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause) + yield* Effect.yieldNow + return exit + }), + ) const chainReaction = ( ctx: Interpreter, diff --git a/packages/codemode/test/promise.test.ts b/packages/codemode/test/promise.test.ts index 7d6bfda7472..5a36c37ea41 100644 --- a/packages/codemode/test/promise.test.ts +++ b/packages/codemode/test/promise.test.ts @@ -1342,3 +1342,61 @@ describe("promise construction", () => { ).toEqual({ kind: "function" }) }) }) + +describe("jobs run to completion", () => { + // Effect preempts a fiber after 2,048 operations; these loops are long enough to be preempted mid-job. + test("updates to shared state between awaits are not lost", async () => { + expect( + await value(` + let total = 0 + const work = async () => { + await null + for (let i = 0; i < 1000; i++) total = total + 1 + } + await Promise.all([work(), work()]) + return total + `), + ).toBe(2000) + }) + + test("an async function runs to its first await before its caller continues", async () => { + expect( + await value(` + let count = 0 + const work = async () => { + for (let i = 0; i < 1000; i++) count = count + 1 + await null + } + work() + return count + `), + ).toBe(1000) + }) + + test("a combinator's reaction runs after the continuations a preempted job queued first", async () => { + for (const op of ["race", "any", "all", "allSettled"]) { + expect( + await value(` + const burn = () => { for (let i = 0; i < 400; i++) {} } + const log = [] + const settled = Promise.${op}([{ then(resolve) { burn(); resolve(1) } }]).then(() => log.push("result")) + const job = (async () => { await null; burn(); log.push("b0"); await null; log.push("b1") })() + await Promise.all([settled, job]) + return log + `), + ).toEqual(["b0", "b1", "result"]) + } + }) + + test("a job that never awaits still times out while other jobs wait for it", async () => { + const failure = await error( + ` + const spin = async () => { await null; while (true) {} } + const quick = async () => { await null; return 1 } + return await Promise.all([spin(), quick(), quick()]) + `, + { limits: { timeoutMs: 100 } }, + ) + expect(failure.kind).toBe("TimeoutExceeded") + }) +})