Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions packages/opencode/test/cli/run/run-retry-wait.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ import { httpError, reply } from "../../lib/llm-server"

// #555: a provider quota rejection that asks for a long retry delay must not
// leave a headless run silent until it is killed.
//
// Temporal coverage split: the FIRST case below stays on the REAL clock and
// genuinely sleeps out a 12s retry-after — the wall-clock end-to-end guarantee
// for long retry waits. The remaining cases set `clockScale` so the spawned
// CLI observes an accelerated clock (test/lib/clock-scale.preload.ts): every
// wait still exceeds the same 10s notice threshold and keeps its production
// delay values, ordering and recovery assertions — only the wall-clock cost
// shrinks (59s of explicit waits → 12s real + ~4.7s controlled).
type Body = { messages?: { role?: string; content?: unknown }[] }
const lastText = (body: Body) => {
const content = body.messages?.at(-1)?.content
Expand Down Expand Up @@ -61,7 +69,7 @@ describe("headless run provider retry delay (#555)", () => {
yield* llm.error(429, { error: { message: "Too many requests, try again later", type: "rate_limit_error" } }, { "retry-after": "12" })
yield* llm.text("recovered after the long wait")
const result = yield* opencode.run("rate limited", {
timeoutMs: 40_000, extraArgs: ["--continue"], model: "opencode/local-quota-test", env,
timeoutMs: 40_000, extraArgs: ["--continue"], model: "opencode/local-quota-test", env, clockScale: 10,
})
expect(result.exitCode).toBe(0)
expect(result.stderr).toMatch(/waiting about \d+s before retrying \(attempt 1\): retrying after a provider error/)
Expand All @@ -77,7 +85,7 @@ describe("headless run provider retry delay (#555)", () => {
yield* llm.error(429, quota, { "retry-after": "1" })
yield* llm.text("recovered after retry")
const result = yield* opencode.run("short retry", {
timeoutMs: 20_000, extraArgs: ["--continue"], model: "opencode/local-quota-test", env,
timeoutMs: 20_000, extraArgs: ["--continue"], model: "opencode/local-quota-test", env, clockScale: 10,
})
expect(result.exitCode).toBe(0)
expect(result.stdout).toContain("recovered after retry")
Expand All @@ -90,7 +98,7 @@ describe("headless run provider retry delay (#555)", () => {
yield* llm.push(reply().text("first step").tool("bash", { command: "printf step", description: "First step" }))
yield* llm.error(429, quota, { "retry-after": "11" })
yield* llm.text("done after two waits")
const result = yield* opencode.run("two long waits", { timeoutMs: 50_000, extraArgs: ["--dangerously-skip-permissions"] })
const result = yield* opencode.run("two long waits", { timeoutMs: 50_000, extraArgs: ["--dangerously-skip-permissions"], clockScale: 10 })
expect(result.exitCode).toBe(0)
expect(result.stdout).toContain("done after two waits")
expect(result.stderr.match(/waiting about \d+s before retrying \(attempt 1\)/g)?.length).toBe(2)
Expand Down Expand Up @@ -126,7 +134,7 @@ describe("headless run provider retry delay (#555)", () => {
yield* llm.pushMatch((hit) => lastText(hit.body as Body).includes("child done"),
reply().text("ROOT_FINAL").tool("finish", { reason: "success", result: "done" }).stop())
const result = yield* opencode.run("Research the child wait report", {
timeoutMs: 50_000, extraArgs: ["--continue", "--dangerously-skip-permissions"], model: "opencode/local-quota-test", env,
timeoutMs: 50_000, extraArgs: ["--continue", "--dangerously-skip-permissions"], model: "opencode/local-quota-test", env, clockScale: 10,
})
// Retry policy unchanged: the child waits, retries and the run finishes.
expect(result.exitCode).toBe(0)
Expand Down
65 changes: 53 additions & 12 deletions packages/opencode/test/lib/cli-process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,32 @@ import { it } from "./effect"

const opencodeRoot = path.resolve(import.meta.dir, "../../")
const cliEntry = path.join(opencodeRoot, "src/index.ts")
// Preloaded into spawned CLI children only when a test opts in via
// SpawnOpts.clockScale — see clock-scale.preload.ts.
const clockScalePreload = path.join(import.meta.dir, "clock-scale.preload.ts")

// The accelerated clock is only active above 1; anything else runs real time.
function activeClockScale(opts?: SpawnOpts) {
const scale = opts?.clockScale
return scale !== undefined && Number.isFinite(scale) && scale > 1 ? scale : undefined
}

// argv for bun so clock-scale opting tests preload the virtual clock before
// the CLI entry module loads (see clock-scale.preload.ts).
function bunArgv(args: string[], opts?: SpawnOpts) {
return [
"run",
...(activeClockScale(opts) ? ["--preload", clockScalePreload] : []),
"--conditions=browser",
cliEntry,
...args,
]
}

function clockScaleEnv(opts?: SpawnOpts): Record<string, string> {
const scale = activeClockScale(opts)
return scale === undefined ? {} : { OPENCODE_TEST_CLOCK_SCALE: String(scale) }
}

export const testModelID = "test/test-model"

Expand Down Expand Up @@ -90,7 +116,18 @@ export type RunHandle = {
readonly result: Effect.Effect<RunResult>
}

export type SpawnOpts = { readonly timeoutMs?: number; readonly env?: Record<string, string> }
export type SpawnOpts = {
readonly timeoutMs?: number
readonly env?: Record<string, string>
// Run the spawned CLI child on an accelerated clock: the child observes
// time `clockScale` times faster than wall time (Date.now + timers scaled
// together, see clock-scale.preload.ts). Long provider retry waits then
// cost real_seconds / clockScale while still exercising the full notice /
// ordering / recovery path at production values. Omit (or leave <= 1) for
// the real clock; at least one end-to-end long-retry test should stay on
// it so wall-clock behavior remains covered.
readonly clockScale?: number
}

// Typed equivalent of constructing argv for `opencode run`. New flags should
// land here so tests stay grep-able and refactor-safe.
Expand Down Expand Up @@ -212,9 +249,9 @@ export function withCliFixture<A, E>(
// on `Bun.stdin.text()` (see src/cli/cmd/run.ts — non-TTY stdin is
// consumed as the prompt). The old Process.run wrapper defaulted to
// ignore; ChildProcess.make defaults to pipe, so we set it explicitly.
const command = ChildProcess.make("bun", ["run", "--conditions=browser", cliEntry, ...args], {
const command = ChildProcess.make("bun", bunArgv(args, opts), {
cwd: home,
env: { ...env, ...opts?.env },
env: { ...env, ...clockScaleEnv(opts), ...opts?.env },
extendEnv: true,
stdin: "ignore",
})
Expand Down Expand Up @@ -284,9 +321,9 @@ export function withCliFixture<A, E>(
const options = runOpts(opts)
const proc = yield* Effect.acquireRelease(
Effect.sync(() =>
Bun.spawn(["bun", "run", "--conditions=browser", cliEntry, ...runArgs(message, opts)], {
Bun.spawn(["bun", ...bunArgv(runArgs(message, opts), options)], {
cwd: home,
env: { ...process.env, ...env, ...options?.env },
env: { ...process.env, ...env, ...clockScaleEnv(options), ...options?.env },
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
Expand Down Expand Up @@ -325,9 +362,9 @@ export function withCliFixture<A, E>(
// as a finalizer error during test teardown.
const proc = yield* Effect.acquireRelease(
Effect.sync(() =>
Bun.spawn(["bun", "run", "--conditions=browser", cliEntry, ...argv], {
Bun.spawn(["bun", ...bunArgv(argv, opts)], {
cwd: home,
env: { ...process.env, ...env, ...opts?.env },
env: { ...process.env, ...env, ...clockScaleEnv(opts), ...opts?.env },
stdout: "pipe",
stderr: "pipe",
}),
Expand Down Expand Up @@ -396,9 +433,9 @@ export function withCliFixture<A, E>(
// Either way we await proc.exited so the test scope doesn't leak.
const proc = yield* Effect.acquireRelease(
Effect.sync(() =>
Bun.spawn(["bun", "run", "--conditions=browser", cliEntry, ...argv], {
Bun.spawn(["bun", ...bunArgv(argv, opts)], {
cwd: opts?.cwd ?? home,
env: { ...process.env, ...env, ...opts?.env },
env: { ...process.env, ...env, ...clockScaleEnv(opts), ...opts?.env },
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
Expand Down Expand Up @@ -511,9 +548,13 @@ function expectExit(result: RunResult, expected: number, label = "opencode") {
// `it.live(name, () => withCliFixture(fixture))` — one fewer nesting level at
// every call site. Use this for any test that needs the opencode CLI fixture.
//
// Subprocess tests must run against the real clock — a TestClock-paused
// environment can't drive a child process. If you need `.only` or `.skip`, fall
// back to `it.live` + `withCliFixture` directly.
// Subprocess tests run against the real clock by default — a TestClock-paused
// environment can't drive a child process. Tests that only need a long delay
// to be *observed* (notice, ordering, recovery) can opt into the accelerated
// child clock with SpawnOpts.clockScale (see clock-scale.preload.ts); keep at
// least one genuinely wall-clock delayed case per behavior when doing so. If
// you need `.only` or `.skip`, fall back to `it.live` + `withCliFixture`
// directly.
// Body's R is `Scope.Scope | never` so tests can yield* scope-requiring
// resources (e.g. `opencode.serve`) without an extra `Effect.scoped` wrapper —
// `withCliFixture`'s outer scope is the natural lifetime.
Expand Down
44 changes: 44 additions & 0 deletions packages/opencode/test/lib/clock-scale.preload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Test-only accelerated clock for CLI subprocesses spawned by the harness
// (cli-process.ts). Injected with `bun run --preload` when a test opts in via
// SpawnOpts.clockScale — production code never reads this file or the env var.
//
// WHY (#555 / test-cost): a long provider retry wait must outlive run.ts's
// 10s notice threshold, so end-to-end retry tests used to sleep 11-12s of
// wall time per wait (~59s across run-retry-wait.test.ts alone). Setting
// OPENCODE_TEST_CLOCK_SCALE=N makes this process observe time running N times
// faster: Date.now and setTimeout/setInterval are scaled together against one
// anchor, so every deadline stays internally consistent — a delay of D
// milliseconds elapses after D/N real milliseconds while the clock still
// reports D milliseconds passed. Notices, thresholds and retry ordering are
// therefore exercised at the same values as production, only in less wall
// time. Tests that need genuine wall-clock behavior (e.g. one real long-retry
// end-to-end case in run-retry-wait.test.ts) simply omit clockScale.
//
// No-op unless OPENCODE_TEST_CLOCK_SCALE is present and greater than 1.
const scale = Number(process.env.OPENCODE_TEST_CLOCK_SCALE)

if (Number.isFinite(scale) && scale > 1) {
const realNow = Date.now
const realSetTimeout = globalThis.setTimeout
const realSetInterval = globalThis.setInterval
// Anchor at this process's start: virtual and real time coincide there, so
// absolute timestamps (files, messages) don't jump; only the elapsed rate differs.
const anchor = realNow()

// Virtual time = anchor + real elapsed × scale.
Date.now = () => anchor + (realNow() - anchor) * scale

// A timer scheduled for D ms must fire when virtual time advanced by D,
// i.e. after D/scale real ms — same invariant for intervals, so periodic
// polls keep their virtual cadence. Sub-millisecond results are left for
// the runtime to clamp, matching its usual behavior.
globalThis.setTimeout = ((handler: TimerHandler, ms?: number, ...args: unknown[]) =>
typeof ms === "number" && Number.isFinite(ms) && ms > 0
? realSetTimeout(handler, ms / scale, ...args)
: realSetTimeout(handler, ms, ...args)) as typeof setTimeout

globalThis.setInterval = ((handler: TimerHandler, ms?: number, ...args: unknown[]) =>
typeof ms === "number" && Number.isFinite(ms) && ms > 0
? realSetInterval(handler, ms / scale, ...args)
: realSetInterval(handler, ms, ...args)) as typeof setInterval
}
Loading