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
138 changes: 138 additions & 0 deletions packages/core/test/fixture/git.test.ts
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,
)
}
187 changes: 155 additions & 32 deletions packages/core/test/fixture/git.ts
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]()),

Copy link
Copy Markdown

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 in Effect.try or adding .catch().


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

)
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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 setTimeout is created at line 60 but only cleared in the finally block starting at line 78. If any code between lines 60-70 throws (e.g., future modifications adding fallible operations), the timer would leak and hold the test process open for the full budget duration. Move timer creation inside the try block or use a try/finally wrapper around the timer creation itself.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

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[]) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: fixture.git() doesn't accept AbortSignal for cancellation

Test code using fixture.git() cannot be cancelled by test budgets or deadlines, risking the same hanging process issues this fixture was designed to prevent. Consider adding an optional signal parameter.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: settle() never escalates past SIGTERM or times out, so a child that ignores SIGTERM hangs teardown forever

child.kill("SIGTERM") followed by await Promise.allSettled(finished) (line 141) never resolves if a fixture git process fails to exit on SIGTERM — for example a child stuck on a Windows file lock, a hung daemon, or a process that traps signals. Teardown then hangs indefinitely: the Effect scope never closes and the test runner has to be killed externally, which is a worse failure mode than the fast in-test failure this PR adds for setup. Consider bounding the wait and escalating to child.kill("SIGKILL") so teardown fails fast instead of hanging.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

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 })
},
)
}
17 changes: 3 additions & 14 deletions packages/core/test/git.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Effect } from "effect"
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { Git } from "@opencode-ai/core/git"
import { AbsolutePath, RelativePath } from "@opencode-ai/core/schema"
import { branch, commit, gitRemote } from "./fixture/git"
import { withRemote } from "./fixture/git"
import { tmpdir } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect"

Expand Down Expand Up @@ -48,12 +48,12 @@ describe("Git", () => {
const target = AbsolutePath.make(path.join(fixture.root, "checkout"))
const repository = yield* git.repo.clone({ remote: fixture.remote, directory: target })

yield* Effect.promise(() => commit(fixture.source, "two\n", "second"))
yield* Effect.promise(() => fixture.commit("two\n", "second"))
yield* git.sync.fetchRemotes(repository)
yield* git.sync.resetHard(repository, "origin/main")
expect(yield* read(path.join(target, "README.md"))).toBe("two\n")

yield* Effect.promise(() => branch(fixture.source, "feature/docs", "feature\n"))
yield* Effect.promise(() => fixture.branch("feature/docs", "feature\n"))
yield* git.sync.fetchBranch(repository, { branch: "feature/docs" })
yield* git.sync.checkoutRemoteBranch(repository, { branch: "feature/docs" })
yield* git.sync.resetHard(repository, "origin/feature/docs")
Expand All @@ -68,17 +68,6 @@ describe("Git", () => {
)
})

function withRemote<A, E, R>(body: (fixture: Awaited<ReturnType<typeof gitRemote>>) => Effect.Effect<A, E, R>) {
return Effect.acquireUseRelease(
Effect.promise(async () => {
const root = await tmpdir()
return { root, fixture: await gitRemote(root.path) }
}),
(input) => body(input.fixture),
(input) => Effect.promise(() => input.root[Symbol.asyncDispose]()),
)
}

function read(file: string) {
return Effect.promise(() => fs.readFile(file, "utf8")).pipe(Effect.map((content) => content.replace(/\r\n/g, "\n")))
}
Expand Down
Loading
Loading