11// OpenClaw test instance tests cover spawned test instance lifecycle.
22import { EventEmitter } from "node:events" ;
33import fs from "node:fs/promises" ;
4+ import { tmpdir } from "node:os" ;
45import path from "node:path" ;
5- import { describe , expect , it , vi } from "vitest" ;
6+ import { PassThrough } from "node:stream" ;
7+ import { afterEach , describe , expect , it , vi } from "vitest" ;
68import { createOpenClawTestInstance , testing } from "./openclaw-test-instance.js" ;
9+ import { isProcessAlive } from "./process-wait.js" ;
10+
11+ const MIGRATION_CONVERGENCE_REFUSAL =
12+ "OpenClaw plugin migration inputs changed during startup convergence;" ;
13+ const RESTART_MARKER =
14+ "[openclaw-test-instance] restarting gateway after migration convergence refusal" ;
15+ const fakeInstances : Awaited < ReturnType < typeof createOpenClawTestInstance > > [ ] = [ ] ;
16+ const fakeRoots : string [ ] = [ ] ;
17+
18+ type FakeGatewayAttempt = {
19+ argv : string [ ] ;
20+ config : unknown ;
21+ cwd : string ;
22+ env : Record < string , string | undefined > ;
23+ pid : number ;
24+ port : number ;
25+ } ;
26+
27+ afterEach ( async ( ) => {
28+ await Promise . allSettled ( fakeInstances . splice ( 0 ) . map ( ( instance ) => instance . cleanup ( ) ) ) ;
29+ await Promise . allSettled ( fakeRoots . splice ( 0 ) . map ( ( root ) => fs . rm ( root , { recursive : true } ) ) ) ;
30+ } ) ;
31+
32+ async function createFakeGateway ( sequence : string , startTimeoutMs = 1_000 , stopTimeoutMs = 1_500 ) {
33+ const cwd = await fs . mkdtemp ( path . join ( tmpdir ( ) , "openclaw-test-instance-gateway-" ) ) ;
34+ fakeRoots . push ( cwd ) ;
35+ const distDir = path . join ( cwd , "dist" ) ;
36+ const tracePath = path . join ( cwd , "attempts.jsonl" ) ;
37+ await fs . mkdir ( distDir ) ;
38+ await Promise . all ( [
39+ fs . writeFile ( path . join ( distDir , ".buildstamp" ) , "" ) ,
40+ fs . writeFile ( path . join ( distDir , ".runtime-postbuildstamp" ) , "" ) ,
41+ fs . writeFile (
42+ path . join ( distDir , "index.mjs" ) ,
43+ `
44+ import { spawn } from "node:child_process";
45+ import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
46+ import { createServer } from "node:http";
47+ const tracePath = process.env.OPENCLAW_FAKE_GATEWAY_TRACE;
48+ const countPath = tracePath + ".count";
49+ let attempt = 1;
50+ try { attempt = Number(readFileSync(countPath, "utf8")) + 1; } catch {}
51+ writeFileSync(countPath, String(attempt));
52+ const argv = process.argv.slice(2);
53+ const port = Number(argv[argv.indexOf("--port") + 1]);
54+ const env = Object.fromEntries(["HOME", "OPENCLAW_CONFIG_PATH", "OPENCLAW_GATEWAY_TOKEN", "OPENCLAW_STATE_DIR"].map((key) => [key, process.env[key]]));
55+ appendFileSync(tracePath, JSON.stringify({ argv, config: JSON.parse(readFileSync(process.env.OPENCLAW_CONFIG_PATH, "utf8")), cwd: process.cwd(), env, pid: process.pid, port }) + "\\n");
56+ const action = (process.env.OPENCLAW_FAKE_GATEWAY_SEQUENCE || "ready").split(",")[attempt - 1] || "ready";
57+ const [kind, delay] = action.split(":");
58+ if (delay) await new Promise((resolve) => setTimeout(resolve, Number(delay)));
59+ process.stdout.write("fake gateway attempt " + attempt + "\\n");
60+ const refusal = ${ JSON . stringify ( MIGRATION_CONVERGENCE_REFUSAL ) } ;
61+ if (kind === "refuse") { process.stderr.write(refusal + " fixture\\n"); process.exit(1); }
62+ if (kind === "late-refuse") { spawn(process.execPath, ["-e", 'setTimeout(() => process.stderr.write(process.argv[1]), 50)', refusal + " delayed fixture\\n"], { stdio: ["ignore", "ignore", "inherit"] }); process.exit(1); }
63+ if (kind === "resist-after-exit") {
64+ const resistant = spawn(process.execPath, ["-e", 'const fs = require("node:fs");fs.writeFileSync(process.argv[1], String(process.pid));process.on("SIGTERM", () => fs.appendFileSync(process.argv[2], "SIGTERM"));process.send("ready");setInterval(() => {}, 1_000);', tracePath + ".resistant-pid", tracePath + ".signals"], { stdio: ["ignore", "ignore", "inherit", "ipc"] });
65+ await new Promise((resolve) => resistant.once("message", resolve));
66+ process.stderr.write("unrelated startup failure\\n"); process.exit(1);
67+ }
68+ if (kind === "terminal-drain") {
69+ const draining = spawn(process.execPath, ["-e", 'const fs = require("node:fs");const release = process.argv[1];const deadline = Date.now() + 5_000;const timer = setInterval(() => { if (fs.existsSync(release) || Date.now() >= deadline) clearInterval(timer); }, 10);', tracePath + ".draining-release"], { detached: true, stdio: ["ignore", "ignore", "inherit"] });
70+ draining.unref();
71+ writeFileSync(tracePath + ".draining-pid", String(draining.pid));
72+ process.stderr.write("terminal startup failure\\n"); process.exit(7);
73+ }
74+ if (kind === "near") { process.stderr.write(refusal.slice(0, -1) + " fixture\\n"); process.exit(1); }
75+ if (kind === "stdout") { process.stdout.write(refusal + " fixture\\n"); process.exit(1); }
76+ if (kind === "status2") { process.stderr.write(refusal + " fixture\\n"); process.exit(2); }
77+ if (kind === "signal") { process.stderr.write(refusal + " fixture\\n"); process.kill(process.pid, "SIGTERM"); }
78+ if (kind === "unrelated") { process.stderr.write("unrelated startup failure\\n"); process.exit(1); }
79+ if (kind === "hang") { process.on("SIGTERM", () => process.exit(0)); setInterval(() => {}, 1_000); } else {
80+ const server = createServer((req, res) => { res.writeHead(req.url === "/readyz" ? 200 : 404, { "content-type": "application/json" }); res.end(JSON.stringify({ ready: req.url === "/readyz" })); });
81+ process.on("SIGTERM", () => server.close(() => process.exit(0))); server.listen(port, "127.0.0.1");
82+ }
83+ ` ,
84+ ) ,
85+ ] ) ;
86+ const instance = await createOpenClawTestInstance ( {
87+ name : `fake-gateway-${ path . basename ( cwd ) } ` ,
88+ cwd,
89+ env : {
90+ OPENCLAW_FAKE_GATEWAY_SEQUENCE : sequence ,
91+ OPENCLAW_FAKE_GATEWAY_TRACE : tracePath ,
92+ } ,
93+ startTimeoutMs,
94+ stopTimeoutMs,
95+ } ) ;
96+ fakeInstances . push ( instance ) ;
97+ return {
98+ instance,
99+ tracePath,
100+ readAttempts : async ( ) : Promise < FakeGatewayAttempt [ ] > =>
101+ ( await fs . readFile ( tracePath , "utf8" ) )
102+ . trim ( )
103+ . split ( "\n" )
104+ . filter ( Boolean )
105+ . map ( ( line ) => JSON . parse ( line ) as FakeGatewayAttempt ) ,
106+ } ;
107+ }
7108
8109async function expectPathMissing ( targetPath : string ) : Promise < void > {
9110 try {
@@ -26,6 +127,158 @@ function createGatewayProcessState(
26127}
27128
28129describe ( "openclaw test instance" , ( ) => {
130+ it ( "classifies only exact stderr convergence refusals with status 1" , ( ) => {
131+ const classify = testing . isGatewayMigrationConvergenceRefusal ;
132+ expect ( classify ( 1 , null , `notice\n${ MIGRATION_CONVERGENCE_REFUSAL } retry\n` ) ) . toBe ( true ) ;
133+ for ( const candidate of [
134+ [ 2 , null , MIGRATION_CONVERGENCE_REFUSAL ] ,
135+ [ 1 , "SIGTERM" , MIGRATION_CONVERGENCE_REFUSAL ] ,
136+ [ 1 , null , MIGRATION_CONVERGENCE_REFUSAL . slice ( 0 , - 1 ) ] ,
137+ [ 1 , null , `prefix ${ MIGRATION_CONVERGENCE_REFUSAL } ` ] ,
138+ ] ) {
139+ expect ( classify ( ...( candidate as [ number , NodeJS . Signals | null , string ] ) ) ) . toBe ( false ) ;
140+ }
141+ } ) ;
142+
143+ it . each ( [ "refuse" , "late-refuse" ] ) (
144+ "restarts one %s refusal with identical launch state and owns the ready child" ,
145+ async ( refusalAction ) => {
146+ const { instance, readAttempts } = await createFakeGateway ( `${ refusalAction } ,ready` ) ;
147+ await instance . startGateway ( ) ;
148+ const attempts = await readAttempts ( ) ;
149+ expect ( attempts ) . toHaveLength ( 2 ) ;
150+ expect ( attempts [ 0 ] ?. pid ) . not . toBe ( attempts [ 1 ] ?. pid ) ;
151+ expect ( { ...attempts [ 0 ] , pid : 0 } ) . toEqual ( { ...attempts [ 1 ] , pid : 0 } ) ;
152+ expect ( instance . logs ( ) ) . toContain ( MIGRATION_CONVERGENCE_REFUSAL ) ;
153+ expect ( instance . logs ( ) ) . toContain ( RESTART_MARKER ) ;
154+ const readyPid = instance . child ?. pid ;
155+ expect ( readyPid ) . toBeTypeOf ( "number" ) ;
156+ await instance . stopGateway ( ) ;
157+ expect ( instance . child ) . toBeUndefined ( ) ;
158+ expect ( isProcessAlive ( readyPid as number ) ) . toBe ( false ) ;
159+ } ,
160+ ) ;
161+
162+ it . each ( [ "near" , "stdout" , "status2" , "signal" , "unrelated" ] ) (
163+ "keeps %s convergence lookalikes terminal" ,
164+ async ( action ) => {
165+ const { instance, readAttempts } = await createFakeGateway ( `${ action } ,ready` ) ;
166+ await expect ( instance . startGateway ( ) ) . rejects . toThrow ( "gateway exited before readiness" ) ;
167+ expect ( await readAttempts ( ) ) . toHaveLength ( 1 ) ;
168+ expect ( instance . logs ( ) ) . not . toContain ( RESTART_MARKER ) ;
169+ expect ( instance . child ) . toBeUndefined ( ) ;
170+ } ,
171+ ) ;
172+
173+ it ( "preserves both refusals and never spawns a third gateway" , async ( ) => {
174+ const { instance, readAttempts } = await createFakeGateway ( "refuse,refuse,ready" ) ;
175+ await expect ( instance . startGateway ( ) ) . rejects . toThrow ( "gateway exited before readiness" ) ;
176+ expect ( await readAttempts ( ) ) . toHaveLength ( 2 ) ;
177+ expect ( instance . logs ( ) . split ( MIGRATION_CONVERGENCE_REFUSAL ) ) . toHaveLength ( 3 ) ;
178+ expect ( instance . logs ( ) . split ( RESTART_MARKER ) ) . toHaveLength ( 2 ) ;
179+ } ) ;
180+
181+ it ( "bounds both attempts by one startup deadline" , async ( ) => {
182+ const { instance, readAttempts } = await createFakeGateway ( "refuse:200,hang" , 500 ) ;
183+ const startedAt = Date . now ( ) ;
184+ await expect ( instance . startGateway ( ) ) . rejects . toThrow ( "timeout waiting for gateway readiness" ) ;
185+ expect ( await readAttempts ( ) ) . toHaveLength ( 2 ) ;
186+ expect ( Date . now ( ) - startedAt ) . toBeLessThan ( 650 ) ;
187+ } ) ;
188+
189+ it . runIf ( process . platform !== "win32" ) (
190+ "SIGKILLs a TERM-resistant gateway group before releasing state" ,
191+ async ( ) => {
192+ const { instance, tracePath } = await createFakeGateway ( "resist-after-exit" , 500 , 40 ) ;
193+ const stateRoot = instance . state . root ;
194+ const startedAt = Date . now ( ) ;
195+ await expect ( instance . startGateway ( ) ) . rejects . toThrow ( "gateway exited before readiness" ) ;
196+ const resistantPid = Number ( await fs . readFile ( `${ tracePath } .resistant-pid` , "utf8" ) ) ;
197+ expect ( await fs . readFile ( `${ tracePath } .signals` , "utf8" ) ) . toBe ( "SIGTERM" ) ;
198+ expect ( instance . child ) . toBeUndefined ( ) ;
199+ expect ( Date . now ( ) - startedAt ) . toBeLessThan ( 500 ) ;
200+ await expect . poll ( ( ) => isProcessAlive ( resistantPid ) , { timeout : 500 } ) . toBe ( false ) ;
201+ await expect ( fs . stat ( stateRoot ) ) . resolves . toBeDefined ( ) ;
202+ await instance . cleanup ( ) ;
203+ await expectPathMissing ( stateRoot ) ;
204+ } ,
205+ ) ;
206+
207+ it . runIf ( process . platform !== "win32" ) (
208+ "reaps terminal children with inherited stdio before starting a new gateway" ,
209+ async ( ) => {
210+ const { instance, readAttempts, tracePath } = await createFakeGateway (
211+ "terminal-drain,ready" ,
212+ 300 ,
213+ 100 ,
214+ ) ;
215+
216+ const startupError = await instance . startGateway ( ) . catch ( ( error : unknown ) => error ) ;
217+ expect ( startupError ) . toBeInstanceOf ( Error ) ;
218+ expect ( ( startupError as Error ) . message ) . toContain (
219+ "gateway exited before readiness (code=7 signal=null)" ,
220+ ) ;
221+ expect ( ( startupError as Error ) . message ) . toContain ( "terminal startup failure" ) ;
222+ expect ( instance . child ?. exitCode ) . toBe ( 7 ) ;
223+ expect ( instance . child ?. stderr . closed ) . toBe ( false ) ;
224+ const firstAttempt = ( await readAttempts ( ) ) [ 0 ] ;
225+ const drainingPid = Number ( await fs . readFile ( `${ tracePath } .draining-pid` , "utf8" ) ) ;
226+ expect ( isProcessAlive ( drainingPid ) ) . toBe ( true ) ;
227+
228+ await fs . writeFile ( `${ tracePath } .draining-release` , "" ) ;
229+ await instance . startGateway ( ) ;
230+
231+ const attempts = await readAttempts ( ) ;
232+ expect ( attempts ) . toHaveLength ( 2 ) ;
233+ expect ( attempts [ 1 ] ?. pid ) . not . toBe ( firstAttempt ?. pid ) ;
234+ expect ( instance . child ?. pid ) . toBe ( attempts [ 1 ] ?. pid ) ;
235+ await instance . stopGateway ( ) ;
236+ expect ( instance . child ) . toBeUndefined ( ) ;
237+ expect ( isProcessAlive ( attempts [ 1 ] ?. pid as number ) ) . toBe ( false ) ;
238+ await expect . poll ( ( ) => isProcessAlive ( drainingPid ) , { timeout : 500 } ) . toBe ( false ) ;
239+ } ,
240+ ) ;
241+
242+ it ( "force-kills Windows gateway descendants before retry cleanup settles" , async ( ) => {
243+ const stdout = new PassThrough ( ) ;
244+ const stderr = new PassThrough ( ) ;
245+ const child = {
246+ exitCode : 1 ,
247+ kill : vi . fn ( ( ) => true ) ,
248+ pid : 12345 ,
249+ signalCode : null ,
250+ stderr,
251+ stdout,
252+ } as unknown as Parameters < typeof testing . stopGatewayProcess > [ 0 ] ;
253+ const runTaskkill = vi . fn ( ( ) => {
254+ stdout . destroy ( ) ;
255+ stderr . destroy ( ) ;
256+ return { status : 0 } ;
257+ } ) ;
258+
259+ await expect (
260+ testing . stopGatewayProcess ( child , Date . now ( ) + 500 , 250 , {
261+ forceWindowsTree : true ,
262+ platform : "win32" ,
263+ runTaskkill,
264+ } ) ,
265+ ) . resolves . toBe ( true ) ;
266+
267+ expect ( runTaskkill ) . toHaveBeenCalledOnce ( ) ;
268+ expect ( runTaskkill ) . toHaveBeenCalledWith (
269+ path . win32 . join ( "C:\\Windows" , "System32" , "taskkill.exe" ) ,
270+ [ "/PID" , "12345" , "/T" , "/F" ] ,
271+ {
272+ killSignal : "SIGKILL" ,
273+ stdio : "ignore" ,
274+ timeout : 10_000 ,
275+ } ,
276+ ) ;
277+ expect ( child . kill ) . not . toHaveBeenCalled ( ) ;
278+ expect ( stdout . closed ) . toBe ( true ) ;
279+ expect ( stderr . closed ) . toBe ( true ) ;
280+ } ) ;
281+
29282 it ( "keeps only bounded child output tails in helper logs" , ( ) => {
30283 const stdout = testing . createBoundedStringLog ( ) ;
31284 const stderr = testing . createBoundedStringLog ( ) ;
0 commit comments