fix(codemode): run each job to completion (#54276)

Co-authored-by: Aiden Cline <aidenpcline@gmail.com>
This commit is contained in:
Rhys Sullivan
2026-10-20 11:19:00 -07:00
committed by GitHub
Unverified
parent c8e2e1e4fb
commit 3b593dd5d2
6 changed files with 354 additions and 58 deletions
+3
View File
@@ -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.
+15 -10
View File
@@ -40,16 +40,21 @@ export const executeProgram = <R>(
const program = parseProgram(code)
const pending = new Pending<R>(scope, builtins.Promise)
const ctx = new Interpreter<R>({ 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),
)
@@ -155,7 +155,7 @@ export const extensionGlobals = <R>(
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) =>
@@ -419,9 +419,11 @@ class Frame<R> {
}).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<string>, args: Array<Value>): Effect.Effect<PromiseObj, never, R> {
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<R> {
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<void> {
return this.ctx.pending.turn.suspend(Effect.yieldNow)
}
private evaluateStatement(node: Statement | ModuleDeclaration): Effect.Effect<StatementResult, unknown, R> {
switch (node.type) {
case "ExpressionStatement":
@@ -730,7 +739,7 @@ class Frame<R> {
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<R> {
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<R> {
}),
)
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<R> {
awaiting = true,
): Effect.Effect<void, unknown, R> {
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<R> {
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<R> {
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<Value, unknown>() }
// 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<R> {
.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<R> {
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<R> {
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<R> {
if (next) return Effect.succeed(next)
state.available = Deferred.makeUnsafe<void>()
return Effect.andThen(
Deferred.await(state.available),
this.ctx.pending.turn.park(Deferred.await(state.available)),
Effect.sync(() => this.dequeueGeneratorRequest(state)!),
)
}
+239 -32
View File
@@ -16,8 +16,189 @@ const capability = <R>(ctx: Interpreter<R>, name: string, settle: (value: Value)
return undefined
})
type Waiter = {
readonly fiber: Fiber.Fiber<unknown, unknown>
readonly resume: (effect: Effect.Effect<void>) => 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<unknown, unknown>
returned: boolean
resume?: (effect: Effect.Effect<void>) => 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<unknown, unknown> | undefined
// Callers waiting for a callee to hand the turn back, innermost last.
private readonly handbacks: Array<Handback> = []
// 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<void> = Effect.withFiber((fiber) => {
if (this.holder === undefined) {
this.holder = fiber
return Effect.void
}
return Effect.callback<void>((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<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> {
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<unknown, unknown>): 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<A, E, R>(wait: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> {
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<A, E, R>(wait: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> {
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<A, E, R>(start: Effect.Effect<A, E, R>): Effect.Effect<void, E, R> {
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<A, E, R>(wait: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> {
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<A, E, R>(effect: Effect.Effect<A, E, R>, scope: Scope.Scope): Effect.Effect<Fiber.Fiber<A, E>, 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<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> {
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<void>((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<R> {
readonly turn = new Turn()
private readonly active = new Set<PromiseObj>()
private readonly ids = new WeakMap<PromiseObj, number>()
private readonly observed = new WeakSet<PromiseObj>()
@@ -40,7 +221,20 @@ export class Pending<R> {
})
}
// A promise whose work runs program code, on the turn. Host work that runs no program code uses `createHost`.
create(effect: Effect.Effect<Value, unknown, R>): Effect.Effect<PromiseObj, never, R> {
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<Value, unknown, R>): Effect.Effect<PromiseObj, never, R> {
return this.register(effect, (body) => Effect.forkIn(body, this.scope, { startImmediately: true }))
}
private register(
effect: Effect.Effect<Value, unknown, R>,
fork: (body: Effect.Effect<Value, unknown, R>) => Effect.Effect<Fiber.Fiber<Value, unknown>, never, R>,
): Effect.Effect<PromiseObj, never, R> {
return Effect.flatMap(CallSite, (site) => {
if (this.active.size >= MAX_PENDING_PROMISES) {
throw rangeError(
@@ -50,7 +244,7 @@ export class Pending<R> {
// 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<R> {
}
fork(effect: Effect.Effect<unknown, unknown, R>): Effect.Effect<void, never, R> {
return Effect.asVoid(Effect.forkIn(effect, this.scope, { startImmediately: true }))
return Effect.asVoid(this.turn.fork(effect, this.scope))
}
diagnostics(): Array<Diagnostic> {
@@ -118,7 +312,7 @@ export const resolvePromiseValue = <R>(
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<Value, unknown>()
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 = <R>(
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 = <R>(
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 = <R>(
)
}
if (name === "allSettled") {
const outcomes: Array<Value> = []
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<Value> = []
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 = <R>(
}),
)
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 = <R>(ctx: Interpreter<R>) =>
Effect.gen(function* () {
const deferred = Deferred.makeUnsafe<Value, unknown>()
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 = <R>(ctx: Interpreter<R>, executor: Value): Effect.Effec
})
}
// Settle one reaction turn after the deciding member, after its existing reactions.
const settleAfterTurn = <A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
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 = <A, E, R>(ctx: Interpreter<R>, body: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
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 = <R>(
ctx: Interpreter<R>,
source: PromiseObj,
): Effect.Effect<Exit.Exit<Value, unknown>, 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 = <R>(
ctx: Interpreter<R>,
+58
View File
@@ -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")
})
})