Repository navigation
test(core): cancel and clean up the local git clone fixture #299
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| import { describe, expect, test } from "bun:test" | ||
| import { $ } from "bun" | ||
| import fs from "fs/promises" | ||
| import path from "path" | ||
| import { Effect, Layer } from "effect" | ||
| import { testEffect } from "../lib/effect" | ||
| import { gitProcesses, gitRemote, type Remote, withRemote } from "./git" | ||
| import { tmpdir } from "./tmpdir" | ||
|
|
||
| const it = testEffect(Layer.empty) | ||
|
|
||
| // A git process that stays alive until something cancels it. It stands in for | ||
| // the `git push -u origin main` that was still running when the Windows test | ||
| // budget expired in #278. | ||
| const blocked = (fixture: Remote) => fixture.git(fixture.source, "hash-object", "--stdin", "-w") | ||
|
|
||
| describe("Git fixture", () => { | ||
| test("awaits the pushed remote before setup resolves", async () => { | ||
| await using root = await tmpdir() | ||
| const processes = gitProcesses() | ||
| const fixture = await gitRemote(processes, root.path) | ||
| const origin = path.join(root.path, "origin.git") | ||
|
|
||
| // Nothing may still be running when setup hands the fixture to a test. | ||
| expect(processes.pending).toBe(0) | ||
| expect((await $`git --git-dir=${origin} rev-parse --verify main`.quiet()).exitCode).toBe(0) | ||
| expect(await fs.readFile(path.join(origin, "HEAD"), "utf8")).toBe("ref: refs/heads/main\n") | ||
| expect(await fs.readFile(path.join(fixture.source, "README.md"), "utf8")).toBe("one\n") | ||
| }) | ||
|
|
||
| test("drops settled promises after repeated successful and failed processes", async () => { | ||
| await using root = await tmpdir() | ||
| const processes = gitProcesses() | ||
| const fixture = await gitRemote(processes, root.path) | ||
|
|
||
| expect(processes.tracked).toBe(0) | ||
| try { | ||
| for (let index = 0; index < 20; index++) { | ||
| await fixture.git(fixture.source, "rev-parse", "--verify", "HEAD") | ||
| expect(processes.tracked).toBe(0) | ||
| const failed = fixture.git(fixture.source, "rev-parse", "--verify", "refs/heads/missing").then( | ||
| () => false, | ||
| () => true, | ||
| ) | ||
| expect(processes.tracked).toBe(1) | ||
| expect(await failed).toBe(true) | ||
| expect(processes.tracked).toBe(0) | ||
| expect(processes.pending).toBe(0) | ||
| } | ||
| } finally { | ||
| await processes.settle() | ||
| } | ||
| }) | ||
|
|
||
| test("cancels its own setup when the budget expires", async () => { | ||
| await using root = await tmpdir() | ||
| const processes = gitProcesses() | ||
| const failure = await gitRemote(processes, root.path, { setupBudget: 1 }).then( | ||
| () => undefined, | ||
| (error: unknown) => (error instanceof Error ? error.message : String(error)), | ||
| ) | ||
|
|
||
| // The fixture ends the slow phase itself and names it, instead of leaving | ||
| // the test runner to SIGTERM that process once the test is already over. | ||
| expect(failure).toMatch(/^git fixture \w+ failed after \d+ms \(completed: .*\)$/) | ||
| expect(processes.pending).toBe(0) | ||
| }) | ||
|
|
||
| test("ends an in-flight process when its deadline aborts", async () => { | ||
| await using root = await tmpdir() | ||
| const processes = gitProcesses() | ||
| const fixture = await gitRemote(processes, root.path) | ||
| const deadline = new AbortController() | ||
| setTimeout(() => deadline.abort(), 100) | ||
| const canceled = processes.run(fixture.source, ["hash-object", "--stdin", "-w"], { signal: deadline.signal }).then( | ||
| () => false, | ||
| () => true, | ||
| ) | ||
| expect(processes.pending).toBe(1) | ||
|
|
||
| // This is how the setup budget ends a phase that is still running, without | ||
| // waiting for the test runner to do it after the test has been reported. | ||
| expect(await canceled).toBe(true) | ||
| expect(processes.pending).toBe(0) | ||
| }) | ||
|
|
||
| test("ends and awaits a process still running at teardown", async () => { | ||
| await using root = await tmpdir() | ||
| const processes = gitProcesses() | ||
| const fixture = await gitRemote(processes, root.path) | ||
| const canceled = blocked(fixture).then( | ||
| () => false, | ||
| () => true, | ||
| ) | ||
| expect(processes.pending).toBe(1) | ||
| expect(processes.tracked).toBe(1) | ||
|
|
||
| await processes.settle() | ||
|
|
||
| expect(processes.pending).toBe(0) | ||
| expect(processes.tracked).toBe(0) | ||
| // Whoever started the process still sees the cancellation; teardown does not | ||
| // let it resurface as an unhandled rejection. | ||
| expect(await canceled).toBe(true) | ||
| await processes.settle() | ||
| expect(processes.pending).toBe(0) | ||
| }) | ||
|
|
||
| it.effect("settles fixture processes before removing the temporary root", () => | ||
| Effect.gen(function* () { | ||
| const fixture = yield* withRemote((remote) => | ||
| Effect.gen(function* () { | ||
| void blocked(remote).catch(() => undefined) | ||
| expect(remote.processes.pending).toBe(1) | ||
| return yield* Effect.fail(remote) | ||
| }), | ||
| ).pipe(Effect.flip, Effect.scoped) | ||
|
|
||
| expect(fixture.processes.pending).toBe(0) | ||
| expect(yield* Effect.promise(() => exists(fixture.root))).toBe(false) | ||
| }), | ||
| ) | ||
|
|
||
| it.effect("removes the temporary root when the test body fails", () => | ||
| Effect.gen(function* () { | ||
| const root = yield* withRemote((fixture) => Effect.fail(fixture.root)).pipe(Effect.flip, Effect.scoped) | ||
|
|
||
| expect(yield* Effect.promise(() => exists(root))).toBe(false) | ||
| }), | ||
| ) | ||
| }) | ||
|
|
||
| function exists(directory: string) { | ||
| return fs.stat(directory).then( | ||
| () => true, | ||
| () => false, | ||
| ) | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,49 +1,172 @@ | ||
| import { execFile } from "child_process" | ||
| import { execFile, type ChildProcess } from "child_process" | ||
| import fs from "fs/promises" | ||
| import path from "path" | ||
| import { promisify } from "util" | ||
| import { pathToFileURL } from "url" | ||
| import { Effect } from "effect" | ||
| import { Repository } from "@opencode-ai/core/repository" | ||
| import { tmpdir } from "./tmpdir" | ||
|
|
||
| const exec = promisify(execFile) | ||
| // Configuration passed to every fixture git process with -c. Inline values keep | ||
| // the process count down, and core.fsmonitor=false stops the globally enabled | ||
| // fsmonitor on Windows runners from reaching the fixture. The other git fixtures | ||
| // in this repo disable fsmonitor for the same reason. | ||
| const config = [ | ||
| "-c", | ||
| "core.fsmonitor=false", | ||
| "-c", | ||
| "commit.gpgsign=false", | ||
| "-c", | ||
| "[email protected]", | ||
| "-c", | ||
| "user.name=Test", | ||
| ] | ||
|
|
||
| export async function gitRemote(root: string) { | ||
| // Absolute budget for building one fixture remote. Bun SIGTERMs children still | ||
| // running when a test hits its budget, and that cancellation resurfaces in the | ||
| // next test as an unhandled error (#278). Canceling here keeps the failure and | ||
| // its cleanup inside the test that owns it. The budget sits far above a healthy | ||
| // setup and below the budgets of the tests using this fixture. | ||
| const setupBudget = 10_000 | ||
|
|
||
| // Scoped fixture remote for tests. The temporary root is acquired first so its | ||
| // finalizer runs last: the repositories are removed once every git process the | ||
| // fixture started has exited, and they are removed even when setup fails. | ||
| // `acquireUseRelease` skips its release when the acquire never completes, which | ||
| // is how a setup that ran out of budget left processes and directories behind. | ||
| export function withRemote<A, E, R>(body: (fixture: Remote) => Effect.Effect<A, E, R>) { | ||
| return Effect.gen(function* () { | ||
| const root = yield* Effect.acquireRelease( | ||
| Effect.promise(() => tmpdir()), | ||
| (directory) => Effect.promise(() => directory[Symbol.asyncDispose]()), | ||
| ) | ||
| const processes = yield* Effect.acquireRelease( | ||
| Effect.sync(() => gitProcesses()), | ||
| (group) => Effect.promise(() => group.settle()), | ||
| ) | ||
| const fixture = yield* Effect.promise(() => gitRemote(processes, root.path)) | ||
| return yield* body(fixture) | ||
| }) | ||
| } | ||
|
|
||
| export async function gitRemote(processes: GitProcesses, root: string, options?: { setupBudget?: number }) { | ||
| 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", "[email protected]") | ||
| await git(source, "config", "user.name", "Test") | ||
| await fs.writeFile(path.join(source, "README.md"), "one\n") | ||
| await git(source, "add", "README.md") | ||
| await git(source, "commit", "-m", "initial") | ||
| await git(source, "branch", "-M", "main") | ||
| await git(source, "remote", "add", "origin", pathToFileURL(origin).href) | ||
| await git(source, "push", "-u", "origin", "main") | ||
| await git(root, "--git-dir", origin, "symbolic-ref", "HEAD", "refs/heads/main") | ||
| return { | ||
| const remote = pathToFileURL(origin).href | ||
| // One deadline shared by every setup process, so a slow phase is canceled by | ||
| // the fixture instead of by the runner after the test has been reported. | ||
| // Bun leaves an AbortSignal.timeout timer unfired while child processes are | ||
| // running, so the budget aborts through an explicit timer instead. | ||
| const deadline = new AbortController() | ||
| const timer = setTimeout(() => deadline.abort(), options?.setupBudget ?? setupBudget) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SUGGESTION: Timer created before try block risks leak if setup throws early The Reply with |
||
| const signal = deadline.signal | ||
| const started = Date.now() | ||
| const phases: string[] = [] | ||
| const step = (name: string, cwd: string, ...args: string[]) => | ||
| record(phases, name, processes.run(cwd, [...config, ...args], { signal })) | ||
|
|
||
| // `--initial-branch=main` replaces the `branch -M main` and `symbolic-ref | ||
| // HEAD` launches this fixture used to need. Process startup, not git work, is | ||
| // what makes the fixture slow on Windows CI. | ||
| try { | ||
| await step("initOrigin", root, "init", "--bare", "--initial-branch=main", origin) | ||
| await step("initSource", root, "init", "--initial-branch=main", source) | ||
| await fs.writeFile(path.join(source, "README.md"), "one\n") | ||
| await step("add", source, "add", "README.md") | ||
| await step("commit", source, "commit", "-m", "initial") | ||
| await step("addRemote", source, "remote", "add", "origin", remote) | ||
| await step("push", source, "push", "-u", "origin", "main") | ||
| } finally { | ||
| // A live timer would hold the test process open for the whole budget. | ||
| clearTimeout(timer) | ||
| } | ||
| console.error(`[git-fixture] setup=${Date.now() - started}ms ${phases.join(" ")}`) | ||
|
|
||
| const fixture = { | ||
| root, | ||
| source, | ||
| remote: pathToFileURL(origin).href, | ||
| reference: { ...Repository.parseRemote("owner/repo"), remote: pathToFileURL(origin).href }, | ||
| remote, | ||
| reference: { ...Repository.parseRemote("owner/repo"), remote }, | ||
| processes, | ||
| git(cwd: string, ...args: string[]) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SUGGESTION: Test code using Reply with |
||
| return processes.run(cwd, [...config, ...args]) | ||
| }, | ||
| async commit(content: string, message: string) { | ||
| await fs.writeFile(path.join(source, "README.md"), content) | ||
| await fixture.git(source, "add", "README.md") | ||
| await fixture.git(source, "commit", "-m", message) | ||
| await fixture.git(source, "push") | ||
| }, | ||
| async branch(name: string, content: string) { | ||
| await fixture.git(source, "checkout", "-b", name) | ||
| await fs.writeFile(path.join(source, "README.md"), content) | ||
| await fixture.git(source, "add", "README.md") | ||
| await fixture.git(source, "commit", "-m", name) | ||
| await fixture.git(source, "push", "-u", "origin", name) | ||
| }, | ||
| } | ||
| return fixture | ||
| } | ||
|
|
||
| export async function commit(source: string, content: string, message: string) { | ||
| await fs.writeFile(path.join(source, "README.md"), content) | ||
| await git(source, "add", "README.md") | ||
| await git(source, "commit", "-m", message) | ||
| await git(source, "push") | ||
| } | ||
| export type Remote = Awaited<ReturnType<typeof gitRemote>> | ||
| export type GitProcesses = ReturnType<typeof gitProcesses> | ||
|
|
||
| export async function branch(source: string, name: string, content: string) { | ||
| await git(source, "checkout", "-b", name) | ||
| await fs.writeFile(path.join(source, "README.md"), content) | ||
| await git(source, "add", "README.md") | ||
| await git(source, "commit", "-m", name) | ||
| await git(source, "push", "-u", "origin", name) | ||
| // Tracks the git processes a fixture starts so teardown can end them and wait | ||
| // for them. The runner SIGTERMs a child still alive when a test hits its budget, | ||
| // and that rejection resurfaces after the test is over as the canceled | ||
| // `git push -u origin main` in #278. Cleanup also deleted the repositories while | ||
| // such a process still held them. | ||
| export function gitProcesses() { | ||
| const children = new Set<ChildProcess>() | ||
| const finished = new Set<Promise<unknown>>() | ||
| return { | ||
| get pending() { | ||
| return children.size | ||
| }, | ||
| get tracked() { | ||
| return finished.size | ||
| }, | ||
| run(cwd: string, args: string[], options?: { signal?: AbortSignal }) { | ||
| const done = new Promise<void>((resolve, reject) => { | ||
| const child = execFile("git", args, { cwd, signal: options?.signal }, (error) => { | ||
| children.delete(child) | ||
| if (error) reject(error) | ||
| else resolve() | ||
| }) | ||
| children.add(child) | ||
| }) | ||
| // A cancellation nobody awaits any more, because the test that started it | ||
| // is already over, must not come back as an unhandled rejection. | ||
| // Keep only unsettled promises, and observe both outcomes without changing | ||
| // the result returned to the caller. Teardown still awaits every live child. | ||
| const observed = done.then( | ||
| () => { | ||
| finished.delete(observed) | ||
| }, | ||
| () => { | ||
| finished.delete(observed) | ||
| }, | ||
| ) | ||
| finished.add(observed) | ||
| return done | ||
| }, | ||
| async settle() { | ||
| for (const child of children) child.kill("SIGTERM") | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SUGGESTION:
Reply with |
||
| await Promise.allSettled(finished) | ||
| children.clear() | ||
| finished.clear() | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| export async function git(cwd: string, ...args: string[]) { | ||
| await exec("git", args, { cwd }) | ||
| // Times one setup phase and, when it fails, names it along with the phases that | ||
| // did finish. | ||
| function record(phases: string[], name: string, run: Promise<void>) { | ||
| const started = Date.now() | ||
| return run.then( | ||
| () => void phases.push(`${name}=${Date.now() - started}ms`), | ||
| (cause) => { | ||
| const completed = phases.join(" ") || "nothing" | ||
| throw new Error(`git fixture ${name} failed after ${Date.now() - started}ms (completed: ${completed})`, { cause }) | ||
| }, | ||
| ) | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
SUGGESTION: Release function doesn't handle asyncDispose errors
If
directory[Symbol.asyncDispose]()throws, the error will propagate and could mask the original error or cause unhandled rejection. Consider wrapping inEffect.tryor adding.catch().Reply with
@kilocode-bot fix itto have Kilo Code address this issue.