Skip to content

Commit b29561a

Browse files
committed
fix(test): roll back failed fixture allocation
1 parent 1b2ce27 commit b29561a

6 files changed

Lines changed: 384 additions & 118 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { describe, expect, it } from "vitest";
5+
import { withTempHomeCore } from "./temp-home.js";
6+
7+
describe("shared temp-home root acquisition", () => {
8+
it("shares a failed acquisition, then recovers on the next explicit call", async () => {
9+
const parent = await fs.mkdtemp(path.join(os.tmpdir(), "sdk-home-acquisition-"));
10+
const missingParent = path.join(parent, "missing");
11+
const prefix = path.join(path.basename(parent), "missing", "shared-");
12+
const options = { prefix, skipSessionCleanup: true };
13+
const unexpectedCallback = async () => {
14+
throw new Error("callback must not run when root acquisition fails");
15+
};
16+
try {
17+
const failures = await Promise.allSettled([
18+
withTempHomeCore(unexpectedCallback, options),
19+
withTempHomeCore(unexpectedCallback, options),
20+
withTempHomeCore(unexpectedCallback, options),
21+
]);
22+
const errors = failures.map((result) => {
23+
expect(result.status).toBe("rejected");
24+
return result.status === "rejected" ? result.reason : undefined;
25+
});
26+
expect(errors[0]).toMatchObject({ code: "ENOENT" });
27+
expect(errors.every((error) => error === errors[0])).toBe(true);
28+
expect(await fs.readdir(parent)).toEqual([]);
29+
30+
await fs.mkdir(missingParent);
31+
const first = await withTempHomeCore(
32+
async (home) => {
33+
await fs.writeFile(path.join(home, "retained.txt"), "keep");
34+
return home;
35+
},
36+
{ ...options, skipHomeCleanup: true },
37+
);
38+
const second = await withTempHomeCore(async (home) => home, options);
39+
const third = await withTempHomeCore(async (home) => home, options);
40+
expect(path.dirname(second)).toBe(path.dirname(first));
41+
expect(path.dirname(third)).toBe(path.dirname(first));
42+
expect([first, second, third].map((home) => path.basename(home))).toEqual([
43+
"case-0",
44+
"case-1",
45+
"case-2",
46+
]);
47+
expect(await fs.readdir(path.dirname(first))).toEqual([path.basename(first)]);
48+
expect(await fs.readFile(path.join(first, "retained.txt"), "utf8")).toBe("keep");
49+
const independent = await withTempHomeCore(async (home) => home, {
50+
prefix: path.join(path.basename(parent), "independent-"),
51+
skipSessionCleanup: true,
52+
});
53+
expect(path.dirname(independent)).not.toBe(path.dirname(first));
54+
expect(await fs.readdir(path.dirname(independent))).toEqual([]);
55+
} finally {
56+
await fs.rm(parent, { recursive: true, force: true });
57+
}
58+
});
59+
});

‎src/plugin-sdk/test-helpers/temp-home.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,12 @@ async function allocateTempHomeBase(prefix: string): Promise<string> {
3737
let state = SHARED_HOME_ROOTS.get(prefix);
3838
if (!state) {
3939
state = {
40-
rootPromise: fs.mkdtemp(path.join(os.tmpdir(), prefix)),
40+
rootPromise: fs.mkdtemp(path.join(os.tmpdir(), prefix)).catch((error: unknown) => {
41+
// Only the creator evicts a failed acquisition; current waiters keep its
42+
// rejection and cannot evict a later caller's replacement root.
43+
SHARED_HOME_ROOTS.delete(prefix);
44+
throw error;
45+
}),
4146
nextCaseId: 0,
4247
};
4348
SHARED_HOME_ROOTS.set(prefix, state);

‎src/test-utils/openclaw-test-state.test.ts‎

Lines changed: 129 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,9 @@ import {
2323
closeOpenClawStateDatabaseByPath,
2424
openOpenClawStateDatabase,
2525
} from "../state/openclaw-state-db.js";
26-
import { setTestEnvValue, withEnvAsync } from "./env.js";
26+
import { captureEnv, setTestEnvValue, withEnvAsync } from "./env.js";
2727
import { createOpenClawTestState, withOpenClawTestState } from "./openclaw-test-state.js";
28+
import * as sessionCleanup from "./session-state-cleanup.js";
2829

2930
async function expectPathMissing(targetPath: string): Promise<void> {
3031
try {
@@ -37,6 +38,133 @@ async function expectPathMissing(targetPath: string): Promise<void> {
3738
}
3839

3940
describe("openclaw test state", () => {
41+
it.each([
42+
{ stage: "realpath", layout: "home" },
43+
{ stage: ".openclaw", layout: "home" },
44+
{ stage: "workspace", layout: "state-only" },
45+
{ stage: "home", layout: "split" },
46+
{ stage: "config", layout: "split" },
47+
{ stage: "environment", layout: "home" },
48+
] as const)("rolls back $stage acquisition in $layout layout", async ({ stage, layout }) => {
49+
const parent = await fs.realpath(
50+
await fs.mkdtemp(path.join(os.tmpdir(), "test-state-acquisition-")),
51+
);
52+
const prefix = path.join(path.basename(parent), "fixture-");
53+
const unrelated = openOpenClawStateDatabase({
54+
env: { OPENCLAW_STATE_DIR: path.join(parent, "unrelated") },
55+
});
56+
try {
57+
await withEnvAsync(
58+
{
59+
OPENCLAW_AGENT_DIR: path.join(parent, "previous-agent"),
60+
OPENCLAW_ACQUISITION_EMPTY: "",
61+
OPENCLAW_ACQUISITION_ABSENT: undefined,
62+
},
63+
async () => {
64+
const keys = [
65+
"HOME",
66+
"USERPROFILE",
67+
"HOMEDRIVE",
68+
"HOMEPATH",
69+
"OPENCLAW_HOME",
70+
"OPENCLAW_STATE_DIR",
71+
"OPENCLAW_CONFIG_PATH",
72+
"OPENCLAW_AGENT_DIR",
73+
"OPENCLAW_ACQUISITION_EMPTY",
74+
"OPENCLAW_ACQUISITION_ABSENT",
75+
];
76+
const previous = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
77+
const snapshot = captureEnv(keys);
78+
const fault = new Error(`failed ${stage} acquisition`);
79+
const mkdir = fs.mkdir;
80+
const writeFile = fs.writeFile;
81+
const set = Reflect.set;
82+
const cleanupSpy = vi.spyOn(sessionCleanup, "cleanupSessionStateForTest");
83+
const faultSpy =
84+
stage === "realpath"
85+
? vi.spyOn(fs, "realpath").mockRejectedValueOnce(fault)
86+
: stage === "config"
87+
? vi.spyOn(fs, "writeFile").mockImplementationOnce(async (...args) => {
88+
await writeFile(...args);
89+
throw fault;
90+
})
91+
: stage === "environment"
92+
? vi.spyOn(Reflect, "set").mockImplementation((...args) => {
93+
const result = set(...args);
94+
const [target, key] = args;
95+
if (target === process.env && key === "HOME") {
96+
faultSpy.mockRestore();
97+
throw fault;
98+
}
99+
return result;
100+
})
101+
: vi.spyOn(fs, "mkdir").mockImplementation(async (...args) => {
102+
const result = await mkdir(...args);
103+
if (path.basename(String(args[0])) === stage) {
104+
throw fault;
105+
}
106+
return result;
107+
});
108+
try {
109+
await expect(
110+
createOpenClawTestState({
111+
prefix,
112+
layout,
113+
scenario: "minimal",
114+
applyEnv: stage !== "config",
115+
env: {
116+
OPENCLAW_ACQUISITION_EMPTY: "changed",
117+
OPENCLAW_ACQUISITION_ABSENT: "added",
118+
},
119+
}),
120+
).rejects.toBe(fault);
121+
expect(Object.fromEntries(keys.map((key) => [key, process.env[key]]))).toEqual(
122+
previous,
123+
);
124+
expect(await fs.readdir(parent)).toEqual(["unrelated"]);
125+
expect(unrelated.db.isOpen).toBe(true);
126+
expect(cleanupSpy).not.toHaveBeenCalled();
127+
faultSpy.mockRestore();
128+
129+
const recovered = await createOpenClawTestState({
130+
prefix,
131+
layout: "split",
132+
scenario: "minimal",
133+
applyEnv: false,
134+
});
135+
try {
136+
expect(Object.fromEntries(keys.map((key) => [key, process.env[key]]))).toEqual(
137+
previous,
138+
);
139+
expect(recovered.configPath).toBe(
140+
path.join(recovered.root, "config", "openclaw.json"),
141+
);
142+
expect(JSON.parse(await fs.readFile(recovered.configPath, "utf8"))).toEqual({});
143+
recovered.applyEnv();
144+
expect(process.env.HOME).toBe(recovered.home);
145+
expect(process.env.OPENCLAW_STATE_DIR).toBe(recovered.stateDir);
146+
} finally {
147+
await recovered.cleanup();
148+
}
149+
await recovered.cleanup();
150+
expect(Object.fromEntries(keys.map((key) => [key, process.env[key]]))).toEqual(
151+
previous,
152+
);
153+
expect(await fs.readdir(parent)).toEqual(["unrelated"]);
154+
expect(unrelated.db.isOpen).toBe(true);
155+
} finally {
156+
faultSpy.mockRestore();
157+
cleanupSpy.mockRestore();
158+
snapshot.restore();
159+
}
160+
},
161+
);
162+
} finally {
163+
closeOpenClawStateDatabaseByPath(unrelated.path);
164+
await fs.rm(parent, { recursive: true, force: true });
165+
}
166+
});
167+
40168
it("creates an isolated home layout with spawn env and restores process env", async () => {
41169
const previousHome = process.env.HOME;
42170
const previousOpenClawHome = process.env.OPENCLAW_HOME;

0 commit comments

Comments
 (0)