From e4243dbc8cb91d57a56d2b4ccd9a84e72b717e2e Mon Sep 17 00:00:00 2001 From: Filip Hejmowski Date: Thu, 15 Oct 2026 22:04:46 +0200 Subject: [PATCH] test(core): fix load-sensitive tests and spawn fewer git processes - process.test: every AppProcess test spawns a real child, so run them with it.live. Under TestClock the spawner's 1s post-exit capture deadline never fired, and a late close event hung until the timeout. - browser-idle: give LocationActivity its own clock and advance it by the TTL only after the first browser state attached, instead of racing a real 2s TTL against slow plugin activation. - config/reload: wait for the skills change too before asserting it. - Raise the four file-level 15s defaults to the runner's 30s default; they had become the strictest timeouts in the suite. - The runner passes --timeout=30000 like cli and tui; npm.test's Git installs ran past Bun's 5s default on Windows. - Git fixtures write repo-local settings in one config write instead of a git config spawn per setting. Git for Windows spawns cost about 40ms each, and core spawned about 2,850 per run. --- packages/core/script/test.ts | 3 +- packages/core/test/browser-idle.test.ts | 24 ++++++++++- packages/core/test/config/reload.test.ts | 4 +- packages/core/test/filesystem/watcher.test.ts | 8 +--- packages/core/test/fixture/git.ts | 26 ++++++++---- packages/core/test/integration.test.ts | 14 +++++-- .../test/plugin/supervisor-reload.test.ts | 2 +- packages/core/test/process/process.test.ts | 41 ++++++++++--------- packages/core/test/project.test.ts | 7 +--- packages/core/test/repository-cache.test.ts | 2 +- packages/core/test/session-activation.test.ts | 2 +- packages/core/test/session-create.test.ts | 11 ++--- packages/core/test/session-shell.test.ts | 2 +- packages/core/test/vcs.test.ts | 13 ++---- 14 files changed, 91 insertions(+), 68 deletions(-) diff --git a/packages/core/script/test.ts b/packages/core/script/test.ts index cc6f1f6f177..104be387a08 100644 --- a/packages/core/script/test.ts +++ b/packages/core/script/test.ts @@ -35,7 +35,8 @@ const environment = { } const child = Bun.spawn({ - cmd: [process.execPath, "test", "--only-failures", ...process.argv.slice(2)], + // The 30s default timeout matches cli and tui; npm.test's Git package installs ran past Bun's 5s default on Windows. + cmd: [process.execPath, "test", "--only-failures", "--timeout=30000", ...process.argv.slice(2)], env: environment, stdin: "inherit", stdout: "inherit", diff --git a/packages/core/test/browser-idle.test.ts b/packages/core/test/browser-idle.test.ts index a7db22b729d..c0f6fc5ef22 100644 --- a/packages/core/test/browser-idle.test.ts +++ b/packages/core/test/browser-idle.test.ts @@ -1,5 +1,5 @@ import { expect } from "bun:test" -import { Context, Effect, Fiber, RcMap, Schedule } from "effect" +import { Clock, Context, Duration, Effect, Fiber, Layer, RcMap, Schedule } from "effect" import { Browser } from "@opencode/plugin-browser/rpc" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { LayerNode } from "@opencode/util/effect/layer-node" @@ -21,6 +21,22 @@ import { offlineModels } from "./fixture/models" import { tmpdirScoped } from "./fixture/tmpdir" import { testEffect } from "./lib/effect" +// LocationActivity measures idleness on this clock. Its sweep still sleeps in real time, but only the test moves the +// clock past the TTL, so slow plugin activation on a busy machine cannot evict the location before the browser +// attachment exists, as a short real TTL could. +const timeToLive = Duration.minutes(1) +const idle = { millis: 0 } +const live = Clock.Clock.defaultValue() +const activityClock: Clock.Clock = { + currentTimeMillisUnsafe: () => live.currentTimeMillisUnsafe() + idle.millis, + currentTimeMillis: Effect.sync(() => live.currentTimeMillisUnsafe() + idle.millis), + currentTimeNanosUnsafe: () => live.currentTimeNanosUnsafe() + BigInt(idle.millis) * 1_000_000n, + currentTimeNanos: Effect.sync(() => live.currentTimeNanosUnsafe() + BigInt(idle.millis) * 1_000_000n), + monotonicTimeNanosUnsafe: () => live.monotonicTimeNanosUnsafe(), + monotonicTimeNanos: live.monotonicTimeNanos, + sleep: (duration) => live.sleep(duration), +} + const it = testEffect( AppNodeBuilder.build( LayerNode.group([Database.node, Bus.node, Session.node, LocationServiceMap.node, LocationActivity.node]), @@ -30,7 +46,9 @@ const it = testEffect( LocationActivity.node.replace( makeGlobalNode({ service: LocationActivity.Service, - layer: LocationActivity.layer({ timeToLive: "2 seconds", sweepInterval: "100 millis" }), + layer: LocationActivity.layer({ timeToLive, sweepInterval: "100 millis" }).pipe( + Layer.provide(Layer.succeed(Clock.Clock, activityClock)), + ), deps: [Bus.node, LocationServiceMap.node, SessionExecution.node, SessionStore.node], }), ), @@ -62,6 +80,8 @@ it.live( }), Effect.timeout("5 seconds"), ) + // The location has now been idle for its whole TTL; the next sweep evicts it. + idle.millis += Duration.toMillis(timeToLive) // Real idle cleanup must end the long-lived request, not leave a second registry behind it. expect(yield* Fiber.join(pending).pipe(Effect.timeout("10 seconds"))).toMatchObject({ type: "rpc.unavailable" }) diff --git a/packages/core/test/config/reload.test.ts b/packages/core/test/config/reload.test.ts index c1ee9d63e96..f6acae19fc7 100644 --- a/packages/core/test/config/reload.test.ts +++ b/packages/core/test/config/reload.test.ts @@ -309,7 +309,9 @@ describe("config plugin reloads", () => { (yield* integrations.get(Integration.ID.make("second"))) !== undefined && (yield* references.list()).some((reference) => reference.name === "second") && (yield* providers.get(Provider.ID.make("first"))) === undefined && - (yield* providers.get(Provider.ID.make("second"))) !== undefined + (yield* providers.get(Provider.ID.make("second"))) !== undefined && + (yield* skills.list()).every((skill) => skill.id !== "first") && + (yield* skills.list()).some((skill) => skill.id === "second") ) }), ) diff --git a/packages/core/test/filesystem/watcher.test.ts b/packages/core/test/filesystem/watcher.test.ts index feaaeecb8fe..c880c31ec72 100644 --- a/packages/core/test/filesystem/watcher.test.ts +++ b/packages/core/test/filesystem/watcher.test.ts @@ -19,6 +19,7 @@ import { Location } from "@opencode/core/location" import { Plugin } from "@opencode/core/plugin" import { PluginSupervisor } from "@opencode/core/plugin/supervisor" import { AbsolutePath } from "@opencode/core/schema" +import { initRepo } from "../fixture/git" import { location } from "../fixture/location" import { tmpdir } from "../fixture/tmpdir" import { testEffect } from "../lib/effect" @@ -267,12 +268,7 @@ function withTmp( return { tmp, vcs: { type: "hg" as const, store: AbsolutePath.make(path.join(tmp.path, ".hg")) } } } if (options?.vcs !== "git") return { tmp, vcs: undefined } - await $`git init`.cwd(tmp.path).quiet() - await $`git config core.fsmonitor false`.cwd(tmp.path).quiet() - await $`git config commit.gpgsign false`.cwd(tmp.path).quiet() - await $`git config user.email test@opencode.test`.cwd(tmp.path).quiet() - await $`git config user.name Test`.cwd(tmp.path).quiet() - await $`git commit --allow-empty -m root`.cwd(tmp.path).quiet() + await initRepo(tmp.path) await options.init?.(tmp.path) return { tmp, vcs: { type: "git" as const, store: AbsolutePath.make(path.join(tmp.path, ".git")) } } }), diff --git a/packages/core/test/fixture/git.ts b/packages/core/test/fixture/git.ts index 2fadb80f4da..4971dd10c95 100644 --- a/packages/core/test/fixture/git.ts +++ b/packages/core/test/fixture/git.ts @@ -10,13 +10,27 @@ import { tmpdir } from "./tmpdir" const exec = promisify(execFile) +// Appended to the new repository's own config instead of running one `git config` process per key, which costs +// tens of milliseconds each on Windows. Repositories created by production code still have no identity. +const repositoryConfig = `[core] + fsmonitor = false +[commit] + gpgsign = false +[user] + email = test@opencode.test + name = Test +` + +export async function initGit(directory: string, ...args: string[]) { + await $`git init ${args} ${directory}`.quiet() + await fs.appendFile(path.join(directory, ".git", "config"), repositoryConfig) +} + export async function gitRemote(root: string) { const origin = path.join(root, "origin.git") const source = path.join(root, "source") await git(root, "init", "--bare", origin) - await git(root, "init", source) - await git(source, "config", "user.email", "test@example.com") - await git(source, "config", "user.name", "Test") + await initGit(source) await fs.writeFile(path.join(source, "README.md"), "one\n") await git(source, "add", "README.md") await git(source, "commit", "-m", "initial") @@ -48,11 +62,7 @@ export function read(file: string) { } export async function initRepo(directory: string) { - await $`git init`.cwd(directory).quiet() - await $`git config core.fsmonitor false`.cwd(directory).quiet() - await $`git config commit.gpgsign false`.cwd(directory).quiet() - await $`git config user.email test@opencode.test`.cwd(directory).quiet() - await $`git config user.name Test`.cwd(directory).quiet() + await initGit(directory) await $`git commit --allow-empty -m root`.cwd(directory).quiet() } diff --git a/packages/core/test/integration.test.ts b/packages/core/test/integration.test.ts index f2b10246b10..5d352c76679 100644 --- a/packages/core/test/integration.test.ts +++ b/packages/core/test/integration.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from "bun:test" +import path from "path" import { Cause, Clock, Duration, Effect, Exit, Fiber, Layer, Scope, Stream } from "effect" import { TestClock } from "effect/testing" import { Credential } from "@opencode/core/credential" @@ -8,6 +9,7 @@ import { LayerNode } from "@opencode/util/effect/layer-node" import { Bus } from "@opencode/core/bus" import { Integration } from "@opencode/core/integration" import { State } from "@opencode/core/state" +import { tmpdirScoped } from "./fixture/tmpdir" import { testEffect } from "./lib/effect" const it = testEffect(AppNodeBuilder.build(LayerNode.group([Integration.node, Credential.node, Bus.node]))) @@ -31,17 +33,18 @@ const failingIt = testEffect( AppNodeBuilder.build(LayerNode.group([Integration.node, Bus.node]), [Credential.node.replace(failingCredentialNode)]), ) +// Bounded by elapsed time rather than attempts, so a slow child process start on a busy machine still fits. function eventually( effect: Effect.Effect, predicate: (value: A) => boolean, - remaining = 1000, + deadline = Date.now() + 10_000, ): Effect.Effect { return Effect.gen(function* () { const value = yield* effect if (predicate(value)) return value - if (remaining === 0) return yield* Effect.fail(new Error("Timed out waiting for value")) + if (Date.now() > deadline) return yield* Effect.fail(new Error("Timed out waiting for value")) yield* Effect.promise(() => Bun.sleep(1)) - return yield* eventually(effect, predicate, remaining - 1) + return yield* eventually(effect, predicate, deadline) }) } @@ -224,6 +227,8 @@ describe("Integration", () => { const credentials = yield* Credential.Service const integrationID = Integration.ID.make("company") const methodID = Integration.MethodID.make("login") + // The command prints its secret only after the test has seen it pending, however slow the machine is. + const release = path.join((yield* tmpdirScoped()).path, "release") yield* integrations.transform((editor) => editor.method.update({ integrationID, @@ -234,7 +239,7 @@ describe("Integration", () => { command: [ process.execPath, "-e", - 'console.error("https://example.com/login"); await Bun.sleep(50); console.log("secret")', + `console.error("https://example.com/login"); while (!(await Bun.file(${JSON.stringify(release)}).exists())) await Bun.sleep(10); console.log("secret")`, ], }, }), @@ -246,6 +251,7 @@ describe("Integration", () => { (status) => status.status === "pending" && status.message?.includes("https://example.com/login") === true, ) expect(pending).toMatchObject({ status: "pending", message: "https://example.com/login\n" }) + yield* Effect.promise(() => Bun.write(release, "")) expect( yield* eventually( diff --git a/packages/core/test/plugin/supervisor-reload.test.ts b/packages/core/test/plugin/supervisor-reload.test.ts index c136ce17ef2..e2ed79e23f9 100644 --- a/packages/core/test/plugin/supervisor-reload.test.ts +++ b/packages/core/test/plugin/supervisor-reload.test.ts @@ -28,7 +28,7 @@ import { advance } from "../lib/clock" import { testEffect } from "../lib/effect" // Real Location boot with plugin-directory discovery, so local plugin files are loaded and reloaded. -setDefaultTimeout(15_000) +setDefaultTimeout(30_000) // Package resolution can be held open so overlapping activations become observable. const npm = { diff --git a/packages/core/test/process/process.test.ts b/packages/core/test/process/process.test.ts index e644aafe276..ed365a1cf3c 100644 --- a/packages/core/test/process/process.test.ts +++ b/packages/core/test/process/process.test.ts @@ -10,6 +10,8 @@ import { LayerNode } from "@opencode/util/effect/layer-node" import { AppProcess } from "@opencode/util/process" import { testEffect } from "../lib/effect" +// Every test spawns a real child, so all of them use the live clock. The spawner's 1s post-exit capture deadline +// never fires under TestClock, and a child whose close event arrives late would hang until the test timeout. const it = testEffect(LayerNode.compile(AppProcess.node)) const NODE = process.execPath @@ -31,7 +33,7 @@ const waitForFile = (file: string) => describe("AppProcess", () => { describe("run", () => { - it.effect( + it.live( "captures stdout and exit code zero", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -54,14 +56,15 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "captures stdout and stderr in emission order", Effect.gen(function* () { const svc = yield* AppProcess.Service const script = [ 'process.stdout.write("out 1\\n")', - 'setTimeout(() => process.stderr.write("err 1\\n"), 10)', - 'setTimeout(() => process.stdout.write("out 2\\n"), 20)', + // Gaps wide enough that a busy test machine still reads each write before the next one. + 'setTimeout(() => process.stderr.write("err 1\\n"), 100)', + 'setTimeout(() => process.stdout.write("out 2\\n"), 200)', ].join(";") const result = yield* svc.run(cmd("-e", script), { combineOutput: true }) expect(result.output?.toString("utf8")).toBe("out 1\nerr 1\nout 2\n") @@ -70,7 +73,7 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "non-zero exit returns RunResult; caller can require success", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -79,7 +82,7 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "requireSuccess fails on non-zero exit", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -92,7 +95,7 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "requireSuccess succeeds on exit 0", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -101,7 +104,7 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "requireExitIn allowlists multiple exit codes", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -116,7 +119,7 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "truncates stdout when maxOutputBytes is set", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -129,7 +132,7 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "truncates stderr when maxErrorBytes is set", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -142,7 +145,7 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "result includes command description", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -197,7 +200,7 @@ describe("AppProcess", () => { }) describe("inherited platform methods", () => { - it.effect( + it.live( "string returns stdout as string", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -206,7 +209,7 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "lines returns the platform's array of lines", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -219,7 +222,7 @@ describe("AppProcess", () => { describe("run with stdin option", () => { const echoStdin = "process.stdin.on('data', c => process.stdout.write(c))" - it.effect( + it.live( "feeds a string to stdin and returns it on stdout", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -229,7 +232,7 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "feeds a Uint8Array to stdin", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -240,7 +243,7 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "feeds a Stream of Uint8Array chunks to stdin", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -252,7 +255,7 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "completes correctly with empty input", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -262,7 +265,7 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "carries existing Command options like env", Effect.gen(function* () { const svc = yield* AppProcess.Service @@ -275,7 +278,7 @@ describe("AppProcess", () => { }), ) - it.effect( + it.live( "carries existing Command options like cwd", Effect.gen(function* () { const svc = yield* AppProcess.Service diff --git a/packages/core/test/project.test.ts b/packages/core/test/project.test.ts index e84873247ad..1c1e1e70d70 100644 --- a/packages/core/test/project.test.ts +++ b/packages/core/test/project.test.ts @@ -12,6 +12,7 @@ import { ProjectSchema } from "@opencode/core/project/schema" import { ProjectTable } from "@opencode/core/project/sql" import { AbsolutePath } from "@opencode/core/schema" import { Hash } from "@opencode/util/hash" +import { initGit } from "./fixture/git" import { tmpdir } from "./fixture/tmpdir" import { testEffect } from "./lib/effect" @@ -326,11 +327,7 @@ function real(value: string) { } async function initRepo(dir: string, opts?: { commit?: boolean; remote?: string }) { - await $`git init`.cwd(dir).quiet() - await $`git config core.fsmonitor false`.cwd(dir).quiet() - await $`git config commit.gpgsign false`.cwd(dir).quiet() - await $`git config user.email test@opencode.test`.cwd(dir).quiet() - await $`git config user.name Test`.cwd(dir).quiet() + await initGit(dir) if (opts?.commit) await $`git commit --allow-empty -m root`.cwd(dir).quiet() if (opts?.remote) await $`git remote add origin ${opts.remote}`.cwd(dir).quiet() } diff --git a/packages/core/test/repository-cache.test.ts b/packages/core/test/repository-cache.test.ts index fde7c331589..e6cab75507f 100644 --- a/packages/core/test/repository-cache.test.ts +++ b/packages/core/test/repository-cache.test.ts @@ -16,7 +16,7 @@ import { testEffect } from "./lib/effect" const it = testEffect(Layer.empty) // Cold Git setup and cloning can exceed Bun's five-second default on Windows. -setDefaultTimeout(15_000) +setDefaultTimeout(30_000) describe("RepositoryCache", () => { it.live("persists the daily throttle across cache recreation and serializes competing refreshes", () => diff --git a/packages/core/test/session-activation.test.ts b/packages/core/test/session-activation.test.ts index 8a7482fb3c8..d70d0915fa5 100644 --- a/packages/core/test/session-activation.test.ts +++ b/packages/core/test/session-activation.test.ts @@ -18,7 +18,7 @@ import { tmpdirScoped } from "./fixture/tmpdir" import { testEffect } from "./lib/effect" // Real Location boot with plugin discovery, so the first request races the initial plugin activation. -setDefaultTimeout(15_000) +setDefaultTimeout(30_000) const it = testEffect( AppNodeBuilder.build( diff --git a/packages/core/test/session-create.test.ts b/packages/core/test/session-create.test.ts index edb83d48f8a..10895fc5b73 100644 --- a/packages/core/test/session-create.test.ts +++ b/packages/core/test/session-create.test.ts @@ -36,6 +36,7 @@ import { Workspace } from "@opencode/core/workspace" import { Expected } from "./lib/session-message" import { testEffect } from "./lib/effect" import { LocationServiceMap } from "@opencode/core/location-service-map" +import { initGit } from "./fixture/git" import { offlineModels } from "./fixture/models" import { promptLocationNode } from "./fixture/prompt-location" import { globalProjectNode } from "./lib/project" @@ -158,11 +159,7 @@ describe("Session.create", () => { .pipe(Effect.orDie) if (!before) return yield* Effect.die(new Error("created session not found")) - yield* Effect.promise(async () => { - await $`git init -q`.cwd(directory) - await $`git config user.email test@example.com`.cwd(directory) - await $`git config user.name Test`.cwd(directory) - }) + yield* Effect.promise(() => initGit(directory)) const unborn = yield* projects.resolve(ref.directory) const unbornRoot = yield* session.get(created.id) const unbornNested = yield* session.get(child.id) @@ -269,9 +266,7 @@ describe("Session.create", () => { yield* Effect.promise(async () => { for (const root of [nested, outer]) { - await $`git init -q`.cwd(root) - await $`git config user.email test@example.com`.cwd(root) - await $`git config user.name Test`.cwd(root) + await initGit(root) await $`git commit --allow-empty -qm initial`.cwd(root) } }) diff --git a/packages/core/test/session-shell.test.ts b/packages/core/test/session-shell.test.ts index 1340c0f67ed..35c7248e81c 100644 --- a/packages/core/test/session-shell.test.ts +++ b/packages/core/test/session-shell.test.ts @@ -19,7 +19,7 @@ import { tmpdirScoped } from "./fixture/tmpdir" import { testEffect } from "./lib/effect" // Every test boots a real Location, so shell start waits for cold plugin activation before spawning. -setDefaultTimeout(15_000) +setDefaultTimeout(30_000) class ExecutionControl extends Context.Service< ExecutionControl, diff --git a/packages/core/test/vcs.test.ts b/packages/core/test/vcs.test.ts index 8bcc471adfd..2911166b5d2 100644 --- a/packages/core/test/vcs.test.ts +++ b/packages/core/test/vcs.test.ts @@ -17,6 +17,7 @@ import { VcsGitPlugin } from "@opencode/core/plugin/vcs/git" import type { VcsDefinition, VcsDiffInput } from "@opencode/plugin/effect/vcs" import { FileSystem } from "@opencode/schema/filesystem" import { VcsEvent } from "@opencode/schema/vcs-event" +import { initGit } from "./fixture/git" import { location } from "./fixture/location" import { tmpdir } from "./fixture/tmpdir" import { it, testEffect } from "./lib/effect" @@ -61,7 +62,7 @@ const withTmp = (f: (directory: string) => Effect.Effect) => const withGit = (f: (directory: string) => Effect.Effect, input: { scope?: string } = {}) => withTmp((directory) => Effect.promise(async () => { - await initRepo(directory) + await initGit(directory, "-b", "main") if (input.scope) await fs.mkdir(path.join(directory, input.scope), { recursive: true }) }).pipe( Effect.andThen( @@ -78,14 +79,6 @@ const withGit = (f: (directory: string) => Effect.Effect, inpu ), ) -async function initRepo(directory: string) { - await $`git init -b main`.cwd(directory).quiet() - await $`git config core.fsmonitor false`.cwd(directory).quiet() - await $`git config commit.gpgsign false`.cwd(directory).quiet() - await $`git config user.email test@opencode.test`.cwd(directory).quiet() - await $`git config user.name Test`.cwd(directory).quiet() -} - async function commitAll(directory: string, message: string) { await $`git add -A`.cwd(directory).quiet() await $`git commit -m ${message}`.cwd(directory).quiet() @@ -586,7 +579,7 @@ describe("Vcs", () => { Effect.gen(function* () { const count = 40 yield* Effect.promise(async () => { - await initRepo(directory) + await initGit(directory, "-b", "main") await fs.writeFile(path.join(directory, "keep.txt"), "one\n") await fs.writeFile(path.join(directory, ".gitignore"), "*.log\n") await commitAll(directory, "initial")