Skip to content

Commit 7b8bba2

Browse files
authored
fix(qa): report cleanup failures truthfully (#119727)
* fix(qa): report cleanup failures truthfully Punchcard-Session: silver-valley-valley-dt * fix(qa): satisfy cleanup runner static checks Punchcard-Session: silver-meadow-lantern-vx
1 parent e9e6ef3 commit 7b8bba2

9 files changed

Lines changed: 736 additions & 116 deletions

‎extensions/qa-lab/src/suite-launch.runtime.test.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
55
import { QaSuiteInfraError } from "./errors.js";
66
import type { QaLabServerHandle } from "./lab-server.types.js";
77
import type { QaSuiteScenarioResult } from "./suite.js";
8+
import { throwQaSuiteCleanupErrors } from "./suite.js";
89
import type {
910
QaTestFileScenario,
1011
QaTestFileScenarioRunResult,
@@ -31,7 +32,7 @@ vi.mock("./test-file-scenario-runner.js", async (importOriginal) => ({
3132
runQaTestFileScenarios,
3233
}));
3334

34-
import { runQaSuite } from "./suite-launch.runtime.js";
35+
import { runQaSuite, runQaSuiteWithInfraRetry } from "./suite-launch.runtime.js";
3536

3637
const tempRoots: string[] = [];
3738

@@ -251,6 +252,34 @@ describe("qa suite runtime launcher", () => {
251252
}
252253
});
253254

255+
it("retries a cleanup-only ECONNRESET through its preserved cause", async () => {
256+
const cleanupError = Object.assign(new Error("cleanup socket reset"), {
257+
code: "ECONNRESET",
258+
});
259+
const stderrWrite = vi.spyOn(process.stderr, "write").mockReturnValue(true);
260+
let attempts = 0;
261+
262+
try {
263+
const result = await runQaSuiteWithInfraRetry(async () => {
264+
attempts += 1;
265+
if (attempts === 1) {
266+
throwQaSuiteCleanupErrors({
267+
cleanupFailures: [{ phase: "lab stop", error: cleanupError }],
268+
runFailed: false,
269+
runError: undefined,
270+
});
271+
}
272+
return "retried";
273+
}, 1);
274+
275+
expect(result).toBe("retried");
276+
expect(attempts).toBe(2);
277+
expect(stderrWrite.mock.calls.flat().join("")).toContain("[qa-suite] infra retry 1/1:");
278+
} finally {
279+
stderrWrite.mockRestore();
280+
}
281+
});
282+
254283
it("partitions flow-only suites that request isolated workers", async () => {
255284
const repoRoot = await makeTempRepo("qa-suite-flow-only-isolated-");
256285
const result = await runQaSuite({

‎extensions/qa-lab/src/suite-run-isolated.cleanup.test.ts‎

Lines changed: 179 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,61 @@
1-
import { describe, expect, it, vi } from "vitest";
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
22
import { createQaBusState } from "./bus-state.js";
33
import type { QaLabServerHandle } from "./lab-server.types.js";
44
import type { QaTransportAdapterFactory } from "./qa-transport-registry.js";
55
import { runQaFlowSuiteIsolated } from "./suite-run-isolated.js";
6+
import { runQaFlowSuiteStandard } from "./suite-run-standard.js";
67
import { makeQaSuiteTestScenario } from "./suite-test-helpers.js";
7-
import type { QaSuiteResolvedRunContext, QaSuiteRunner } from "./suite-types.js";
8+
import type {
9+
QaSuiteResolvedRunContext,
10+
QaSuiteRunner,
11+
QaSuiteScenarioRunner,
12+
} from "./suite-types.js";
13+
14+
const mocks = vi.hoisted(() => ({
15+
disposeRegisteredAgentHarnesses: vi.fn(async () => {}),
16+
fetchWithSsrFGuard: vi.fn(async () => ({
17+
response: new Response(null, { status: 204 }),
18+
release: vi.fn(async () => {}),
19+
})),
20+
startQaGatewayChild: vi.fn(async () => ({
21+
baseUrl: "http://127.0.0.1:18789",
22+
token: "qa-test-token",
23+
cfg: {},
24+
getProcessCpuMs: () => null,
25+
getProcessRssBytes: () => null,
26+
stop: vi.fn(async () => {}),
27+
})),
28+
writeQaSuiteArtifacts: vi.fn(async () => ({
29+
evidence: undefined,
30+
evidencePath: "/qa-output/qa-evidence.json",
31+
report: "",
32+
reportPath: "/qa-output/qa-suite-report.md",
33+
summaryPath: "/qa-output/qa-suite-summary.json",
34+
})),
35+
}));
36+
37+
vi.mock("openclaw/plugin-sdk/agent-harness", () => ({
38+
disposeRegisteredAgentHarnesses: mocks.disposeRegisteredAgentHarnesses,
39+
}));
40+
vi.mock("openclaw/plugin-sdk/ssrf-runtime", () => ({
41+
fetchWithSsrFGuard: mocks.fetchWithSsrFGuard,
42+
}));
43+
vi.mock("./gateway-child.js", () => ({
44+
startQaGatewayChild: mocks.startQaGatewayChild,
45+
}));
46+
vi.mock("./providers/server-runtime.js", () => ({
47+
startQaProviderServer: vi.fn(async () => undefined),
48+
}));
49+
vi.mock("./suite-artifacts.js", () => ({
50+
writeQaSuiteArtifacts: mocks.writeQaSuiteArtifacts,
51+
}));
52+
vi.mock("./suite-runtime-gateway.js", () => ({
53+
waitForGatewayHealthy: vi.fn(async () => {}),
54+
waitForTransportReady: vi.fn(async () => {}),
55+
}));
56+
vi.mock("./web-runtime.js", () => ({
57+
closeQaWebSessions: vi.fn(async () => {}),
58+
}));
859

960
function createCleanupTestLab(): QaLabServerHandle {
1061
return {
@@ -41,6 +92,132 @@ function createCleanupTestContext(): QaSuiteResolvedRunContext {
4192
}
4293

4394
describe("isolated QA suite transport cleanup", () => {
95+
beforeEach(() => {
96+
vi.clearAllMocks();
97+
mocks.disposeRegisteredAgentHarnesses.mockResolvedValue(undefined);
98+
});
99+
100+
it("retains passing artifacts and finishes owned cleanup before reporting teardown failure", async () => {
101+
const lab = createCleanupTestLab();
102+
const release = vi.fn(async () => {});
103+
const factory: QaTransportAdapterFactory = {
104+
id: "leased",
105+
matches: ({ channelId, driver }) => channelId === "leased" && driver === "live",
106+
async create() {
107+
return {
108+
id: "leased",
109+
label: "Leased channel",
110+
accountId: "sut",
111+
requiredPluginIds: [],
112+
supportedActions: [],
113+
sendInbound: async (input) => lab.state.addInboundMessage(input),
114+
createGatewayConfig: () => ({}),
115+
async waitReady() {},
116+
buildAgentDelivery: ({ target }) => ({
117+
channel: "leased",
118+
to: target,
119+
replyChannel: "leased",
120+
replyTo: target,
121+
}),
122+
async handleAction() {},
123+
createReportNotes: () => [],
124+
cleanup: release,
125+
};
126+
},
127+
};
128+
const cleanupError = new Error("agent harness disposal failed");
129+
mocks.disposeRegisteredAgentHarnesses.mockRejectedValueOnce(cleanupError);
130+
const stderrWrite = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
131+
const runChild = vi.fn<QaSuiteRunner>().mockResolvedValue({
132+
outputDir: "/qa-child",
133+
evidencePath: "/qa-child/qa-evidence.json",
134+
reportPath: "/qa-child/qa-suite-report.md",
135+
summaryPath: "/qa-child/qa-suite-summary.json",
136+
report: "",
137+
scenarios: [{ name: "leased-channel-scenario", status: "pass", steps: [] }],
138+
watchUrl: lab.baseUrl,
139+
});
140+
const context = createCleanupTestContext();
141+
context.progressEnabled = true;
142+
143+
const thrown = await runQaFlowSuiteIsolated(
144+
{
145+
adapterFactories: [factory],
146+
channelDriver: "live",
147+
channelId: "leased",
148+
startLab: async () => lab,
149+
},
150+
context,
151+
runChild,
152+
).catch((error: unknown) => error);
153+
154+
expect(release).toHaveBeenCalledOnce();
155+
expect(mocks.disposeRegisteredAgentHarnesses).toHaveBeenCalledOnce();
156+
expect(lab.stop).toHaveBeenCalledOnce();
157+
expect(lab.setLatestReport).toHaveBeenCalledWith(
158+
expect.objectContaining({ outputPath: "/qa-output/qa-suite-report.md" }),
159+
);
160+
expect((thrown as Error).message.split("\n")[0]).toBe(
161+
"QA scenarios passed, but cleanup failed",
162+
);
163+
expect((thrown as Error).message).toContain(
164+
"failed cleanup phases: agent harnesses: agent harness disposal failed",
165+
);
166+
expect((thrown as Error).message).toContain(
167+
"retained artifacts: output=/qa-output report=/qa-output/qa-suite-report.md summary=/qa-output/qa-suite-summary.json",
168+
);
169+
expect((thrown as Error).cause).toBe(cleanupError);
170+
expect(stderrWrite.mock.calls.flat().join("")).not.toContain("run complete");
171+
stderrWrite.mockRestore();
172+
});
173+
174+
it("prints one generic completion after a real nested standard run and parent cleanup", async () => {
175+
const parentLab = createCleanupTestLab();
176+
const childLab = createCleanupTestLab();
177+
const startLab = vi
178+
.fn<() => Promise<QaLabServerHandle>>()
179+
.mockResolvedValueOnce(parentLab)
180+
.mockResolvedValueOnce(childLab);
181+
const context = createCleanupTestContext();
182+
context.channelDriver = undefined;
183+
context.progressEnabled = true;
184+
const runScenario = vi
185+
.fn<QaSuiteScenarioRunner>()
186+
.mockResolvedValue({ name: "leased-channel-scenario", status: "pass", steps: [] });
187+
const runChild: QaSuiteRunner = async (childParams) => {
188+
if (!childParams) {
189+
throw new Error("expected nested standard run params");
190+
}
191+
return await runQaFlowSuiteStandard(
192+
childParams,
193+
{
194+
...context,
195+
startedAt: new Date("2026-08-04T00:00:01.000Z"),
196+
outputDir: childParams.outputDir ?? "/qa-output/scenarios/leased-channel-scenario",
197+
concurrency: 1,
198+
},
199+
runScenario,
200+
);
201+
};
202+
const stderrWrite = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
203+
204+
try {
205+
await runQaFlowSuiteIsolated({ startLab }, context, runChild);
206+
207+
const completionLines = stderrWrite.mock.calls
208+
.flat()
209+
.join("")
210+
.split("\n")
211+
.filter((line) => line.startsWith("[qa-suite] run complete"));
212+
expect(completionLines).toEqual(["[qa-suite] run complete"]);
213+
expect(runScenario).toHaveBeenCalledOnce();
214+
expect(childLab.stop).toHaveBeenCalledOnce();
215+
expect(parentLab.stop).toHaveBeenCalledOnce();
216+
} finally {
217+
stderrWrite.mockRestore();
218+
}
219+
});
220+
44221
it.each(["cleanup", "cleanupAfterGatewayStop"] as const)(
45222
"retries a failed parent %s phase before disposing its owned lab",
46223
async (cleanupPhase) => {

‎extensions/qa-lab/src/suite-run-isolated.ts‎

Lines changed: 42 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import type {
1515
} from "./suite-types.js";
1616
import {
1717
createQaSuiteTransportAdapter,
18+
markQaSuiteNestedRun,
1819
requireQaSuiteStartLab,
1920
runQaSuiteCleanupSteps,
2021
throwQaSuiteCleanupErrors,
@@ -135,6 +136,9 @@ export async function runQaFlowSuiteIsolated(
135136
let isolatedRunFailed = false;
136137
let isolatedRunError: unknown;
137138
let parentTransportCleaned = false;
139+
let result: QaSuiteResult | undefined;
140+
let completionProgress: string | undefined;
141+
let evidenceWritten = false;
138142
try {
139143
if (params?.channelDriver === "live") {
140144
// The parent only renders aggregate artifacts. Release its live credentials
@@ -164,24 +168,26 @@ export async function runQaFlowSuiteIsolated(
164168
updateScenarioRun();
165169
try {
166170
const scenarioOutputDir = path.join(outputDir, "scenarios", scenario.id);
167-
const result: QaSuiteResult = await runQaFlowSuite(
168-
buildQaIsolatedScenarioWorkerParams({
169-
repoRoot,
170-
outputDir: scenarioOutputDir,
171-
providerMode,
172-
transportId,
173-
channelDriver: params?.channelDriver,
174-
channelDriverSelection: params?.channelDriverSelection,
175-
primaryModel,
176-
alternateModel,
177-
fastMode,
178-
startLab,
179-
scenario,
180-
input: params,
181-
}),
171+
const childSuiteResult: QaSuiteResult = await runQaFlowSuite(
172+
markQaSuiteNestedRun(
173+
buildQaIsolatedScenarioWorkerParams({
174+
repoRoot,
175+
outputDir: scenarioOutputDir,
176+
providerMode,
177+
transportId,
178+
channelDriver: params?.channelDriver,
179+
channelDriverSelection: params?.channelDriverSelection,
180+
primaryModel,
181+
alternateModel,
182+
fastMode,
183+
startLab,
184+
scenario,
185+
input: params,
186+
}),
187+
),
182188
);
183189
const scenarioResult: QaSuiteScenarioResult =
184-
result.scenarios[0] ??
190+
childSuiteResult.scenarios[0] ??
185191
({
186192
name: scenario.title,
187193
status: "fail",
@@ -246,13 +252,12 @@ export async function runQaFlowSuiteIsolated(
246252
},
247253
{
248254
startStaggerMs: workerStartStaggerMs,
249-
shouldStop: (result) => params?.failFast === true && result.status === "fail",
255+
shouldStop: (scenarioResult) =>
256+
params?.failFast === true && scenarioResult.status === "fail",
250257
},
251258
);
252259
await artifactWriteQueue;
253260
const finishedAt = new Date();
254-
const failedCount = scenarios.filter((scenario) => scenario.status === "fail").length;
255-
const skippedCount = scenarios.filter((scenario) => scenario.status === "skip").length;
256261
lab.setScenarioRun({
257262
kind: "suite",
258263
status: "completed",
@@ -296,11 +301,9 @@ export async function runQaFlowSuiteIsolated(
296301
markdown: report,
297302
generatedAt: finishedAt.toISOString(),
298303
} satisfies QaLabLatestReport);
299-
writeQaSuiteProgress(
300-
progressEnabled,
301-
`run complete: passed=${scenarios.length - failedCount - skippedCount} failed=${failedCount} skipped=${skippedCount} total=${scenarios.length}`,
302-
);
303-
return {
304+
completionProgress = "run complete";
305+
evidenceWritten = evidence !== undefined && (params?.writeEvidenceFile ?? true);
306+
result = {
304307
outputDir,
305308
evidence,
306309
evidencePath,
@@ -315,18 +318,27 @@ export async function runQaFlowSuiteIsolated(
315318
isolatedRunError = error;
316319
throw error;
317320
} finally {
318-
const cleanupSteps: Array<() => Promise<void>> = [
319-
...(!parentTransportCleaned ? [() => transportFactoryResult.cleanupWithoutGateway()] : []),
320-
() => disposeRegisteredAgentHarnesses(),
321+
const cleanupSteps = [
322+
...(!parentTransportCleaned
323+
? [{ phase: "parent transport", run: () => transportFactoryResult.cleanupWithoutGateway() }]
324+
: []),
325+
{ phase: "agent harnesses", run: () => disposeRegisteredAgentHarnesses() },
321326
];
322327
if (ownsLab) {
323-
cleanupSteps.push(() => lab.stop());
328+
cleanupSteps.push({ phase: "lab stop", run: () => lab.stop() });
324329
}
325-
const cleanupErrors = await runQaSuiteCleanupSteps(cleanupSteps);
330+
const cleanupFailures = await runQaSuiteCleanupSteps(cleanupSteps);
326331
throwQaSuiteCleanupErrors({
327-
cleanupErrors,
332+
cleanupFailures,
328333
runFailed: isolatedRunFailed,
329334
runError: isolatedRunError,
335+
result,
336+
evidenceWritten,
330337
});
331338
}
339+
if (!result || !completionProgress) {
340+
throw new Error("QA suite completed without terminal result metadata");
341+
}
342+
writeQaSuiteProgress(progressEnabled, completionProgress);
343+
return result;
332344
}

0 commit comments

Comments
 (0)