Skip to content

Commit ceef488

Browse files
authored
test: settle Windows ACL work and owner locks before fixture removal (lidge-jun#7528)
Settle async Windows ACL work and native-main owner locks before fixture removal, so hosted-Windows teardowns no longer fail with EPERM after passing assertions. No retry, sleep or timeout changes. Refs lidge-jun#7515
1 parent 2494848 commit ceef488

7 files changed

Lines changed: 168 additions & 31 deletions

File tree

‎src/codex/native-main-owner.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { join } from "node:path";
1+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
22

33
import { Database } from "bun:sqlite";
44

@@ -299,6 +299,32 @@ export function nativeMainOwnerSnapshot(context: NativeProfileContext): NativeMa
299299
return entry ? { ...entry.snapshot } : null;
300300
}
301301

302+
/**
303+
* Homes at or below `root` whose owner entry may still hold or reopen handles there.
304+
*
305+
* Conservative on purpose: besides a published database or side descriptor, an
306+
* acquisition in flight (`drive`) holds its descriptor and database in locals until
307+
* hardening returns, a pending retry timer will reopen them, and a detached entry is
308+
* still closing. Removal code asks this before deleting a home. Windows refuses to
309+
* delete a file SQLite holds open, so a removal that starts early fails with EBUSY
310+
* only after its whole retry budget, without naming the owner.
311+
*/
312+
export function nativeMainOwnerHomesOpenAtOrBelow(root: string): string[] {
313+
const fold = (path: string) => (process.platform === "win32" ? resolve(path).toLowerCase() : resolve(path));
314+
const base = fold(root);
315+
const open: string[] = [];
316+
const candidates = [
317+
...[...entries.values()].filter(entry => entry.database || entry.file || entry.drive || entry.timer),
318+
...detachedEntries,
319+
];
320+
for (const entry of candidates) {
321+
const suffix = relative(base, fold(entry.context.codexHome));
322+
if (suffix === ".." || suffix.startsWith(`..${sep}`) || isAbsolute(suffix)) continue;
323+
open.push(entry.context.codexHome);
324+
}
325+
return open;
326+
}
327+
302328
export function assertNativeMainOwner(context: NativeProfileContext): void {
303329
const entry = entries.get(context.homeId);
304330
if (entry?.snapshot.status === "held" && entry.database && !entry.closing) return;

‎structure/ops/test-sandbox-cleanup.md‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,16 @@ fixture-specific cleanup or claim OS ACL coverage for synthetic tests.
7777
case roots (`tests/codex-integration/codex-quota-auto-refresh.test.ts`), and Anthropic instance
7878
root removal (`tests/helpers/anthropic-instance-fixture.ts`).
7979
It settles producers, then each root's config flights, closes the request-history SQLite index,
80-
drains each root's ACL work, and only then removes drained roots. A producer or history failure
81-
blocks every removal; a root-specific drain failure preserves that root while other drained roots
82-
can be removed. Removal failures do not stop later roots. Environment restoration runs in finally,
83-
and the first failure is rethrown. Undrained roots remain for run-level sandbox cleanup.
84-
`tests/ci-workflows/fixture-teardown-helper.test.ts` verifies ordering and failure gating with injected owners.
80+
drains each root's ACL work, then asks `nativeMainOwnerHomesOpenAtOrBelow` whether a native-main
81+
owner below the root is still open, acquiring (descriptor and SQLite handle held while its hardener
82+
runs), waiting on a retry, or closing; only roots that pass both are removed. An open owner fails
83+
that root at once with an error naming the owner home, without spending the removal retry budget.
84+
A producer or history failure blocks every removal; a root-specific drain or owner failure
85+
preserves that root while other ready roots can be removed. Removal failures do not stop later
86+
roots. Environment restoration runs in finally, and the first failure is rethrown. Undrained roots
87+
remain for run-level sandbox cleanup.
88+
`tests/ci-workflows/fixture-teardown-helper.test.ts` verifies ordering and failure gating with injected
89+
owners, and with a real owner whose hardener is paused mid-acquisition.
8590

8691
`tests/helpers/spawn-test-child.ts` owns behavior and warm-up children on the parent's live
8792
event loop. It captures output continuously, kills at the child deadline, and bounds exit/pipe

‎tests/ci-workflows/fixture-teardown-helper.test.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
import { describe, expect, test } from "bun:test";
2+
import { mkdirSync, mkdtempSync } from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
5+
import { retainNativeMainOwner } from "../../src/codex/native-main-owner";
26
import { flushConfigDirHardening } from "../../src/config/paths";
37
import {
48
defaultFixtureTeardownDeps,
59
drainAndRemoveFixtureRoots,
610
type FixtureTeardownDeps,
711
type FixtureTeardownPlan,
812
} from "../helpers/fixture-teardown";
13+
import { removeTreeWithRetry } from "../helpers/remove-tree";
914

1015
function harness(overrides: Partial<FixtureTeardownDeps> = {}) {
1116
const calls: string[] = [];
@@ -14,6 +19,7 @@ function harness(overrides: Partial<FixtureTeardownDeps> = {}) {
1419
settleConfigFlights: async root => { calls.push(`flight:${root}`); },
1520
closeHistory: () => { calls.push("history"); },
1621
drainAcl: async root => { calls.push(`acl:${root}`); },
22+
openLocks: () => [],
1723
remove: root => { calls.push(`remove:${root}`); },
1824
...overrides,
1925
};
@@ -127,4 +133,71 @@ describe("fixture removal ownership", () => {
127133
h.plan.restoreEnvironment = () => { throw last; };
128134
await expect(drainAndRemoveFixtureRoots(h.plan, h.deps)).rejects.toBe(first);
129135
});
136+
137+
test("an owner still open under a root keeps only that root and names it", async () => {
138+
const h = harness({ openLocks: root => (root === "A" ? ["A/codex"] : []) });
139+
await expect(drainAndRemoveFixtureRoots(h.plan, h.deps)).rejects.toThrow("native-main owner still open for A/codex");
140+
expect(h.calls).not.toContain("remove:A");
141+
expect(h.calls).toContain("remove:B");
142+
expect(h.calls.filter(call => call === "restore")).toHaveLength(1);
143+
});
144+
145+
test("the default lock probe sees a held owner below the root until its release closes", async () => {
146+
const root = mkdtempSync(join(tmpdir(), "ocx-teardown-lock-"));
147+
const codexHome = join(root, "codex");
148+
const sibling = `${root}-sibling`;
149+
mkdirSync(codexHome);
150+
const owner = retainNativeMainOwner(
151+
{ codexHome, homeId: `teardown-lock-${process.pid}` } as never,
152+
{ hardenPath: async () => {} },
153+
);
154+
try {
155+
await new Promise<void>(held => owner.subscribe(snapshot => { if (snapshot.status === "held") held(); }));
156+
expect(defaultFixtureTeardownDeps.openLocks(root)).toEqual([codexHome]);
157+
expect(defaultFixtureTeardownDeps.openLocks(codexHome)).toEqual([codexHome]);
158+
expect(defaultFixtureTeardownDeps.openLocks(sibling)).toEqual([]);
159+
await owner.release();
160+
expect(defaultFixtureTeardownDeps.openLocks(root)).toEqual([]);
161+
} finally {
162+
await owner.release();
163+
removeTreeWithRetry(root);
164+
}
165+
});
166+
167+
test("an owner paused mid-acquisition keeps its root until preparation and release finish", async () => {
168+
const root = mkdtempSync(join(tmpdir(), "ocx-teardown-acquire-"));
169+
const codexHome = join(root, "codex");
170+
mkdirSync(codexHome);
171+
let entered!: () => void, resume!: () => void;
172+
const hardening = new Promise<void>(done => { entered = done; });
173+
const resumed = new Promise<void>(done => { resume = done; });
174+
const owner = retainNativeMainOwner(
175+
{ codexHome, homeId: `teardown-acquire-${process.pid}` } as never,
176+
{ hardenPath: async () => { entered(); await resumed; } },
177+
);
178+
const removed: string[] = [];
179+
const plan = (): FixtureTeardownPlan => ({ roots: [{ path: root, remove: path => { removed.push(path); removeTreeWithRetry(path); } }], restoreEnvironment: () => {} });
180+
try {
181+
// The descriptor and SQLite handle exist only in locals while the hardener runs.
182+
await hardening;
183+
expect(owner.snapshot().status).toBe("acquiring");
184+
await expect(drainAndRemoveFixtureRoots(plan())).rejects.toThrow(`native-main owner still open for ${codexHome}`);
185+
expect(removed).toEqual([]);
186+
187+
const released = owner.release();
188+
// Still closing: the release waits for the paused acquisition.
189+
await expect(drainAndRemoveFixtureRoots(plan())).rejects.toThrow("native-main owner still open");
190+
expect(removed).toEqual([]);
191+
192+
resume();
193+
await released;
194+
expect(defaultFixtureTeardownDeps.openLocks(root)).toEqual([]);
195+
await drainAndRemoveFixtureRoots(plan());
196+
expect(removed).toEqual([root]);
197+
} finally {
198+
resume();
199+
await owner.release();
200+
if (removed.length === 0) removeTreeWithRetry(root);
201+
}
202+
});
130203
});

‎tests/codex-integration/codex-auth-context.test.ts‎

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ import {
6969
resetCodexRoutingForManualSelection,
7070
} from "../../src/codex/routing";
7171
import type { OcxConfig, OcxProviderConfig } from "../../src/types";
72-
import { setIcaclsRunnerForTests } from "../../src/lib/windows-secret-acl";
72+
import { setAsyncIcaclsRunnerForTests, setIcaclsRunnerForTests } from "../../src/lib/windows-secret-acl";
7373
import {
7474
blockNativeMainStartupForUnownedServiceHome,
7575
completeNativeMainRecovery,
@@ -86,17 +86,19 @@ import { recordContextSessionOwner, clearContextSessionOwnersForTests } from "..
8686
import { handleContextHistory } from "../../src/server/context-history";
8787
import { resetContextRelayActivationForTests } from "../../src/codex/context-compat";
8888
import { hasForwardableCodexBearer } from "../../src/server/auth-cors";
89-
import { removeTreeWithRetry } from "../helpers/remove-tree";
89+
import { drainAndRemoveFixtureRoots } from "../helpers/fixture-teardown";
9090

9191
let testDir: string;
9292
let previousOpencodexHome: string | undefined;
9393
let previousCodexHome: string | undefined;
9494

9595
beforeEach(() => {
96-
// This suite validates refresh admission and auth-context outcomes. Real icacls
97-
// processes are covered elsewhere and can retain temp-dir handles long enough
98-
// to obscure those assertions under Windows isolated-test load.
96+
// This suite validates refresh admission and auth-context outcomes; real icacls is
97+
// covered by tests/windows. Both runners are stubbed: the native-main claim lock is
98+
// hardened through the ASYNC runner, and with only the sync one stubbed, real icacls
99+
// still rewrote that lock's DACL under the home this teardown removes (#7515).
99100
setIcaclsRunnerForTests(() => ({ success: true, exitCode: 0, timedOut: false, stdout: "" }));
101+
setAsyncIcaclsRunnerForTests(async () => ({ success: true, exitCode: 0, timedOut: false, stdout: "" }));
100102
testDir = mkdtempSync(join(tmpdir(), "ocx-auth-ctx-"));
101103
previousOpencodexHome = process.env.OPENCODEX_HOME;
102104
process.env.OPENCODEX_HOME = testDir;
@@ -113,21 +115,28 @@ beforeEach(() => {
113115
clearAccountNeedsReauth("pool-b");
114116
});
115117

116-
afterEach(() => {
118+
afterEach(async () => {
117119
resetContextRelayActivationForTests();
118-
setIcaclsRunnerForTests(null);
119-
removeTreeWithRetry(testDir);
120-
clearThreadAccountMap();
121-
clearCodexUpstreamHealth();
122-
clearAccountQuota();
123-
setMainAccountPlan(null);
124-
__resetGuardianState();
125-
clearAccountNeedsReauth("pool-a");
126-
clearAccountNeedsReauth("pool-b");
127-
if (previousOpencodexHome === undefined) delete process.env.OPENCODEX_HOME;
128-
else process.env.OPENCODEX_HOME = previousOpencodexHome;
129-
if (previousCodexHome === undefined) delete process.env.CODEX_HOME;
130-
else process.env.CODEX_HOME = previousCodexHome;
120+
// Settle producers, config flights and ACL work, and refuse a home whose native-main
121+
// owner is still open, before removal; the stubs stay installed until removal ends.
122+
await drainAndRemoveFixtureRoots({
123+
roots: [{ path: testDir }],
124+
restoreEnvironment: () => {
125+
setIcaclsRunnerForTests(null);
126+
setAsyncIcaclsRunnerForTests(null);
127+
clearThreadAccountMap();
128+
clearCodexUpstreamHealth();
129+
clearAccountQuota();
130+
setMainAccountPlan(null);
131+
__resetGuardianState();
132+
clearAccountNeedsReauth("pool-a");
133+
clearAccountNeedsReauth("pool-b");
134+
if (previousOpencodexHome === undefined) delete process.env.OPENCODEX_HOME;
135+
else process.env.OPENCODEX_HOME = previousOpencodexHome;
136+
if (previousCodexHome === undefined) delete process.env.CODEX_HOME;
137+
else process.env.CODEX_HOME = previousCodexHome;
138+
},
139+
});
131140
});
132141

133142
function config(): OcxConfig {

‎tests/codex-integration/main-account-hard-lock-fallback-routing.test.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import { captureConfigGeneration } from "../../src/lib/state-store-sweeper";
1818
import type { RequestLogContext } from "../../src/server/request-log";
1919
import type { OcxConfig } from "../../src/types";
2020
import { acquireOwnedSpendHome } from "../helpers/owned-spend-home";
21-
import { removeTreeWithRetry } from "../helpers/remove-tree";
21+
import { drainAndRemoveFixtureRoots } from "../helpers/fixture-teardown";
2222

2323
const now = Date.UTC(2026, 8, 5);
2424
const FALLBACK = { model: "deepseek/deepseek-chat", reasoningEffort: "low" };
@@ -39,17 +39,23 @@ beforeEach(() => {
3939
observeMainQuotaIdentity("fallback-account-a");
4040
});
4141

42-
afterEach(() => {
42+
afterEach(async () => {
4343
releaseSpendHome?.();
4444
releaseSpendHome = undefined;
4545
globalThis.fetch = originalFetch;
4646
clearAccountQuota();
4747
clearMainAccountInfoCache();
4848
deleteAllScopedHealth("pool-a");
4949
clearComboRecallForTests();
50-
if (previousHome === undefined) delete process.env.OPENCODEX_HOME;
51-
else process.env.OPENCODEX_HOME = previousHome;
52-
removeTreeWithRetry(home);
50+
// Saving a pool account starts the config-dir ACL harden without awaiting it; the
51+
// shared teardown settles that flight and its icacls child before removing the home.
52+
await drainAndRemoveFixtureRoots({
53+
roots: [{ path: home }],
54+
restoreEnvironment: () => {
55+
if (previousHome === undefined) delete process.env.OPENCODEX_HOME;
56+
else process.env.OPENCODEX_HOME = previousHome;
57+
},
58+
});
5359
});
5460

5561
function observe(quota: Omit<StoredAccountQuota, "updatedAt">): void {

‎tests/helpers/fixture-teardown.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { flushNativeMainStartupReleases } from "../../src/codex/native-profile-startup";
2+
import { nativeMainOwnerHomesOpenAtOrBelow } from "../../src/codex/native-main-owner";
23
import { flushConfigDirHardening } from "../../src/config/paths";
34
import { closeRequestHistoryIndex } from "../../src/routing/history/indexer";
45
import { flushWindowsSecretAclReapsBeforeRemoval } from "../../src/lib/windows-secret-acl";
@@ -11,16 +12,26 @@ export interface FixtureTeardownDeps {
1112
settleConfigFlights(root: string): Promise<void>;
1213
closeHistory(): void;
1314
drainAcl(root: string): Promise<void>;
15+
openLocks(root: string): string[];
1416
remove(path: string): void;
1517
}
1618
export const defaultFixtureTeardownDeps: Readonly<FixtureTeardownDeps> = {
1719
settleProducers: flushNativeMainStartupReleases,
1820
settleConfigFlights: flushConfigDirHardening,
1921
closeHistory: closeRequestHistoryIndex,
2022
drainAcl: flushWindowsSecretAclReapsBeforeRemoval,
23+
openLocks: nativeMainOwnerHomesOpenAtOrBelow,
2124
remove: removeTreeWithRetry,
2225
};
2326

27+
/** A lock this process still holds keeps its root: the owner is named now, not after a retry budget. */
28+
function assertNoOpenLocks(root: string, openLocks: (root: string) => string[]): void {
29+
const open = openLocks(root);
30+
if (open.length === 0) return;
31+
throw new Error(`[test] not removing ${root}: native-main owner still open for ${open.join(", ")}; `
32+
+ "stop the server or release the owner before teardown");
33+
}
34+
2435
/** Remove only roots whose owners settled; restoration cannot mask the first failure. */
2536
export async function drainAndRemoveFixtureRoots(
2637
plan: FixtureTeardownPlan,
@@ -39,7 +50,8 @@ export async function drainAndRemoveFixtureRoots(
3950
const historyClosed = await attempt(() => deps.closeHistory());
4051
for (const [index, root] of plan.roots.entries()) {
4152
const drained = await attempt(() => deps.drainAcl(root.path));
42-
ready[index] = ready[index] && drained;
53+
const unlocked = drained && await attempt(() => assertNoOpenLocks(root.path, deps.openLocks));
54+
ready[index] = ready[index] && unlocked;
4355
}
4456
if (producersSettled && historyClosed) {
4557
for (const [index, root] of plan.roots.entries()) {

‎tests/server/server-management-auth.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
hardenSecretPath,
2929
hardenedSecretPathCountForTests,
3030
resetHardenedStateForTests,
31+
setAsyncIcaclsRunnerForTests,
3132
setIcaclsRunnerForTests,
3233
setPlatformForTests,
3334
timedOutSecretPathCountForTests,
@@ -117,6 +118,10 @@ beforeEach(() => {
117118
resetContextRelayActivationForTests();
118119
process.env.OPENCODEX_API_AUTH_TOKEN = "data-secret";
119120
process.env.OPENCODEX_ADMIN_AUTH_TOKEN = "admin-secret";
121+
// These cases assert credential separation, not ACLs (tests/windows owns those). Real
122+
// async icacls on the native-main owner lock under testHome left it with an empty DACL
123+
// that the teardown could not delete (#7515). Sync-runner cases still inject their own.
124+
setAsyncIcaclsRunnerForTests(async () => ({ success: true, exitCode: 0, timedOut: false, stdout: "" }));
120125
});
121126

122127
afterEach(async () => {
@@ -130,6 +135,7 @@ afterEach(async () => {
130135
else process.env.CODEX_HOME = previousCodexHome;
131136
setSystemRestartIoForTests();
132137
setIcaclsRunnerForTests(null);
138+
setAsyncIcaclsRunnerForTests(null);
133139
setPlatformForTests(null);
134140
resetHardenedStateForTests();
135141
if (previousHome === undefined) delete process.env.OPENCODEX_HOME;

0 commit comments

Comments
 (0)