Skip to content
91 changes: 71 additions & 20 deletions packages/opencode/test/lib/effect.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ownedDeadlineTest, validateOwnedDeadline, type OwnedDeadline } from "./owned-deadline"
import { test, type TestOptions } from "bun:test"
import { onTestFinished, test, type TestOptions } from "bun:test"
import { ConfigV1 } from "@opencode-ai/core/v1/config/config"
import { Cause, Duration, Effect, Exit, Layer } from "effect"
import * as Scope from "effect/Scope"
Expand Down Expand Up @@ -36,6 +36,54 @@ const body = <A, E, R>(value: Body<A, E, R>) => Effect.suspend(() => (typeof val

type Runner = <A, E, R, E2>(value: Body<A, E, R | Scope.Scope>, layer: Layer.Layer<R, E2>, deadline?: OwnedDeadline) => Promise<A>

// A host-level Bun timeout only rejects the test Promise; it never interrupts the Effect
// fiber, so scoped finalizers (and anything they restore) could still run while the next test
// is already running. Own each run instead: a per-test AbortController interrupts the fiber,
// and the test-scoped `onTestFinished` hook joins that interruption, so finalizers complete
// before Bun moves on.
//
// The hook must be registered synchronously from the test callback, before the callback
// yields anything (Bun only collects hooks registered while the callback starts; a hook
// registered later never runs). Runs that settle on their own make it a no-op — it only
// aborts while settlement is still pending — and the callback keeps observing the same
// promise the hook joins, so a genuine failure is still reported to Bun.
//
// Concurrent tests are unsupported: Bun rejects onTestFinished inside test.concurrent, and
// the registration-first ordering above turns that rejection into a test failure before any
// fiber starts rather than an orphan run. Finalizers that hang forever stay unowned: the
// hook joins settlement without a budget of its own, so the before-next guarantee covers
// only finite, cooperative finalizers. A finalizer that never settles can hang the test
// process (observed: a host timeout with an uninterruptible Effect.never release made no
// progress until an external kill); nothing here bounds that case.
function runOwned<A, E>(execution: Effect.Effect<A, E>): Promise<A> {
const controller = new AbortController()
let settled = false
// Assigned synchronously right after the hook is registered; the hook can only fire once
// the test has finished, which is after this function returned.
let run: Promise<Exit.Exit<A, E>>
// Registering before the fiber starts keeps a registration failure from orphaning work:
// Bun rejects onTestFinished outside a serial test (e.g. inside test.concurrent), and with
// this ordering that rejection propagates out of the test callback before any fiber
// launches, so an unsupported context fails the calling test instead of leaking a run.
onTestFinished(async () => {
if (settled) return
controller.abort()
await run
})
run = Effect.runPromiseExit(execution, { signal: controller.signal }).then((exit) => {
settled = true
return exit
})
return run.then((exit) => {
if (!Exit.isFailure(exit)) return exit.value
// Only reachable here because this run was abandoned: the host already reported the
// timeout, so keep the abandoned callback pending instead of adding a second, redundant
// interruption failure for a test that is already failed.
if (controller.signal.aborted) return new Promise<A>(() => {})
throw Cause.squash(exit.cause)
})
}

const isolatedRun: Runner = (value, layer, deadline) => {
const execution = Effect.gen(function* () {
const exit = yield* body(value).pipe(Effect.scoped, Effect.provide(layer), Effect.exit)
Expand All @@ -46,33 +94,36 @@ const isolatedRun: Runner = (value, layer, deadline) => {
}
return yield* exit
})
return deadline ? ownedDeadlineTest(() => execution, deadline)() : Effect.runPromise(execution)
return deadline ? ownedDeadlineTest(() => execution, deadline)() : runOwned(execution)
}

// Builds the test layer through the shared process-wide memoMap so cached
// services (Bus, Session, …) match Server.Default's instances. Use for tests
// that publish to an in-process HTTP server and need pub/sub identity with
// the server's handlers.
const sharedRun: Runner = (value, layer) =>
Effect.gen(function* () {
const scope = yield* Scope.make()
const ctx = yield* Layer.buildWithMemoMap(layer, memoMap, scope)
const exit = yield* body(value).pipe(Effect.scoped, Effect.provide(ctx), Effect.exit)
yield* Scope.close(scope, Exit.void)
if (Exit.isFailure(exit)) {
for (const err of Cause.prettyErrors(exit.cause)) {
yield* Effect.logError(err)
runOwned(
Effect.gen(function* () {
// Close the shared scope as a finalizer, not as a trailing statement: when a host
// timeout interrupts the body, the fiber unwinds past any following statement, so only
// a finalizer still releases the layer's resources before the run settles.
const scope = yield* Effect.acquireRelease(Scope.make(), (scope) => Scope.close(scope, Exit.void))
const ctx = yield* Layer.buildWithMemoMap(layer, memoMap, scope)
const exit = yield* body(value).pipe(Effect.scoped, Effect.provide(ctx), Effect.exit)
if (Exit.isFailure(exit)) {
for (const err of Cause.prettyErrors(exit.cause)) {
yield* Effect.logError(err)
}
}
}
return yield* exit
}).pipe(Effect.runPromise)

// A Bun test-level timeout only rejects the test promise; it does not interrupt the Effect
// fiber, so scoped finalizers could run after the next test started. When the test declares
// its own host timeout, own cancellation a little before it so the fiber is interrupted and
// joined first. Bun does not expose the configured default (CLI --timeout or its 5000ms
// default), so tests without an explicit timeout keep the previous unowned behavior rather
// than guessing a budget.
return yield* exit
}).pipe(Effect.scoped),
)

// A test that declares its own host timeout can be cancelled a little before Bun gives up, so
// cooperative Effect work is interrupted and joined while the test still owns the clock. Bun
// does not expose the configured default (CLI --timeout or its 5000ms default), so tests
// without an explicit timeout cannot pick a deadline and rely on the host-timeout hook in
// `runOwned` instead of a guessed budget.
function ownedFor(opts?: number | TestOptions): OwnedDeadline | undefined {
const hostTimeoutMs = typeof opts === "number" ? opts : opts?.timeout
if (hostTimeoutMs === undefined || !Number.isFinite(hostTimeoutMs) || hostTimeoutMs <= 0) return undefined
Expand Down
6 changes: 6 additions & 0 deletions packages/opencode/test/lib/fixtures/host-timeout-plain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Control for host-timeout.test.ts: no testEffect, no Effect. A plain Bun test hangs forever and
// must be reported as timed out by `bun test --timeout`.
import { test } from "bun:test"

test("plain hang is abandoned by the host timeout", () => new Promise<void>(() => {}))
test("next plain test still runs", () => {})
63 changes: 63 additions & 0 deletions packages/opencode/test/lib/fixtures/host-timeout-shared.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Same probe as host-timeout.ts for the memoMap-backed shared runner, where the layer scope is
// closed by a finalizer instead of a trailing statement. A host timeout must still release the
// layer before the next test observes the environment, and a settled run must still release it.
import { expect, test } from "bun:test"
import { Context, Effect, Layer } from "effect"
import { testEffectShared } from "../effect"

class Resource extends Context.Service<Resource, {}>()("HostTimeoutSharedResource") {}

const key = "SILVERCODE_TEST_HOST_TIMEOUT_SHARED_VALUE"
const previous = process.env[key]
const events: string[] = []

const restore = () => {
if (previous === undefined) delete process.env[key]
else process.env[key] = previous
}

const layer = Layer.effect(
Resource,
Effect.acquireRelease(
Effect.sync(() => {
process.env[key] = "active"
events.push("acquired")
return {}
}),
() =>
Effect.promise(async () => {
events.push("release-start")
await new Promise((resolve) => setTimeout(resolve, 50))
restore()
events.push("release-end")
}),
),
)

const it = testEffectShared(layer)

it.live("settles after acquiring the shared resource", () =>
Effect.gen(function* () {
yield* Resource
}),
)

test("next Bun test sees the settled shared run released", () => {
expect(process.env[key]).toBe(previous)
expect(events).toEqual(["acquired", "release-start", "release-end"])
events.length = 0
})

it.live("hangs on a scoped Effect until the host timeout abandons it", () =>
Effect.gen(function* () {
yield* Resource
yield* Effect.never
}),
)

test("next Bun test sees the restored shared environment value", () => {
expect(process.env[key]).toBe(previous)
expect(events).toEqual(["acquired", "release-start", "release-end"])
})

it.live("a settled failure is still reported", () => Effect.fail(new Error("expected settled failure")))
52 changes: 52 additions & 0 deletions packages/opencode/test/lib/fixtures/host-timeout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Spawned with `bun test --timeout 800` by host-timeout.test.ts. The first test hangs on
// Effect.never while a scoped resource holds an environment value, so Bun abandons the test
// callback. testEffect's per-test onTestFinished hook must interrupt and join the fiber, so
// the release finalizer restores the previous value before the next test runs.
import { expect, test } from "bun:test"
import { Context, Effect, Layer } from "effect"
import { testEffect } from "../effect"

class Resource extends Context.Service<Resource, {}>()("HostTimeoutResource") {}

const key = "SILVERCODE_TEST_HOST_TIMEOUT_VALUE"
const previous = process.env[key]
const events: string[] = []

const restore = () => {
if (previous === undefined) delete process.env[key]
else process.env[key] = previous
}

const layer = Layer.effect(
Resource,
Effect.acquireRelease(
Effect.sync(() => {
process.env[key] = "active"
events.push("acquired")
return {}
}),
() =>
Effect.promise(async () => {
events.push("release-start")
await new Promise((resolve) => setTimeout(resolve, 50))
restore()
events.push("release-end")
}),
),
)

const it = testEffect(layer)

it.live("hangs on a scoped Effect until the host timeout abandons it", () =>
Effect.gen(function* () {
yield* Resource
yield* Effect.never
}),
)

test("next Bun test sees the restored environment value", () => {
expect(process.env[key]).toBe(previous)
expect(events).toEqual(["acquired", "release-start", "release-end"])
})

it.live("a settled failure is still reported", () => Effect.fail(new Error("expected settled failure")))
144 changes: 144 additions & 0 deletions packages/opencode/test/lib/host-timeout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { expect, test } from "bun:test"
import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { collectDeadlineChild } from "./owned-deadline-child"

const cwd = path.resolve(import.meta.dir, "../..")
// Passed to the child as the host timeout, because Bun ignores bunfig and only reads the flag.
const HOST_TIMEOUT_MS = 800
// Hang guard for the spawned fixture, not an ownership budget. The child has to load the
// package preload and the Effect runtime before its first test starts (measured ~1.8s on a
// 2-core host), so the guard stays far above startup and above HOST_TIMEOUT_MS.
const CHILD_GUARD_MS = 15000

test(
"testEffect owns runs abandoned by a host-level Bun timeout",
async () => {
for (const probe of [
{ fixture: "host-timeout.ts", restored: "next Bun test sees the restored environment value", pass: 1, fail: 2 },
{
fixture: "host-timeout-shared.ts",
restored: "next Bun test sees the restored shared environment value",
pass: 3,
fail: 2,
},
]) {
const started = Date.now()
const { stdout, stderr, code, timedOut } = await collectDeadlineChild(
[
process.execPath,
"test",
"--timeout",
String(HOST_TIMEOUT_MS),
path.join(import.meta.dir, "fixtures", probe.fixture),
],
cwd,
CHILD_GUARD_MS,
)
const output = stdout + stderr
// Carry the child's own output into the failure: a guard hit with no output says nothing.
if (timedOut)
throw new Error(
[
`child ${probe.fixture} hit the ${CHILD_GUARD_MS}ms guard (elapsed ${Date.now() - started}ms, exit ${code})`,
`bun ${Bun.version} ${process.platform} ${path.basename(process.execPath)}`,
`stdout (last 3000): ${stdout.slice(-3000)}`,
`stderr (last 3000): ${stderr.slice(-3000)}`,
].join("\n"),
)
expect(code).toBe(1)
// The host timeout stays the failure Bun reports for the abandoned test.
expect(output).toContain(`this test timed out after ${HOST_TIMEOUT_MS}ms`)
// The finalizer ran before Bun started the next test, which saw the previous value.
expect(output).toContain(`(pass) ${probe.restored}`)
// Settled runs keep reporting their own failure.
expect(output).toContain("error: expected settled failure")
expect(output).toContain(`${probe.pass} pass`)
expect(output).toContain(`${probe.fail} fail`)
}
},
CHILD_GUARD_MS * 2 + 10000,
)

// Diagnostic control, not an ownership claim: does Bun's own host timeout fire for a plain hung test on this
// platform within a bounded wait? It records the observation and asserts nothing about the outcome.
test("control: plain Bun host timeout observation", async () => {
const started = Date.now()
const { stdout, stderr, code, timedOut } = await collectDeadlineChild(
[process.execPath, "test", "--timeout", String(HOST_TIMEOUT_MS), path.join(import.meta.dir, "fixtures", "host-timeout-plain.ts")],
cwd,
8000,
)
console.log(
`host-timeout control: ${process.platform} bun ${Bun.version} timedOut=${timedOut} elapsed=${Date.now() - started}ms exit=${code}\nstdout: ${stdout.slice(-1500)}\nstderr: ${stderr.slice(-1500)}`,
)
}, 20000)

// Diagnostic matrix (assertion-free, no ownership claim): where does the host timeout stop on Windows?
// Children append markers to a file synchronously, so the record survives a kill that loses piped output.
// clean-plain : bare bun:test, hung promise, scratch cwd outside the repo (no bunfig/preloads)
// clean-effect : the exact repo testEffect + Effect (resolved explicitly), same hang, 50ms finalizer, scratch cwd
// preloaded : the existing plain fixture from the package cwd (preloads present)
test("control: host timeout matrix with markers", async () => {
const scratch = mkdtempSync(path.join(tmpdir(), "host-timeout-matrix-"))
try {
const ancestors: string[] = []
for (let dir = scratch; ; dir = path.dirname(dir)) {
for (const name of ["bunfig.toml", "package.json"]) if (existsSync(path.join(dir, name))) ancestors.push(path.join(dir, name))
if (path.dirname(dir) === dir) break
}
console.log(`matrix: ${process.platform} bun ${Bun.version} scratch-ancestor bunfig/package files: ${JSON.stringify(ancestors)}`)
const posix = (value: string) => value.replaceAll("\\", "/")
const effectEntry = posix(Bun.resolveSync("effect", import.meta.dir))
const testEffect = posix(path.resolve(import.meta.dir, "effect.ts"))
console.log(`matrix: effect resolved to ${effectEntry}`)
const head = `import { test } from "bun:test"
import { appendFileSync } from "node:fs"
const mark = (m: string) => appendFileSync(process.env.MARK_FILE!, (Date.now() - Number(process.env.T0)) + " " + m + "\\n")
const arm = () => { mark("body-enter"); setTimeout(() => mark("timer-100"), 100); setTimeout(() => mark("timer-1200"), 1200) }
`
writeFileSync(
path.join(scratch, "clean-plain.ts"),
head +
`test("hang", () => new Promise<void>(() => arm()))
test("next", () => { mark("next-test") })
`,
)
writeFileSync(
path.join(scratch, "clean-effect.ts"),
head +
`import { Context, Effect, Layer } from "${effectEntry}"
import { testEffect } from "${testEffect}"
class Resource extends Context.Service<Resource, {}>()("MatrixResource") {}
const layer = Layer.effect(
Resource,
Effect.acquireRelease(Effect.sync(() => { mark("acquired"); return {} }), () =>
Effect.promise(async () => { mark("finalizer-start"); await new Promise((r) => setTimeout(r, 50)); mark("finalizer-end") })),
)
const it = testEffect(layer)
it.live("hang", () => Effect.gen(function* () { arm(); yield* Resource; yield* Effect.never }))
test("next", () => { mark("next-test") })
`,
)
const runs = [
{ name: "clean-plain", file: path.join(scratch, "clean-plain.ts"), cwd: scratch },
{ name: "clean-effect", file: path.join(scratch, "clean-effect.ts"), cwd: scratch },
{ name: "preloaded-plain", file: path.join(import.meta.dir, "fixtures", "host-timeout-plain.ts"), cwd },
]
for (const run of runs) {
const markFile = path.join(scratch, run.name + ".marks")
writeFileSync(markFile, "")
const started = Date.now()
const out = await collectDeadlineChild([process.execPath, "test", "--timeout", String(HOST_TIMEOUT_MS), run.file], run.cwd, 8000, {
MARK_FILE: markFile,
T0: String(started),
})
console.log(
`matrix ${run.name}: timedOut=${out.timedOut} elapsed=${Date.now() - started}ms exit=${out.code}\nmarks: ${JSON.stringify(readFileSync(markFile, "utf8").trim().split("\n"))}\nstdout: ${out.stdout.slice(-800)}\nstderr: ${out.stderr.slice(-800)}`,
)
}
} finally {
rmSync(scratch, { recursive: true, force: true })
}
}, 60000)
4 changes: 2 additions & 2 deletions packages/opencode/test/lib/owned-deadline-child.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** Own the spawned process even if collection or a child fixture fails. */
export async function collectDeadlineChild(argv: string[], cwd: string, timeoutMs: number) {
const child = Bun.spawn(argv, { cwd, stdout: "pipe", stderr: "pipe" })
export async function collectDeadlineChild(argv: string[], cwd: string, timeoutMs: number, env?: Record<string, string>) {
const child = Bun.spawn(argv, { cwd, stdout: "pipe", stderr: "pipe", ...(env ? { env: { ...process.env, ...env } } : {}) })
let timedOut = false
const timer = setTimeout(() => { timedOut = true; child.kill() }, timeoutMs)
try {
Expand Down
Loading