Skip to content

Commit fdae60d

Browse files
anandgupta42claude
andcommitted
fix: fold cycle-stability tests into one, isolate state dir from real Flock lock artifacts
This repo's rule is no order-dependent or resource-contention-prone tests; both cubic findings on cycle-stability.test.tsx are in scope: 1. The three sequential `test.serial` blocks sharing one `beforeAll`/`afterAll` mount made the third test depend on mutations the first two produced — running it alone (a `-t` filter or `--only-failures`) failed. Folded into ONE `test()` over a single local mount, with five labelled phases (a small `phase()` helper wraps each block so an assertion failure's message names exactly which stage failed) covering the same ground as before: stable traversal order, persisting picks to the front of `recent`, picker-driven staleness/re-discovery, and stable re-traversal afterward. 2. `kv.tsx`'s `Flock.withLock` lock directory is derived from `Global.Path.state` (packages/core/src/global.ts), which had no test-isolation override at all — only `Global.Path.home` did. The test's `kv.json` FILE itself was always correctly isolated via `paths.state` (TestTuiContexts), but the LOCK it takes while reading/writing that file was not, so it could still touch the real, current developer's global state directory. Added an `OPENCODE_TEST_STATE_HOME` override to `Global.Path.state` (mirroring `Global.Path.home`'s existing `OPENCODE_TEST_HOME` pattern, already used throughout this codebase's tests), and made `Flock.setGlobal` take a getter over `Path.state` instead of a frozen snapshot — `Flock`'s lock root was captured once at this module's import time, before any test's own setup code could set the env var, so a plain override on `Path.state` alone would not have been enough. The test now sets/restores this env var around its mount. Verified empirically: before this fix, this test's own runs left new (and orphaned, if killed mid-run) `.lock` directories in the real `~/.local/state/altimate-code/locks` — confirmed via the directory's own mtime changing across a run with the fix temporarily reverted, and staying untouched with it applied. Also confirmed via typecheck (packages/core, packages/tui, packages/opencode) that the getter-based `Flock.setGlobal` argument still satisfies `FlockGlobal`'s type. Removed both items from tracking issue #1303 (fixed directly, not deferred). Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 parent 2fc58ac commit fdae60d

2 files changed

Lines changed: 133 additions & 82 deletions

File tree

‎packages/core/src/global.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,34 @@ const paths = {
3030
repos: path.join(data, "repos"),
3131
cache,
3232
config,
33-
state,
33+
// altimate_change start — cubic review (3986917361): unlike `home` above, `state` was a plain
34+
// const with no test-isolation override, so any consumer reading `Global.Path.state` — or
35+
// `Flock`'s lock directory, which is derived from it (see the `Flock.setGlobal` call below) —
36+
// silently touched the REAL, current developer's state directory in tests. Mirror `home`'s
37+
// pattern: a getter honoring `OPENCODE_TEST_STATE_HOME`, read fresh on every access.
38+
get state() {
39+
return process.env.OPENCODE_TEST_STATE_HOME ?? state
40+
},
41+
// altimate_change end
3442
tmp,
3543
}
3644

3745
export const Path = paths
3846

39-
Flock.setGlobal({ state })
47+
// altimate_change start — cubic review (3986917361): `Flock.setGlobal` used to be given the
48+
// frozen `state` const directly, snapshotted once at this module's import time — even after
49+
// adding the `OPENCODE_TEST_STATE_HOME` override to `Path.state` above, `Flock`'s own internal
50+
// lock-directory resolution would still have kept using whatever `state` was BEFORE any test set
51+
// that env var (module imports happen once, before a test's own `beforeAll`/mount code runs). A
52+
// getter-backed property here means `Flock`'s `root()` — which just reads `global.state` as a
53+
// plain property — re-evaluates `Path.state` fresh on every lock acquisition instead, so setting
54+
// `OPENCODE_TEST_STATE_HOME` redirects BOTH `Global.Path.state` reads and `Flock`'s lock root.
55+
Flock.setGlobal({
56+
get state() {
57+
return Path.state
58+
},
59+
})
60+
// altimate_change end
4061

4162
await Promise.all([
4263
fs.mkdir(Path.data, { recursive: true }),

‎packages/tui/test/context/cycle-stability.test.tsx‎

Lines changed: 110 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/** @jsxImportSource @opentui/solid */
2-
// altimate_change start — Codex HOLD finding 2 (+ re-review round 8): `cycle()` must traverse a
2+
// altimate_change start — Codex HOLD finding 2 (+ re-review rounds 8-9): `cycle()` must traverse a
33
// STABLE order, and that order must stay correct as `recent` changes for reasons OTHER than
44
// cycle() itself.
55
//
@@ -20,15 +20,28 @@
2020
// (the round-7 check never re-fires because A is still present in the stale snapshot). The
2121
// `cycleOrderVersion` counter (local.tsx) fixes this.
2222
//
23-
// This file calls the REAL `local.model.cycle()` against a REAL mounted `LocalProvider`, in
24-
// three named `test.serial` blocks that all share ONE mount (`beforeAll`/`afterAll`) rather than
25-
// each calling their own — cycle() is inherently a SEQUENCE of interactions anyway, and, more
26-
// practically, a second or third independent heavy provider-tree mount in this same file was
27-
// found to reproducibly hang during its own bootstrap (a test-infrastructure resource-contention
28-
// issue unrelated to anything under test here, worse the more work the PRIOR mount did). Each
29-
// test block's own comment states the state it assumes at that point in the sequence.
23+
// Round 9 (cubic 3987174885, repo rule: no order-dependent tests): this file used to spread the
24+
// scenario across three `test.serial` blocks sharing one `beforeAll`/`afterAll` mount — cycle()
25+
// is inherently a sequence of interactions, so splitting the scenario into separately-named
26+
// blocks made each one implicitly depend on the ones before it, which broke a `-t` filter or
27+
// `--only-failures` run of just one of them. Folded into ONE `test()`, with the mount local to
28+
// it and labelled phases (a `phase()` helper below just for readable failure messages — plain
29+
// comments would work too, but this makes an assertion failure show exactly which stage of the
30+
// sequence it happened in). A second/third independent heavy provider-tree mount in this same
31+
// file was ALSO found to reproducibly hang during its own bootstrap (a resource-contention issue
32+
// unrelated to anything under test) — folding into one test with one mount sidesteps that too.
33+
//
34+
// Round 9 (cubic 3986917361, repo rule: tests must not touch real global state): `kv.tsx`'s
35+
// `Flock.withLock` lock directory is derived from `Global.Path.state` (packages/core/src/global.ts),
36+
// which used to have no test-isolation override at all — only `Global.Path.home` did. This test's
37+
// `kv.json` FILE itself was always correctly isolated (`paths.state`, via `TestTuiContexts`), but
38+
// the LOCK it takes while reading/writing that file was not — it could still land in the real,
39+
// current developer's global state directory. Setting `OPENCODE_TEST_STATE_HOME` (mirroring
40+
// `OPENCODE_TEST_HOME`'s established pattern, used throughout this codebase's tests) around the
41+
// mount redirects both `Global.Path.state` and `Flock`'s lock root to this test's own throwaway
42+
// temp dir instead.
3043
import { testRender } from "@opentui/solid"
31-
import { afterAll, beforeAll, expect, test } from "bun:test"
44+
import { expect, test } from "bun:test"
3245
import { mkdir } from "node:fs/promises"
3346
import path from "node:path"
3447
import { tmpdir } from "../fixture/fixture"
@@ -96,7 +109,7 @@ async function mount() {
96109
// Three free models, all persisted as recents in order A, B, C — this is the "order as of TUI
97110
// launch" `cycle()` must traverse, independent of how it self-reorders `recent` on each pick.
98111
// A fourth (D) is registered with the provider but NOT in the initial `recent` — it only
99-
// enters via a later picker selection, in the round-8 regression test below.
112+
// enters via a later picker selection, in the round-8 regression phase below.
100113
await Bun.write(path.join(state, "model.json"), JSON.stringify({ recent: [MODEL_A, MODEL_B, MODEL_C] }))
101114

102115
const openCodeProvider = {
@@ -183,82 +196,99 @@ async function mount() {
183196
}
184197
}
185198

186-
let mounted: Awaited<ReturnType<typeof mount>>
187-
188-
beforeAll(async () => {
189-
mounted = await mount()
190-
})
191-
192-
afterAll(async () => {
193-
await mounted.cleanup()
194-
})
199+
/** Labels a phase for a clearer assertion-failure message; otherwise a no-op. */
200+
function phase(name: string, fn: () => void | Promise<void>) {
201+
try {
202+
return fn()
203+
} catch (err) {
204+
throw err instanceof Error ? new Error(`[phase: ${name}] ${err.message}`, { cause: err }) : err
205+
}
206+
}
195207

196-
test.serial(
197-
"cycle() traverses a stable order across repeated presses — visits every model, does not bounce (Codex HOLD finding 2)",
198-
() => {
199-
// Starting state (from `mount()`): current = B, recent = [A, B, C].
200-
const visited: string[] = []
201-
mounted.local.model.cycle(1)
202-
visited.push(mounted.local.model.current()!.modelID)
203-
mounted.local.model.cycle(1)
204-
visited.push(mounted.local.model.current()!.modelID)
205-
mounted.local.model.cycle(1)
206-
visited.push(mounted.local.model.current()!.modelID)
208+
test("cycle() traverses a stable order, re-discovers picker-added entries after recents reorder, and persists picks to the front of recent (Codex HOLD finding 2 + re-review rounds 8-9)", async () => {
209+
const originalStateHome = process.env.OPENCODE_TEST_STATE_HOME
210+
const isolatedState = await tmpdir()
211+
process.env.OPENCODE_TEST_STATE_HOME = isolatedState.path
207212

208-
// Starting at B, forward cycling must visit C then A (not bounce back to A immediately —
209-
// the bug Codex's own execution caught was B -> A -> B) and complete the traversal back to
213+
const mounted = await mount()
214+
try {
215+
// Phase 1 (Codex HOLD finding 2): starting state (from `mount()`) is current = B,
216+
// recent = [A, B, C]. Forward cycling must visit C then A (not bounce back to A immediately
217+
// — the bug Codex's own execution caught was B -> A -> B) and complete the traversal back to
210218
// B on the third press, having visited every one of the three models exactly once.
211-
expect(visited).toEqual(["model-c", "model-a", "model-b"])
212-
expect(new Set(visited).size).toBe(3)
213219
// Ends: current = B, recent = [B, A, C].
214-
},
215-
)
220+
await phase("1: stable traversal order", async () => {
221+
const visited: string[] = []
222+
mounted.local.model.cycle(1)
223+
visited.push(mounted.local.model.current()!.modelID)
224+
mounted.local.model.cycle(1)
225+
visited.push(mounted.local.model.current()!.modelID)
226+
mounted.local.model.cycle(1)
227+
visited.push(mounted.local.model.current()!.modelID)
216228

217-
test.serial("cycle() still moves the picked model to the front of persisted recent on every press", async () => {
218-
// Continues from the previous test: current = B, recent = [B, A, C], cycleOrder still [A, B, C]
219-
// (unchanged — nothing but cycle() itself has written to `recent` so far).
220-
mounted.local.model.cycle(1)
221-
await waitUntil(() => mounted.local.model.recent()[0]?.modelID === "model-c")
222-
expect(mounted.local.model.recent()[0]).toEqual({ providerID: "opencode", modelID: "model-c" })
223-
// Ends: current = C, recent = [C, B, A].
224-
})
229+
expect(visited).toEqual(["model-c", "model-a", "model-b"])
230+
expect(new Set(visited).size).toBe(3)
231+
})
232+
233+
// Phase 2: continues from phase 1 (current = B, recent = [B, A, C], cycleOrder still
234+
// [A, B, C] — unchanged, nothing but cycle() itself has written to `recent` so far). Every
235+
// cycle() pick must still move the picked model to the front of PERSISTED `recent` — that's
236+
// the only state headless/ACP default resolution reads.
237+
// Ends: current = C, recent = [C, B, A].
238+
await phase("2: picks move to the front of persisted recent", async () => {
239+
mounted.local.model.cycle(1)
240+
await waitUntil(() => mounted.local.model.recent()[0]?.modelID === "model-c")
241+
expect(mounted.local.model.recent()[0]).toEqual({ providerID: "opencode", modelID: "model-c" })
242+
})
225243

226-
test.serial(
227-
"cycle() re-discovers a model the picker adds after recents were reordered externally, instead of excluding it forever (Codex re-review round 8)",
228-
async () => {
229-
// Continues from the previous test: current = C, recent = [C, B, A], cycleOrder still
230-
// [A, B, C] (still unchanged — cycle() is the only thing that has written to `recent`).
231-
//
232-
// Reproduces Codex's exact repro from here: pick D and A via the PICKER (an explicit /model
233-
// selection with `recent: true`, like DialogModel uses). Round 7's fix only re-captured
234-
// `cycleOrder` when the CURRENT model fell OUT of the stale snapshot — A stays present in
235-
// the stale `[A, B, C]` snapshot throughout, so that check never fires, and D — never in
236-
// that snapshot at all — stays permanently unreachable by cycling. `cycleOrderVersion` (its
237-
// declaration in local.tsx) fixes this: it also invalidates on ANY external write to
238-
// `recent`, picker included.
239-
mounted.local.model.set(MODEL_D, { recent: true })
240-
await waitUntil(() => mounted.local.model.current()?.modelID === "model-d")
241-
mounted.local.model.set(MODEL_A, { recent: true })
242-
await waitUntil(() => mounted.local.model.current()?.modelID === "model-a")
243-
expect(mounted.local.model.recent().map((m) => m.modelID)).toEqual(["model-a", "model-d", "model-c", "model-b"])
244+
// Phase 3 (Codex re-review round 8): continues from phase 2 (current = C,
245+
// recent = [C, B, A], cycleOrder still [A, B, C] — still unchanged). Reproduces Codex's exact
246+
// repro from here: pick D and A via the PICKER (an explicit /model selection with
247+
// `recent: true`, like DialogModel uses). Round 7's fix only re-captured `cycleOrder` when
248+
// the CURRENT model fell OUT of the stale snapshot — A stays present in the stale
249+
// `[A, B, C]` snapshot throughout, so that check never fires, and D — never in that snapshot
250+
// at all — stays permanently unreachable by cycling. `cycleOrderVersion` (its declaration in
251+
// local.tsx) fixes this: it also invalidates on ANY external write to `recent`, picker
252+
// included.
253+
await phase("3: picker selections reorder recent", async () => {
254+
mounted.local.model.set(MODEL_D, { recent: true })
255+
await waitUntil(() => mounted.local.model.current()?.modelID === "model-d")
256+
mounted.local.model.set(MODEL_A, { recent: true })
257+
await waitUntil(() => mounted.local.model.current()?.modelID === "model-a")
258+
expect(mounted.local.model.recent().map((m) => m.modelID)).toEqual([
259+
"model-a",
260+
"model-d",
261+
"model-c",
262+
"model-b",
263+
])
264+
})
244265

245-
// cycleOrder must re-capture from the CURRENT [A, D, C, B] here (recentsVersion moved past
246-
// cycleOrderVersion since the last cycle() call, from these two picker picks) — forward from
247-
// A lands on D. The OLD bug: the stale `[A, B, C]` snapshot's "next after A" was B, and D was
248-
// never reachable from it at all.
249-
mounted.local.model.cycle(1)
250-
await waitUntil(() => mounted.local.model.current()?.modelID === "model-d")
266+
// Phase 4: cycleOrder must re-capture from the CURRENT [A, D, C, B] here (recentsVersion
267+
// moved past cycleOrderVersion since the last cycle() call, from phase 3's two picker picks)
268+
// — forward from A lands on D. The OLD bug: the stale `[A, B, C]` snapshot's "next after A"
269+
// was B, and D was never reachable from it at all.
270+
await phase("4: cycle() re-discovers the picker-added model", async () => {
271+
mounted.local.model.cycle(1)
272+
await waitUntil(() => mounted.local.model.current()?.modelID === "model-d")
273+
})
251274

252-
// And the newly re-captured order stays stable for subsequent presses, same guarantee as the
253-
// original finding-2 fix — visits C then B then wraps back to A.
254-
const visitedAfterD: string[] = []
255-
mounted.local.model.cycle(1)
256-
visitedAfterD.push(mounted.local.model.current()!.modelID)
257-
mounted.local.model.cycle(1)
258-
visitedAfterD.push(mounted.local.model.current()!.modelID)
259-
mounted.local.model.cycle(1)
260-
visitedAfterD.push(mounted.local.model.current()!.modelID)
261-
expect(visitedAfterD).toEqual(["model-c", "model-b", "model-a"])
262-
},
263-
)
275+
// Phase 5: the newly re-captured order stays stable for subsequent presses, same guarantee
276+
// as phase 1 — visits C then B then wraps back to A.
277+
await phase("5: the re-captured order stays stable", async () => {
278+
const visitedAfterD: string[] = []
279+
mounted.local.model.cycle(1)
280+
visitedAfterD.push(mounted.local.model.current()!.modelID)
281+
mounted.local.model.cycle(1)
282+
visitedAfterD.push(mounted.local.model.current()!.modelID)
283+
mounted.local.model.cycle(1)
284+
visitedAfterD.push(mounted.local.model.current()!.modelID)
285+
expect(visitedAfterD).toEqual(["model-c", "model-b", "model-a"])
286+
})
287+
} finally {
288+
await mounted.cleanup()
289+
if (originalStateHome === undefined) delete process.env.OPENCODE_TEST_STATE_HOME
290+
else process.env.OPENCODE_TEST_STATE_HOME = originalStateHome
291+
await isolatedState[Symbol.asyncDispose]()
292+
}
293+
})
264294
// altimate_change end

0 commit comments

Comments
 (0)