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
24 changes: 19 additions & 5 deletions packages/core/test/lib/owned-deadline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ type OwnedTestScope = {
const runs = new Map<symbol, OwnedRun>()

let activeScope: OwnedTestScope | undefined
// Bun can abandon the afterEach Promise too. Closed means no new runs may
// attach, not that the fiber's finalizers have finished.
const drainingScopes = new Set<Promise<void>>()

export function inflightOwnedRunCount(): number {
return runs.size
Expand Down Expand Up @@ -186,7 +189,16 @@ function performReleaseScope(scope: OwnedTestScope): Promise<void> {
}

function releaseScope(scope: OwnedTestScope): Promise<void> {
scope.releasePromise ??= performReleaseScope(scope)
if (!scope.releasePromise) {
const pending = performReleaseScope(scope)
scope.releasePromise = pending
drainingScopes.add(pending)
// Observe both outcomes without producing an unhandled rejected Promise.
void pending.then(
() => drainingScopes.delete(pending),
() => drainingScopes.delete(pending),
)
}
return scope.releasePromise
}

Expand All @@ -200,12 +212,14 @@ async function reportScope(scope: OwnedTestScope): Promise<void> {
}

/**
* Used by top-level test wrappers (`testEffect` / `testEffectShared`) to flush an unclosed scope
* if the previous test registered an async dynamic `afterEach` that threw and aborted hooks.
* Join both an unclosed scope (hooks skipped) and closed scopes whose release
* Promise Bun abandoned on hook timeout. Used by the next-test entry barrier
* and by top-level test wrappers (`testEffect` / `testEffectShared`).
*/
export function takeActiveOwnedScope(): Promise<void> | undefined {
if (!activeScope || activeScope.closed) return undefined
return releaseScope(activeScope)
if (activeScope && !activeScope.closed) void releaseScope(activeScope)
if (drainingScopes.size === 0) return undefined
return Promise.all(drainingScopes).then(() => undefined)
}

export function beginOwned<A>(start: () => Promise<A>): Promise<A> {
Expand Down
5 changes: 5 additions & 0 deletions packages/core/test/preload.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import path from "path"
import { beforeEach } from "bun:test"
import { takeActiveOwnedScope } from "./lib/owned-deadline"
import { traceAborts } from "./lib/abort-trace"

// Also protect plain Bun tests following an abandoned Effect cleanup hook.
beforeEach(() => takeActiveOwnedScope())

// Installed before any test file so it covers the whole run; inert unless
// OPENCODE_TRACE_TEST_ABORTS is set (#560).
traceAborts()
Expand Down
71 changes: 71 additions & 0 deletions packages/opencode/test/lib/abandoned-entry-barrier.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { expect, test } from "bun:test"
import path from "node:path"

const CHILD_GUARD_MS = 15000

test(
"host timeout and hook cutoff cannot let the next test enter an unfinalized Effect scope",
async () => {
const child = Bun.spawn(
[
process.execPath,
"test",
"--timeout",
"800",
path.join(import.meta.dir, "fixtures", "abandoned-entry-barrier.ts"),
],
{
cwd: path.resolve(import.meta.dir, "../.."),
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
},
)
let timedOut = false
let released = false
const timer = setTimeout(() => {
timedOut = true
child.kill()
}, CHILD_GUARD_MS)
try {
const stderr = (async () => {
const decoder = new TextDecoder()
let output = ""
const reader = child.stderr.getReader()
try {
while (true) {
const { done, value } = await reader.read()
if (done) break
output += decoder.decode(value, { stream: true })
if (!released && output.includes("a beforeEach/afterEach hook timed out for this test")) {
released = true
// Handshake, not a timing guess: cleanup is blocked until Bun has
// abandoned the hook. Restoration still needs another event-loop turn.
await child.stdin.write("release\n")
await child.stdin.end()
}
}
} finally {
reader.releaseLock()
}
return output + decoder.decode()
})()
const [stdout, errors, code] = await Promise.all([new Response(child.stdout).text(), stderr, child.exited])
const output = stdout + errors
expect({ timedOut, released, output }).toMatchObject({ timedOut: false, released: true })
expect(code).toBe(1)
expect(output).toContain("(fail) host timeout interrupts a scope whose finalizer outlives the cleanup hook")
expect(output).toContain("(pass) next plain test enters only after abandoned scope and child are joined")
expect(output).toContain("(pass) no abandoned work or late finalizer overwrites the newer test state")
expect(output).toContain("2 pass")
expect(output).toContain("1 fail")
expect(output).not.toContain("Unhandled error")
expect(output).not.toMatch(/^\s*\d+\s+errors?\b/m)
} finally {
clearTimeout(timer)
if (child.exitCode === null) child.kill()
await child.exited
}
},
CHILD_GUARD_MS + 10000,
)
64 changes: 64 additions & 0 deletions packages/opencode/test/lib/fixtures/abandoned-entry-barrier.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// No elapsed-time assertions or cleanup sleeps: the finalizer cannot finish until
// the parent sees Bun report the hook cutoff and opens the gate over stdin.
import { afterAll, expect, test } from "bun:test"
import { Effect, Layer } from "effect"
import { testEffect } from "../effect"
import { inflightOwnedRunCount } from "../owned-deadline"
import { hangWithLiveHandle } from "./abandoned-keepalive"

const envKey = "SILVERCODE_TEST_ABANDONED_ENTRY_ENV"
const previousEnv = process.env[envKey]
const events: string[] = []
const gate = new Response(Bun.stdin.stream()).text()

const restoreEnv = () => {
if (previousEnv === undefined) delete process.env[envKey]
else process.env[envKey] = previousEnv
}
afterAll(restoreEnv)

const it = testEffect(Layer.empty)
it.live("host timeout interrupts a scope whose finalizer outlives the cleanup hook", () =>
Effect.gen(function* () {
yield* Effect.acquireRelease(
Effect.sync(() => {
process.env[envKey] = "active"
events.push("acquired")
}),
() =>
Effect.promise(async () => {
events.push("finalizer-start")
expect(await gate).toBe("release\n")
restoreEnv()
events.push("finalizer-end")
}),
)
yield* Effect.never.pipe(
Effect.ensuring(
Effect.sync(() => {
events.push("child-interrupted")
}),
),
Effect.forkChild,
)
yield* hangWithLiveHandle
yield* Effect.sync(() => {
events.push("orphan-body-write")
})
}),
)

test("next plain test enters only after abandoned scope and child are joined", () => {
expect(process.env[envKey]).toBe(previousEnv)
expect(events).toEqual(["acquired", "finalizer-start", "finalizer-end", "child-interrupted"])
expect(inflightOwnedRunCount()).toBe(0)
process.env[envKey] = "newer-test"
events.push("next-test")
})

test("no abandoned work or late finalizer overwrites the newer test state", async () => {
await new Promise<void>((resolve) => setImmediate(resolve))
expect(process.env[envKey]).toBe("newer-test")
expect(events).toEqual(["acquired", "finalizer-start", "finalizer-end", "child-interrupted", "next-test"])
expect(inflightOwnedRunCount()).toBe(0)
})
7 changes: 6 additions & 1 deletion packages/opencode/test/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ import os from "os"
import path from "path"
import fs from "fs/promises"
import { setTimeout as sleep } from "node:timers/promises"
import { afterAll } from "bun:test"
import { afterAll, beforeEach } from "bun:test"
import { takeActiveOwnedScope } from "./lib/owned-deadline"

// Bun may time out afterEach while an interrupted Effect is still finalizing.
// Do not enter another test body until that owned execution has settled.
beforeEach(() => takeActiveOwnedScope())

// Set XDG env vars FIRST, before any src/ imports
const dir = path.join(os.tmpdir(), "opencode-test-data-" + process.pid)
Expand Down
Loading