From d723569e52609119f6dc68a94a87a53b448f281d Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Thu, 23 Jul 2026 09:33:48 -0700 Subject: [PATCH 01/10] fix(e2e): isolate cleanup from test cancellation Signed-off-by: Apurv Kumaria --- test/e2e/fixtures/cleanup.ts | 73 ++++-- test/e2e/fixtures/docker-probe.ts | 6 +- test/e2e/fixtures/e2e-test.ts | 14 +- test/e2e/fixtures/shell-probe.ts | 9 +- test/e2e/support/e2e-cleanup-signal.test.ts | 242 ++++++++++++++++++++ 5 files changed, 315 insertions(+), 29 deletions(-) create mode 100644 test/e2e/support/e2e-cleanup-signal.test.ts diff --git a/test/e2e/fixtures/cleanup.ts b/test/e2e/fixtures/cleanup.ts index 18c13cee0eb..cdb7d9dafc0 100644 --- a/test/e2e/fixtures/cleanup.ts +++ b/test/e2e/fixtures/cleanup.ts @@ -18,6 +18,13 @@ type CleanupFn = () => Promise | void; type RedactFn = (text: string) => string; type CleanupProgress = Pick; const MAX_PROGRESS_CLEANUP_NAME_LENGTH = 120; +export const DEFAULT_CLEANUP_TIMEOUT_MS = 10 * 60_000; + +export interface CleanupRegistryOptions { + testSignal?: AbortSignal; + /** Shared deadline for signal-aware cleanup commands; callbacks are still awaited in order. */ + timeoutMs?: number; +} export interface CleanupHost { cleanupSandbox(name: string, options?: ShellProbeRunOptions): Promise; @@ -34,10 +41,26 @@ export class CleanupRegistry { private readonly entries: CleanupEntry[] = []; private readonly redact: RedactFn; private readonly progress?: CleanupProgress; - - constructor(redact: RedactFn = (text) => text, progress?: CleanupProgress) { + private readonly testSignal: AbortSignal; + private readonly timeoutMs: number; + private cleanupController?: AbortController; + + constructor( + redact: RedactFn = (text) => text, + progress?: CleanupProgress, + options: CleanupRegistryOptions = {}, + ) { this.redact = redact; this.progress = progress; + this.testSignal = options.testSignal ?? new AbortController().signal; + this.timeoutMs = options.timeoutMs ?? DEFAULT_CLEANUP_TIMEOUT_MS; + if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0) { + throw new Error("cleanup timeoutMs must be a positive safe integer"); + } + } + + currentSignal(): AbortSignal { + return this.cleanupController?.signal ?? this.testSignal; } private safeRedact(text: string): string { @@ -120,25 +143,39 @@ export class CleanupRegistry { } async runAll(): Promise { + if (this.cleanupController) { + throw new Error("cleanup is already running"); + } + + const cleanupController = new AbortController(); + this.cleanupController = cleanupController; + const deadline = setTimeout(() => cleanupController.abort(), this.timeoutMs); + deadline.unref(); const result: CleanupResult = { passed: [], failures: [] }; - for (const entry of [...this.entries].reverse()) { - const finishProgress = this.startProgress(entry.name); - try { - await entry.run(); - result.passed.push(this.safeRedact(entry.name)); - this.reportProgress("passed", entry.name); - } catch (error) { - result.failures.push({ - name: this.safeRedact(entry.name), - message: this.safeRedact(error instanceof Error ? error.message : String(error)), - }); - this.reportProgress("failed", entry.name); - } finally { - finishProgress(); + try { + for (const entry of [...this.entries].reverse()) { + const finishProgress = this.startProgress(entry.name); + try { + await entry.run(); + result.passed.push(this.safeRedact(entry.name)); + this.reportProgress("passed", entry.name); + } catch (error) { + result.failures.push({ + name: this.safeRedact(entry.name), + message: this.safeRedact(error instanceof Error ? error.message : String(error)), + }); + this.reportProgress("failed", entry.name); + } finally { + finishProgress(); + } } + return result; + } finally { + clearTimeout(deadline); + cleanupController.abort(); + this.cleanupController = undefined; + this.entries.length = 0; } - this.entries.length = 0; - return result; } } diff --git a/test/e2e/fixtures/docker-probe.ts b/test/e2e/fixtures/docker-probe.ts index d8ffd00329f..f8b41696d2d 100644 --- a/test/e2e/fixtures/docker-probe.ts +++ b/test/e2e/fixtures/docker-probe.ts @@ -11,6 +11,7 @@ import { type ChildProcessProgress, spawnObservedChild } from "./observed-child- import { buildChildEnv } from "./redaction.ts"; import type { SecretStore } from "./secrets.ts"; import { superviseChild } from "./shell/supervisor.ts"; +import type { AbortSignalSource } from "./shell-probe.ts"; export type DockerCommandResult = { command: string[]; @@ -104,7 +105,7 @@ export class DockerProbe { private readonly redact: SecretStore["redact"], private readonly runDocker?: DockerProbeRunner, private readonly progress?: ChildProcessProgress, - private readonly signal?: AbortSignal, + private readonly signal?: AbortSignalSource, ) { this.dockerConfigDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-config-")); } @@ -113,6 +114,7 @@ export class DockerProbe { args: string[], options: DockerProbeRunOptions = { artifactName: "docker" }, ): Promise { + const signal = typeof this.signal === "function" ? this.signal() : this.signal; fs.mkdirSync(this.dockerConfigDir, { recursive: true }); const command = ["docker", ...args]; const timeoutMs = options.timeoutMs ?? 30_000; @@ -163,7 +165,7 @@ export class DockerProbe { const supervised = await superviseChild(child, { timeoutMs, killGraceMs: 1_000, - signal: this.signal, + signal, onStdout: (chunk) => { if (outputExceeded) return; const next = appendBoundedOutput(stdout, chunk); diff --git a/test/e2e/fixtures/e2e-test.ts b/test/e2e/fixtures/e2e-test.ts index 1edc8caed8a..8599afe2a28 100644 --- a/test/e2e/fixtures/e2e-test.ts +++ b/test/e2e/fixtures/e2e-test.ts @@ -174,18 +174,20 @@ export const test = base.extend({ }, { auto: true }, ], - docker: async ({ artifacts, progress, secrets, signal, skip }, use) => { + docker: async ({ artifacts, cleanup, progress, secrets, skip }, use) => { const probe = new DockerProbe( artifacts, (text, extra) => secrets.redact(text, extra), undefined, progress, - signal, + () => cleanup.currentSignal(), ); await use(new DockerPrerequisite(probe, skip)); }, - cleanup: async ({ artifacts, progress, secrets }, use) => { - const cleanup = new CleanupRegistry((text) => secrets.redact(text), progress); + cleanup: async ({ artifacts, progress, secrets, signal }, use) => { + const cleanup = new CleanupRegistry((text) => secrets.redact(text), progress, { + testSignal: signal, + }); try { await use(cleanup); } finally { @@ -195,13 +197,13 @@ export const test = base.extend({ assertCleanupPassed(result); } }, - shellProbe: async ({ artifacts, progress, secrets, signal }, use) => { + shellProbe: async ({ artifacts, cleanup, progress, secrets }, use) => { await use( new ShellProbe({ artifacts, progress, redact: (text, extraValues) => secrets.redact(text, extraValues), - signal, + signal: () => cleanup.currentSignal(), }), ); }, diff --git a/test/e2e/fixtures/shell-probe.ts b/test/e2e/fixtures/shell-probe.ts index e694d101497..bb84e7a80a0 100644 --- a/test/e2e/fixtures/shell-probe.ts +++ b/test/e2e/fixtures/shell-probe.ts @@ -59,9 +59,11 @@ export interface ShellProbeDeps { artifacts: ArtifactSink; progress: ChildProcessProgress; redact: (text: string, extraValues?: string[]) => string; - signal: AbortSignal; + signal: AbortSignalSource; } +export type AbortSignalSource = AbortSignal | (() => AbortSignal); + const DEFAULT_TIMEOUT_MS = 60_000; const DEFAULT_KILL_GRACE_MS = 1_000; @@ -153,7 +155,7 @@ export class ShellProbe { private readonly artifacts: ArtifactSink; private readonly progress: ChildProcessProgress; private readonly redact: (text: string, extraValues?: string[]) => string; - private readonly signal: AbortSignal; + private readonly signal: AbortSignalSource; constructor(deps: ShellProbeDeps) { this.artifacts = deps.artifacts; @@ -166,6 +168,7 @@ export class ShellProbe { trustedCommand: TrustedShellCommand, options: ShellProbeRunOptions = {}, ): Promise { + const signal = typeof this.signal === "function" ? this.signal() : this.signal; const command = trustedCommand.command; const args = [...trustedCommand.args]; const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; @@ -221,7 +224,7 @@ export class ShellProbe { const supervised = await superviseChild(child, { timeoutMs, killGraceMs, - signal: this.signal, + signal, onStdout: (chunk) => { stdout.append(chunk); try { diff --git a/test/e2e/support/e2e-cleanup-signal.test.ts b/test/e2e/support/e2e-cleanup-signal.test.ts new file mode 100644 index 00000000000..b52bf346b55 --- /dev/null +++ b/test/e2e/support/e2e-cleanup-signal.test.ts @@ -0,0 +1,242 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { expect, it, onTestFinished } from "vitest"; + +import { ArtifactSink } from "../fixtures/artifacts.ts"; +import { CleanupRegistry } from "../fixtures/cleanup.ts"; +import { DockerProbe } from "../fixtures/docker-probe.ts"; +import { startTestProgress } from "../fixtures/progress.ts"; +import { + type AbortSignalSource, + ShellProbe, + trustedShellCommand, +} from "../fixtures/shell-probe.ts"; + +async function createShellProbe(signal: AbortSignalSource): Promise { + const artifactRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cleanup-signal-")); + const artifacts = new ArtifactSink(artifactRoot); + await artifacts.ensureRoot(); + const progress = startTestProgress( + "cleanup signal support", + ["exercise cleanup signal", "verify cleanup signal"], + { + clearTimer: () => undefined, + logLine: () => undefined, + setTimer: () => ({}), + }, + ); + onTestFinished(() => { + progress.stop(); + fs.rmSync(artifactRoot, { force: true, recursive: true }); + }); + return new ShellProbe({ + artifacts, + progress, + redact: (text) => text, + signal, + }); +} + +it("cleanup commands receive a fresh signal after the test signal is aborted", async () => { + const testController = new AbortController(); + const cleanup = new CleanupRegistry((text) => text, undefined, { + testSignal: testController.signal, + }); + const observedSignals: AbortSignal[] = []; + const probe = await createShellProbe(() => { + const signal = cleanup.currentSignal(); + observedSignals.push(signal); + return signal; + }); + let cleanupSignalWasLive = false; + let cleanupExitCode: number | null | undefined; + cleanup.add("run cleanup command", async () => { + const signal = cleanup.currentSignal(); + cleanupSignalWasLive = signal !== testController.signal && !signal.aborted; + const result = await probe.run( + trustedShellCommand({ + command: process.execPath, + args: ["-e", "process.exit(0)"], + reason: "verify cleanup commands outlive the test signal", + }), + { artifactName: "fresh-cleanup-signal", timeoutMs: 5_000 }, + ); + cleanupExitCode = result.exitCode; + }); + + testController.abort(); + expect(cleanup.currentSignal()).toBe(testController.signal); + expect(cleanup.currentSignal().aborted).toBe(true); + + const result = await cleanup.runAll(); + + expect(result).toEqual({ passed: ["run cleanup command"], failures: [] }); + expect(cleanupSignalWasLive).toBe(true); + expect(cleanupExitCode).toBe(0); + expect(observedSignals).toHaveLength(1); + expect(observedSignals[0]).not.toBe(testController.signal); + expect(cleanup.currentSignal()).toBe(testController.signal); + expect(cleanup.currentSignal().aborted).toBe(true); +}); + +it("normal commands retain cancellation from the original test signal", async () => { + const testController = new AbortController(); + const cleanup = new CleanupRegistry((text) => text, undefined, { + testSignal: testController.signal, + }); + const probe = await createShellProbe(() => cleanup.currentSignal()); + + const run = probe.run( + trustedShellCommand({ + command: process.execPath, + args: ["-e", "setInterval(() => {}, 1000)"], + reason: "verify normal commands retain test cancellation", + }), + { + artifactName: "normal-command-test-signal", + killGraceMs: 25, + timeoutMs: 5_000, + }, + ); + setTimeout(() => testController.abort(), 50).unref(); + const result = await run; + + expect(result.signal).toMatch(/^SIG(TERM|KILL)$/); + expect(result.timedOut).toBe(false); + expect(cleanup.currentSignal()).toBe(testController.signal); +}); + +it("shell and Docker probes latch their signal source once per command", async () => { + const originalController = new AbortController(); + const preAbortedController = new AbortController(); + preAbortedController.abort(); + let activeSignal = originalController.signal; + const shellSignals: AbortSignal[] = []; + const shellProbe = await createShellProbe(() => { + shellSignals.push(activeSignal); + return activeSignal; + }); + + const shellRun = shellProbe.run( + trustedShellCommand({ + command: process.execPath, + args: ["-e", "setTimeout(() => process.exit(0), 50)"], + reason: "verify each shell command latches its starting signal", + }), + { artifactName: "latched-shell-signal", timeoutMs: 5_000 }, + ); + activeSignal = preAbortedController.signal; + const shellResult = await shellRun; + + expect(shellResult.exitCode).toBe(0); + expect(shellSignals).toEqual([originalController.signal]); + + const artifactRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-signal-")); + const artifacts = new ArtifactSink(artifactRoot); + await artifacts.ensureRoot(); + onTestFinished(() => fs.rmSync(artifactRoot, { force: true, recursive: true })); + activeSignal = originalController.signal; + const dockerSignals: AbortSignal[] = []; + const dockerProbe = new DockerProbe( + artifacts, + (text) => text, + () => ({ + error: undefined, + output: [null, "", ""], + pid: 1, + signal: null, + status: 0, + stderr: "", + stdout: "", + }), + undefined, + () => { + dockerSignals.push(activeSignal); + return activeSignal; + }, + ); + + const firstDockerRun = dockerProbe.run(["version"], { artifactName: "first-signal" }); + activeSignal = preAbortedController.signal; + await firstDockerRun; + await dockerProbe.run(["info"], { artifactName: "second-signal" }); + + expect(dockerSignals).toEqual([originalController.signal, preAbortedController.signal]); +}); + +it("the shared cleanup deadline aborts commands without skipping later callbacks", async () => { + const testController = new AbortController(); + const cleanup = new CleanupRegistry((text) => text, undefined, { + testSignal: testController.signal, + timeoutMs: 75, + }); + const probe = await createShellProbe(() => cleanup.currentSignal()); + const callbacks: string[] = []; + let commandSignal: NodeJS.Signals | null | undefined; + let commandTimedOut: boolean | undefined; + cleanup.add("release later resource", () => { + callbacks.push("later resource"); + }); + cleanup.add("stop hanging command", async () => { + callbacks.push("command started"); + const result = await probe.run( + trustedShellCommand({ + command: process.execPath, + args: ["-e", "setInterval(() => {}, 1000)"], + reason: "verify the cleanup command deadline", + }), + { + artifactName: "cleanup-deadline", + killGraceMs: 25, + timeoutMs: 5_000, + }, + ); + commandSignal = result.signal; + commandTimedOut = result.timedOut; + callbacks.push("command finished"); + }); + + const startedAt = Date.now(); + const result = await cleanup.runAll(); + + expect(Date.now() - startedAt).toBeLessThan(2_000); + expect(commandSignal).toMatch(/^SIG(TERM|KILL)$/); + expect(commandTimedOut).toBe(false); + expect(callbacks).toEqual(["command started", "command finished", "later resource"]); + expect(result).toEqual({ + passed: ["stop hanging command", "release later resource"], + failures: [], + }); + expect(cleanup.currentSignal()).toBe(testController.signal); +}); + +it("rejects concurrent cleanup without clearing the active registry", async () => { + const cleanup = new CleanupRegistry(); + const callbacks: string[] = []; + let releaseFirstCleanup: (() => void) | undefined; + const firstCleanupBlocked = new Promise((resolve) => { + releaseFirstCleanup = resolve; + }); + cleanup.add("release earlier resource", () => { + callbacks.push("earlier resource"); + }); + cleanup.add("release blocking resource", async () => { + callbacks.push("blocking resource"); + await firstCleanupBlocked; + }); + + const firstRun = cleanup.runAll(); + await expect(cleanup.runAll()).rejects.toThrow("cleanup is already running"); + releaseFirstCleanup?.(); + + expect(await firstRun).toEqual({ + passed: ["release blocking resource", "release earlier resource"], + failures: [], + }); + expect(callbacks).toEqual(["blocking resource", "earlier resource"]); +}); From b811db4efd2c978821b45641d416e58adf47403d Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Thu, 23 Jul 2026 09:49:35 -0700 Subject: [PATCH 02/10] fix(e2e): checkpoint observed child lifecycles Signed-off-by: Apurv Kumaria --- test/e2e/fixtures/observed-child-process.ts | 48 +- test/e2e/fixtures/progress.ts | 54 +- .../support/e2e-semantic-phase-check.test.ts | 127 +++- .../support/observed-child-process.test.ts | 241 +++++++- tools/e2e/check-semantic-phases.mts | 578 ++++++++++++++++-- 5 files changed, 1002 insertions(+), 46 deletions(-) diff --git a/test/e2e/fixtures/observed-child-process.ts b/test/e2e/fixtures/observed-child-process.ts index ee31bc5d56c..9add2b80bfb 100644 --- a/test/e2e/fixtures/observed-child-process.ts +++ b/test/e2e/fixtures/observed-child-process.ts @@ -2,7 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 import { type ChildProcess, type SpawnOptions, spawn } from "node:child_process"; -import { isTestProgressCapability, type TestProgressCapability } from "./progress.ts"; +import { + type ChildLifecycleOutcome, + type ChildLifecycleTerminalReporter, + isTestProgressCapability, + type TestProgressCapability, +} from "./progress.ts"; export interface ChildProcessProgress extends TestProgressCapability { activity(label: string): (() => void) | void; @@ -15,6 +20,10 @@ export interface ObservedChildProcessOptions { spawn: SpawnOptions; } +const NOOP_CHILD_LIFECYCLE_REPORTER: ChildLifecycleTerminalReporter = Object.freeze( + (_outcome: ChildLifecycleOutcome) => undefined, +); + /** * The single direct asynchronous child-process boundary used by live E2E code. * It owns content-free activity and timestamp-only output observation so a @@ -35,6 +44,13 @@ export function spawnObservedChild( // Progress diagnostics must never change process execution. } + let finishChildLifecycle = NOOP_CHILD_LIFECYCLE_REPORTER; + try { + finishChildLifecycle = options.progress.beginChildLifecycle(); + } catch { + // Progress diagnostics must never change process execution. + } + let child: ChildProcess; try { child = spawn(command, [...args], options.spawn); @@ -44,6 +60,11 @@ export function spawnObservedChild( } catch { // Progress diagnostics must never replace the spawn failure. } + try { + finishChildLifecycle("spawn-failed"); + } catch { + // Progress diagnostics must never replace the spawn failure. + } throw error; } @@ -61,12 +82,35 @@ export function spawnObservedChild( // Child contents never cross this timestamp-only observer boundary. } }); - child.once("close", () => { + let childSpawned = false; + let childLaunchFailed = false; + child.once("spawn", () => { + childSpawned = true; + }); + child.once("error", () => { + if (!childSpawned) childLaunchFailed = true; + }); + child.once("close", (code, signal) => { try { finishActivity(); } catch { // Progress diagnostics must never change process completion. } + try { + finishChildLifecycle( + childLaunchFailed + ? "spawn-failed" + : signal !== null + ? "signaled" + : code === 0 + ? "exited-zero" + : code === null + ? "closed-unknown" + : "exited-nonzero", + ); + } catch { + // Progress diagnostics must never change process completion. + } }); return child; } diff --git a/test/e2e/fixtures/progress.ts b/test/e2e/fixtures/progress.ts index 81be19b4ad1..c1162717971 100644 --- a/test/e2e/fixtures/progress.ts +++ b/test/e2e/fixtures/progress.ts @@ -62,6 +62,15 @@ export interface TestProgressTimeline { export type ProgressPhaseOutcome = "passed" | "failed" | "skipped"; +export type ChildLifecycleOutcome = + | "spawn-failed" + | "exited-zero" + | "exited-nonzero" + | "signaled" + | "closed-unknown"; + +export type ChildLifecycleTerminalReporter = (outcome: ChildLifecycleOutcome) => void; + const TEST_PROGRESS_CAPABILITY: unique symbol = Symbol("nemoclaw.test-progress"); const TEST_PROGRESS_INSTANCES = new WeakSet(); @@ -76,6 +85,7 @@ export interface TestProgressCapability { export interface TestProgress extends TestProgressCapability { onOutput: (event: ShellProbeOutputEvent) => void; activity: (label: string) => () => void; + beginChildLifecycle: () => ChildLifecycleTerminalReporter; /** Emit a content-free semantic status event. Never pass child output or request data. */ event: (label: string) => void; phase: (label: string) => void; @@ -86,7 +96,7 @@ export interface TestProgress extends TestProgressCapability { timeline: () => TestProgressTimeline; } -export function isTestProgressCapability(value: unknown): value is TestProgressCapability { +export function isTestProgressCapability(value: unknown): value is TestProgress { if (typeof value !== "object" || value === null || !TEST_PROGRESS_INSTANCES.has(value)) { return false; } @@ -240,6 +250,7 @@ export function startTestProgress( const reachedPhases = new Set([runtimePhasePlan[0] as string]); const activities = new Map(); let nextActivityId = 0; + let nextChildLifecycleOrdinal = 1; let phaseIndex = 0; let phaseStartedAt = scenarioStartedAt; let lastOutputAt: number | null = null; @@ -306,6 +317,22 @@ export function startTestProgress( } }; + const logChildLifecycleBestEffort = ( + ordinal: number, + checkpoint: "started" | ChildLifecycleOutcome, + ) => { + try { + const current = now(); + logLine( + `${phasePrefix()} child lifecycle ${ordinal}: ${checkpoint} (` + + `total ${formatElapsed(current - scenarioStartedAt)}; ` + + `phase ${formatElapsed(current - phaseStartedAt)})`, + ); + } catch { + // Diagnostics must not change child-process execution. + } + }; + const activityEvidence = (): string => { const active = [...activities.values()]; if (active.length === 0) return "no active command"; @@ -469,6 +496,31 @@ export function startTestProgress( activities.delete(activityId); }; }, + beginChildLifecycle() { + if (finishedAt !== null) { + return Object.freeze((_outcome: ChildLifecycleOutcome) => undefined); + } + const ordinal = nextChildLifecycleOrdinal; + nextChildLifecycleOrdinal += 1; + logChildLifecycleBestEffort(ordinal, "started"); + let terminalReported = false; + const reportTerminal: ChildLifecycleTerminalReporter = (outcome) => { + if (terminalReported) return; + switch (outcome) { + case "spawn-failed": + case "exited-zero": + case "exited-nonzero": + case "signaled": + case "closed-unknown": + break; + default: + return; + } + terminalReported = true; + logChildLifecycleBestEffort(ordinal, outcome); + }; + return Object.freeze(reportTerminal); + }, event(label) { if (finishedAt !== null) return; validateProgressEventLabel(label); diff --git a/test/e2e/support/e2e-semantic-phase-check.test.ts b/test/e2e/support/e2e-semantic-phase-check.test.ts index 92967ee5c9f..18ce989de04 100644 --- a/test/e2e/support/e2e-semantic-phase-check.test.ts +++ b/test/e2e/support/e2e-semantic-phase-check.test.ts @@ -173,6 +173,7 @@ describe("semantic E2E phase checker", () => { observesOutput: false, outputIgnored: false, tracksActivity: false, + tracksLifecycle: false, }, ], forwardedTestModules: ["test/e2e/live/launchable-smoke.test.ts"], @@ -404,6 +405,7 @@ getBuiltinModule("child_process").spawn("bare-child", [], { stdio: "ignore" }); boundary: "spawnObservedChild", observesOutput: true, tracksActivity: true, + tracksLifecycle: true, }), ]); @@ -457,14 +459,76 @@ getBuiltinModule("child_process").spawn("bare-child", [], { stdio: "ignore" }); const conditionalLifecycle = scanDirectChildProcessSource( OBSERVED_CHILD_PROCESS_SOURCE, canonicalSource.replace( - 'child.once("close", () => {\n try {\n finishActivity();', - 'child.once("close", () => {\n try {\n if (false) finishActivity();', + 'child.once("close", (code, signal) => {\n try {\n finishActivity();', + 'child.once("close", (code, signal) => {\n try {\n if (false) finishActivity();', ), ); expect(conditionalLifecycle.calls[0]).toEqual( expect.objectContaining({ tracksActivity: false }), ); + const missingLifecycleStart = scanDirectChildProcessSource( + OBSERVED_CHILD_PROCESS_SOURCE, + canonicalSource.replace( + "finishChildLifecycle = options.progress.beginChildLifecycle();", + "finishChildLifecycle = NOOP_CHILD_LIFECYCLE_REPORTER;", + ), + ); + expect(missingLifecycleStart.calls[0]).toEqual( + expect.objectContaining({ tracksLifecycle: false }), + ); + + const unconditionalLaunchFailure = scanDirectChildProcessSource( + OBSERVED_CHILD_PROCESS_SOURCE, + canonicalSource.replace( + "if (!childSpawned) childLaunchFailed = true;", + "childLaunchFailed = true;", + ), + ); + expect(unconditionalLaunchFailure.calls[0]).toEqual( + expect.objectContaining({ tracksLifecycle: false }), + ); + + const preconfirmedLaunch = scanDirectChildProcessSource( + OBSERVED_CHILD_PROCESS_SOURCE, + canonicalSource.replace("let childSpawned = false;", "let childSpawned = true;"), + ); + expect(preconfirmedLaunch.calls[0]).toEqual( + expect.objectContaining({ tracksLifecycle: false }), + ); + + const payloadBearingTerminal = scanDirectChildProcessSource( + OBSERVED_CHILD_PROCESS_SOURCE, + canonicalSource.replace(': "exited-nonzero",', ": `exited-nonzero-${String(code)}`,"), + ); + expect(payloadBearingTerminal.calls[0]).toEqual( + expect.objectContaining({ tracksLifecycle: false }), + ); + + const missingLifecycleFailures = validateCollectedSemanticPhaseModule({ + relativeModuleId: "test/e2e/live/observed-child-lifecycle-contract.test.ts", + errors: [], + tests: [{ fullName: "audits child lifecycle checkpoints", phases: ["prepare", "verify"] }], + source: { + directChildProcessCalls: missingLifecycleStart.calls, + importsDirectTest: false, + importsSharedTest: true, + phaseCalls: [ + { + file: "test/e2e/live/observed-child-lifecycle-contract.test.ts", + label: "verify", + line: 1, + }, + ], + testPhaseBodies: [], + }, + }); + expect(missingLifecycleFailures).toEqual( + expect.arrayContaining([ + expect.stringMatching(/must emit canonical content-free lifecycle checkpoints/u), + ]), + ); + const conditionalOutput = scanDirectChildProcessSource( OBSERVED_CHILD_PROCESS_SOURCE, canonicalSource.replace( @@ -587,6 +651,20 @@ getBuiltinModule("child_process").spawn("bare-child", [], { stdio: "ignore" }); expect.stringMatching(/must use a reviewed progress-capability callsite/u), ]); + const lifecycleCapabilityCallsite = scanDirectChildProcessSource( + FAKE_OPENAI_SOURCE, + `${canonicalSource}\nexport function bypassObservedChild(options: FakeOpenAiCompatibleServerOptions) {\n options.progress.beginChildLifecycle();\n}\n`, + ); + expect(lifecycleCapabilityCallsite.auditFailures).toEqual([ + expect.stringMatching(/reserved for the canonical observed-child boundary/u), + ]); + + const supportLifecycleProbe = scanDirectChildProcessSource( + path.join(REPO_ROOT, "test/e2e/support/lifecycle-probe.fixture.ts"), + "export function probe(progress: { beginChildLifecycle(): () => void }) { progress.beginChildLifecycle(); }", + ); + expect(supportLifecycleProbe.auditFailures).toEqual([]); + const escapedWrapper = scanDirectChildProcessSource( FAKE_OPENAI_SOURCE, `${canonicalSource}\nconst wrapperBag = { spawnObservedChild };\nconst wrapperList = [spawnObservedChild];\nexport { spawnObservedChild };\nvoid [wrapperBag, wrapperList];\n`, @@ -668,6 +746,51 @@ getBuiltinModule("child_process").spawn("bare-child", [], { stdio: "ignore" }); progressSource.replace("return Object.freeze(progress);", "return progress;"), ).auditFailures, ).toEqual([expect.stringMatching(/privately brand, register, and freeze/u)]); + expect( + scanDirectChildProcessSource( + TEST_PROGRESS_SOURCE, + progressSource.replace( + " beginChildLifecycle: () => ChildLifecycleTerminalReporter;\n", + "", + ), + ).auditFailures, + ).toEqual([expect.stringMatching(/zero-argument child lifecycle capability/u)]); + expect( + scanDirectChildProcessSource( + TEST_PROGRESS_SOURCE, + progressSource.replace( + " beginChildLifecycle() {", + " beginChildLifecycle(_label: string) {", + ), + ).auditFailures, + ).toEqual([expect.stringMatching(/synchronously start and freeze idempotent/u)]); + expect( + scanDirectChildProcessSource( + TEST_PROGRESS_SOURCE, + progressSource.replace( + " return Object.freeze(reportTerminal);", + " return reportTerminal;", + ), + ).auditFailures, + ).toEqual([expect.stringMatching(/synchronously start and freeze idempotent/u)]); + expect( + scanDirectChildProcessSource( + TEST_PROGRESS_SOURCE, + progressSource.replace(" if (terminalReported) return;\n", ""), + ).auditFailures, + ).toEqual([expect.stringMatching(/synchronously start and freeze idempotent/u)]); + expect( + scanDirectChildProcessSource( + TEST_PROGRESS_SOURCE, + progressSource.replace(" terminalReported = true;\n", ""), + ).auditFailures, + ).toEqual([expect.stringMatching(/synchronously start and freeze idempotent/u)]); + expect( + scanDirectChildProcessSource( + TEST_PROGRESS_SOURCE, + progressSource.replace(' | "closed-unknown";', ' | "raw-exit-code";'), + ).auditFailures, + ).toEqual([expect.stringMatching(/fixed content-free terminal vocabulary/u)]); const observedSource = fs.readFileSync(OBSERVED_CHILD_PROCESS_SOURCE, "utf8"); expect( diff --git a/test/e2e/support/observed-child-process.test.ts b/test/e2e/support/observed-child-process.test.ts index 3ce67360798..25a56be1d4d 100644 --- a/test/e2e/support/observed-child-process.test.ts +++ b/test/e2e/support/observed-child-process.test.ts @@ -2,14 +2,33 @@ // SPDX-License-Identifier: Apache-2.0 import type { ChildProcess } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; -import { describe, expect, test } from "vitest"; +import { afterEach, describe, expect, test } from "vitest"; import { spawnObservedChild } from "../fixtures/observed-child-process.ts"; -import { startTestProgress, type TestProgress } from "../fixtures/progress.ts"; +import { + startTestProgress, + type TestProgress, + type TestProgressOptions, +} from "../fixtures/progress.ts"; + +const progressInstances: TestProgress[] = []; + +function trackedProgress( + scenario: string, + phasePlan: readonly string[], + options: TestProgressOptions = {}, +): TestProgress { + const progress = startTestProgress(scenario, phasePlan, options); + progressInstances.push(progress); + return progress; +} function observedProgress(): TestProgress { - return startTestProgress("observed child support", ["run observed child", "verify observation"], { + return trackedProgress("observed child support", ["run observed child", "verify observation"], { logLine: () => undefined, }); } @@ -23,12 +42,20 @@ function waitForClose( }); } +function lifecycleLines(lines: readonly string[]): string[] { + return lines.filter((line) => line.includes("child lifecycle")); +} + describe("observed E2E child process", () => { + afterEach(() => { + for (const progress of progressInstances.splice(0)) progress.stop(); + }); + test("ties activity completion and timestamp-only output events to the child", async () => { const secret = "OBSERVED_CHILD_SECRET"; const lines: string[] = []; const timers: Array<() => void> = []; - const progress = startTestProgress( + const progress = trackedProgress( "observed child support", ["run observed child", "verify observation"], { @@ -60,6 +87,206 @@ describe("observed E2E child process", () => { expect(JSON.stringify(progress.summary())).not.toContain(secret); }); + test.each([ + ["exited-zero", "process.exit(0)"], + ["exited-nonzero", "process.exit(7)"], + ] as const)("classifies a child that terminates as %s", async (outcome, script) => { + const lines: string[] = []; + const progress = trackedProgress( + "observed child classification", + ["run classified child", "verify child classification"], + { + logLine: (line) => lines.push(line), + }, + ); + const child = spawnObservedChild(process.execPath, ["-e", script], { + activityLabel: "command: classified-child", + progress, + spawn: { stdio: "ignore" }, + }); + + await waitForClose(child); + expect(lifecycleLines(lines)).toEqual([ + expect.stringContaining("child lifecycle 1: started"), + expect.stringContaining(`child lifecycle 1: ${outcome}`), + ]); + }); + + test("keeps a post-launch process error distinct from a spawn failure", async () => { + const secret = "POST_LAUNCH_ERROR_SECRET"; + const lines: string[] = []; + const progress = trackedProgress( + "observed child post-launch error", + ["start launched child", "verify launched child outcome"], + { + logLine: (line) => lines.push(line), + }, + ); + const child = spawnObservedChild( + process.execPath, + ["-e", "setTimeout(() => process.exit(0), 100)"], + { + activityLabel: "command: launched-child", + progress, + spawn: { stdio: "ignore" }, + }, + ); + await new Promise((resolve) => child.once("spawn", resolve)); + child.emit("error", new Error(secret)); + + await waitForClose(child); + const checkpoints = lifecycleLines(lines); + expect(checkpoints).toEqual([ + expect.stringContaining("child lifecycle 1: started"), + expect.stringContaining("child lifecycle 1: exited-zero"), + ]); + expect(checkpoints.join("\n")).not.toContain(secret); + expect(checkpoints.join("\n")).not.toContain("spawn-failed"); + }); + + test("classifies a child terminated by a signal without exposing that signal", async () => { + const lines: string[] = []; + const progress = trackedProgress( + "observed child signal classification", + ["start signal-bound child", "verify signal classification"], + { + logLine: (line) => lines.push(line), + }, + ); + const child = spawnObservedChild( + process.execPath, + ["-e", "setInterval(() => undefined, 1_000)"], + { + activityLabel: "command: signal-bound-child", + progress, + spawn: { stdio: "ignore" }, + }, + ); + await new Promise((resolve) => child.once("spawn", resolve)); + child.kill("SIGTERM"); + + await waitForClose(child); + const checkpoints = lifecycleLines(lines); + expect(checkpoints).toEqual([ + expect.stringContaining("child lifecycle 1: started"), + expect.stringContaining("child lifecycle 1: signaled"), + ]); + expect(checkpoints.join("\n")).not.toContain("SIGTERM"); + }); + + test("records one launch failure only after the failed child closes", async () => { + const lines: string[] = []; + const progress = trackedProgress( + "observed child launch failure", + ["start unavailable child", "verify launch failure"], + { + logLine: (line) => lines.push(line), + }, + ); + const child = spawnObservedChild("nemoclaw-observed-child-missing-binary", [], { + activityLabel: "command: unavailable-child", + progress, + spawn: { stdio: "ignore" }, + }); + const closed = new Promise((resolve) => { + child.once("error", () => undefined); + child.once("close", () => resolve()); + }); + + expect(lifecycleLines(lines)).toEqual([expect.stringContaining("child lifecycle 1: started")]); + await closed; + expect(lifecycleLines(lines)).toEqual([ + expect.stringContaining("child lifecycle 1: started"), + expect.stringContaining("child lifecycle 1: spawn-failed"), + ]); + }); + + test("keeps lifecycle checkpoints ordinal, idempotent, frozen, and content-free", async () => { + const secret = "OBSERVED_CHILD_LIFECYCLE_SECRET"; + const workdir = fs.mkdtempSync(path.join(os.tmpdir(), `${secret}-`)); + const lines: string[] = []; + try { + const progress = trackedProgress( + "observed child content boundary", + ["run secret-bearing child", "verify content-free lifecycle"], + { + logLine: (line) => lines.push(line), + }, + ); + const unfinished = progress.beginChildLifecycle(); + expect(Object.isFrozen(unfinished)).toBe(true); + unfinished("closed-unknown"); + unfinished("exited-zero"); + + const child = spawnObservedChild( + process.execPath, + [ + "-e", + "process.stdout.write([process.argv[1], process.env.CHILD_SECRET, process.cwd(), process.pid].join(':'))", + secret, + ], + { + activityLabel: `command: ${secret}`, + progress, + spawn: { + cwd: workdir, + env: { ...process.env, CHILD_SECRET: secret }, + stdio: ["ignore", "pipe", "pipe"], + }, + }, + ); + await waitForClose(child); + + const checkpoints = lifecycleLines(lines); + expect(checkpoints).toHaveLength(4); + expect(checkpoints).toEqual([ + expect.stringContaining("child lifecycle 1: started"), + expect.stringContaining("child lifecycle 1: closed-unknown"), + expect.stringContaining("child lifecycle 2: started"), + expect.stringContaining("child lifecycle 2: exited-zero"), + ]); + expect(checkpoints.join("\n")).not.toContain(secret); + expect(checkpoints.join("\n")).not.toMatch(/\bpid\b|command:/iu); + } finally { + fs.rmSync(workdir, { force: true, recursive: true }); + } + }); + + test("leaves a durable start checkpoint without inventing a terminal outcome", () => { + const lines: string[] = []; + const progress = trackedProgress( + "observed child interrupted runner", + ["start interrupted child", "verify interruption evidence"], + { + logLine: (line) => lines.push(line), + }, + ); + + progress.beginChildLifecycle(); + progress.stop("failed"); + + expect(lifecycleLines(lines)).toEqual([expect.stringContaining("child lifecycle 1: started")]); + }); + + test("keeps process execution independent from rejected lifecycle logging", async () => { + const progress = trackedProgress( + "observed child logging failure", + ["run child with failed logger", "verify child completion"], + { + logLine: () => { + throw new Error("diagnostic logger failed"); + }, + }, + ); + const child = spawnObservedChild(process.execPath, ["-e", "process.exit(0)"], { + activityLabel: "command: logging-failure-child", + progress, + spawn: { stdio: "ignore" }, + }); + + await expect(waitForClose(child)).resolves.toEqual({ code: 0, signal: null }); + }); + test("keeps process execution independent from rejected activity diagnostics", async () => { const child = spawnObservedChild(process.execPath, ["-e", "process.stdout.write('ok')"], { activityLabel: "invalid\nactivity", @@ -73,7 +300,7 @@ describe("observed E2E child process", () => { test("finishes the activity when spawn throws synchronously", () => { const lines: string[] = []; const timers: Array<() => void> = []; - const progress = startTestProgress( + const progress = trackedProgress( "observed child support", ["run observed child", "verify observation"], { @@ -94,6 +321,10 @@ describe("observed E2E child process", () => { ).toThrow(); timers[0]?.(); expect(lines.at(-1)).toContain("no active command"); + expect(lifecycleLines(lines)).toEqual([ + expect.stringContaining("child lifecycle 1: started"), + expect.stringContaining("child lifecycle 1: spawn-failed"), + ]); }); test("rejects a derived look-alike that copied the private capability", () => { diff --git a/tools/e2e/check-semantic-phases.mts b/tools/e2e/check-semantic-phases.mts index af319aa6bad..6e93c128c78 100644 --- a/tools/e2e/check-semantic-phases.mts +++ b/tools/e2e/check-semantic-phases.mts @@ -55,6 +55,7 @@ export interface DirectChildProcessCall { observesOutput: boolean; outputIgnored: boolean; tracksActivity: boolean; + tracksLifecycle: boolean; } export interface ScopedPhasePlan { @@ -894,19 +895,8 @@ function inlineCallback( return node && (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) ? node : null; } -function callbackProtectedCall( - callback: ts.ArrowFunction | ts.FunctionExpression, -): ts.CallExpression | null { - if ( - callback.parameters.length !== 0 || - !ts.isBlock(callback.body) || - callback.body.statements.length !== 1 - ) { - return null; - } - const statement = callback.body.statements[0]; +function protectedCallFromStatement(statement: ts.Statement): ts.CallExpression | null { if ( - !statement || !ts.isTryStatement(statement) || statement.finallyBlock || !statement.catchClause || @@ -922,17 +912,18 @@ function callbackProtectedCall( return ts.isCallExpression(expression) ? expression : null; } -function callbackInvokesIdentifier( +function callbackProtectedCall( callback: ts.ArrowFunction | ts.FunctionExpression, - identifiers: ReadonlySet, -): boolean { - const call = callbackProtectedCall(callback); - return ( - !!call && - call.arguments.length === 0 && - ts.isIdentifier(call.expression) && - identifiers.has(call.expression.text) - ); +): ts.CallExpression | null { + if ( + callback.parameters.length !== 0 || + !ts.isBlock(callback.body) || + callback.body.statements.length !== 1 + ) { + return null; + } + const statement = callback.body.statements[0]; + return statement ? protectedCallFromStatement(statement) : null; } function childLifecycleListener( @@ -946,12 +937,265 @@ function childLifecycleListener( if (!["on", "once", "addListener"].includes(expression.name.text)) return null; if (expressionPath(expression.expression) !== childBinding) return null; const event = call.arguments[0]; - if (!event || !ts.isStringLiteralLike(event) || !["close", "exit"].includes(event.text)) { + if (!event || !ts.isStringLiteralLike(event) || event.text !== "close") { return null; } return inlineCallback(call.arguments[1]); } +function childLaunchErrorListener( + call: ts.CallExpression, + childBinding: string, + scope: ts.Node, +): ts.ArrowFunction | ts.FunctionExpression | null { + if (!isUnconditionalBoundaryNode(call, scope)) return null; + const expression = call.expression; + if (!ts.isPropertyAccessExpression(expression)) return null; + if (!["on", "once", "addListener"].includes(expression.name.text)) return null; + if (expressionPath(expression.expression) !== childBinding) return null; + const event = call.arguments[0]; + if (!event || !ts.isStringLiteralLike(event) || event.text !== "error") return null; + return inlineCallback(call.arguments[1]); +} + +function childSpawnListener( + call: ts.CallExpression, + childBinding: string, + scope: ts.Node, +): ts.ArrowFunction | ts.FunctionExpression | null { + if (!isUnconditionalBoundaryNode(call, scope)) return null; + const expression = call.expression; + if (!ts.isPropertyAccessExpression(expression)) return null; + if (!["on", "once", "addListener"].includes(expression.name.text)) return null; + if (expressionPath(expression.expression) !== childBinding) return null; + const event = call.arguments[0]; + if (!event || !ts.isStringLiteralLike(event) || event.text !== "spawn") return null; + return inlineCallback(call.arguments[1]); +} + +function callInvokesIdentifier( + call: ts.CallExpression | null, + identifiers: ReadonlySet, + argument?: string, +): boolean { + if (!call || !ts.isIdentifier(call.expression) || !identifiers.has(call.expression.text)) { + return false; + } + if (argument === undefined) return call.arguments.length === 0; + return ( + call.arguments.length === 1 && + ts.isStringLiteralLike(call.arguments[0] as ts.Expression) && + (call.arguments[0] as ts.StringLiteralLike).text === argument + ); +} + +function closeTerminalOutcome( + expression: ts.Expression, + codeBinding: string, + signalBinding: string, + launchFailedBinding: string, +): boolean { + const launchFailed = unwrapExpression(expression); + if ( + !ts.isConditionalExpression(launchFailed) || + expressionPath(launchFailed.condition) !== launchFailedBinding || + !ts.isStringLiteralLike(launchFailed.whenTrue) || + launchFailed.whenTrue.text !== "spawn-failed" + ) { + return false; + } + + const signaled = unwrapExpression(launchFailed.whenFalse); + if (!ts.isConditionalExpression(signaled)) return false; + if ( + !ts.isBinaryExpression(signaled.condition) || + signaled.condition.operatorToken.kind !== ts.SyntaxKind.ExclamationEqualsEqualsToken || + expressionPath(signaled.condition.left) !== signalBinding || + signaled.condition.right.kind !== ts.SyntaxKind.NullKeyword || + !ts.isStringLiteralLike(signaled.whenTrue) || + signaled.whenTrue.text !== "signaled" + ) { + return false; + } + + const exitedZero = unwrapExpression(signaled.whenFalse); + if ( + !ts.isConditionalExpression(exitedZero) || + !ts.isBinaryExpression(exitedZero.condition) || + exitedZero.condition.operatorToken.kind !== ts.SyntaxKind.EqualsEqualsEqualsToken || + expressionPath(exitedZero.condition.left) !== codeBinding || + !ts.isNumericLiteral(exitedZero.condition.right) || + exitedZero.condition.right.text !== "0" || + !ts.isStringLiteralLike(exitedZero.whenTrue) || + exitedZero.whenTrue.text !== "exited-zero" + ) { + return false; + } + + const unknown = unwrapExpression(exitedZero.whenFalse); + return ( + ts.isConditionalExpression(unknown) && + ts.isBinaryExpression(unknown.condition) && + unknown.condition.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken && + expressionPath(unknown.condition.left) === codeBinding && + unknown.condition.right.kind === ts.SyntaxKind.NullKeyword && + ts.isStringLiteralLike(unknown.whenTrue) && + unknown.whenTrue.text === "closed-unknown" && + ts.isStringLiteralLike(unknown.whenFalse) && + unknown.whenFalse.text === "exited-nonzero" + ); +} + +function closeCallbackEvidence( + callback: ts.ArrowFunction | ts.FunctionExpression, + activityHandles: ReadonlySet, + lifecycleHandles: ReadonlySet, + launchFailedBinding: string, +): { finishesActivity: boolean; reportsLifecycle: boolean } { + if ( + callback.parameters.length !== 2 || + !ts.isIdentifier(callback.parameters[0]?.name) || + !ts.isIdentifier(callback.parameters[1]?.name) || + !ts.isBlock(callback.body) || + callback.body.statements.length !== 2 + ) { + return { finishesActivity: false, reportsLifecycle: false }; + } + const activityCall = protectedCallFromStatement(callback.body.statements[0] as ts.Statement); + const terminalCall = protectedCallFromStatement(callback.body.statements[1] as ts.Statement); + return { + finishesActivity: callInvokesIdentifier(activityCall, activityHandles), + reportsLifecycle: + !!terminalCall && + ts.isIdentifier(terminalCall.expression) && + lifecycleHandles.has(terminalCall.expression.text) && + terminalCall.arguments.length === 1 && + closeTerminalOutcome( + terminalCall.arguments[0] as ts.Expression, + callback.parameters[0].name.text, + callback.parameters[1].name.text, + launchFailedBinding, + ), + }; +} + +function spawnConfirmationBinding( + callback: ts.ArrowFunction | ts.FunctionExpression, +): string | null { + if ( + callback.parameters.length !== 0 || + !ts.isBlock(callback.body) || + callback.body.statements.length !== 1 + ) { + return null; + } + const statement = callback.body.statements[0]; + if (!statement || !ts.isExpressionStatement(statement)) return null; + const assignment = unwrapExpression(statement.expression); + return ts.isBinaryExpression(assignment) && + assignment.operatorToken.kind === ts.SyntaxKind.EqualsToken && + ts.isIdentifier(assignment.left) && + assignment.right.kind === ts.SyntaxKind.TrueKeyword + ? assignment.left.text + : null; +} + +function launchFailureBindings( + callback: ts.ArrowFunction | ts.FunctionExpression, +): { launchFailed: string; spawned: string } | null { + if ( + callback.parameters.length !== 0 || + !ts.isBlock(callback.body) || + callback.body.statements.length !== 1 + ) { + return null; + } + const statement = callback.body.statements[0]; + if ( + !statement || + !ts.isIfStatement(statement) || + statement.elseStatement || + !ts.isPrefixUnaryExpression(statement.expression) || + statement.expression.operator !== ts.SyntaxKind.ExclamationToken || + !ts.isIdentifier(statement.expression.operand) + ) { + return null; + } + const assignmentStatement = ts.isBlock(statement.thenStatement) + ? statement.thenStatement.statements.length === 1 + ? statement.thenStatement.statements[0] + : undefined + : statement.thenStatement; + if (!assignmentStatement || !ts.isExpressionStatement(assignmentStatement)) return null; + const assignment = unwrapExpression(assignmentStatement.expression); + if ( + !ts.isBinaryExpression(assignment) || + assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken || + !ts.isIdentifier(assignment.left) || + assignment.right.kind !== ts.SyntaxKind.TrueKeyword + ) { + return null; + } + return { + launchFailed: assignment.left.text, + spawned: statement.expression.operand.text, + }; +} + +function hasSingleFalseBooleanBinding(scope: ts.Node, binding: string): boolean { + let declarations = 0; + function inspect(node: ts.Node): void { + if (node !== scope && ts.isFunctionLike(node)) return; + if ( + ts.isVariableDeclaration(node) && + ts.isIdentifier(node.name) && + node.name.text === binding && + node.initializer?.kind === ts.SyntaxKind.FalseKeyword + ) { + declarations += 1; + } + ts.forEachChild(node, inspect); + } + inspect(scope); + return declarations === 1; +} + +function syncSpawnFailureEvidence( + node: ts.CallExpression, + activityHandles: ReadonlySet, + lifecycleHandles: ReadonlySet, +): { finishesActivity: boolean; reportsLifecycle: boolean } { + let current: ts.Node | undefined = node; + while (current && !ts.isTryStatement(current)) current = current.parent; + const catchClause = current && ts.isTryStatement(current) ? current.catchClause : undefined; + const catchBinding = catchClause?.variableDeclaration?.name; + const statements = catchClause?.block.statements; + if ( + !catchClause || + !catchBinding || + !ts.isIdentifier(catchBinding) || + !statements || + statements.length !== 3 + ) { + return { finishesActivity: false, reportsLifecycle: false }; + } + const activityCall = protectedCallFromStatement(statements[0] as ts.Statement); + const lifecycleCall = protectedCallFromStatement(statements[1] as ts.Statement); + const thrown = statements[2]; + if ( + !thrown || + !ts.isThrowStatement(thrown) || + !thrown.expression || + expressionPath(thrown.expression) !== catchBinding.text + ) { + return { finishesActivity: false, reportsLifecycle: false }; + } + return { + finishesActivity: callInvokesIdentifier(activityCall, activityHandles), + reportsLifecycle: callInvokesIdentifier(lifecycleCall, lifecycleHandles, "spawn-failed"), + }; +} + function exactTimestampOutputCall(node: ts.CallExpression, stream: "stdout" | "stderr"): boolean { if ( !ts.isPropertyAccessExpression(node.expression) || @@ -1015,18 +1259,27 @@ function childOutputListener( function observedChildProcessEvidence( node: ts.CallExpression, sourceFile: ts.SourceFile, -): { observesOutput: boolean; tracksActivity: boolean } { +): { observesOutput: boolean; tracksActivity: boolean; tracksLifecycle: boolean } { const scope = childProcessObservationScope(node, sourceFile); const childBinding = childBindingForCall(node, scope); if (!childBinding || !isUnconditionalBoundaryNode(node, scope)) { - return { observesOutput: false, tracksActivity: false }; + return { observesOutput: false, tracksActivity: false, tracksLifecycle: false }; } const observedChildBinding = childBinding; const activityHandles = new Set(); - let lifecycleListeners = 0; - let validLifecycleListeners = 0; + const lifecycleHandles = new Set(); + let closeListeners = 0; + let validActivityCloseListeners = 0; + let validLifecycleCloseListeners = 0; + let spawnListeners = 0; + let validSpawnListeners = 0; + let errorListeners = 0; + let validLaunchFailureListeners = 0; + let spawnedBinding: string | null = null; + let launchFailedBinding: string | null = null; let childBindingReassigned = false; let activityHandleReassigned = false; + let lifecycleHandleReassigned = false; let unsafeChildOperation = false; const outputListeners = new Map<"stdout" | "stderr", number>([ ["stdout", 0], @@ -1048,6 +1301,7 @@ function observedChildProcessEvidence( ) { if (candidate.left.text === observedChildBinding) childBindingReassigned = true; if (activityHandles.has(candidate.left.text)) activityHandleReassigned = true; + if (lifecycleHandles.has(candidate.left.text)) lifecycleHandleReassigned = true; } if ( candidate.getStart(sourceFile) > node.getStart(sourceFile) && @@ -1072,14 +1326,48 @@ function observedChildProcessEvidence( const handle = assignedIdentifierForCall(candidate, scope); if (handle) activityHandles.add(handle); } + if ( + candidate.getStart(sourceFile) < node.getStart(sourceFile) && + isUnconditionalBoundaryNode(candidate, scope) && + candidate.arguments.length === 0 && + expressionPath(candidate.expression) === "options.progress.beginChildLifecycle" + ) { + const handle = assignedIdentifierForCall(candidate, scope); + if (handle) lifecycleHandles.add(handle); + } if (candidate.getStart(sourceFile) > node.getStart(sourceFile)) { - const lifecycle = childLifecycleListener(candidate, observedChildBinding, scope); - if (lifecycle) { - lifecycleListeners += 1; - if (callbackInvokesIdentifier(lifecycle, activityHandles)) { - validLifecycleListeners += 1; + const spawnListener = childSpawnListener(candidate, observedChildBinding, scope); + if (spawnListener) { + spawnListeners += 1; + const binding = spawnConfirmationBinding(spawnListener); + if (binding) { + validSpawnListeners += 1; + spawnedBinding = binding; } } + const errorListener = childLaunchErrorListener(candidate, observedChildBinding, scope); + if (errorListener) { + errorListeners += 1; + const bindings = launchFailureBindings(errorListener); + if (bindings && bindings.spawned === spawnedBinding) { + validLaunchFailureListeners += 1; + launchFailedBinding = bindings.launchFailed; + } + } + const closeListener = childLifecycleListener(candidate, observedChildBinding, scope); + if (closeListener) { + closeListeners += 1; + const evidence = launchFailedBinding + ? closeCallbackEvidence( + closeListener, + activityHandles, + lifecycleHandles, + launchFailedBinding, + ) + : { finishesActivity: false, reportsLifecycle: false }; + if (evidence.finishesActivity) validActivityCloseListeners += 1; + if (evidence.reportsLifecycle) validLifecycleCloseListeners += 1; + } for (const stream of ["stdout", "stderr"] as const) { const callback = childOutputListener(candidate, observedChildBinding, stream, scope); if (callback) { @@ -1104,7 +1392,9 @@ function observedChildProcessEvidence( const callPath = expressionPath(candidate.expression); if ( callPath?.startsWith(`${observedChildBinding}.`) && - !lifecycle && + !closeListener && + !errorListener && + !spawnListener && !(["stdout", "stderr"] as const).some((stream) => childOutputListener(candidate, observedChildBinding, stream, scope), ) @@ -1116,6 +1406,7 @@ function observedChildProcessEvidence( ts.forEachChild(candidate, inspect); } inspect(scope); + const synchronousFailure = syncSpawnFailureEvidence(node, activityHandles, lifecycleHandles); return { observesOutput: !childBindingReassigned && @@ -1129,8 +1420,25 @@ function observedChildProcessEvidence( !activityHandleReassigned && !unsafeChildOperation && activityHandles.size === 1 && - lifecycleListeners === 1 && - validLifecycleListeners === 1, + closeListeners === 1 && + validActivityCloseListeners === 1 && + synchronousFailure.finishesActivity, + tracksLifecycle: + !childBindingReassigned && + !lifecycleHandleReassigned && + !unsafeChildOperation && + lifecycleHandles.size === 1 && + spawnListeners === 1 && + validSpawnListeners === 1 && + !!spawnedBinding && + hasSingleFalseBooleanBinding(scope, spawnedBinding) && + closeListeners === 1 && + validLifecycleCloseListeners === 1 && + errorListeners === 1 && + validLaunchFailureListeners === 1 && + !!launchFailedBinding && + hasSingleFalseBooleanBinding(scope, launchFailedBinding) && + synchronousFailure.reportsLifecycle, }; } @@ -1468,12 +1776,86 @@ function auditTestProgressCapabilityContract( "TestProgress must retain the private progress capability", ); } + const childLifecycleMember = progressInterface?.members.find( + (member) => propertyNameText(member.name) === "beginChildLifecycle", + ); + const validChildLifecycleMember = + !!childLifecycleMember && + ts.isPropertySignature(childLifecycleMember) && + !childLifecycleMember.questionToken && + !!childLifecycleMember.type && + ts.isFunctionTypeNode(childLifecycleMember.type) && + childLifecycleMember.type.parameters.length === 0 && + ts.isTypeReferenceNode(childLifecycleMember.type.type) && + ts.isIdentifier(childLifecycleMember.type.type.typeName) && + childLifecycleMember.type.type.typeName.text === "ChildLifecycleTerminalReporter"; + if (!validChildLifecycleMember) { + reportUnsupported( + childLifecycleMember ?? progressInterface ?? sourceFile, + "TestProgress must expose the non-optional zero-argument child lifecycle capability", + ); + } + + const outcomeType = sourceFile.statements.find( + (statement): statement is ts.TypeAliasDeclaration => + ts.isTypeAliasDeclaration(statement) && statement.name.text === "ChildLifecycleOutcome", + ); + const lifecycleOutcomes = + outcomeType && ts.isUnionTypeNode(outcomeType.type) + ? outcomeType.type.types + .filter( + (type): type is ts.LiteralTypeNode => + ts.isLiteralTypeNode(type) && ts.isStringLiteralLike(type.literal), + ) + .map((type) => (type.literal as ts.StringLiteralLike).text) + .sort() + : []; + const expectedLifecycleOutcomes = [ + "closed-unknown", + "exited-nonzero", + "exited-zero", + "signaled", + "spawn-failed", + ]; + if ( + !outcomeType || + !ts.isUnionTypeNode(outcomeType.type) || + outcomeType.type.types.length !== expectedLifecycleOutcomes.length || + JSON.stringify(lifecycleOutcomes) !== JSON.stringify(expectedLifecycleOutcomes) + ) { + reportUnsupported( + outcomeType ?? sourceFile, + "ChildLifecycleOutcome must remain the fixed content-free terminal vocabulary", + ); + } + + const reporterType = sourceFile.statements.find( + (statement): statement is ts.TypeAliasDeclaration => + ts.isTypeAliasDeclaration(statement) && + statement.name.text === "ChildLifecycleTerminalReporter", + ); + const validReporterType = + !!reporterType && + ts.isFunctionTypeNode(reporterType.type) && + reporterType.type.parameters.length === 1 && + !!reporterType.type.parameters[0]?.type && + ts.isTypeReferenceNode(reporterType.type.parameters[0].type) && + ts.isIdentifier(reporterType.type.parameters[0].type.typeName) && + reporterType.type.parameters[0].type.typeName.text === "ChildLifecycleOutcome" && + reporterType.type.type.kind === ts.SyntaxKind.VoidKeyword; + if (!validReporterType) { + reportUnsupported( + reporterType ?? sourceFile, + "ChildLifecycleTerminalReporter must accept only one fixed lifecycle outcome", + ); + } const factory = sourceFile.statements.find( (statement): statement is ts.FunctionDeclaration => ts.isFunctionDeclaration(statement) && statement.name?.text === "startTestProgress", ); let initializesBrand = false; + let childLifecycleImplementation: ts.MethodDeclaration | undefined; if (factory) { function inspectFactory(node: ts.Node): void { if ( @@ -1485,6 +1867,9 @@ function auditTestProgressCapabilityContract( ) { initializesBrand = true; } + if (ts.isMethodDeclaration(node) && propertyNameText(node.name) === "beginChildLifecycle") { + childLifecycleImplementation = node; + } ts.forEachChild(node, inspectFactory); } inspectFactory(factory); @@ -1508,6 +1893,89 @@ function auditTestProgressCapabilityContract( "startTestProgress must privately brand, register, and freeze the canonical capability", ); } + let frozenLifecycleReporterReturns = 0; + let logsSynchronousLifecycleStart = false; + let hasIdempotentLifecycleTerminal = false; + if (childLifecycleImplementation) { + function inspectChildLifecycle(node: ts.Node): void { + if (node !== childLifecycleImplementation && ts.isFunctionLike(node)) return; + if ( + ts.isReturnStatement(node) && + node.expression && + ts.isCallExpression(node.expression) && + expressionPath(node.expression.expression) === "Object.freeze" && + node.expression.arguments.length === 1 + ) { + frozenLifecycleReporterReturns += 1; + } + if ( + ts.isCallExpression(node) && + expressionPath(node.expression) === "logChildLifecycleBestEffort" && + node.arguments.length === 2 && + ts.isStringLiteralLike(node.arguments[1] as ts.Expression) && + (node.arguments[1] as ts.StringLiteralLike).text === "started" + ) { + logsSynchronousLifecycleStart = true; + } + ts.forEachChild(node, inspectChildLifecycle); + } + inspectChildLifecycle(childLifecycleImplementation); + + const methodStatements = childLifecycleImplementation.body?.statements ?? []; + const methodDeclarations: ts.VariableDeclaration[] = []; + for (const statement of methodStatements) { + if (ts.isVariableStatement(statement)) { + methodDeclarations.push(...statement.declarationList.declarations); + } + } + const terminalFlag = methodDeclarations.find( + (declaration) => + ts.isIdentifier(declaration.name) && + declaration.initializer?.kind === ts.SyntaxKind.FalseKeyword, + ); + const terminalReporter = methodDeclarations.find( + (declaration) => declaration.initializer && ts.isArrowFunction(declaration.initializer), + ); + const terminalFlagName = + terminalFlag && ts.isIdentifier(terminalFlag.name) ? terminalFlag.name.text : null; + if ( + terminalFlagName && + terminalReporter?.initializer && + ts.isArrowFunction(terminalReporter.initializer) && + ts.isBlock(terminalReporter.initializer.body) + ) { + const reporterStatements: readonly ts.Statement[] = + terminalReporter.initializer.body.statements; + const guard = reporterStatements[0]; + const assignments = reporterStatements.filter( + (statement) => + ts.isExpressionStatement(statement) && + ts.isBinaryExpression(statement.expression) && + statement.expression.operatorToken.kind === ts.SyntaxKind.EqualsToken && + expressionPath(statement.expression.left) === terminalFlagName && + statement.expression.right.kind === ts.SyntaxKind.TrueKeyword, + ); + hasIdempotentLifecycleTerminal = + !!guard && + ts.isIfStatement(guard) && + expressionPath(guard.expression) === terminalFlagName && + ts.isReturnStatement(guard.thenStatement) && + !guard.thenStatement.expression && + assignments.length === 1; + } + } + if ( + !childLifecycleImplementation || + childLifecycleImplementation.parameters.length !== 0 || + frozenLifecycleReporterReturns !== 2 || + !logsSynchronousLifecycleStart || + !hasIdempotentLifecycleTerminal + ) { + reportUnsupported( + childLifecycleImplementation ?? factory ?? sourceFile, + "startTestProgress must synchronously start and freeze idempotent child lifecycle reporters", + ); + } } if (file === OBSERVED_CHILD_PROCESS_MODULE) { @@ -1692,7 +2160,7 @@ function collectDirectChildProcessCalls( const evidence = boundaryId === AUDITED_ASYNC_CHILD_PROCESS_BOUNDARY ? observedChildProcessEvidence(node, sourceFile) - : { observesOutput: false, tracksActivity: false }; + : { observesOutput: false, tracksActivity: false, tracksLifecycle: false }; const location = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)); calls.push({ api: apiProvenance.api, @@ -1704,6 +2172,7 @@ function collectDirectChildProcessCalls( observesOutput: evidence.observesOutput, outputIgnored: ignoresChildOutput(options), tracksActivity: evidence.tracksActivity, + tracksLifecycle: evidence.tracksLifecycle, }); } const wrapperCreation = isChildProcessWrapperCreation(node, bindings); @@ -1751,6 +2220,22 @@ function collectDirectChildProcessCalls( if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { const receiver = expressionProvenance(node.expression, bindings); const name = memberName(node); + if (name === "beginChildLifecycle") { + const invocation = + ts.isCallExpression(node.parent) && node.parent.expression === node ? node.parent : null; + const isCanonicalBoundaryUse = + file === OBSERVED_CHILD_PROCESS_MODULE && + !!invocation && + invocation.arguments.length === 0 && + childProcessBoundaryName(invocation, sourceFile) === "spawnObservedChild"; + const isSupportOnlyUse = relativeFile.startsWith("test/e2e/support/"); + if (!isCanonicalBoundaryUse && !isSupportOnlyUse && file !== TEST_PROGRESS_MODULE) { + reportUnsupported( + node, + "beginChildLifecycle is reserved for the canonical observed-child boundary", + ); + } + } if ( receiver?.kind === "namespace" && name !== null && @@ -1769,6 +2254,22 @@ function collectDirectChildProcessCalls( ); } } + if (ts.isBindingElement(node)) { + const boundName = + propertyNameText(node.propertyName) ?? + (ts.isIdentifier(node.name) ? node.name.text : undefined); + if ( + boundName === "beginChildLifecycle" && + file !== OBSERVED_CHILD_PROCESS_MODULE && + file !== TEST_PROGRESS_MODULE && + !relativeFile.startsWith("test/e2e/support/") + ) { + reportUnsupported( + node, + "beginChildLifecycle is reserved for the canonical observed-child boundary", + ); + } + } if ( ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name) && @@ -2106,6 +2607,11 @@ function validateDirectChildProcessCalls(calls: readonly DirectChildProcessCall[ `${call.file}:${call.line}: audited child-process boundary must register a content-free progress activity`, ); } + if (!call.tracksLifecycle) { + failures.push( + `${call.file}:${call.line}: audited child-process boundary must emit canonical content-free lifecycle checkpoints`, + ); + } if (!call.outputIgnored && !call.observesOutput) { failures.push( `${call.file}:${call.line}: audited child-process boundary with child output must forward timestamp-only output observations`, From dca2cde977eb1513e40d472ae2a7c1023fbd24a5 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Thu, 23 Jul 2026 08:31:25 -0700 Subject: [PATCH 03/10] test(e2e): bound gateway health deadline Signed-off-by: Apurv Kumaria --- test/e2e/live/gateway-health-honest.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/e2e/live/gateway-health-honest.test.ts b/test/e2e/live/gateway-health-honest.test.ts index b82baceaf28..7635759e533 100644 --- a/test/e2e/live/gateway-health-honest.test.ts +++ b/test/e2e/live/gateway-health-honest.test.ts @@ -22,6 +22,7 @@ import { expect, test } from "../fixtures/e2e-test.ts"; import { REPO_ROOT } from "../fixtures/paths.ts"; const GATEWAY_NAME = "nemoclaw-18080"; +const LIVE_TIMEOUT_MS = 10 * 60_000; function gatewayStateDir(): string { return path.join(os.homedir(), ".local", "state", "nemoclaw", "openshell-docker-gateway-18080"); @@ -34,6 +35,7 @@ function writeExecutable(file: string, content: string): void { } test("onboard surfaces crashed Docker-driver gateway instead of reporting healthy (#3111)", { + timeout: LIVE_TIMEOUT_MS, meta: { e2ePhases: [ "stage crashed Docker gateway fixture", From 2037432a19bef04fc7b17f81c5150474a81de861 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Thu, 23 Jul 2026 08:34:12 -0700 Subject: [PATCH 04/10] test(e2e): bound credential-free deadlines Signed-off-by: Apurv Kumaria --- test/e2e/live/onboard-negative-paths.test.ts | 2 ++ test/e2e/live/openshell-version-pin.test.ts | 4 ++++ test/e2e/live/ubuntu-repo-cli-smoke.test.ts | 3 +++ 3 files changed, 9 insertions(+) diff --git a/test/e2e/live/onboard-negative-paths.test.ts b/test/e2e/live/onboard-negative-paths.test.ts index 0b9f89201d7..23d38b5cb41 100644 --- a/test/e2e/live/onboard-negative-paths.test.ts +++ b/test/e2e/live/onboard-negative-paths.test.ts @@ -18,6 +18,7 @@ import { CLI_DIST_ENTRYPOINT, CLI_ENTRYPOINT } from "../fixtures/paths.ts"; const SESSION_FILE = path.join(process.env.HOME ?? "/tmp", ".nemoclaw", "onboard-session.json"); const INVALID_NVIDIA_INFERENCE_API_KEY = "not-a-nvidia-key"; const STACK_TRACE_PATTERNS = [/(^|\s)(TypeError|ReferenceError|SyntaxError):/m, /^\s+at /m]; +const LIVE_TIMEOUT_MS = 10 * 60_000; process.env.NEMOCLAW_CLI_BIN ??= CLI_ENTRYPOINT; @@ -69,6 +70,7 @@ async function cleanupInvalidKeyState(host: HostCliClient, sandboxName: string): } test("onboard invalid NVIDIA key exits cleanly without a stack trace", { + timeout: LIVE_TIMEOUT_MS, meta: { e2ePhases: [ "confirm Docker and built CLI prerequisites", diff --git a/test/e2e/live/openshell-version-pin.test.ts b/test/e2e/live/openshell-version-pin.test.ts index 6b996e02953..da4b28ccbdc 100644 --- a/test/e2e/live/openshell-version-pin.test.ts +++ b/test/e2e/live/openshell-version-pin.test.ts @@ -22,8 +22,10 @@ import { REPO_ROOT } from "../fixtures/paths.ts"; // fixture from e2e-test.ts so failures attach the per-target artifact root. const INSTALL_SCRIPT = path.join(REPO_ROOT, "scripts", "install-openshell.sh"); +const LIVE_TIMEOUT_MS = 2 * 60_000; test("openshell-version-pin: selects shipping 0.0.85 between older and too-new releases", { + timeout: LIVE_TIMEOUT_MS, meta: { e2ePhases: [ "prepare a mixed OpenShell release catalog", @@ -425,6 +427,7 @@ async function runVersionPinTarget( } test("openshell-version-pin: replaces sticky too-new openshell with pinned 0.0.85 via gh download", { + timeout: LIVE_TIMEOUT_MS, meta: { e2ePhases: [ "stage a too-new OpenShell installation", @@ -440,6 +443,7 @@ test("openshell-version-pin: replaces sticky too-new openshell with pinned 0.0.8 }); test("openshell-version-pin: falls back to curl when gh cannot fetch the pinned release", { + timeout: LIVE_TIMEOUT_MS, meta: { e2ePhases: [ "stage a too-new OpenShell installation", diff --git a/test/e2e/live/ubuntu-repo-cli-smoke.test.ts b/test/e2e/live/ubuntu-repo-cli-smoke.test.ts index 09f016441d4..eb368877819 100644 --- a/test/e2e/live/ubuntu-repo-cli-smoke.test.ts +++ b/test/e2e/live/ubuntu-repo-cli-smoke.test.ts @@ -8,7 +8,10 @@ import path from "node:path"; import { expect, test } from "../fixtures/e2e-test.ts"; import { CLI_DIST_ENTRYPOINT, REPO_ROOT } from "../fixtures/paths.ts"; +const LIVE_TIMEOUT_MS = 2 * 60_000; + test("ubuntu repo cli smoke", { + timeout: LIVE_TIMEOUT_MS, meta: { e2ePhases: [ "confirm the compiled NemoClaw CLI is available", From 9db3620547e72c774b95757651896a90a4cc5fa2 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Thu, 23 Jul 2026 08:36:40 -0700 Subject: [PATCH 05/10] test(e2e): fit Hermes rebuild within job deadline Signed-off-by: Apurv Kumaria --- test/e2e/live/rebuild-hermes.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/e2e/live/rebuild-hermes.test.ts b/test/e2e/live/rebuild-hermes.test.ts index 786f888966a..7b2a55917b3 100644 --- a/test/e2e/live/rebuild-hermes.test.ts +++ b/test/e2e/live/rebuild-hermes.test.ts @@ -131,7 +131,7 @@ const DOCKER_PULL_TIMEOUT_MS = 20 * 60_000; const OPENSHELL_TIMEOUT_MS = 2 * 60_000; const SANDBOX_CREATE_TIMEOUT_MS = 10 * 60_000; const REBUILD_TIMEOUT_MS = 45 * 60_000; -const LIVE_TIMEOUT_MS = 100 * 60_000; +const LIVE_TIMEOUT_MS = 70 * 60_000; // Long Docker and onboard commands can become noisy when they wedge. Keep a // generous diagnostic tail without letting a stuck child exhaust the hosted // runner by growing the fixture's in-memory stdout/stderr buffers forever. From cd5c91b2c80b8ddb03813450c7370214503f9158 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Thu, 23 Jul 2026 08:40:17 -0700 Subject: [PATCH 06/10] test(e2e): stabilize credential-free discovery Signed-off-by: Apurv Kumaria --- .../shared-e2e-workflow-boundary.test.ts | 39 +++++++++++-------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/test/e2e/support/shared-e2e-workflow-boundary.test.ts b/test/e2e/support/shared-e2e-workflow-boundary.test.ts index 8851f86d623..604785dbc61 100644 --- a/test/e2e/support/shared-e2e-workflow-boundary.test.ts +++ b/test/e2e/support/shared-e2e-workflow-boundary.test.ts @@ -14,6 +14,7 @@ import { } from "../../../tools/e2e/credential-free-tests.mts"; import { validateE2eWorkflowBoundary } from "../../../tools/e2e/workflow-boundary.mts"; import { readWorkflow } from "../../helpers/e2e-workflow-contract"; +import { testTimeoutOptions } from "../../helpers/timeouts"; type Workflow = { jobs: Record< @@ -40,24 +41,28 @@ function validateMutatedWorkflow(mutator: (workflow: Workflow) => void): string[ } describe("shared E2E workflow boundary", () => { - it("keeps every tagged credential-free test visible to Vitest discovery", () => { - const declaredFiles = fs - .globSync(["**/*.test.js", "**/*.test.ts"], { - cwd: process.cwd(), - exclude: ["**/dist/**", "**/node_modules/**"], - }) - .filter((file) => { - const source = fs.readFileSync(path.join(process.cwd(), file), "utf8"); - return stripCredentialFreeTestDeclarations(source) !== source; - }) - .sort(); + it( + "keeps every tagged credential-free test visible to Vitest discovery", + testTimeoutOptions(15_000), + () => { + const declaredFiles = fs + .globSync(["**/*.test.js", "**/*.test.ts"], { + cwd: process.cwd(), + exclude: ["**/dist/**", "**/node_modules/**"], + }) + .filter((file) => { + const source = fs.readFileSync(path.join(process.cwd(), file), "utf8"); + return stripCredentialFreeTestDeclarations(source) !== source; + }) + .sort(); - expect( - discoverCredentialFreeTests() - .map(({ file }) => file) - .sort(), - ).toEqual(declaredFiles); - }); + expect( + discoverCredentialFreeTests() + .map(({ file }) => file) + .sort(), + ).toEqual(declaredFiles); + }, + ); it("ratchets shared setup, tagged test execution, and aggregation", () => { const errors = validateMutatedWorkflow((workflow) => { From 8b3fb1fa27b0c680ada1b6386a8d9c0eb72bddea Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Thu, 23 Jul 2026 12:12:49 -0700 Subject: [PATCH 07/10] fix(ci): retry exit-143 hosted runner shutdowns Signed-off-by: Apurv Kumaria --- ...pr-e2e-gate-runner-loss-classifier.test.ts | 132 ++++++++++++++++++ test/pr-e2e-gate-runner-loss-retry.test.ts | 56 ++++++-- tools/e2e/pr-e2e-gate.mts | 121 +++++++++++----- 3 files changed, 262 insertions(+), 47 deletions(-) diff --git a/test/pr-e2e-gate-runner-loss-classifier.test.ts b/test/pr-e2e-gate-runner-loss-classifier.test.ts index c5275e183ec..2647336ee33 100644 --- a/test/pr-e2e-gate-runner-loss-classifier.test.ts +++ b/test/pr-e2e-gate-runner-loss-classifier.test.ts @@ -10,6 +10,7 @@ const RUNNER_LOSS_MESSAGE = "The hosted runner lost communication with the server. Anything in your workflow that terminates the runner process, starves it for CPU/Memory, or blocks its network access can cause this error."; const RUNNER_SHUTDOWN_MESSAGE = "The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled."; +const EXIT_143_MESSAGE = "Process completed with exit code 143."; const JOB_STARTED_AT = "2026-07-23T07:26:56Z"; const CANCELLED_STEP_STARTED_AT = "2026-07-23T07:27:43Z"; const CANCELLED_STEP_COMPLETED_AT = "2026-07-23T07:32:49Z"; @@ -39,6 +40,14 @@ function genericCancellationAnnotation() { }; } +function exit143Annotation(message = EXIT_143_MESSAGE) { + return { + ...runnerLossAnnotation(message), + startLine: 34, + endLine: 34, + }; +} + function orphanProcessLogLine(index: number, pid = index + 1, processName = `node-${pid}`) { return `2026-07-23T07:32:50.${String(1_000_000 + index).padStart( 7, @@ -64,6 +73,16 @@ function runnerShutdownLogEvidence(tail = runnerShutdownLogTail()) { }; } +function exit143ShutdownLogTail() { + return [ + `2026-07-23T17:08:00.1259536Z ##[error]${RUNNER_SHUTDOWN_MESSAGE}`, + `2026-07-23T17:08:00.1346243Z ##[error]${EXIT_143_MESSAGE}`, + "2026-07-23T17:08:00.7221761Z Cleaning up orphan processes", + "2026-07-23T17:08:00.7978522Z Terminate orphan process: pid (2509) (node)", + "", + ].join("\n"); +} + function hostedRunnerLossJob(overrides: Record = {}) { return { id: 89_074_697_099, @@ -133,6 +152,66 @@ function legacyHostedRunnerLossJob(id: number, runnerId: number) { }); } +function exit143HostedRunnerLossJob(overrides: Record = {}) { + const tail = exit143ShutdownLogTail(); + return hostedRunnerLossJob({ + id: 89_271_065_810, + name: "security-posture (hermes, e2e-hermes-security-posture)", + runnerId: 1_021_384_642, + runnerName: "GitHub Actions 1021384642", + startedAt: "2026-07-23T16:41:05Z", + completedAt: "2026-07-23T17:08:02Z", + annotations: [ + exit143Annotation(), + { + ...runnerLossAnnotation("Docker Hub credentials are withheld for this ref."), + startLine: 53, + endLine: 53, + annotationLevel: "notice", + }, + ], + logEvidence: runnerShutdownLogEvidence(tail), + steps: [ + { + name: "Set up job", + status: "completed", + conclusion: "success", + startedAt: "2026-07-23T16:41:06Z", + completedAt: "2026-07-23T16:41:15Z", + }, + { + name: "Run security posture live Vitest test", + status: "completed", + conclusion: "failure", + startedAt: "2026-07-23T16:41:51Z", + completedAt: "2026-07-23T17:08:00Z", + }, + { + name: "Upload security posture artifacts", + status: "completed", + conclusion: "skipped", + startedAt: "2026-07-23T17:08:00Z", + completedAt: "2026-07-23T17:08:00Z", + }, + { + name: "Clean up Docker auth", + status: "completed", + conclusion: "skipped", + startedAt: "2026-07-23T17:08:00Z", + completedAt: "2026-07-23T17:08:00Z", + }, + { + name: "Complete job", + status: "completed", + conclusion: "success", + startedAt: "2026-07-23T17:08:00Z", + completedAt: "2026-07-23T17:08:00Z", + }, + ], + ...overrides, + }); +} + function confirmsRunnerLoss( options: { workflowConclusion?: string; @@ -169,6 +248,10 @@ describe("PR E2E hosted-runner-loss classifier", () => { ).toBe(true); }); + it("accepts the exit-143 hosted shutdown from run 30026115852", () => { + expect(confirmsRunnerLoss({ jobs: [exit143HostedRunnerLossJob()] })).toBe(true); + }); + it("accepts a bounded orphan-process suffix after the terminal shutdown block", () => { expect( confirmsRunnerLoss({ @@ -290,6 +373,55 @@ describe("PR E2E hosted-runner-loss classifier", () => { ], }, }, + { + label: "an exit-143 failure has no preceding hosted-runner shutdown", + options: { + jobs: [ + exit143HostedRunnerLossJob({ + logEvidence: runnerShutdownLogEvidence( + `2026-07-23T17:08:00.1346243Z ##[error]${EXIT_143_MESSAGE}\n`, + ), + }), + ], + }, + }, + { + label: "a shutdown reports an exit code other than 143", + options: { + jobs: [ + exit143HostedRunnerLossJob({ + annotations: [exit143Annotation("Process completed with exit code 137.")], + logEvidence: runnerShutdownLogEvidence( + exit143ShutdownLogTail().replaceAll("exit code 143", "exit code 137"), + ), + }), + ], + }, + }, + { + label: "an exit-143 annotation accompanies a normal failed step", + options: { + jobs: [ + exit143HostedRunnerLossJob({ + logEvidence: undefined, + }), + ], + }, + }, + { + label: "the exit-143 terminal timestamp does not match the failed step", + options: { + jobs: [ + exit143HostedRunnerLossJob({ + steps: exit143HostedRunnerLossJob().steps.map((step) => + step.conclusion === "failure" + ? { ...step, completedAt: "2026-07-23T17:07:59Z" } + : step, + ), + }), + ], + }, + }, { label: "the shutdown log is followed by later output", options: { diff --git a/test/pr-e2e-gate-runner-loss-retry.test.ts b/test/pr-e2e-gate-runner-loss-retry.test.ts index 91f3b9ea368..a8384e3bbdf 100644 --- a/test/pr-e2e-gate-runner-loss-retry.test.ts +++ b/test/pr-e2e-gate-runner-loss-retry.test.ts @@ -34,6 +34,7 @@ const JOB_LOG_ETAG = '"hosted-runner-log"'; const JOB_LOG_RANGE_BYTES = 64 * 1024; const RUNNER_SHUTDOWN_MESSAGE = "The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled."; +const EXIT_143_MESSAGE = "Process completed with exit code 143."; afterEach(() => { vi.restoreAllMocks(); @@ -143,6 +144,16 @@ function hostedRunnerLossJob(runId = 23) { }; } +function exit143HostedRunnerLossJob(runId = 23) { + const job = hostedRunnerLossJob(runId); + return { + ...job, + steps: job.steps.map((step) => + step.conclusion === "cancelled" ? { ...step, conclusion: "failure" } : step, + ), + }; +} + function runnerLossAnnotation() { return { path: ".github", @@ -168,6 +179,15 @@ function genericCancellationAnnotation() { }; } +function exit143Annotation() { + return { + ...runnerLossAnnotation(), + start_line: 34, + end_line: 34, + message: EXIT_143_MESSAGE, + }; +} + function runnerShutdownJobLog() { return [ "x".repeat(JOB_LOG_RANGE_BYTES), @@ -178,6 +198,13 @@ function runnerShutdownJobLog() { ].join("\n"); } +function exit143ShutdownJobLog() { + return runnerShutdownJobLog().replace( + "##[error]The operation was canceled.", + `##[error]${EXIT_143_MESSAGE}`, + ); +} + type JobLogFixture = { body?: string; downloadUrl?: string; @@ -1074,7 +1101,20 @@ describe("PR E2E one-time hosted-runner-loss retry", () => { } }); - it("writes the retry authorization marker for an authenticated shutdown log", async () => { + it.each([ + { + label: "a cancelled workload", + job: hostedRunnerLossJob(), + annotation: genericCancellationAnnotation(), + log: runnerShutdownJobLog(), + }, + { + label: "an exit-143 failed workload", + job: exit143HostedRunnerLossJob(), + annotation: exit143Annotation(), + log: exit143ShutdownJobLog(), + }, + ])("writes the retry authorization marker for $label", async ({ job, annotation, log }) => { const context = setup(); const requests: RecordedGitHubRequest[] = []; const currentCheck = checkRun(17, { @@ -1097,20 +1137,18 @@ describe("PR E2E one-time hosted-runner-loss retry", () => { githubFetchRoute( ({ url, method }) => url.includes("/actions/runs/23/attempts/1/jobs?") && method === "GET", - () => githubResponse({ total_count: 1, jobs: [hostedRunnerLossJob()] }), + () => githubResponse({ total_count: 1, jobs: [job] }), ), githubFetchRoute( - ({ url, method }) => - url.endsWith(`/check-runs/${hostedRunnerLossJob().id}`) && method === "GET", - () => githubResponse(workflowJobCheckRun(hostedRunnerLossJob())), + ({ url, method }) => url.endsWith(`/check-runs/${job.id}`) && method === "GET", + () => githubResponse(workflowJobCheckRun(job)), ), githubFetchRoute( ({ url, method }) => - url.includes(`/check-runs/${hostedRunnerLossJob().id}/annotations?`) && - method === "GET", - () => githubResponse([genericCancellationAnnotation()]), + url.includes(`/check-runs/${job.id}/annotations?`) && method === "GET", + () => githubResponse([annotation]), ), - ...jobLogRoutes(), + ...jobLogRoutes({ body: log }), githubFetchRoute( ({ url, method }) => url.endsWith("/pulls/42") && method === "GET", () => githubResponse(pullRequest()), diff --git a/tools/e2e/pr-e2e-gate.mts b/tools/e2e/pr-e2e-gate.mts index 3a0e6fe6e38..73b6bdc8b45 100755 --- a/tools/e2e/pr-e2e-gate.mts +++ b/tools/e2e/pr-e2e-gate.mts @@ -91,6 +91,7 @@ const HOSTED_RUNNER_LOST_COMMUNICATION_MESSAGE = const HOSTED_RUNNER_SHUTDOWN_MESSAGE = "The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled."; const HOSTED_RUNNER_OPERATION_CANCELLED_MESSAGE = "The operation was canceled."; +const HOSTED_RUNNER_EXIT_143_MESSAGE = "Process completed with exit code 143."; const HOSTED_RUNNER_ORPHAN_CLEANUP_MESSAGE = "Cleaning up orphan processes"; const MAX_RUNNER_LOSS_JOB_INSPECTIONS = 20; const MAX_RUNNER_LOSS_JOB_LOG_TAIL_BYTES = 64 * 1024; @@ -301,9 +302,11 @@ type WorkflowJobLogEvidence = { }; type HostedRunnerShutdownLogMarker = { shutdownTimestamp: string; - operationTimestamp: string; + terminalTimestamp: string; cleanupTimestamp: string; lastTimestamp: string; + annotationMessage: string; + interruptedStepConclusion: "cancelled" | "failure"; }; type WorkflowJob = { id: number; @@ -2176,7 +2179,9 @@ async function listNonPassingWorkflowJobs( (job) => !["success", "skipped", "neutral"].includes(job.conclusion ?? ""), ); if (options.includeAnnotations) { - const runnerLossCandidates = nonPassingJobs.filter(hasTrustedHostedRunnerLossStepShape); + const runnerLossCandidates = nonPassingJobs.filter( + hasTrustedHostedRunnerLossInspectionStepShape, + ); if (runnerLossCandidates.length > MAX_RUNNER_LOSS_JOB_INSPECTIONS) { throw new Error("workflow run exceeded the hosted-runner-loss inspection limit"); } @@ -2191,7 +2196,18 @@ async function listNonPassingWorkflowJobs( const workflowSha = job.headSha ?? ""; if ( !hasTrustedHostedRunnerLossAnnotation(job, repository, workflowSha) && - hasCompatibleHostedRunnerShutdownAnnotations(job, repository, workflowSha) + (hasCompatibleHostedRunnerShutdownAnnotations( + job, + repository, + workflowSha, + HOSTED_RUNNER_OPERATION_CANCELLED_MESSAGE, + ) || + hasCompatibleHostedRunnerShutdownAnnotations( + job, + repository, + workflowSha, + HOSTED_RUNNER_EXIT_143_MESSAGE, + )) ) { try { job.logEvidence = await downloadWorkflowJobLogTail(repository, token, job.id); @@ -2390,6 +2406,7 @@ function hasCompatibleHostedRunnerShutdownAnnotations( job: WorkflowJob, repository: string, workflowSha: string, + expectedMessage: string, ): boolean { const annotations = trustedWorkflowJobAnnotations(job, repository, workflowSha); if (!annotations) return false; @@ -2403,7 +2420,7 @@ function hasCompatibleHostedRunnerShutdownAnnotations( failure.endColumn === null && failure.title === "" && failure.rawDetails === "" && - failure.message === HOSTED_RUNNER_OPERATION_CANCELLED_MESSAGE + failure.message === expectedMessage ); } @@ -2434,10 +2451,17 @@ function parseHostedRunnerShutdownLogTail(logTail: string): HostedRunnerShutdown const timestamps = parsed.map((line) => line?.[1] ?? ""); const timestampSeconds = timestamps.map(jobLogTimestampSecond); const messages = parsed.map((line) => line?.[2] ?? ""); + const terminalMessage = messages[1]; + const interruptedStepConclusion = + terminalMessage === `##[error]${HOSTED_RUNNER_OPERATION_CANCELLED_MESSAGE}` + ? "cancelled" + : terminalMessage === `##[error]${HOSTED_RUNNER_EXIT_143_MESSAGE}` + ? "failure" + : null; if ( timestampSeconds.some((timestamp) => timestamp === null) || messages[0] !== shutdownMessage || - messages[1] !== `##[error]${HOSTED_RUNNER_OPERATION_CANCELLED_MESSAGE}` || + interruptedStepConclusion === null || messages[2] !== HOSTED_RUNNER_ORPHAN_CLEANUP_MESSAGE || timestamps[0]! >= timestamps[1]! || timestamps.slice(1).some((timestamp, index) => timestamp < timestamps[index]!) @@ -2456,9 +2480,11 @@ function parseHostedRunnerShutdownLogTail(logTail: string): HostedRunnerShutdown } return { shutdownTimestamp: timestamps[0]!, - operationTimestamp: timestamps[1]!, + terminalTimestamp: timestamps[1]!, cleanupTimestamp: timestamps[2]!, lastTimestamp: timestamps.at(-1)!, + annotationMessage: terminalMessage!.slice("##[error]".length), + interruptedStepConclusion, }; } @@ -2480,47 +2506,55 @@ function hasTrustedHostedRunnerShutdownLog( workflowSha: string, ): boolean { const evidence = job.logEvidence; + if (!evidence || !isBoundedWorkflowJobLogEvidence(evidence)) return false; + const marker = parseHostedRunnerShutdownLogTail(evidence.tail); if ( - !evidence || - !isBoundedWorkflowJobLogEvidence(evidence) || - !hasCompatibleHostedRunnerShutdownAnnotations(job, repository, workflowSha) + !marker || + !hasCompatibleHostedRunnerShutdownAnnotations( + job, + repository, + workflowSha, + marker.annotationMessage, + ) || + !hasTrustedHostedRunnerLossStepShapeForConclusion(job, marker.interruptedStepConclusion) ) { return false; } - const marker = parseHostedRunnerShutdownLogTail(evidence.tail); - const cancelledSteps = job.steps.filter( - (step) => step.status === "completed" && step.conclusion === "cancelled", + const interruptedSteps = job.steps.filter( + (step) => step.status === "completed" && step.conclusion === marker.interruptedStepConclusion, ); - const cancelledStep = cancelledSteps[0]; + const interruptedStep = interruptedSteps[0]; if ( - !marker || - cancelledSteps.length !== 1 || + interruptedSteps.length !== 1 || !job.startedAt || !job.completedAt || - !cancelledStep?.startedAt || - !cancelledStep.completedAt + !interruptedStep?.startedAt || + !interruptedStep.completedAt ) { return false; } const shutdownSecond = jobLogTimestampSecond(marker.shutdownTimestamp); - const operationSecond = jobLogTimestampSecond(marker.operationTimestamp); + const terminalSecond = jobLogTimestampSecond(marker.terminalTimestamp); const cleanupSecond = jobLogTimestampSecond(marker.cleanupTimestamp); const lastSecond = jobLogTimestampSecond(marker.lastTimestamp); return ( shutdownSecond !== null && - operationSecond !== null && + terminalSecond !== null && cleanupSecond !== null && lastSecond !== null && - job.startedAt <= cancelledStep.startedAt && - cancelledStep.startedAt <= shutdownSecond && - operationSecond === cancelledStep.completedAt && - cancelledStep.completedAt <= cleanupSecond && + job.startedAt <= interruptedStep.startedAt && + interruptedStep.startedAt <= shutdownSecond && + terminalSecond === interruptedStep.completedAt && + interruptedStep.completedAt <= cleanupSecond && cleanupSecond <= lastSecond && lastSecond <= job.completedAt ); } -function hasTrustedHostedRunnerLossStepShape(job: WorkflowJob): boolean { +function hasTrustedHostedRunnerLossStepShapeForConclusion( + job: WorkflowJob, + interruptedStepConclusion: "cancelled" | "failure", +): boolean { if ( job.status !== "completed" || job.conclusion !== "failure" || @@ -2553,20 +2587,20 @@ function hasTrustedHostedRunnerLossStepShape(job: WorkflowJob): boolean { job.steps .slice(strandedIndex + 1) .every((step) => step.status === "pending" && step.conclusion === null); - if (legacyStrandedStep) return true; + if (interruptedStepConclusion === "cancelled" && legacyStrandedStep) return true; - const cancelledStepIndexes = job.steps.flatMap((step, index) => - step.status === "completed" && step.conclusion === "cancelled" ? [index] : [], + const interruptedStepIndexes = job.steps.flatMap((step, index) => + step.status === "completed" && step.conclusion === interruptedStepConclusion ? [index] : [], ); - if (cancelledStepIndexes.length !== 1) return false; - const cancelledIndex = cancelledStepIndexes[0]!; - if (job.steps[cancelledIndex]?.name === "Complete job") return false; - const beforeCancellation = job.steps.slice(0, cancelledIndex); - const afterCancellation = job.steps.slice(cancelledIndex + 1); - const syntheticCompletion = afterCancellation.at(-1); - const skippedCleanup = afterCancellation.slice(0, -1); + if (interruptedStepIndexes.length !== 1) return false; + const interruptedIndex = interruptedStepIndexes[0]!; + if (job.steps[interruptedIndex]?.name === "Complete job") return false; + const beforeInterruption = job.steps.slice(0, interruptedIndex); + const afterInterruption = job.steps.slice(interruptedIndex + 1); + const syntheticCompletion = afterInterruption.at(-1); + const skippedCleanup = afterInterruption.slice(0, -1); return ( - beforeCancellation.every( + beforeInterruption.every( (step) => step.status === "completed" && ["success", "skipped"].includes(step.conclusion ?? ""), ) && @@ -2583,15 +2617,26 @@ function hasTrustedHostedRunnerLossStepShape(job: WorkflowJob): boolean { ); } +function hasTrustedHostedRunnerLossStepShape(job: WorkflowJob): boolean { + return hasTrustedHostedRunnerLossStepShapeForConclusion(job, "cancelled"); +} + +function hasTrustedHostedRunnerLossInspectionStepShape(job: WorkflowJob): boolean { + return ( + hasTrustedHostedRunnerLossStepShape(job) || + hasTrustedHostedRunnerLossStepShapeForConclusion(job, "failure") + ); +} + function hasTrustedHostedRunnerLossMarker( job: WorkflowJob, repository: string, workflowSha: string, ): boolean { return ( - hasTrustedHostedRunnerLossStepShape(job) && - (hasTrustedHostedRunnerLossAnnotation(job, repository, workflowSha) || - hasTrustedHostedRunnerShutdownLog(job, repository, workflowSha)) + (hasTrustedHostedRunnerLossStepShape(job) && + hasTrustedHostedRunnerLossAnnotation(job, repository, workflowSha)) || + hasTrustedHostedRunnerShutdownLog(job, repository, workflowSha) ); } From 5146c4ee2813400c5626fda8ae0fc8e01db85792 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Thu, 23 Jul 2026 12:20:48 -0700 Subject: [PATCH 08/10] fix(ci): bind runner-loss retries to selected run Signed-off-by: Apurv Kumaria --- test/pr-e2e-gate-runner-loss-retry.test.ts | 146 +++++++++++++++++++-- tools/e2e/pr-e2e-gate.mts | 48 ++++--- 2 files changed, 165 insertions(+), 29 deletions(-) diff --git a/test/pr-e2e-gate-runner-loss-retry.test.ts b/test/pr-e2e-gate-runner-loss-retry.test.ts index a8384e3bbdf..f51f3fc9ffa 100644 --- a/test/pr-e2e-gate-runner-loss-retry.test.ts +++ b/test/pr-e2e-gate-runner-loss-retry.test.ts @@ -90,6 +90,26 @@ function checkRun(id: number, overrides: Record = {}) { }; } +function runnerLossSummary(runId = 23) { + const runUrl = `https://github.com/NVIDIA/NemoClaw/actions/runs/${runId}`; + return [ + `[Selected E2E run ${runId}](${runUrl}) concluded \`failure\`. No passing result was accepted.`, + "Runner-loss policy: retry once after confirmed GitHub-hosted runner loss.", + "", + RETRY_MARKER, + ].join("\n"); +} + +function canonicalRunnerLossCheck(id = 17, runId = 23) { + return checkRun(id, { + details_url: `https://github.com/NVIDIA/NemoClaw/runs/${id}`, + output: { + title: "Hermes security-posture failed", + summary: runnerLossSummary(runId), + }, + }); +} + function workflowRun(overrides: Record = {}) { return { id: 23, @@ -303,8 +323,8 @@ function mutationResponse(request: RecordedGitHubRequest, id = 18): Response { checkRun(id, { status: "in_progress", conclusion: null, - details_url: null, ...(request.body as Record | undefined), + details_url: `https://github.com/NVIDIA/NemoClaw/runs/${id}`, }), ); } @@ -360,10 +380,11 @@ function retryRoutes( ) { let historyRead = 0; let annotationRead = 0; + const source = canonicalRunnerLossCheck(); const defaultHistories = [ - [checkRun(17)], - [checkRun(17), checkRun(18, { status: "in_progress", conclusion: null, details_url: null })], - [checkRun(17), checkRun(18, { status: "in_progress", conclusion: null, details_url: null })], + [source], + [source, checkRun(18, { status: "in_progress", conclusion: null, details_url: null })], + [source, checkRun(18, { status: "in_progress", conclusion: null, details_url: null })], ]; return createGitHubFetchRouter( [ @@ -476,7 +497,71 @@ describe("PR E2E one-time hosted-runner-loss retry", () => { } }); - it("dispatches the same plan once with fresh state and an independently bound check", async () => { + it.each([ + { + label: "the canonical URL names another check", + source: { + ...canonicalRunnerLossCheck(), + details_url: "https://github.com/NVIDIA/NemoClaw/runs/999", + }, + }, + { + label: "the summary label and link name different runs", + source: { + ...canonicalRunnerLossCheck(), + output: { + title: "Hermes security-posture failed", + summary: runnerLossSummary().replace( + "actions/runs/23) concluded", + "actions/runs/24) concluded", + ), + }, + }, + }, + { + label: "the selected run differs from the controller command", + source: canonicalRunnerLossCheck(17, 24), + }, + { + label: "the details URL is unrelated", + source: { + ...canonicalRunnerLossCheck(), + details_url: "https://github.com/NVIDIA/NemoClaw/pull/7450", + }, + }, + { + label: "the details URL is missing", + source: { + ...canonicalRunnerLossCheck(), + details_url: null, + }, + }, + { + label: "a malformed selected-run prefix attempts legacy fallback", + source: checkRun(17, { + output: { + title: "Hermes security-posture failed", + summary: `[Selected E2E run invalid](${ORIGINAL_RUN_URL}) concluded \`failure\`.\n\n${RETRY_MARKER}`, + }, + }), + }, + ])("rejects retry authorization when $label", async ({ source }) => { + const context = setup(); + const requests: RecordedGitHubRequest[] = []; + vi.spyOn(globalThis, "fetch").mockImplementation( + retryRoutes(requests, { histories: [[source]] }), + ); + + try { + await expect(retryRunnerLossPrGate(context.command)).rejects.toThrow(/does not authorize/u); + expect(requests.some((request) => request.method === "POST")).toBe(false); + expect(requests.some((request) => request.method === "PATCH")).toBe(false); + } finally { + fs.rmSync(context.workDir, { recursive: true, force: true }); + } + }); + + it("dispatches the same plan once from GitHub's canonical source-check URL", async () => { const context = setup(); const requests: RecordedGitHubRequest[] = []; vi.spyOn(globalThis, "fetch").mockImplementation(retryRoutes(requests)); @@ -630,14 +715,7 @@ describe("PR E2E one-time hosted-runner-loss retry", () => { const requests: RecordedGitHubRequest[] = []; vi.spyOn(globalThis, "fetch").mockImplementation( retryRoutes(requests, { - histories: [ - [ - checkRun(16, { - details_url: "https://github.com/NVIDIA/NemoClaw/actions/runs/22", - }), - checkRun(17), - ], - ], + histories: [[canonicalRunnerLossCheck(16, 22), canonicalRunnerLossCheck(17, 23)]], }), ); @@ -871,6 +949,17 @@ describe("PR E2E one-time hosted-runner-loss retry", () => { details_url: "https://github.com/NVIDIA/NemoClaw/actions/runs/999", }), }, + { + name: "selected-run summary", + source: canonicalRunnerLossCheck(17, 24), + }, + { + name: "canonical check URL", + source: { + ...canonicalRunnerLossCheck(), + details_url: "https://github.com/NVIDIA/NemoClaw/runs/999", + }, + }, ])("fails closed when the source $name changes immediately before dispatch", async ({ source, }) => { @@ -1016,7 +1105,7 @@ describe("PR E2E one-time hosted-runner-loss retry", () => { summary: "Prerequisite CI failed.\n\n", }, }); - const source = checkRun(17); + const source = canonicalRunnerLossCheck(); const reserved = checkRun(18, { status: "in_progress", conclusion: null, @@ -1101,6 +1190,35 @@ describe("PR E2E one-time hosted-runner-loss retry", () => { } }); + it("rejects retry cleanup when the canonical URL names another source check", async () => { + const context = setup(); + const requests: RecordedGitHubRequest[] = []; + const source = { + ...canonicalRunnerLossCheck(), + details_url: "https://github.com/NVIDIA/NemoClaw/runs/999", + }; + vi.spyOn(globalThis, "fetch").mockImplementation( + createGitHubFetchRouter( + [ + githubFetchRoute( + ({ url, method }) => url.endsWith("/check-runs/17") && method === "GET", + () => githubResponse(source), + ), + ], + requests, + ), + ); + + try { + await expect(abandonRunnerLossRetrySource(17, 23, 1)).rejects.toThrow( + /exact runner-loss retry source/u, + ); + expect(requests.some((request) => request.method === "PATCH")).toBe(false); + } finally { + fs.rmSync(context.workDir, { recursive: true, force: true }); + } + }); + it.each([ { label: "a cancelled workload", diff --git a/tools/e2e/pr-e2e-gate.mts b/tools/e2e/pr-e2e-gate.mts index 73b6bdc8b45..4a93fbb0a36 100755 --- a/tools/e2e/pr-e2e-gate.mts +++ b/tools/e2e/pr-e2e-gate.mts @@ -63,6 +63,9 @@ const CHECK_EXTERNAL_ID_PREFIX = "nemoclaw-pr-e2e:v2"; const LEGACY_CHECK_EXTERNAL_ID_PREFIX = "nemoclaw-pr-e2e:v1"; const CHECK_EXTERNAL_ID_PATTERN = /^nemoclaw-pr-e2e:v2:([1-9][0-9]*):([0-9a-f]{40}):([0-9a-f]{40})$/u; +const SELECTED_E2E_RUN_SUMMARY_PATTERN = + /^\[Selected E2E run ([1-9][0-9]*)\]\((https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/actions\/runs\/([1-9][0-9]*))\) concluded /u; +const SELECTED_E2E_RUN_SUMMARY_PREFIX = "[Selected E2E run "; const GITHUB_ACTIONS_APP_ID = 15368; const USER_AGENT = "nemoclaw-pr-e2e-gate"; const SHA_PATTERN = /^[a-f0-9]{40}$/u; @@ -1157,12 +1160,36 @@ function retryableFailureReason(check: CheckRun): RetryableFailureReason | undef return reason as RetryableFailureReason; } +function runnerLossChildRunUrl(repository: string, check: CheckRun): string | null { + if (retryableFailureReason(check) !== "child-cancelled") return null; + const summary = check.output?.summary ?? ""; + const selectedRun = SELECTED_E2E_RUN_SUMMARY_PATTERN.exec(summary); + if (selectedRun) { + const [, labelRunId, linkedUrl, linkedRunId] = selectedRun; + if (labelRunId !== linkedRunId) return null; + const expectedUrl = `https://github.com/${repository}/actions/runs/${labelRunId}`; + if (linkedUrl !== expectedUrl) return null; + const canonicalCheckUrl = `https://github.com/${repository}/runs/${check.id}`; + return check.details_url === expectedUrl || check.details_url === canonicalCheckUrl + ? expectedUrl + : null; + } + if (summary.includes(SELECTED_E2E_RUN_SUMMARY_PREFIX)) return null; + + const prefix = `https://github.com/${repository}/actions/runs/`; + const detailsUrl = check.details_url; + return typeof detailsUrl === "string" && + detailsUrl.startsWith(prefix) && + /^[1-9][0-9]*$/u.test(detailsUrl.slice(prefix.length)) + ? detailsUrl + : null; +} + function priorRunnerLossRunUrls( repository: string, history: readonly CheckRun[], currentCheckId: number, ): string[] { - const prefix = `https://github.com/${repository}/actions/runs/`; const priorRunnerLossChecks = history.filter( (check) => check.id !== currentCheckId && retryableFailureReason(check) === "child-cancelled", ); @@ -1170,12 +1197,8 @@ function priorRunnerLossRunUrls( throw new Error("Runner-loss retry history exceeds the single permitted retry"); } return priorRunnerLossChecks.map((check) => { - const url = check.details_url; - if ( - typeof url !== "string" || - !url.startsWith(prefix) || - !/^[1-9][0-9]*$/u.test(url.slice(prefix.length)) - ) { + const url = runnerLossChildRunUrl(repository, check); + if (!url) { throw new Error("Runner-loss retry history has an invalid child-run URL"); } return url; @@ -3445,10 +3468,7 @@ export async function retryRunnerLossPrGate( if (current?.id !== command.checkRunId) { throw new Error("runner-loss retry source is not the current PR gate check"); } - if ( - retryableFailureReason(current) !== "child-cancelled" || - current.details_url !== originalRunUrl - ) { + if (!current || runnerLossChildRunUrl(repository, current) !== originalRunUrl) { throw new Error("PR gate check does not authorize this runner-loss retry"); } if (priorRunnerLossRunUrls(repository, history, command.checkRunId).length !== 0) { @@ -3605,8 +3625,7 @@ export async function retryRunnerLossPrGate( dispatchHistory.length !== historySize + 1 || dispatchHistory.at(-1)?.id !== retryCheckRunId || !dispatchSource || - retryableFailureReason(dispatchSource) !== "child-cancelled" || - dispatchSource.details_url !== originalRunUrl || + runnerLossChildRunUrl(repository, dispatchSource) !== originalRunUrl || priorRunnerLossRunUrls(repository, dispatchHistory, retryCheckRunId).length !== 1 ) { throw new Error("runner-loss retry lost the current PR gate check before dispatch"); @@ -4421,8 +4440,7 @@ export async function abandonRunnerLossRetrySource( source.app?.id !== GITHUB_ACTIONS_APP_ID || source.status !== "completed" || source.conclusion !== "failure" || - source.details_url !== childRunUrl || - retryableFailureReason(source) !== "child-cancelled" || + runnerLossChildRunUrl(repository, source) !== childRunUrl || !externalIdMatch ) { throw new Error("completed check does not match the exact runner-loss retry source"); From 85b12725ff749629d832e2100df7c90fb15e7b73 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Thu, 23 Jul 2026 12:24:44 -0700 Subject: [PATCH 09/10] docs(e2e): document runner-loss retry evidence Signed-off-by: Apurv Kumaria --- test/e2e/README.md | 92 +++++++++++++++++++++++++++------------------- 1 file changed, 54 insertions(+), 38 deletions(-) diff --git a/test/e2e/README.md b/test/e2e/README.md index 4957fbadbe5..8c9fa3e0944 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -287,13 +287,14 @@ revision, or closed PR can leave the controller green while coordination is failed or cancelled and the native job is non-passing. Only a successful native `E2E / PR Gate` for the current head and base satisfies the required check. An eligible prerequisite-CI failure records the versioned retry reason -`prerequisite-ci`. A selected child records `child-cancelled` only when a -trusted GitHub-hosted runner-loss annotation is bound to the exact failed job -and workflow commit and no other terminal classification was produced. -Cancellation alone is not retryable. Assertion failures and other selected-E2E -outcomes do not receive a retry reason. An unexpected controller error still -fails the controller workflow and fails coordination closed, which prevents -the native job from passing. +`prerequisite-ci`. A selected child records `child-cancelled` only when the +controller authenticates either a trusted GitHub-hosted runner-loss annotation +or the exact terminal-shutdown fallback against the failed job and workflow +commit, and no other terminal classification was produced. Cancellation alone +is not retryable. Assertion failures and other selected-E2E outcomes do not +receive a retry reason. An unexpected controller error still fails the +controller workflow and fails coordination closed, which prevents the native +job from passing. On open, synchronization, reopen, transition out of draft, or base retarget, `.github/workflows/pr-e2e-gate.yaml` reserves `E2E / PR Gate Coordination` for @@ -557,24 +558,28 @@ attempt, workflow commit, job check, standard hosted runner group, and runner name. The controller accepts one canonical runner-loss failure annotation bound to `.github` at that workflow commit. -When GitHub emits a generic cancellation instead, the controller requires -exactly one failure annotation whose message is `The operation was canceled.` -The annotation must use `.github`, equal start and end lines, null columns, and -empty title and detail fields. Every annotation must use a blob URL bound to the -same workflow commit. The controller accepts at most 20 annotations, bounds -each text field, and limits the normalized annotation evidence to 64 KiB. This -permits trusted bounded non-failure notices beside the sole failure annotation -without allowing annotation output to exhaust the coordinator. - -GitHub Actions creates this `.github` failure annotation after the hosted runner -shuts down; NemoClaw workflow code cannot replace its generic message with the -canonical lost-communication annotation. The classifier test `accepts the -exact authenticated terminal shutdown block from run 29988226653` preserves -the observed fallback contract. Remove the fallback and that test together -only after GitHub's documented Jobs or Checks API contract provides an -authenticated structured runner-loss reason for this exact shutdown path. - -The generic-cancellation fallback also authenticates the job log. The +When GitHub emits a generic terminal result instead, the controller requires +exactly one failure annotation. Its message must be +`The operation was canceled.` for one completed `cancelled` workload step or +`Process completed with exit code 143.` for one completed `failure` workload +step. The annotation must use `.github`, equal start and end lines, null +columns, and empty title and detail fields. Every annotation must use a blob URL +bound to the same workflow commit. The controller accepts at most 20 +annotations, bounds each text field, and limits the normalized annotation +evidence to 64 KiB. This permits trusted bounded non-failure notices beside the +sole failure annotation without allowing annotation output to exhaust the +coordinator. + +GitHub Actions creates these `.github` failure annotations after the hosted +runner shuts down; NemoClaw workflow code cannot replace their generic messages +with the canonical lost-communication annotation. The classifier tests +`accepts the exact authenticated terminal shutdown block from run 29988226653` +and `accepts the exit-143 hosted shutdown from run 30026115852` preserve the +two observed fallback contracts. Remove a fallback and its test together only +after GitHub's documented Jobs or Checks API contract provides an authenticated +structured runner-loss reason for that shutdown path. + +The terminal-shutdown fallback also authenticates the job log. The controller requests the GitHub job-log endpoint and accepts only its signed HTTPS redirect to GitHub Actions result storage. It does not forward the repository token to that signed URL. A metadata request must return plain, @@ -583,19 +588,21 @@ controller then reads at most the final 64 KiB with `If-Match` and requires an exact partial-content range, length, and matching ETag. The authenticated tail must end with exactly one line feed after the -timestamped shutdown error, operation-cancelled error, and orphan-cleanup -record, in that order. Up to 64 unique orphan-process termination records may -follow the cleanup record. Each record must contain a positive process ID and a -bounded process name. The record timestamps must not move backward. The -job must start no later than the cancelled step. The shutdown must occur at or -after that step starts, and the cancellation second must equal the step's -completion time. Cleanup must not precede cancellation. Cleanup and -orphan-process records must finish no later than the job completion time. - -A generic cancellation without this log contract, timeout, unknown runner -identity, self-hosted or custom runner group, ordinary failed step, another -non-passing job, incomplete pagination, or mismatched annotation identity -fails closed without a retry. +timestamped shutdown error, matching operation-cancelled or exit-143 error, and +orphan-cleanup record, in that order. Up to 64 unique orphan-process termination +records may follow the cleanup record. Each record must contain a positive +process ID and a bounded process name. The record timestamps must not move +backward. The job must start no later than the interrupted step. The shutdown +must occur at or after that step starts, and the terminal-error second must +equal the step's completion time. Cleanup must not precede the terminal error. +Cleanup and orphan-process records must finish no later than the job completion +time. + +A generic terminal result without this log contract, an ordinary exit 143 +without the exact preceding shutdown block, timeout, unknown runner identity, +self-hosted or custom runner group, ordinary failed step, another non-passing +job, incomplete pagination, or mismatched annotation identity fails closed +without a retry. Before the one-time retry dispatch, the controller revalidates the unchanged internal PR head and base, original child, current coordination-check lineage, @@ -606,6 +613,15 @@ including pagination state, log ETag, log length, and log-tail hash. After the second classification, it validates the live PR head and base and the current coordination-check lineage again. +The source coordination check binds that original child through the +controller-generated `Selected E2E run ` summary. The summary label, +linked run ID, repository, and exact Actions run URL must agree. GitHub may set +the check details URL to either that exact child run or the canonical +`/runs/` URL for the source check. A malformed selected-run prefix or +any mismatch fails closed. Compatibility checks that predate the selected-run +summary remain eligible only when their details URL is the exact child Actions +run URL. + The controller reserves a distinct replacement coordination check before dispatch so the native observer can follow the retry without mutating completed attempt-one history. Attempt two uses separate private state and evidence paths. From 6c7f567af286fe5d242d79f0c710fdb6bddb42ca Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Thu, 23 Jul 2026 12:42:23 -0700 Subject: [PATCH 10/10] fix(ci): keep stranded retries fail closed Signed-off-by: Apurv Kumaria --- ...pr-e2e-gate-runner-loss-classifier.test.ts | 30 +++++++++++++++++-- tools/e2e/pr-e2e-gate.mts | 21 ++++++++++--- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/test/pr-e2e-gate-runner-loss-classifier.test.ts b/test/pr-e2e-gate-runner-loss-classifier.test.ts index 2647336ee33..9d9b096b7f4 100644 --- a/test/pr-e2e-gate-runner-loss-classifier.test.ts +++ b/test/pr-e2e-gate-runner-loss-classifier.test.ts @@ -139,16 +139,27 @@ function hostedRunnerLossJob(overrides: Record = {}) { }; } -function legacyHostedRunnerLossJob(id: number, runnerId: number) { +function legacyHostedRunnerLossJob( + id: number, + runnerId: number, + overrides: Record = {}, +) { return hostedRunnerLossJob({ id, runnerId, runnerName: `GitHub Actions ${runnerId}`, steps: [ { name: "Set up job", status: "completed", conclusion: "success" }, - { name: "Run live test", status: "in_progress", conclusion: null }, + { + name: "Run live test", + status: "in_progress", + conclusion: null, + startedAt: CANCELLED_STEP_STARTED_AT, + completedAt: null, + }, { name: "Upload artifacts", status: "pending", conclusion: null }, ], + ...overrides, }); } @@ -320,7 +331,7 @@ describe("PR E2E hosted-runner-loss classifier", () => { ).toBe(true); }); - it("accepts two strict standard-hosted legacy markers from run 29964500642", () => { + it("accepts two canonical standard-hosted legacy markers from run 29964500642", () => { expect( confirmsRunnerLoss({ jobs: [ @@ -331,6 +342,19 @@ describe("PR E2E hosted-runner-loss classifier", () => { ).toBe(true); }); + it("rejects generic shutdown-log evidence for a legacy stranded workload step", () => { + expect( + confirmsRunnerLoss({ + jobs: [ + legacyHostedRunnerLossJob(89_073_235_001, 1_021_276_370, { + annotations: [genericCancellationAnnotation()], + logEvidence: runnerShutdownLogEvidence(), + }), + ], + }), + ).toBe(false); + }); + it("allows an unrelated notice beside the sole canonical failure annotation", () => { expect( confirmsRunnerLoss({ diff --git a/tools/e2e/pr-e2e-gate.mts b/tools/e2e/pr-e2e-gate.mts index 4a93fbb0a36..d790c8852a9 100755 --- a/tools/e2e/pr-e2e-gate.mts +++ b/tools/e2e/pr-e2e-gate.mts @@ -2539,7 +2539,9 @@ function hasTrustedHostedRunnerShutdownLog( workflowSha, marker.annotationMessage, ) || - !hasTrustedHostedRunnerLossStepShapeForConclusion(job, marker.interruptedStepConclusion) + !hasTrustedHostedRunnerLossStepShapeForConclusion(job, marker.interruptedStepConclusion, { + allowLegacyStrandedStep: false, + }) ) { return false; } @@ -2577,6 +2579,7 @@ function hasTrustedHostedRunnerShutdownLog( function hasTrustedHostedRunnerLossStepShapeForConclusion( job: WorkflowJob, interruptedStepConclusion: "cancelled" | "failure", + options: { allowLegacyStrandedStep: boolean }, ): boolean { if ( job.status !== "completed" || @@ -2610,7 +2613,13 @@ function hasTrustedHostedRunnerLossStepShapeForConclusion( job.steps .slice(strandedIndex + 1) .every((step) => step.status === "pending" && step.conclusion === null); - if (interruptedStepConclusion === "cancelled" && legacyStrandedStep) return true; + if ( + options.allowLegacyStrandedStep && + interruptedStepConclusion === "cancelled" && + legacyStrandedStep + ) { + return true; + } const interruptedStepIndexes = job.steps.flatMap((step, index) => step.status === "completed" && step.conclusion === interruptedStepConclusion ? [index] : [], @@ -2641,13 +2650,17 @@ function hasTrustedHostedRunnerLossStepShapeForConclusion( } function hasTrustedHostedRunnerLossStepShape(job: WorkflowJob): boolean { - return hasTrustedHostedRunnerLossStepShapeForConclusion(job, "cancelled"); + return hasTrustedHostedRunnerLossStepShapeForConclusion(job, "cancelled", { + allowLegacyStrandedStep: true, + }); } function hasTrustedHostedRunnerLossInspectionStepShape(job: WorkflowJob): boolean { return ( hasTrustedHostedRunnerLossStepShape(job) || - hasTrustedHostedRunnerLossStepShapeForConclusion(job, "failure") + hasTrustedHostedRunnerLossStepShapeForConclusion(job, "failure", { + allowLegacyStrandedStep: false, + }) ); }