Skip to content

Commit 04c981b

Browse files
test(api): poll observable conditions instead of sleeping in the opencode-go spec
The base's api-provider-hygiene ruleset restricts setTimeout in provider specs (packages/config-eslint/api-provider-hygiene.js, blob 46fc303 on main). That rule reaches this file only on the merge tree: the branch's own copy of the rules file (blob 99dac3a) does not carry it, so lint at the branch head prints 0 problems while CI's run on pull/1652/merge printed 13 no-restricted-globals errors. This commit removes all 13 sleep sites so the merge-tree lint clears; it exists because of the rule, not because a reviewer asked for it. Each wait now names the condition the sleep stood in for: - the two model-catalog gates park the exact promise the provider awaits and poll getModels being called once before aborting, then await that same promise so the provider's continuation drains first; - the three streaming mocks publish firstChunkDelivered after their first yield, poll the captured request signal for aborted, and then throw the path's abort error unconditionally, so abort identity assertions still run against a real abort; - the three test-side waits poll firstChunkDelivered before calling controller.abort(); - the two SDK-timeout mocks poll the forwarded request signal for aborted before throwing AnthropicTimeoutError / APIConnectionTimeoutError, which also proves the provider forwarded a signal at all; - the deadline helper gates resolveModel instead of delaying it, so the bounded resolution test asserts the lookup is still pending at the deadline instead of assuming it after a sleep. Verification (node 22.23.4, interpreter pinned by .nvmrc apart from PATH's v25.9.0): - src tsc --noEmit -p tsconfig.json: exit 0, 0 error lines. - vitest run api/providers/__tests__/opencode-go.spec.ts from src: 187 passed (187), exit 0, on three consecutive runs. - Two-sided catch control: neutering the Anthropic completion catch fails 'preserves abort identity when the caller aborts mid-request (Anthropic path)' and 'preserves abort identity for a name-based AbortError rejection (Anthropic path)' (2 failed | 5 passed | 180 skipped); restoring the provider to blob ba80291 and re-running prints 7 passed. - Converted waits are not hang detectors: breaking each polled condition prints a failure at that test. Park count 1 -> 2 fails with 'expected vi.fn() to be called 2 times, but got 1 times' on both park tests; never releasing the parked lookup times the test out; never setting firstChunkDelivered fails 'aborts the in-flight request when the external signal fires mid-stream'; removing the controller.abort() call fails the same test through the stream's own abort poll; raising the Anthropic timeout to 30_000 makes 'surfaces request timeouts as an AbortError (Anthropic path)' fail with the wait failure surfacing as the completion error. - Merge-tree reproduction (scratch worktree, merge commit 6a843edd99476ac247a7e6a277 d13cd9491cdf93 = e487cd7 + 9ae937b a2de3c3b727b72ac08): its lint prints exactly CI's 13 errors; with these conversions replayed onto the merged copy the same lint exits 0 and the spec against the merged provider prints 188 passed (188). - src/eslint-suppressions.json was left byte-identical (prune run restored). Gate accounting: packageForPath() returns null for a __tests__/ spec path, so the mutation-diff leg charges 0 executable changed lines for this file — cancelled for this commit's content, not green.
1 parent 9ae937b commit 04c981b

1 file changed

Lines changed: 125 additions & 48 deletions

File tree

‎src/api/providers/__tests__/opencode-go.spec.ts‎

Lines changed: 125 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -691,9 +691,16 @@ describe("OpencodeGoHandler", () => {
691691
const resolutionGate = new Promise<void>((resolve) => {
692692
releaseResolution = resolve
693693
})
694-
vitest.mocked(getModels).mockImplementationOnce(async () => {
695-
await resolutionGate
696-
return { "glm-5.1": { ...opencodeGoModels["glm-5.1"] } }
694+
// The exact promise the provider awaits, so the test can await the lookup's own
695+
// settlement instead of guessing how long a parked lookup takes.
696+
let lookupPromise: Promise<Record<string, unknown>> | undefined
697+
vitest.mocked(getModels).mockImplementationOnce(() => {
698+
const parked = (async () => {
699+
await resolutionGate
700+
return { "glm-5.1": { ...opencodeGoModels["glm-5.1"] } }
701+
})()
702+
lookupPromise = parked
703+
return parked
697704
})
698705

699706
const handler = new OpencodeGoHandler(mockOptions)
@@ -707,8 +714,12 @@ describe("OpencodeGoHandler", () => {
707714
),
708715
)
709716

710-
// Let the lookup park on the gate, then abort while it is still pending.
711-
await new Promise((resolve) => setTimeout(resolve, 10))
717+
// Observable condition: the catalog lookup has been invoked and is parked on the
718+
// gate, which is what the 10 ms sleep was standing in for.
719+
await vitest.waitFor(() => expect(vitest.mocked(getModels)).toHaveBeenCalledTimes(1), {
720+
timeout: 1000,
721+
interval: 5,
722+
})
712723
controller.abort()
713724

714725
const error = await consumed.then(
@@ -722,9 +733,12 @@ describe("OpencodeGoHandler", () => {
722733
expect(error).toMatchObject({ name: "AbortError" })
723734
expect((error as Error).message).toBe("The Opencode Go request was aborted")
724735

725-
// Releasing the lookup afterwards must not start a late request.
736+
// Observable condition: the parked lookup has actually settled. Awaiting the same
737+
// promise the provider awaits drains the provider's continuation first, because the
738+
// provider subscribed to it before this test did; only then is "no late request" a
739+
// statement about drained state rather than about a 10 ms window.
726740
releaseResolution()
727-
await new Promise((resolve) => setTimeout(resolve, 10))
741+
await lookupPromise
728742
expect(mockCreate).not.toHaveBeenCalled()
729743
})
730744

@@ -816,16 +830,22 @@ describe("OpencodeGoHandler", () => {
816830
// hang if the bridge stops forwarding aborts, and it rejects as
817831
// soon as the bridge aborts the controller.
818832
let capturedSignal: AbortSignal | undefined
833+
let firstChunkDelivered = false
819834
mockCreate.mockImplementation(async (_params: unknown, options: { signal?: AbortSignal }) => {
820835
capturedSignal = options?.signal
821836
return (async function* () {
822837
yield { choices: [{ delta: { content: "partial" }, index: 0 }], index: 0 }
823-
for (let i = 0; i < 40 && !capturedSignal?.aborted; i++) {
824-
await new Promise((resolve) => setTimeout(resolve, 5))
825-
}
826-
if (capturedSignal?.aborted) {
827-
throw new DOMException("The operation was aborted.", "AbortError")
828-
}
838+
// Runs only once the consumer has taken the first chunk and asked for the next
839+
// one, which is the state the 25 ms sleep was approximating.
840+
firstChunkDelivered = true
841+
// Observable condition: the bridge aborted the internal controller. Polling it
842+
// means a bridge that stops forwarding aborts fails on a printed condition
843+
// instead of quietly running the stream to its end.
844+
await vitest.waitFor(() => expect(capturedSignal?.aborted).toBe(true), {
845+
timeout: 1000,
846+
interval: 5,
847+
})
848+
throw new DOMException("The operation was aborted.", "AbortError")
829849
})()
830850
})
831851

@@ -840,8 +860,9 @@ describe("OpencodeGoHandler", () => {
840860
),
841861
)
842862

843-
// Let the request start and the first chunk be yielded before aborting.
844-
await new Promise((resolve) => setTimeout(resolve, 25))
863+
// Observable condition: the first chunk has been consumed and the stream is asking for
864+
// the next one; abort mid-stream from there rather than after a fixed 25 ms.
865+
await vitest.waitFor(() => expect(firstChunkDelivered).toBe(true), { timeout: 1000, interval: 5 })
845866
controller.abort()
846867

847868
const error = await consumed.then(
@@ -1049,18 +1070,29 @@ describe("OpencodeGoHandler", () => {
10491070
const resolutionGate = new Promise<void>((resolve) => {
10501071
releaseResolution = resolve
10511072
})
1052-
vitest.mocked(getModels).mockImplementationOnce(async () => {
1053-
await resolutionGate
1054-
return { "glm-5.1": { ...opencodeGoModels["glm-5.1"] } }
1073+
// The exact promise the provider awaits, so the test can await the lookup's own
1074+
// settlement instead of guessing how long a parked lookup takes.
1075+
let lookupPromise: Promise<Record<string, unknown>> | undefined
1076+
vitest.mocked(getModels).mockImplementationOnce(() => {
1077+
const parked = (async () => {
1078+
await resolutionGate
1079+
return { "glm-5.1": { ...opencodeGoModels["glm-5.1"] } }
1080+
})()
1081+
lookupPromise = parked
1082+
return parked
10551083
})
10561084

10571085
const handler = new OpencodeGoHandler(mockOptions)
10581086
const controller = new AbortController()
10591087

10601088
const completion = handler.completePrompt("ping", { abortSignal: controller.signal })
10611089

1062-
// Park the lookup on the gate, then abort while it is still pending.
1063-
await new Promise((resolve) => setTimeout(resolve, 10))
1090+
// Observable condition: the catalog lookup has been invoked and is parked on the
1091+
// gate, which is what the 10 ms sleep was standing in for.
1092+
await vitest.waitFor(() => expect(vitest.mocked(getModels)).toHaveBeenCalledTimes(1), {
1093+
timeout: 1000,
1094+
interval: 5,
1095+
})
10641096
controller.abort()
10651097

10661098
await expect(completion).rejects.toMatchObject({
@@ -1071,9 +1103,12 @@ describe("OpencodeGoHandler", () => {
10711103
expect(vitest.mocked(getModels)).toHaveBeenCalledTimes(1)
10721104
expect(mockCreate).not.toHaveBeenCalled()
10731105

1074-
// Releasing the lookup afterwards must not start a late request.
1106+
// Observable condition: the parked lookup has actually settled. Awaiting the same
1107+
// promise the provider awaits drains the provider's continuation first, because the
1108+
// provider subscribed to it before this test did; only then is "no late request" a
1109+
// statement about drained state rather than about a 10 ms window.
10751110
releaseResolution()
1076-
await new Promise((resolve) => setTimeout(resolve, 10))
1111+
await lookupPromise
10771112
expect(mockCreate).not.toHaveBeenCalled()
10781113
})
10791114

@@ -1447,8 +1482,16 @@ describe("OpencodeGoHandler", () => {
14471482
// Emulate the Anthropic SDK: when the request timeout fires, the SDK
14481483
// surfaces APIConnectionTimeoutError ("Request timed out.") once retries
14491484
// are exhausted — verified against @anthropic-ai/sdk against a hung server.
1450-
mockAnthropicCreate.mockImplementation(async (_params: unknown, options: { timeout?: number }) => {
1451-
await new Promise((resolve) => setTimeout(resolve, options?.timeout ?? 50))
1485+
mockAnthropicCreate.mockImplementation(async (_params: unknown, options: { signal?: AbortSignal }) => {
1486+
const requestSignal = options?.signal
1487+
if (!requestSignal) {
1488+
throw new Error("the provider forwarded no request signal")
1489+
}
1490+
// Observable condition: the deadline signal the provider shares with this request has
1491+
// fired. The 50 ms sleep stood in for that same instant — the SDK's own timeout
1492+
// budget and this deadline are the same number by design, so the signal is the only
1493+
// witness that either leg of the race actually ran.
1494+
await vitest.waitFor(() => expect(requestSignal.aborted).toBe(true), { timeout: 1000, interval: 5 })
14521495
throw new AnthropicTimeoutError()
14531496
})
14541497
const handler = new OpencodeGoHandler(anthropicOptions)
@@ -1650,8 +1693,14 @@ describe("OpencodeGoHandler", () => {
16501693
// Emulate the OpenAI SDK: when the request timeout fires, the SDK
16511694
// surfaces APIConnectionTimeoutError ("Request timed out.") once retries
16521695
// are exhausted — verified against openai v5.23.2 against a hung server.
1653-
mockCreate.mockImplementation(async (_params: unknown, options: { timeout?: number }) => {
1654-
await new Promise((resolve) => setTimeout(resolve, options?.timeout ?? 50))
1696+
mockCreate.mockImplementation(async (_params: unknown, options: { signal?: AbortSignal }) => {
1697+
const requestSignal = options?.signal
1698+
if (!requestSignal) {
1699+
throw new Error("the provider forwarded no request signal")
1700+
}
1701+
// Observable condition: the deadline signal the provider shares with this request
1702+
// has fired, the same instant the 50 ms sleep was standing in for.
1703+
await vitest.waitFor(() => expect(requestSignal.aborted).toBe(true), { timeout: 1000, interval: 5 })
16551704
throw new APIConnectionTimeoutError()
16561705
})
16571706
const handler = new OpencodeGoHandler(openaiOptions)
@@ -1959,6 +2008,7 @@ describe("OpencodeGoHandler", () => {
19592008
// started must normalize to the standardized AbortError like the
19602009
// other wire formats, not leak the raw SDK rejection.
19612010
let capturedSignal: AbortSignal | undefined
2011+
let firstChunkDelivered = false
19622012
mockAnthropicCreate.mockImplementation(async (_params: unknown, options: { signal?: AbortSignal }) => {
19632013
capturedSignal = options?.signal
19642014
return (async function* () {
@@ -1967,12 +2017,15 @@ describe("OpencodeGoHandler", () => {
19672017
index: 0,
19682018
delta: { type: "text_delta", text: "partial" },
19692019
}
1970-
for (let i = 0; i < 40 && !capturedSignal?.aborted; i++) {
1971-
await new Promise((resolve) => setTimeout(resolve, 5))
1972-
}
1973-
if (capturedSignal?.aborted) {
1974-
throw new AnthropicAbortError()
1975-
}
2020+
// Runs only once the consumer has taken the first chunk and asked for the next
2021+
// one, which is the state the 25 ms sleep was approximating.
2022+
firstChunkDelivered = true
2023+
// Observable condition: the bridge aborted the internal controller.
2024+
await vitest.waitFor(() => expect(capturedSignal?.aborted).toBe(true), {
2025+
timeout: 1000,
2026+
interval: 5,
2027+
})
2028+
throw new AnthropicAbortError()
19762029
})()
19772030
})
19782031
const controller = new AbortController()
@@ -1983,8 +2036,9 @@ describe("OpencodeGoHandler", () => {
19832036
handler.createMessage("sys", messages, { taskId: "test-task", abortSignal: controller.signal }),
19842037
)
19852038

1986-
// Let the request start and the first chunk be yielded before aborting.
1987-
await new Promise((resolve) => setTimeout(resolve, 25))
2039+
// Observable condition: the first chunk has been consumed and the stream is asking for
2040+
// the next one; abort mid-stream from there rather than after a fixed 25 ms.
2041+
await vitest.waitFor(() => expect(firstChunkDelivered).toBe(true), { timeout: 1000, interval: 5 })
19882042
controller.abort()
19892043

19902044
const error = await consumed.then(
@@ -2084,16 +2138,20 @@ describe("OpencodeGoHandler", () => {
20842138
// started must normalize to the standardized AbortError like the
20852139
// other wire formats, not leak the raw SDK rejection.
20862140
let capturedSignal: AbortSignal | undefined
2141+
let firstChunkDelivered = false
20872142
mockResponsesCreate.mockImplementation(async (_body: unknown, options: { signal?: AbortSignal }) => {
20882143
capturedSignal = options?.signal
20892144
return (async function* () {
20902145
yield { type: "response.output_text.delta", delta: "partial" }
2091-
for (let i = 0; i < 40 && !capturedSignal?.aborted; i++) {
2092-
await new Promise((resolve) => setTimeout(resolve, 5))
2093-
}
2094-
if (capturedSignal?.aborted) {
2095-
throw new APIUserAbortError()
2096-
}
2146+
// Runs only once the consumer has taken the first chunk and asked for the next
2147+
// one, which is the state the 25 ms sleep was approximating.
2148+
firstChunkDelivered = true
2149+
// Observable condition: the bridge aborted the internal controller.
2150+
await vitest.waitFor(() => expect(capturedSignal?.aborted).toBe(true), {
2151+
timeout: 1000,
2152+
interval: 5,
2153+
})
2154+
throw new APIUserAbortError()
20972155
})()
20982156
})
20992157
const controller = new AbortController()
@@ -2104,8 +2162,9 @@ describe("OpencodeGoHandler", () => {
21042162
handler.createMessage("sys", messages, { taskId: "test-task", abortSignal: controller.signal }),
21052163
)
21062164

2107-
// Let the request start and the first chunk be yielded before aborting.
2108-
await new Promise((resolve) => setTimeout(resolve, 25))
2165+
// Observable condition: the first chunk has been consumed and the stream is asking for
2166+
// the next one; abort mid-stream from there rather than after a fixed 25 ms.
2167+
await vitest.waitFor(() => expect(firstChunkDelivered).toBe(true), { timeout: 1000, interval: 5 })
21092168
controller.abort()
21102169

21112170
const error = await consumed.then(
@@ -2999,10 +3058,23 @@ describe("OpencodeGoHandler", () => {
29993058
})
30003059

30013060
describe("completePrompt shared timeout deadline", () => {
3002-
const delayResolveModel = (handler: OpencodeGoHandler, delayMs: number) =>
3003-
vi
3004-
.spyOn(handler as unknown as { resolveModel: () => Promise<unknown> }, "resolveModel")
3005-
.mockImplementation(() => new Promise((resolve) => setTimeout(() => resolve({}), delayMs)))
3061+
// Stands in for a slow catalog lookup: it stays pending until the test releases it, so
3062+
// "the deadline fired first" is an observable state the test can assert, not a race
3063+
// against a fixed delay the test cannot see.
3064+
const gateResolveModel = (handler: OpencodeGoHandler) => {
3065+
let release!: () => void
3066+
let pending = true
3067+
const lookup = new Promise<Record<string, unknown>>((resolve) => {
3068+
release = () => {
3069+
pending = false
3070+
resolve({})
3071+
}
3072+
})
3073+
vi.spyOn(handler as unknown as { resolveModel: () => Promise<unknown> }, "resolveModel").mockImplementation(
3074+
() => lookup,
3075+
)
3076+
return { isPending: () => pending, release }
3077+
}
30063078

30073079
it.each([
30083080
[
@@ -3018,13 +3090,18 @@ describe("OpencodeGoHandler", () => {
30183090
["OpenAI", () => new OpencodeGoHandler(mockOptions), mockCreate],
30193091
])("bounds %s model resolution by the request timeout", async (_label, makeHandler, createMock) => {
30203092
const handler = makeHandler() as OpencodeGoHandler
3021-
delayResolveModel(handler, 80)
3093+
const { isPending, release } = gateResolveModel(handler)
30223094

30233095
const error = await handler.completePrompt("ping", { timeoutMs: 20 }).catch((caught: unknown) => caught)
30243096

30253097
expect(error).toMatchObject({ name: "AbortError" })
3026-
// Resolution timed out, so no completion request may start.
3098+
// The lookup was still parked when the deadline fired, which is the condition the old
3099+
// 80 ms delay was approximating; it must still be pending here, and no completion
3100+
// request may have started.
3101+
expect(isPending()).toBe(true)
30273102
expect(createMock).not.toHaveBeenCalled()
3103+
// Release the parked lookup so the test leaves no pending promise behind.
3104+
release()
30283105
})
30293106

30303107
it.each([

0 commit comments

Comments
 (0)