From 5bf10d6590ba35f4169f1fb9762c324781562537 Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Fri, 4 Sep 2026 12:18:38 -0700 Subject: [PATCH 01/43] fix(e2e): retry transient OpenClaw provider turns Signed-off-by: Charan Jagwani --- test/e2e/live/launch-agent-turn.ts | 84 ++++++++----- ...h-agent-turn-provider-availability.test.ts | 111 ++++++++++++++++++ 2 files changed, 167 insertions(+), 28 deletions(-) create mode 100644 test/e2e/support/launch-agent-turn-provider-availability.test.ts diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index 9519aea10e2..34527afbe21 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -8,6 +8,21 @@ import { resultText } from "../fixtures/clients/command.ts"; import type { HostCliClient } from "../fixtures/clients/host.ts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; +const OPENCLAW_LAUNCH_PROVIDER_ATTEMPTS = 2; +const TRANSIENT_PROVIDER_AVAILABILITY_RE = + /\bServiceUnavailable(?:Error)?\b|\bHTTP(?: status(?: code)?)?[:= ]+5\d{2}\b|\bstatus(?: code)?[:= ]+5\d{2}\b|\b5\d{2} (?:Bad Gateway|Gateway Timeout|Internal Server Error|Service Unavailable)\b/iu; +const TERMINAL_LAUNCH_FAILURE_RE = + /authentication failed|authorization failed|unauthorized|forbidden|HTTP(?: status)?[:= ]+40[13]\b|\b40[13]\b|invalid[^\r\n]*(?:api[_ -]?key|credential|JSON|response)|denied by network policy|network policy denied|policy [^\r\n]*failed|routing [^\r\n]*failed|route [^\r\n]*failed|proxy [^\r\n]*failed|malformed|structured session evidence was invalid|launch final structured session evidence did not qualify|message_(?:content_empty|order_invalid)|session_(?:record_incomplete|removed|rewritten|truncated)|multiple_sessions_changed|extra_message|verifier_failed|PTY [^\r\n]*(?:failed|invalid|unavailable)|structured session baseline cleanup failed|launch host session cleanup failed|launch PTY monitor cleanup failed|launch could not remove/iu; + +function isTransientProviderAvailabilityFailure( + result: Pick, +): boolean { + const output = resultText(result); + return ( + TRANSIENT_PROVIDER_AVAILABILITY_RE.test(output) && !TERMINAL_LAUNCH_FAILURE_RE.test(output) + ); +} + export const OPENCLAW_LAUNCH_RUNTIME_ENV_SCRIPT = 'if [ -r "/tmp/nemoclaw-proxy-env.sh" ]; then builtin source "/tmp/nemoclaw-proxy-env.sh" || exit $?; fi; builtin unset OPENCLAW_GATEWAY_TOKEN; builtin exec -- "$@"'; @@ -1346,35 +1361,48 @@ export async function runOpenClawLaunchSession( if (!options.host.openshellCommandPath.startsWith("/")) { throw new Error("launch session coverage requires an absolute OpenShell command path"); } - const inputs = uniqueTurnInputs(); - const result = await options.host.command("bash", ["-lc", LAUNCH_TURN_SCRIPT], { - artifactName: options.artifactName, - env: { - ...options.env, - NEMOCLAW_LAUNCH_COMMAND: options.cliCommand, - NEMOCLAW_LAUNCH_ENTRYPOINT: options.cliEntrypoint ?? "", - NEMOCLAW_LAUNCH_EXIT_COMMAND: options.exitCommand ?? "", - NEMOCLAW_LAUNCH_FIRST_INPUT: inputs.first, - NEMOCLAW_LAUNCH_HOST_TMP_ROOT: resolve(options.env.TMPDIR || "/tmp"), - NEMOCLAW_LAUNCH_RUN_ID: randomUUID().replaceAll("-", ""), - NEMOCLAW_LAUNCH_SANDBOX: options.sandboxName, - NEMOCLAW_LAUNCH_SESSION_BUDGET_SECONDS: "230", - NEMOCLAW_LAUNCH_SECOND_INPUT: inputs.second, - NEMOCLAW_LAUNCH_OPENSHELL_SHIM_SCRIPT: OPENCLAW_LAUNCH_OPENSHELL_SHIM_SCRIPT, - NEMOCLAW_LAUNCH_PTY_MONITOR_STARTER_SCRIPT: OPENCLAW_PTY_MONITOR_STARTER_SCRIPT, - NEMOCLAW_LAUNCH_RUNTIME_ENV_SCRIPT: OPENCLAW_LAUNCH_RUNTIME_ENV_SCRIPT, - NEMOCLAW_LAUNCH_SESSION_EVIDENCE_SCRIPT: OPENCLAW_SESSION_EVIDENCE_SCRIPT, - NEMOCLAW_LAUNCH_SESSION_ROOT: "/sandbox/.openclaw/agents/main/sessions", - NEMOCLAW_OPENSHELL_COMMAND: options.host.openshellCommandPath, - TERM: "xterm-256color", - }, - redactionValues: options.redactionValues, - timeoutMs: 280_000, - }); - if (result.exitCode !== 0) { - throw new Error(`launch session failed: ${resultText(result)}`); + let finalFailure: ShellProbeResult | undefined; + let providerUnavailable = false; + for (let attempt = 1; attempt <= OPENCLAW_LAUNCH_PROVIDER_ATTEMPTS; attempt += 1) { + const inputs = uniqueTurnInputs(); + const result = await options.host.command("bash", ["-lc", LAUNCH_TURN_SCRIPT], { + artifactName: + attempt === 1 + ? options.artifactName + : `${options.artifactName}-provider-retry-${String(attempt).padStart(2, "0")}`, + env: { + ...options.env, + NEMOCLAW_LAUNCH_COMMAND: options.cliCommand, + NEMOCLAW_LAUNCH_ENTRYPOINT: options.cliEntrypoint ?? "", + NEMOCLAW_LAUNCH_EXIT_COMMAND: options.exitCommand ?? "", + NEMOCLAW_LAUNCH_FIRST_INPUT: inputs.first, + NEMOCLAW_LAUNCH_HOST_TMP_ROOT: resolve(options.env.TMPDIR || "/tmp"), + NEMOCLAW_LAUNCH_RUN_ID: randomUUID().replaceAll("-", ""), + NEMOCLAW_LAUNCH_SANDBOX: options.sandboxName, + NEMOCLAW_LAUNCH_SESSION_BUDGET_SECONDS: "230", + NEMOCLAW_LAUNCH_SECOND_INPUT: inputs.second, + NEMOCLAW_LAUNCH_OPENSHELL_SHIM_SCRIPT: OPENCLAW_LAUNCH_OPENSHELL_SHIM_SCRIPT, + NEMOCLAW_LAUNCH_PTY_MONITOR_STARTER_SCRIPT: OPENCLAW_PTY_MONITOR_STARTER_SCRIPT, + NEMOCLAW_LAUNCH_RUNTIME_ENV_SCRIPT: OPENCLAW_LAUNCH_RUNTIME_ENV_SCRIPT, + NEMOCLAW_LAUNCH_SESSION_EVIDENCE_SCRIPT: OPENCLAW_SESSION_EVIDENCE_SCRIPT, + NEMOCLAW_LAUNCH_SESSION_ROOT: "/sandbox/.openclaw/agents/main/sessions", + NEMOCLAW_OPENSHELL_COMMAND: options.host.openshellCommandPath, + TERM: "xterm-256color", + }, + redactionValues: options.redactionValues, + timeoutMs: 280_000, + }); + if (result.exitCode === 0) return result; + finalFailure = result; + providerUnavailable = isTransientProviderAvailabilityFailure(result); + if (!providerUnavailable) break; } - return result; + const detail = finalFailure ? resultText(finalFailure) : "launch attempt was not executed"; + throw new Error( + providerUnavailable + ? `OpenClaw launch provider unavailable after ${OPENCLAW_LAUNCH_PROVIDER_ATTEMPTS} attempts: ${detail}` + : `launch session failed: ${detail}`, + ); } export async function runOpenClawLaunchReadinessLeaseTurns( diff --git a/test/e2e/support/launch-agent-turn-provider-availability.test.ts b/test/e2e/support/launch-agent-turn-provider-availability.test.ts new file mode 100644 index 00000000000..2406c2f8571 --- /dev/null +++ b/test/e2e/support/launch-agent-turn-provider-availability.test.ts @@ -0,0 +1,111 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { expect, it, vi } from "vitest"; +import { runOpenClawLaunchSession } from "../live/launch-agent-turn.ts"; + +function launchOptions(host: unknown) { + return { + artifactName: "provider-turn", + cliCommand: "node", + env: {}, + host: host as never, + redactionValues: [], + sandboxName: "alpha", + }; +} + +it("retries a transient provider failure in a fresh launch session (#10978)", async () => { + const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + const calls: Array<{ artifactName?: string; env?: NodeJS.ProcessEnv }> = []; + const host = { + command: async ( + _command: string, + _args: string[], + options?: { artifactName?: string; env?: NodeJS.ProcessEnv }, + ) => { + calls.push({ artifactName: options?.artifactName, env: options?.env }); + return calls.length === 1 + ? { + exitCode: 1, + signal: null, + stderr: "litellm.ServiceUnavailableError: NVIDIA upstream unavailable", + stdout: "", + } + : { exitCode: 0, signal: null, stderr: "", stdout: "" }; + }, + openshellCommandPath: "/usr/bin/openshell", + }; + + try { + const result = await runOpenClawLaunchSession(launchOptions(host)); + expect(result.exitCode).toBe(0); + expect(calls.map((call) => call.artifactName)).toEqual([ + "provider-turn", + "provider-turn-provider-retry-02", + ]); + expect(new Set(calls.map((call) => call.env?.NEMOCLAW_LAUNCH_RUN_ID)).size).toBe(2); + expect(new Set(calls.map((call) => call.env?.NEMOCLAW_LAUNCH_FIRST_INPUT)).size).toBe(2); + } finally { + platform.mockRestore(); + } +}); + +it("classifies exhausted transient launch attempts as provider unavailable (#10978)", async () => { + const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + const calls: string[] = []; + const host = { + command: async (_command: string, _args: string[], options?: { artifactName?: string }) => { + calls.push(options?.artifactName ?? ""); + return { + exitCode: 1, + signal: null, + stderr: `launch did not record the required structured session turns\nHTTP ${calls.length === 1 ? "503" : "502"}`, + stdout: "", + }; + }, + openshellCommandPath: "/usr/bin/openshell", + }; + + try { + await expect(runOpenClawLaunchSession(launchOptions(host))).rejects.toThrow( + "OpenClaw launch provider unavailable after 2 attempts", + ); + expect(calls).toEqual(["provider-turn", "provider-turn-provider-retry-02"]); + } finally { + platform.mockRestore(); + } +}); + +it.each([ + [ + "invalid structured session evidence", + 'ServiceUnavailableError\nlaunch final structured session evidence did not qualify (status 2)\n{"reason":"message_order_invalid"}', + ], + [ + "authentication failure", + "ServiceUnavailableError: HTTP 503\nauthentication failed: invalid API key", + ], + ["policy failure", "ServiceUnavailableError: HTTP 503\ndenied by network policy"], + ["invalid response", "ServiceUnavailableError: HTTP 503\ninvalid provider response"], + ["unknown failure", "launch failed for an unknown reason"], +])("does not retry a %s (#10978)", async (_case, stderr) => { + const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + let calls = 0; + const host = { + command: async () => { + calls += 1; + return { exitCode: 1, signal: null, stderr, stdout: "" }; + }, + openshellCommandPath: "/usr/bin/openshell", + }; + + try { + await expect(runOpenClawLaunchSession(launchOptions(host))).rejects.toThrow( + "launch session failed", + ); + expect(calls).toBe(1); + } finally { + platform.mockRestore(); + } +}); From 2c6c6870208b2c0c64ff8bc30e3dab3f04f20c60 Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Fri, 4 Sep 2026 12:27:32 -0700 Subject: [PATCH 02/43] test(e2e): register provider retry parity Signed-off-by: Charan Jagwani --- test/e2e/mock-parity.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 7cc47e2d960..9ff5686dfd5 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -155,11 +155,13 @@ "liveSources": [ "test/e2e/live/agent-turn-latency-helpers.ts", "test/e2e/live/full-e2e-inference-probe.ts", - "test/e2e/live/full-e2e-workload-evidence.ts" + "test/e2e/live/full-e2e-workload-evidence.ts", + "test/e2e/live/launch-agent-turn.ts" ], "fast": [ "test/e2e/support/hosted-inference.test.ts", "test/e2e/support/full-e2e-inference-probe.test.ts", + "test/e2e/support/launch-agent-turn-provider-availability.test.ts", "test/e2e/support/launch-agent-turn.test.ts", "test/e2e/support/openclaw-agent-output.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", @@ -170,10 +172,12 @@ }, { "live": "test/e2e/live/launch-readiness-lease-acceptance.test.ts", + "liveSources": ["test/e2e/live/launch-agent-turn.ts"], "fast": [ "src/lib/actions/sandbox/launch-readiness-gateway-health.test.ts", "src/lib/actions/sandbox/launch-readiness.test.ts", "src/lib/state/launch-readiness-lease.test.ts", + "test/e2e/support/launch-agent-turn-provider-availability.test.ts", "test/e2e/support/launch-agent-turn.test.ts", "test/e2e-runtime/launch-readiness-forward-observation.test.ts" ] From 65677babd90a36043ebc8bf1c21bd9d08dcc2848 Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Fri, 4 Sep 2026 12:40:44 -0700 Subject: [PATCH 03/43] fix(e2e): structure provider retry signals Signed-off-by: Charan Jagwani --- test/e2e/live/launch-agent-turn.ts | 26 ++++++++++-- ...h-agent-turn-provider-availability.test.ts | 42 ++++++++++++++----- 2 files changed, 54 insertions(+), 14 deletions(-) diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index 34527afbe21..232588bbed4 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -3,14 +3,16 @@ import { randomUUID } from "node:crypto"; import { resolve } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; import { resultText } from "../fixtures/clients/command.ts"; import type { HostCliClient } from "../fixtures/clients/host.ts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; const OPENCLAW_LAUNCH_PROVIDER_ATTEMPTS = 2; -const TRANSIENT_PROVIDER_AVAILABILITY_RE = - /\bServiceUnavailable(?:Error)?\b|\bHTTP(?: status(?: code)?)?[:= ]+5\d{2}\b|\bstatus(?: code)?[:= ]+5\d{2}\b|\b5\d{2} (?:Bad Gateway|Gateway Timeout|Internal Server Error|Service Unavailable)\b/iu; +const OPENCLAW_LAUNCH_PROVIDER_RETRY_DELAY_MS = 1_000; +export const OPENCLAW_PROVIDER_UNAVAILABLE_MARKER = + "nemoclaw.e2e.launch-failure=provider-unavailable"; const TERMINAL_LAUNCH_FAILURE_RE = /authentication failed|authorization failed|unauthorized|forbidden|HTTP(?: status)?[:= ]+40[13]\b|\b40[13]\b|invalid[^\r\n]*(?:api[_ -]?key|credential|JSON|response)|denied by network policy|network policy denied|policy [^\r\n]*failed|routing [^\r\n]*failed|route [^\r\n]*failed|proxy [^\r\n]*failed|malformed|structured session evidence was invalid|launch final structured session evidence did not qualify|message_(?:content_empty|order_invalid)|session_(?:record_incomplete|removed|rewritten|truncated)|multiple_sessions_changed|extra_message|verifier_failed|PTY [^\r\n]*(?:failed|invalid|unavailable)|structured session baseline cleanup failed|launch host session cleanup failed|launch PTY monitor cleanup failed|launch could not remove/iu; @@ -19,7 +21,8 @@ function isTransientProviderAvailabilityFailure( ): boolean { const output = resultText(result); return ( - TRANSIENT_PROVIDER_AVAILABILITY_RE.test(output) && !TERMINAL_LAUNCH_FAILURE_RE.test(output) + output.split(/\r?\n/u).includes(OPENCLAW_PROVIDER_UNAVAILABLE_MARKER) && + !TERMINAL_LAUNCH_FAILURE_RE.test(output) ); } @@ -1125,8 +1128,18 @@ terminal_diagnostic() { fi } +transient_provider_availability_failure() { + local diagnostic + diagnostic="$(tail -c 4096 "$capture" 2>/dev/null || true)" + printf '%s\n' "$diagnostic" | grep -Eiq \ + 'ServiceUnavailable(Error)?|HTTP( status( code)?)?[:= ]+5[0-9]{2}|status( code)?[:= ]+5[0-9]{2}|5[0-9]{2} (Bad Gateway|Gateway Timeout|Internal Server Error|Service Unavailable)' || return 1 + ! printf '%s\n' "$diagnostic" | grep -Eiq \ + 'authentication failed|authorization failed|unauthorized|forbidden|HTTP( status)?[:= ]+40[13]|invalid.*(api[_ -]?key|credential|JSON|response)|denied by network policy|network policy denied|policy .*failed|routing .*failed|route .*failed|proxy .*failed|malformed' +} + fail_launch_session() { echo "$1" >&2 + echo "${"$"}{2:-}" >&2 if [[ -s "$evidence_error" ]]; then tail -c 2048 "$evidence_error" >&2 || true fi @@ -1179,6 +1192,10 @@ wait_for_turn_count() { fi sleep 1 done + transient_provider_availability_failure && \ + fail_launch_session \ + "launch did not record the required structured session turns" \ + "${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}" fail_launch_session "launch did not record the required structured session turns" } @@ -1396,6 +1413,9 @@ export async function runOpenClawLaunchSession( finalFailure = result; providerUnavailable = isTransientProviderAvailabilityFailure(result); if (!providerUnavailable) break; + if (attempt < OPENCLAW_LAUNCH_PROVIDER_ATTEMPTS) { + await delay(OPENCLAW_LAUNCH_PROVIDER_RETRY_DELAY_MS); + } } const detail = finalFailure ? resultText(finalFailure) : "launch attempt was not executed"; throw new Error( diff --git a/test/e2e/support/launch-agent-turn-provider-availability.test.ts b/test/e2e/support/launch-agent-turn-provider-availability.test.ts index 2406c2f8571..a3230f852ba 100644 --- a/test/e2e/support/launch-agent-turn-provider-availability.test.ts +++ b/test/e2e/support/launch-agent-turn-provider-availability.test.ts @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { expect, it, vi } from "vitest"; -import { runOpenClawLaunchSession } from "../live/launch-agent-turn.ts"; +import { + OPENCLAW_PROVIDER_UNAVAILABLE_MARKER, + runOpenClawLaunchSession, +} from "../live/launch-agent-turn.ts"; function launchOptions(host: unknown) { return { @@ -17,6 +20,7 @@ function launchOptions(host: unknown) { it("retries a transient provider failure in a fresh launch session (#10978)", async () => { const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + vi.useFakeTimers(); const calls: Array<{ artifactName?: string; env?: NodeJS.ProcessEnv }> = []; const host = { command: async ( @@ -29,7 +33,7 @@ it("retries a transient provider failure in a fresh launch session (#10978)", as ? { exitCode: 1, signal: null, - stderr: "litellm.ServiceUnavailableError: NVIDIA upstream unavailable", + stderr: `${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nlitellm.ServiceUnavailableError: NVIDIA upstream unavailable`, stdout: "", } : { exitCode: 0, signal: null, stderr: "", stdout: "" }; @@ -38,7 +42,12 @@ it("retries a transient provider failure in a fresh launch session (#10978)", as }; try { - const result = await runOpenClawLaunchSession(launchOptions(host)); + const launch = runOpenClawLaunchSession(launchOptions(host)); + expect(calls).toHaveLength(1); + await vi.advanceTimersByTimeAsync(999); + expect(calls).toHaveLength(1); + await vi.advanceTimersByTimeAsync(1); + const result = await launch; expect(result.exitCode).toBe(0); expect(calls.map((call) => call.artifactName)).toEqual([ "provider-turn", @@ -47,12 +56,14 @@ it("retries a transient provider failure in a fresh launch session (#10978)", as expect(new Set(calls.map((call) => call.env?.NEMOCLAW_LAUNCH_RUN_ID)).size).toBe(2); expect(new Set(calls.map((call) => call.env?.NEMOCLAW_LAUNCH_FIRST_INPUT)).size).toBe(2); } finally { + vi.useRealTimers(); platform.mockRestore(); } }); it("classifies exhausted transient launch attempts as provider unavailable (#10978)", async () => { const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + vi.useFakeTimers(); const calls: string[] = []; const host = { command: async (_command: string, _args: string[], options?: { artifactName?: string }) => { @@ -60,7 +71,7 @@ it("classifies exhausted transient launch attempts as provider unavailable (#109 return { exitCode: 1, signal: null, - stderr: `launch did not record the required structured session turns\nHTTP ${calls.length === 1 ? "503" : "502"}`, + stderr: `${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nlaunch did not record the required structured session turns\nHTTP ${calls.length === 1 ? "503" : "502"}`, stdout: "", }; }, @@ -68,11 +79,13 @@ it("classifies exhausted transient launch attempts as provider unavailable (#109 }; try { - await expect(runOpenClawLaunchSession(launchOptions(host))).rejects.toThrow( - "OpenClaw launch provider unavailable after 2 attempts", - ); + const launch = runOpenClawLaunchSession(launchOptions(host)); + expect(calls).toHaveLength(1); + await vi.advanceTimersByTimeAsync(1_000); + await expect(launch).rejects.toThrow("OpenClaw launch provider unavailable after 2 attempts"); expect(calls).toEqual(["provider-turn", "provider-turn-provider-retry-02"]); } finally { + vi.useRealTimers(); platform.mockRestore(); } }); @@ -80,14 +93,21 @@ it("classifies exhausted transient launch attempts as provider unavailable (#109 it.each([ [ "invalid structured session evidence", - 'ServiceUnavailableError\nlaunch final structured session evidence did not qualify (status 2)\n{"reason":"message_order_invalid"}', + `${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nServiceUnavailableError\nlaunch final structured session evidence did not qualify (status 2)\n{"reason":"message_order_invalid"}`, ], [ "authentication failure", - "ServiceUnavailableError: HTTP 503\nauthentication failed: invalid API key", + `${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nServiceUnavailableError: HTTP 503\nauthentication failed: invalid API key`, + ], + [ + "policy failure", + `${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nServiceUnavailableError: HTTP 503\ndenied by network policy`, + ], + [ + "invalid response", + `${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nServiceUnavailableError: HTTP 503\ninvalid provider response`, ], - ["policy failure", "ServiceUnavailableError: HTTP 503\ndenied by network policy"], - ["invalid response", "ServiceUnavailableError: HTTP 503\ninvalid provider response"], + ["unstructured provider output", "ServiceUnavailableError: HTTP 503"], ["unknown failure", "launch failed for an unknown reason"], ])("does not retry a %s (#10978)", async (_case, stderr) => { const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); From 8c240fb4d2efc6b20b051929ecf56e3184f6502a Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Fri, 4 Sep 2026 19:52:40 -0700 Subject: [PATCH 04/43] fix(forward): settle service startup safely Signed-off-by: Prekshi Vyas --- .../openshell/forward-service.test.ts | 80 +++++++++- src/lib/adapters/openshell/forward-service.ts | 141 ++++++++++++++++-- src/lib/onboard/dashboard.ts | 24 ++- 3 files changed, 218 insertions(+), 27 deletions(-) diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index 2de4e61ca73..d8f749569a7 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -47,11 +47,12 @@ describe("OpenShell forward service", () => { it("detaches the OpenShell child and waits for its local port", () => { const unref = vi.fn(); - const spawnDetached = vi.fn(() => ({ unref })); + const spawnDetached = vi.fn(() => ({ pid: 41, unref })); let probes = 0; launchForwardService(target, { isReachable: () => ++probes >= 3, + isProcessRunning: () => true, sleep: () => {}, spawnDetached, timeoutMs: 1_000, @@ -74,14 +75,83 @@ describe("OpenShell forward service", () => { expect(spawnDetached).not.toHaveBeenCalled(); }); - it("fails when the detached service does not bind before the deadline", () => { + it("reports a running service that remains unbound at the deadline (#11084)", () => { + const unboundTarget = { ...target, localPort: 18_791, targetPort: 18_791 }; expect(() => - launchForwardService(target, { + launchForwardService(unboundTarget, { + describeState: () => "SANDBOX BIND PORT PID STATUS", + isProcessRunning: () => true, isReachable: () => false, sleep: () => {}, - spawnDetached: () => ({ unref: () => {} }), + spawnDetached: () => ({ pid: 42, unref: () => {} }), timeoutMs: 0, }), - ).toThrow(/did not bind/u); + ).toThrow(/remained running but did not bind.*forward list: SANDBOX BIND PORT PID STATUS/u); + }); + + it("retries only after the prior service process exited (#11084)", () => { + const spawnDetached = vi + .fn() + .mockReturnValueOnce({ pid: 51, unref: vi.fn() }) + .mockReturnValueOnce({ pid: 52, unref: vi.fn() }); + launchForwardService(target, { + isProcessRunning: (pid) => pid === 52, + isReachable: () => spawnDetached.mock.calls.length === 2, + retryDelayMs: 0, + sleep: () => {}, + spawnDetached, + timeoutMs: 1_000, + }); + + expect(spawnDetached).toHaveBeenCalledTimes(2); + }); + + it("does not duplicate a service that is still settling (#11084)", () => { + const settlingTarget = { ...target, localPort: 18_790, targetPort: 18_790 }; + const spawnDetached = vi.fn(() => ({ pid: 61, unref: vi.fn() })); + const options = { + isProcessRunning: () => true, + isReachable: () => false, + sleep: () => {}, + spawnDetached, + timeoutMs: 0, + }; + + expect(() => launchForwardService(settlingTarget, options)).toThrow(/remained running/u); + expect(() => launchForwardService(settlingTarget, options)).toThrow(/still settling/u); + expect(spawnDetached).toHaveBeenCalledOnce(); + }); + + it("refuses an unknown listener that appears before a safe retry (#11084)", () => { + const spawnDetached = vi.fn(() => ({ pid: 71, unref: vi.fn() })); + let probes = 0; + + expect(() => + launchForwardService(target, { + isProcessRunning: () => false, + isReachable: () => ++probes >= 3, + retryDelayMs: 0, + sleep: () => {}, + spawnDetached, + timeoutMs: 1_000, + }), + ).toThrow(/became occupied.*refusing to adopt/u); + expect(spawnDetached).toHaveBeenCalledOnce(); + }); + + it("does not retry when the service returns no process identity (#11084)", () => { + const spawnDetached = vi.fn(() => ({ unref: vi.fn() })); + + expect(() => + launchForwardService(target, { + describeState: () => { + throw new Error("forward list failed"); + }, + isReachable: () => false, + sleep: () => {}, + spawnDetached, + }), + ).toThrow(/no process identity.*forward list: /u); + expect(spawnDetached).toHaveBeenCalledOnce(); }); }); diff --git a/src/lib/adapters/openshell/forward-service.ts b/src/lib/adapters/openshell/forward-service.ts index 8f78fe81983..0498edd2ec6 100644 --- a/src/lib/adapters/openshell/forward-service.ts +++ b/src/lib/adapters/openshell/forward-service.ts @@ -2,16 +2,28 @@ // SPDX-License-Identifier: Apache-2.0 import { spawn } from "node:child_process"; +import fs from "node:fs"; import path from "node:path"; import { isValidName } from "../../name-validation"; import { buildOpenShellSubprocessEnv } from "./resolve-shared"; import { probeLocalForwardListener } from "./local-forward-listener"; -const START_TIMEOUT_MS = 30_000; +const START_TIMEOUT_MS = 90_000; +const START_RETRY_DELAY_MS = 1_000; +const START_ATTEMPTS = 2; const POLL_INTERVAL_MS = 100; const sleepBuffer = new Int32Array(new SharedArrayBuffer(4)); +type ForwardServiceChild = { + readonly pid?: number; + unref(): void; +}; + +// Keep exact child identity only for this CLI process. A later recovery call may +// observe the same child settling, but must never adopt an unrelated listener. +const settlingChildren = new Map(); + export interface ForwardServiceTarget { readonly executable: string; readonly gatewayName: string; @@ -24,19 +36,68 @@ export interface ForwardServiceTarget { } export interface ForwardServiceLaunchOptions { + readonly describeState?: () => string | null | undefined; + readonly isProcessRunning?: (pid: number) => boolean; readonly isReachable?: (port: number) => boolean; + readonly maxAttempts?: number; + readonly retryDelayMs?: number; readonly sleep?: (milliseconds: number) => void; readonly sourceEnvironment?: NodeJS.ProcessEnv; readonly spawnDetached?: ( executable: string, args: readonly string[], environment: NodeJS.ProcessEnv, - ) => { - unref(): void; - }; + ) => ForwardServiceChild; readonly timeoutMs?: number; } +function forwardKey(target: ForwardServiceTarget): string { + return [ + target.gatewayName, + target.workspace, + target.sandboxName, + target.localHost, + target.localPort, + target.targetHost, + target.targetPort, + ].join("\0"); +} + +function isProcessRunning(pid: number): boolean { + try { + if (process.platform === "linux") { + // Signal 0 still reports a zombie as present. Read its state so a failed + // forward may be retried without starting alongside a live process. + const stat = fs.readFileSync(`/proc/${String(pid)}/stat`, "utf8"); + const state = stat.slice(stat.lastIndexOf(")") + 2).split(" ", 1)[0]; + if (state === "Z") return false; + } + process.kill(pid, 0); + return true; + } catch (error) { + const code = + typeof error === "object" && error !== null && "code" in error ? error.code : undefined; + return code !== "ENOENT" && code !== "ESRCH"; + } +} + +function boundedState(description: string | null | undefined): string { + const compact = (description ?? "").replace(/\s+/gu, " ").trim(); + return compact ? compact.slice(0, 240) : ""; +} + +function describeFailureState(describe: (() => string | null | undefined) | undefined): string { + try { + return boundedState(describe?.()); + } catch { + return ""; + } +} + +function isProcessIdentity(pid: number | undefined): pid is number { + return Number.isSafeInteger(pid) && Number(pid) > 0; +} + function isPort(value: unknown): value is number { return Number.isSafeInteger(value) && Number(value) >= 1 && Number(value) <= 65_535; } @@ -101,6 +162,19 @@ export function launchForwardService( ): void { validateForwardServiceTarget(target); const isReachable = options.isReachable ?? probeLocalForwardListener; + const processIsRunning = options.isProcessRunning ?? isProcessRunning; + const key = forwardKey(target); + const settling = settlingChildren.get(key); + if (isProcessIdentity(settling?.pid) && processIsRunning(settling.pid)) { + if (isReachable(target.localPort)) { + settlingChildren.delete(key); + return; + } + throw new Error( + `OpenShell forward service is still settling on ${target.localHost}:${String(target.localPort)}; refusing to start a duplicate service`, + ); + } + settlingChildren.delete(key); if (isReachable(target.localPort)) { throw new Error(`Host port ${String(target.localPort)} is already occupied`); } @@ -108,21 +182,56 @@ export function launchForwardService( options.spawnDetached ?? ((executable, args, environment) => spawn(executable, [...args], { detached: true, env: environment, stdio: "ignore" })); - const child = spawnDetached( - target.executable, - buildForwardServiceArgs(target), - buildOpenShellSubprocessEnv(options.sourceEnvironment ?? process.env), - ); - child.unref(); - const sleep = options.sleep ?? ((milliseconds: number) => Atomics.wait(sleepBuffer, 0, 0, milliseconds)); - const deadline = Date.now() + (options.timeoutMs ?? START_TIMEOUT_MS); - while (Date.now() < deadline) { - if (isReachable(target.localPort)) return; - sleep(POLL_INTERVAL_MS); + const attempts = options.maxAttempts ?? START_ATTEMPTS; + if (!Number.isSafeInteger(attempts) || attempts < 1 || attempts > START_ATTEMPTS) { + throw new Error(`OpenShell forward service attempts must be between 1 and ${START_ATTEMPTS}`); + } + const args = buildForwardServiceArgs(target); + const environment = buildOpenShellSubprocessEnv(options.sourceEnvironment ?? process.env); + for (let attempt = 1; attempt <= attempts; attempt += 1) { + if (isReachable(target.localPort)) { + throw new Error( + `Host port ${String(target.localPort)} became occupied before forward retry; refusing to adopt its listener`, + ); + } + const child = spawnDetached(target.executable, args, environment); + child.unref(); + if (!isProcessIdentity(child.pid)) { + throw new Error( + `OpenShell forward service returned no process identity for ${target.localHost}:${String(target.localPort)}; ` + + `refusing to start a duplicate service; forward list: ${describeFailureState(options.describeState)}`, + ); + } + const deadline = Date.now() + (options.timeoutMs ?? START_TIMEOUT_MS); + let exited = false; + while (true) { + if (isProcessIdentity(child.pid) && !processIsRunning(child.pid)) { + exited = true; + break; + } + if (isReachable(target.localPort)) { + settlingChildren.delete(key); + return; + } + if (Date.now() >= deadline) break; + sleep(POLL_INTERVAL_MS); + } + if (!exited) { + settlingChildren.set(key, child); + throw new Error( + `OpenShell forward service remained running but did not bind ${target.localHost}:${String(target.localPort)} within ${String(options.timeoutMs ?? START_TIMEOUT_MS)}ms; ` + + `refusing to start a duplicate service; forward list: ${describeFailureState(options.describeState)}`, + ); + } + settlingChildren.delete(key); + if (attempt < attempts) { + sleep(options.retryDelayMs ?? START_RETRY_DELAY_MS); + } } throw new Error( - `OpenShell forward service did not bind ${target.localHost}:${String(target.localPort)}`, + `OpenShell forward service exited before binding ${target.localHost}:${String(target.localPort)} after ${String(attempts)} attempts; ` + + `forward list: ${describeFailureState(options.describeState)}`, ); } diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index 615e45e0ad7..8650f4ae08d 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -273,6 +273,22 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa }; } + function launchForward(target: ForwardServiceTarget): void { + if (forwardService?.launch) { + forwardService.launch(target); + return; + } + launchForwardService(target, { + describeState: () => { + const output = deps.runCaptureOpenshell( + ["forward", "list", "--gateway", target.gatewayName], + { ignoreError: true }, + ); + return output === null ? "unavailable" : deps.redact(output); + }, + }); + } + function getDashboardForwardPort( chatUiUrl = process.env.CHAT_UI_URL || `http://127.0.0.1:${CONTROL_UI_PORT}`, options: Parameters[1] = {}, @@ -443,9 +459,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa `start dashboard forward ${String(actualPort)} for sandbox '${sandboxName}'`, ); forwardService?.retireLegacy?.(sandboxName, actualGateway, [actualPort]); - (forwardService?.launch ?? launchForwardService)( - forwardTarget(sandboxName, actualGateway, actualPort, actualTarget), - ); + launchForward(forwardTarget(sandboxName, actualGateway, actualPort, actualTarget)); fwdOk = true; } catch (error) { fwdDiagnostic = error instanceof Error ? error.message : String(error); @@ -585,9 +599,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa `start ${label} forward ${String(port)} for sandbox '${sandboxName}'`, ); forwardService?.retireLegacy?.(sandboxName, gatewayName, [port]); - (forwardService?.launch ?? launchForwardService)( - forwardTarget(sandboxName, gatewayName, port, String(port)), - ); + launchForward(forwardTarget(sandboxName, gatewayName, port, String(port))); return true; } catch (error) { const diagnostic = error instanceof Error ? error.message : String(error); From b180da4ab03335a414f3fc5d183c0e04dbce7e0d Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Fri, 4 Sep 2026 21:03:04 -0700 Subject: [PATCH 05/43] fix(e2e): make forward retries process-safe Signed-off-by: Prekshi Vyas --- docs/get-started/quickstart-hermes.mdx | 7 +- docs/get-started/quickstart.mdx | 7 +- .../openshell/forward-service.test.ts | 61 +++++++++--- src/lib/adapters/openshell/forward-service.ts | 99 ++++++++++++------- .../launch-readiness-lease-acceptance.test.ts | 4 +- test/e2e/support/launch-agent-turn.test.ts | 23 ++--- 6 files changed, 137 insertions(+), 64 deletions(-) diff --git a/docs/get-started/quickstart-hermes.mdx b/docs/get-started/quickstart-hermes.mdx index b865d109b12..931b597e449 100644 --- a/docs/get-started/quickstart-hermes.mdx +++ b/docs/get-started/quickstart-hermes.mdx @@ -381,8 +381,11 @@ Use these details when your first-run path needs more control. The onboard flow starts both port forwards automatically. For a new sandbox, NemoClaw reserves the selected dashboard loopback port through sandbox preparation and creation. If another listener claims the port before NemoClaw binds the reservation, NemoClaw selects another port before changing sandbox resources. - If OpenShell returns the `sandbox is not ready` response, NemoClaw waits 5 seconds and retries the affected forward up to 12 times. - The readiness-specific delays total at most 1 minute and preserve the existing sandbox and selected host port. + NemoClaw waits up to 90 seconds for each forward to bind. + If the exact forward process exits before it binds, NemoClaw waits 1 second and retries once. + If the process remains unbound at the deadline, NemoClaw stops that exact process and confirms its exit before retrying. + The complete two-attempt sequence can take just over 3 minutes for each forward. + NemoClaw does not adopt an unrelated listener or start another forward while it cannot confirm that the prior process stopped. NemoClaw releases the reservation immediately before OpenShell starts the dashboard forward. If forwarding then fails, onboarding removes the new sandbox and tells you to resolve the reported error before retrying. The Hermes dashboard URL does not include an OpenClaw `#token=` fragment. diff --git a/docs/get-started/quickstart.mdx b/docs/get-started/quickstart.mdx index d414b28054e..ecafeb0db03 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -458,8 +458,11 @@ Use these details when your first-run path needs more control. When that port is occupied, NemoClaw uses the next free dashboard port, such as `18790`, and includes the port in the URL. For a new sandbox, NemoClaw reserves the selected loopback port through sandbox preparation and creation. If another listener claims the port before NemoClaw binds the reservation, NemoClaw selects another port before changing sandbox resources. - If OpenShell returns the `sandbox is not ready` response, NemoClaw waits 5 seconds and retries the dashboard forward up to 12 times. - The readiness-specific delays total at most 1 minute and preserve the existing sandbox and selected port. + NemoClaw waits up to 90 seconds for the dashboard forward to bind. + If the exact forward process exits before it binds, NemoClaw waits 1 second and retries once. + If the process remains unbound at the deadline, NemoClaw stops that exact process and confirms its exit before retrying. + The complete two-attempt sequence can take just over 3 minutes. + NemoClaw does not adopt an unrelated listener or start another forward while it cannot confirm that the prior process stopped. NemoClaw releases the reservation immediately before OpenShell starts the dashboard forward. If forwarding then fails, onboarding removes the new sandbox and tells you to resolve the reported error before retrying. The installation transcript does not print the gateway token. diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index d8f749569a7..55bf142e6fc 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -75,18 +75,25 @@ describe("OpenShell forward service", () => { expect(spawnDetached).not.toHaveBeenCalled(); }); - it("reports a running service that remains unbound at the deadline (#11084)", () => { + it("stops a running service that remains unbound at the deadline (#11084)", () => { const unboundTarget = { ...target, localPort: 18_791, targetPort: 18_791 }; + let running = true; + const stopProcess = vi.fn(() => { + running = false; + }); expect(() => launchForwardService(unboundTarget, { describeState: () => "SANDBOX BIND PORT PID STATUS", - isProcessRunning: () => true, + isProcessRunning: () => running, isReachable: () => false, + maxAttempts: 1, sleep: () => {}, spawnDetached: () => ({ pid: 42, unref: () => {} }), + stopProcess, timeoutMs: 0, }), - ).toThrow(/remained running but did not bind.*forward list: SANDBOX BIND PORT PID STATUS/u); + ).toThrow(/was stopped after failing to bind.*forward list: SANDBOX BIND PORT PID STATUS/u); + expect(stopProcess).toHaveBeenCalledWith(42, "SIGTERM"); }); it("retries only after the prior service process exited (#11084)", () => { @@ -106,20 +113,48 @@ describe("OpenShell forward service", () => { expect(spawnDetached).toHaveBeenCalledTimes(2); }); - it("does not duplicate a service that is still settling (#11084)", () => { + it("does not retry when the timed-out service cannot be stopped (#11084)", () => { const settlingTarget = { ...target, localPort: 18_790, targetPort: 18_790 }; const spawnDetached = vi.fn(() => ({ pid: 61, unref: vi.fn() })); - const options = { - isProcessRunning: () => true, - isReachable: () => false, - sleep: () => {}, - spawnDetached, - timeoutMs: 0, - }; + const stopProcess = vi.fn(); - expect(() => launchForwardService(settlingTarget, options)).toThrow(/remained running/u); - expect(() => launchForwardService(settlingTarget, options)).toThrow(/still settling/u); + expect(() => + launchForwardService(settlingTarget, { + isProcessRunning: () => true, + isReachable: () => false, + sleep: () => {}, + spawnDetached, + stopProcess, + stopTimeoutMs: 0, + timeoutMs: 0, + }), + ).toThrow(/process 61.*could not be stopped.*do not retry/u); expect(spawnDetached).toHaveBeenCalledOnce(); + expect(stopProcess.mock.calls).toEqual([ + [61, "SIGTERM"], + [61, "SIGKILL"], + ]); + }); + + it("confirms exit after escalating a timed-out service to SIGKILL (#11084)", () => { + const signals: NodeJS.Signals[] = []; + let killChecks = 0; + + expect(() => + launchForwardService(target, { + isProcessRunning: () => + signals.at(-1) === "SIGKILL" ? ++killChecks < 2 : true, + isReachable: () => false, + maxAttempts: 1, + sleep: () => {}, + spawnDetached: () => ({ pid: 62, unref: vi.fn() }), + stopProcess: (_pid, signal) => signals.push(signal), + stopTimeoutMs: 1_000, + timeoutMs: 0, + }), + ).toThrow(/was stopped after failing to bind/u); + expect(signals).toEqual(["SIGTERM", "SIGKILL"]); + expect(killChecks).toBe(2); }); it("refuses an unknown listener that appears before a safe retry (#11084)", () => { diff --git a/src/lib/adapters/openshell/forward-service.ts b/src/lib/adapters/openshell/forward-service.ts index 0498edd2ec6..12ab99a63c5 100644 --- a/src/lib/adapters/openshell/forward-service.ts +++ b/src/lib/adapters/openshell/forward-service.ts @@ -12,6 +12,7 @@ import { probeLocalForwardListener } from "./local-forward-listener"; const START_TIMEOUT_MS = 90_000; const START_RETRY_DELAY_MS = 1_000; const START_ATTEMPTS = 2; +const STOP_TIMEOUT_MS = 5_000; const POLL_INTERVAL_MS = 100; const sleepBuffer = new Int32Array(new SharedArrayBuffer(4)); @@ -20,10 +21,6 @@ type ForwardServiceChild = { unref(): void; }; -// Keep exact child identity only for this CLI process. A later recovery call may -// observe the same child settling, but must never adopt an unrelated listener. -const settlingChildren = new Map(); - export interface ForwardServiceTarget { readonly executable: string; readonly gatewayName: string; @@ -43,6 +40,8 @@ export interface ForwardServiceLaunchOptions { readonly retryDelayMs?: number; readonly sleep?: (milliseconds: number) => void; readonly sourceEnvironment?: NodeJS.ProcessEnv; + readonly stopProcess?: (pid: number, signal: NodeJS.Signals) => void; + readonly stopTimeoutMs?: number; readonly spawnDetached?: ( executable: string, args: readonly string[], @@ -51,18 +50,6 @@ export interface ForwardServiceLaunchOptions { readonly timeoutMs?: number; } -function forwardKey(target: ForwardServiceTarget): string { - return [ - target.gatewayName, - target.workspace, - target.sandboxName, - target.localHost, - target.localPort, - target.targetHost, - target.targetPort, - ].join("\0"); -} - function isProcessRunning(pid: number): boolean { try { if (process.platform === "linux") { @@ -98,6 +85,49 @@ function isProcessIdentity(pid: number | undefined): pid is number { return Number.isSafeInteger(pid) && Number(pid) > 0; } +function isMissingProcessError(error: unknown): boolean { + const code = + typeof error === "object" && error !== null && "code" in error ? error.code : undefined; + return code === "ENOENT" || code === "ESRCH"; +} + +function waitForProcessExit( + pid: number, + processIsRunning: (pid: number) => boolean, + sleep: (milliseconds: number) => void, + timeoutMs: number, +): boolean { + const deadline = Date.now() + timeoutMs; + while (processIsRunning(pid)) { + if (Date.now() >= deadline) return false; + sleep(POLL_INTERVAL_MS); + } + return true; +} + +function stopOwnedProcess( + pid: number, + processIsRunning: (pid: number) => boolean, + stopProcess: (pid: number, signal: NodeJS.Signals) => void, + sleep: (milliseconds: number) => void, + timeoutMs: number, +): boolean { + try { + stopProcess(pid, "SIGTERM"); + } catch (error) { + if (isMissingProcessError(error)) return true; + return false; + } + if (waitForProcessExit(pid, processIsRunning, sleep, timeoutMs)) return true; + try { + stopProcess(pid, "SIGKILL"); + } catch (error) { + if (isMissingProcessError(error)) return true; + return false; + } + return waitForProcessExit(pid, processIsRunning, sleep, timeoutMs); +} + function isPort(value: unknown): value is number { return Number.isSafeInteger(value) && Number(value) >= 1 && Number(value) <= 65_535; } @@ -163,18 +193,6 @@ export function launchForwardService( validateForwardServiceTarget(target); const isReachable = options.isReachable ?? probeLocalForwardListener; const processIsRunning = options.isProcessRunning ?? isProcessRunning; - const key = forwardKey(target); - const settling = settlingChildren.get(key); - if (isProcessIdentity(settling?.pid) && processIsRunning(settling.pid)) { - if (isReachable(target.localPort)) { - settlingChildren.delete(key); - return; - } - throw new Error( - `OpenShell forward service is still settling on ${target.localHost}:${String(target.localPort)}; refusing to start a duplicate service`, - ); - } - settlingChildren.delete(key); if (isReachable(target.localPort)) { throw new Error(`Host port ${String(target.localPort)} is already occupied`); } @@ -184,13 +202,17 @@ export function launchForwardService( spawn(executable, [...args], { detached: true, env: environment, stdio: "ignore" })); const sleep = options.sleep ?? ((milliseconds: number) => Atomics.wait(sleepBuffer, 0, 0, milliseconds)); + const stopProcess = + options.stopProcess ?? ((pid: number, signal: NodeJS.Signals) => process.kill(pid, signal)); const attempts = options.maxAttempts ?? START_ATTEMPTS; if (!Number.isSafeInteger(attempts) || attempts < 1 || attempts > START_ATTEMPTS) { throw new Error(`OpenShell forward service attempts must be between 1 and ${START_ATTEMPTS}`); } const args = buildForwardServiceArgs(target); const environment = buildOpenShellSubprocessEnv(options.sourceEnvironment ?? process.env); + let finalFailure = "exited before binding"; for (let attempt = 1; attempt <= attempts; attempt += 1) { + finalFailure = "exited before binding"; if (isReachable(target.localPort)) { throw new Error( `Host port ${String(target.localPort)} became occupied before forward retry; refusing to adopt its listener`, @@ -212,26 +234,33 @@ export function launchForwardService( break; } if (isReachable(target.localPort)) { - settlingChildren.delete(key); return; } if (Date.now() >= deadline) break; sleep(POLL_INTERVAL_MS); } if (!exited) { - settlingChildren.set(key, child); - throw new Error( - `OpenShell forward service remained running but did not bind ${target.localHost}:${String(target.localPort)} within ${String(options.timeoutMs ?? START_TIMEOUT_MS)}ms; ` + - `refusing to start a duplicate service; forward list: ${describeFailureState(options.describeState)}`, + const stopped = stopOwnedProcess( + child.pid, + processIsRunning, + stopProcess, + sleep, + options.stopTimeoutMs ?? STOP_TIMEOUT_MS, ); + if (!stopped) { + throw new Error( + `OpenShell forward service process ${String(child.pid)} remained running after its ${String(options.timeoutMs ?? START_TIMEOUT_MS)}ms bind deadline and could not be stopped; ` + + `do not retry until that process exits; forward list: ${describeFailureState(options.describeState)}`, + ); + } + finalFailure = "was stopped after failing to bind"; } - settlingChildren.delete(key); if (attempt < attempts) { sleep(options.retryDelayMs ?? START_RETRY_DELAY_MS); } } throw new Error( - `OpenShell forward service exited before binding ${target.localHost}:${String(target.localPort)} after ${String(attempts)} attempts; ` + + `OpenShell forward service ${finalFailure} ${target.localHost}:${String(target.localPort)} after ${String(attempts)} attempts; ` + `forward list: ${describeFailureState(options.describeState)}`, ); } diff --git a/test/e2e/live/launch-readiness-lease-acceptance.test.ts b/test/e2e/live/launch-readiness-lease-acceptance.test.ts index 5e72c8b1098..6f94a1b60c8 100644 --- a/test/e2e/live/launch-readiness-lease-acceptance.test.ts +++ b/test/e2e/live/launch-readiness-lease-acceptance.test.ts @@ -11,7 +11,9 @@ const SANDBOX_NAME = process.env.NEMOCLAW_ACCEPTANCE_SANDBOX?.trim() ?? ""; test.runIf(process.platform === "linux" && SANDBOX_NAME.length > 0)( "launch readiness locked-image acceptance", { - timeout: 15 * 60_000, + // The 6-minute readiness probe can be followed by 2 launch sessions, + // each with 2 bounded 280-second provider attempts, plus cleanup time. + timeout: 30 * 60_000, meta: { e2ePhases: [ "verify the existing locked-image sandbox", diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index ff96afb4a73..39aa4bc5bc7 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -497,7 +497,7 @@ if (process.argv[2] !== "tui") { } const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true }); const ask = () => new Promise((resolve) => rl.question("", resolve)); - if (terminalCopy === "ansi") process.stdout.write("\u001b[2Kgateway connected | idle\r"); + if (terminalCopy === "ansi") process.stdout.write("\u001b[2KServiceUnavailableError\r"); if (terminalCopy === "reordered") process.stdout.write("idle | gateway connected\n"); if (mode === "delayed-recording") { @@ -640,13 +640,14 @@ exec "$@" NEMOCLAW_LAUNCH_RUN_ID: runId, NEMOCLAW_LAUNCH_RUNTIME_ENV_SCRIPT: OPENCLAW_LAUNCH_RUNTIME_ENV_SCRIPT, NEMOCLAW_LAUNCH_SANDBOX: "sandbox", - NEMOCLAW_LAUNCH_SESSION_BUDGET_SECONDS: mode === "restored-canonical-timeout" - ? "10" - : mode === "pty-socket-timeout" - ? "5" - : mode.endsWith("-timeout") - ? "2" - : "230", + NEMOCLAW_LAUNCH_SESSION_BUDGET_SECONDS: + mode === "restored-canonical-timeout" + ? "10" + : mode === "pty-socket-timeout" + ? "5" + : mode.endsWith("-timeout") + ? "2" + : "230", NEMOCLAW_LAUNCH_SECOND_INPUT: "second input", NEMOCLAW_LAUNCH_SESSION_EVIDENCE_SCRIPT: OPENCLAW_SESSION_EVIDENCE_SCRIPT, NEMOCLAW_LAUNCH_SESSION_ROOT: sessionRoot, @@ -1248,18 +1249,18 @@ it.runIf(process.platform === "linux")( ); it.runIf(process.platform === "linux")( - "reports missing structured turns before the PTY child timeout (#9160)", + "marks provider unavailability when structured turns remain missing (#9160, #10978)", () => { const { baselineRemoved, result, ttyObserved } = runLaunchSessionFixture( "recording-timeout", - "absent", + "ansi", ); expect(ttyObserved).toBe(true); expect(baselineRemoved).toBe(true); expect(result.signal).toBeNull(); expect(result.status).toBe(1); - expect(result.stderr).toContain("launch did not record the required structured session turns"); + expect(result.stderr).toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); }, ); From 5571a9bae412fb0a4af982e2e24de726de48079c Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Fri, 4 Sep 2026 21:19:12 -0700 Subject: [PATCH 06/43] fix(forward): verify process identity before cleanup Signed-off-by: Prekshi Vyas --- .../openshell/forward-service.test.ts | 43 +++++- src/lib/adapters/openshell/forward-service.ts | 129 +++++++++++++++--- 2 files changed, 152 insertions(+), 20 deletions(-) diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index 55bf142e6fc..cd73557fdc8 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -19,6 +19,7 @@ const target: ForwardServiceTarget = { targetHost: "127.0.0.1", targetPort: 18_789, }; +const stableProcessIdentity = (pid: number): string => `start-${String(pid)}`; describe("OpenShell forward service", () => { it("builds the direct ForwardTcp command with explicit gateway authority", () => { @@ -51,6 +52,7 @@ describe("OpenShell forward service", () => { let probes = 0; launchForwardService(target, { + getProcessIdentity: stableProcessIdentity, isReachable: () => ++probes >= 3, isProcessRunning: () => true, sleep: () => {}, @@ -84,6 +86,7 @@ describe("OpenShell forward service", () => { expect(() => launchForwardService(unboundTarget, { describeState: () => "SANDBOX BIND PORT PID STATUS", + getProcessIdentity: stableProcessIdentity, isProcessRunning: () => running, isReachable: () => false, maxAttempts: 1, @@ -102,6 +105,7 @@ describe("OpenShell forward service", () => { .mockReturnValueOnce({ pid: 51, unref: vi.fn() }) .mockReturnValueOnce({ pid: 52, unref: vi.fn() }); launchForwardService(target, { + getProcessIdentity: stableProcessIdentity, isProcessRunning: (pid) => pid === 52, isReachable: () => spawnDetached.mock.calls.length === 2, retryDelayMs: 0, @@ -120,6 +124,7 @@ describe("OpenShell forward service", () => { expect(() => launchForwardService(settlingTarget, { + getProcessIdentity: stableProcessIdentity, isProcessRunning: () => true, isReachable: () => false, sleep: () => {}, @@ -128,7 +133,7 @@ describe("OpenShell forward service", () => { stopTimeoutMs: 0, timeoutMs: 0, }), - ).toThrow(/process 61.*could not be stopped.*do not retry/u); + ).toThrow(/process 61.*could not stop.*refusing to signal or retry/u); expect(spawnDetached).toHaveBeenCalledOnce(); expect(stopProcess.mock.calls).toEqual([ [61, "SIGTERM"], @@ -142,6 +147,7 @@ describe("OpenShell forward service", () => { expect(() => launchForwardService(target, { + getProcessIdentity: stableProcessIdentity, isProcessRunning: () => signals.at(-1) === "SIGKILL" ? ++killChecks < 2 : true, isReachable: () => false, @@ -157,12 +163,33 @@ describe("OpenShell forward service", () => { expect(killChecks).toBe(2); }); + it("does not signal or retry after the forward PID is reused (#11084)", () => { + const spawnDetached = vi.fn(() => ({ pid: 63, unref: vi.fn() })); + const stopProcess = vi.fn(); + let identityReads = 0; + + expect(() => + launchForwardService(target, { + getProcessIdentity: () => (++identityReads === 1 ? "original" : "replacement"), + isProcessRunning: () => true, + isReachable: () => false, + sleep: () => {}, + spawnDetached, + stopProcess, + timeoutMs: 0, + }), + ).toThrow(/process 63 changed identity.*refusing to signal or retry/u); + expect(stopProcess).not.toHaveBeenCalled(); + expect(spawnDetached).toHaveBeenCalledOnce(); + }); + it("refuses an unknown listener that appears before a safe retry (#11084)", () => { const spawnDetached = vi.fn(() => ({ pid: 71, unref: vi.fn() })); let probes = 0; expect(() => launchForwardService(target, { + getProcessIdentity: stableProcessIdentity, isProcessRunning: () => false, isReachable: () => ++probes >= 3, retryDelayMs: 0, @@ -174,6 +201,20 @@ describe("OpenShell forward service", () => { expect(spawnDetached).toHaveBeenCalledOnce(); }); + it.runIf(process.platform === "linux")( + "tracks the spawned process by its Linux start time (#11084)", + () => { + let probes = 0; + + launchForwardService(target, { + isReachable: () => ++probes >= 2, + spawnDetached: () => ({ pid: process.pid, unref: vi.fn() }), + }); + + expect(probes).toBe(2); + }, + ); + it("does not retry when the service returns no process identity (#11084)", () => { const spawnDetached = vi.fn(() => ({ unref: vi.fn() })); diff --git a/src/lib/adapters/openshell/forward-service.ts b/src/lib/adapters/openshell/forward-service.ts index 12ab99a63c5..824cdfdfb66 100644 --- a/src/lib/adapters/openshell/forward-service.ts +++ b/src/lib/adapters/openshell/forward-service.ts @@ -34,6 +34,7 @@ export interface ForwardServiceTarget { export interface ForwardServiceLaunchOptions { readonly describeState?: () => string | null | undefined; + readonly getProcessIdentity?: (pid: number) => string | null | undefined; readonly isProcessRunning?: (pid: number) => boolean; readonly isReachable?: (port: number) => boolean; readonly maxAttempts?: number; @@ -50,14 +51,32 @@ export interface ForwardServiceLaunchOptions { readonly timeoutMs?: number; } +function readLinuxProcessStat(pid: number): string[] | null | undefined { + if (process.platform !== "linux") return undefined; + try { + const stat = fs.readFileSync(`/proc/${String(pid)}/stat`, "utf8"); + return stat.slice(stat.lastIndexOf(")") + 2).split(" "); + } catch (error) { + const code = + typeof error === "object" && error !== null && "code" in error ? error.code : undefined; + return code === "ENOENT" || code === "ESRCH" ? null : undefined; + } +} + +function getProcessIdentity(pid: number): string | null | undefined { + const stat = readLinuxProcessStat(pid); + const startTime = stat?.[19]; + return startTime && /^\d+$/u.test(startTime) ? startTime : stat === null ? null : undefined; +} + function isProcessRunning(pid: number): boolean { try { if (process.platform === "linux") { // Signal 0 still reports a zombie as present. Read its state so a failed // forward may be retried without starting alongside a live process. - const stat = fs.readFileSync(`/proc/${String(pid)}/stat`, "utf8"); - const state = stat.slice(stat.lastIndexOf(")") + 2).split(" ", 1)[0]; - if (state === "Z") return false; + const stat = readLinuxProcessStat(pid); + if (stat === null) return false; + if (stat?.[0] === "Z") return false; } process.kill(pid, 0); return true; @@ -91,41 +110,83 @@ function isMissingProcessError(error: unknown): boolean { return code === "ENOENT" || code === "ESRCH"; } +type OwnedProcessStopResult = "stopped" | "running" | "unverified"; + +function processIdentityStatus( + pid: number, + expectedIdentity: string | null | undefined, + readIdentity: (pid: number) => string | null | undefined, +): "owned" | "exited" | "unverified" { + if (!expectedIdentity) return "unverified"; + const observedIdentity = readIdentity(pid); + if (observedIdentity === null) return "exited"; + return observedIdentity === expectedIdentity ? "owned" : "unverified"; +} + function waitForProcessExit( pid: number, + expectedIdentity: string, + readIdentity: (pid: number) => string | null | undefined, processIsRunning: (pid: number) => boolean, sleep: (milliseconds: number) => void, timeoutMs: number, -): boolean { +): OwnedProcessStopResult { const deadline = Date.now() + timeoutMs; - while (processIsRunning(pid)) { - if (Date.now() >= deadline) return false; + while (true) { + const identityStatus = processIdentityStatus(pid, expectedIdentity, readIdentity); + if (identityStatus === "exited" || !processIsRunning(pid)) return "stopped"; + if (identityStatus === "unverified") return "unverified"; + if (Date.now() >= deadline) return "running"; sleep(POLL_INTERVAL_MS); } - return true; } function stopOwnedProcess( pid: number, + expectedIdentity: string | null | undefined, + readIdentity: (pid: number) => string | null | undefined, processIsRunning: (pid: number) => boolean, stopProcess: (pid: number, signal: NodeJS.Signals) => void, sleep: (milliseconds: number) => void, timeoutMs: number, -): boolean { +): OwnedProcessStopResult { + if (!expectedIdentity) return "unverified"; + const identity = expectedIdentity; + const initialStatus = processIdentityStatus(pid, identity, readIdentity); + if (initialStatus === "exited") return "stopped"; + if (initialStatus === "unverified") return "unverified"; try { stopProcess(pid, "SIGTERM"); } catch (error) { - if (isMissingProcessError(error)) return true; - return false; + if (isMissingProcessError(error)) return "stopped"; + return "running"; + } + const termResult = waitForProcessExit( + pid, + identity, + readIdentity, + processIsRunning, + sleep, + timeoutMs, + ); + if (termResult !== "running") return termResult; + if (processIdentityStatus(pid, identity, readIdentity) !== "owned") { + return "unverified"; } - if (waitForProcessExit(pid, processIsRunning, sleep, timeoutMs)) return true; try { stopProcess(pid, "SIGKILL"); } catch (error) { - if (isMissingProcessError(error)) return true; - return false; + if (isMissingProcessError(error)) return "stopped"; + return "running"; } - return waitForProcessExit(pid, processIsRunning, sleep, timeoutMs); + return waitForProcessExit( + pid, + identity, + readIdentity, + processIsRunning, + sleep, + timeoutMs, + ); } function isPort(value: unknown): value is number { @@ -193,6 +254,7 @@ export function launchForwardService( validateForwardServiceTarget(target); const isReachable = options.isReachable ?? probeLocalForwardListener; const processIsRunning = options.isProcessRunning ?? isProcessRunning; + const readProcessIdentity = options.getProcessIdentity ?? getProcessIdentity; if (isReachable(target.localPort)) { throw new Error(`Host port ${String(target.localPort)} is already occupied`); } @@ -219,16 +281,33 @@ export function launchForwardService( ); } const child = spawnDetached(target.executable, args, environment); - child.unref(); if (!isProcessIdentity(child.pid)) { throw new Error( `OpenShell forward service returned no process identity for ${target.localHost}:${String(target.localPort)}; ` + `refusing to start a duplicate service; forward list: ${describeFailureState(options.describeState)}`, ); } + const childIdentity = readProcessIdentity(child.pid); + child.unref(); const deadline = Date.now() + (options.timeoutMs ?? START_TIMEOUT_MS); let exited = false; + let ownershipLost = false; while (true) { + if (childIdentity) { + const identityStatus = processIdentityStatus( + child.pid, + childIdentity, + readProcessIdentity, + ); + if (identityStatus === "exited") { + exited = true; + break; + } + if (identityStatus === "unverified") { + ownershipLost = true; + break; + } + } if (isProcessIdentity(child.pid) && !processIsRunning(child.pid)) { exited = true; break; @@ -239,18 +318,30 @@ export function launchForwardService( if (Date.now() >= deadline) break; sleep(POLL_INTERVAL_MS); } + if (ownershipLost) { + throw new Error( + `OpenShell forward service process ${String(child.pid)} changed identity before binding ${target.localHost}:${String(target.localPort)}; ` + + `refusing to signal or retry; forward list: ${describeFailureState(options.describeState)}`, + ); + } if (!exited) { - const stopped = stopOwnedProcess( + const stopResult = stopOwnedProcess( child.pid, + childIdentity, + readProcessIdentity, processIsRunning, stopProcess, sleep, options.stopTimeoutMs ?? STOP_TIMEOUT_MS, ); - if (!stopped) { + if (stopResult !== "stopped") { + const reason = + stopResult === "unverified" + ? "could not verify that it still owned that process" + : "could not stop that process"; throw new Error( - `OpenShell forward service process ${String(child.pid)} remained running after its ${String(options.timeoutMs ?? START_TIMEOUT_MS)}ms bind deadline and could not be stopped; ` + - `do not retry until that process exits; forward list: ${describeFailureState(options.describeState)}`, + `OpenShell forward service process ${String(child.pid)} remained unbound after ${String(options.timeoutMs ?? START_TIMEOUT_MS)}ms and ${reason}; ` + + `refusing to signal or retry; forward list: ${describeFailureState(options.describeState)}`, ); } finalFailure = "was stopped after failing to bind"; From 366866286c14a7dd9a2d5934213f4a80235fde4f Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Fri, 4 Sep 2026 21:57:42 -0700 Subject: [PATCH 07/43] fix(forward): verify supported-host listener ownership Signed-off-by: Prekshi Vyas --- docs/get-started/quickstart-hermes.mdx | 3 +- docs/get-started/quickstart.mdx | 3 +- .../openshell/forward-service.test.ts | 63 +++++++++++++- src/lib/adapters/openshell/forward-service.ts | 85 +++++++++++++++---- 4 files changed, 132 insertions(+), 22 deletions(-) diff --git a/docs/get-started/quickstart-hermes.mdx b/docs/get-started/quickstart-hermes.mdx index 931b597e449..b8859078630 100644 --- a/docs/get-started/quickstart-hermes.mdx +++ b/docs/get-started/quickstart-hermes.mdx @@ -385,7 +385,8 @@ Use these details when your first-run path needs more control. If the exact forward process exits before it binds, NemoClaw waits 1 second and retries once. If the process remains unbound at the deadline, NemoClaw stops that exact process and confirms its exit before retrying. The complete two-attempt sequence can take just over 3 minutes for each forward. - NemoClaw does not adopt an unrelated listener or start another forward while it cannot confirm that the prior process stopped. + NemoClaw accepts each forward only when its spawned process owns the listener. + It does not adopt an unrelated listener or start another forward while it cannot confirm that the prior process stopped. NemoClaw releases the reservation immediately before OpenShell starts the dashboard forward. If forwarding then fails, onboarding removes the new sandbox and tells you to resolve the reported error before retrying. The Hermes dashboard URL does not include an OpenClaw `#token=` fragment. diff --git a/docs/get-started/quickstart.mdx b/docs/get-started/quickstart.mdx index ecafeb0db03..b3ea3c9b4bd 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -462,7 +462,8 @@ Use these details when your first-run path needs more control. If the exact forward process exits before it binds, NemoClaw waits 1 second and retries once. If the process remains unbound at the deadline, NemoClaw stops that exact process and confirms its exit before retrying. The complete two-attempt sequence can take just over 3 minutes. - NemoClaw does not adopt an unrelated listener or start another forward while it cannot confirm that the prior process stopped. + NemoClaw accepts the forward only when the spawned process owns the listener. + It does not adopt an unrelated listener or start another forward while it cannot confirm that the prior process stopped. NemoClaw releases the reservation immediately before OpenShell starts the dashboard forward. If forwarding then fails, onboarding removes the new sandbox and tells you to resolve the reported error before retrying. The installation transcript does not print the gateway token. diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index cd73557fdc8..a4bd48f66dd 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -53,6 +53,7 @@ describe("OpenShell forward service", () => { launchForwardService(target, { getProcessIdentity: stableProcessIdentity, + isListenerOwned: () => true, isReachable: () => ++probes >= 3, isProcessRunning: () => true, sleep: () => {}, @@ -106,6 +107,7 @@ describe("OpenShell forward service", () => { .mockReturnValueOnce({ pid: 52, unref: vi.fn() }); launchForwardService(target, { getProcessIdentity: stableProcessIdentity, + isListenerOwned: () => true, isProcessRunning: (pid) => pid === 52, isReachable: () => spawnDetached.mock.calls.length === 2, retryDelayMs: 0, @@ -148,8 +150,7 @@ describe("OpenShell forward service", () => { expect(() => launchForwardService(target, { getProcessIdentity: stableProcessIdentity, - isProcessRunning: () => - signals.at(-1) === "SIGKILL" ? ++killChecks < 2 : true, + isProcessRunning: () => (signals.at(-1) === "SIGKILL" ? ++killChecks < 2 : true), isReachable: () => false, maxAttempts: 1, sleep: () => {}, @@ -201,17 +202,71 @@ describe("OpenShell forward service", () => { expect(spawnDetached).toHaveBeenCalledOnce(); }); + it("refuses a reachable listener not owned by the launched process (#11084)", () => { + let running = true; + let probes = 0; + const stopProcess = vi.fn(() => { + running = false; + }); + + expect(() => + launchForwardService(target, { + getProcessIdentity: stableProcessIdentity, + isListenerOwned: () => false, + isProcessRunning: () => running, + isReachable: () => ++probes >= 3, + sleep: () => {}, + spawnDetached: () => ({ pid: 72, unref: vi.fn() }), + stopProcess, + timeoutMs: 1_000, + }), + ).toThrow(/became reachable.*owned by another process.*refused to report success/u); + expect(stopProcess).toHaveBeenCalledWith(72, "SIGTERM"); + }); + it.runIf(process.platform === "linux")( "tracks the spawned process by its Linux start time (#11084)", () => { let probes = 0; launchForwardService(target, { - isReachable: () => ++probes >= 2, + isListenerOwned: () => true, + isReachable: () => ++probes >= 3, spawnDetached: () => ({ pid: process.pid, unref: vi.fn() }), }); - expect(probes).toBe(2); + expect(probes).toBe(3); + }, + ); + + it.runIf(process.platform === "darwin")( + "stops and retries a spawned process using its macOS start time (#11084)", + () => { + let running = true; + let spawnCount = 0; + const stopProcess = vi.fn(() => { + running = false; + }); + const spawnDetached = vi.fn(() => { + spawnCount += 1; + running = true; + return { pid: process.pid, unref: vi.fn() }; + }); + + launchForwardService(target, { + isListenerOwned: () => true, + isProcessRunning: () => running, + isReachable: () => spawnCount === 2, + retryDelayMs: 0, + sleep: () => {}, + spawnDetached, + stopProcess, + timeoutMs: 0, + }); + + expect(spawnDetached).toHaveBeenCalledTimes(2); + expect(stopProcess).toHaveBeenCalledOnce(); + expect(stopProcess).toHaveBeenCalledWith(process.pid, "SIGTERM"); }, ); diff --git a/src/lib/adapters/openshell/forward-service.ts b/src/lib/adapters/openshell/forward-service.ts index 824cdfdfb66..9e0c820a264 100644 --- a/src/lib/adapters/openshell/forward-service.ts +++ b/src/lib/adapters/openshell/forward-service.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawn } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; @@ -36,6 +36,7 @@ export interface ForwardServiceLaunchOptions { readonly describeState?: () => string | null | undefined; readonly getProcessIdentity?: (pid: number) => string | null | undefined; readonly isProcessRunning?: (pid: number) => boolean; + readonly isListenerOwned?: (pid: number, port: number) => boolean | null; readonly isReachable?: (port: number) => boolean; readonly maxAttempts?: number; readonly retryDelayMs?: number; @@ -66,7 +67,39 @@ function readLinuxProcessStat(pid: number): string[] | null | undefined { function getProcessIdentity(pid: number): string | null | undefined { const stat = readLinuxProcessStat(pid); const startTime = stat?.[19]; - return startTime && /^\d+$/u.test(startTime) ? startTime : stat === null ? null : undefined; + if (startTime && /^\d+$/u.test(startTime)) return `linux:${startTime}`; + if (stat === null) return null; + if (process.platform === "linux") return undefined; + const result = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], { + encoding: "utf8", + env: buildOpenShellSubprocessEnv(process.env), + stdio: ["ignore", "pipe", "ignore"], + timeout: 1_000, + }); + if (result.error) return undefined; + const startedAt = result.status === 0 ? result.stdout.trim() : ""; + if (startedAt) return `${process.platform}:${startedAt}`; + return result.status === 1 ? null : undefined; +} + +function isListenerOwned(pid: number, port: number): boolean | null { + const result = spawnSync( + "lsof", + ["-nP", "-a", "-p", String(pid), `-iTCP:${String(port)}`, "-sTCP:LISTEN", "-t"], + { + encoding: "utf8", + env: buildOpenShellSubprocessEnv(process.env), + stdio: ["ignore", "pipe", "ignore"], + timeout: 1_000, + }, + ); + if (result.error) return null; + const listenerPids = result.stdout + .split(/\r?\n/u) + .map((value) => value.trim()) + .filter(Boolean); + if (result.status === 0) return listenerPids.includes(String(pid)); + return result.status === 1 && listenerPids.length === 0 ? false : null; } function isProcessRunning(pid: number): boolean { @@ -179,14 +212,7 @@ function stopOwnedProcess( if (isMissingProcessError(error)) return "stopped"; return "running"; } - return waitForProcessExit( - pid, - identity, - readIdentity, - processIsRunning, - sleep, - timeoutMs, - ); + return waitForProcessExit(pid, identity, readIdentity, processIsRunning, sleep, timeoutMs); } function isPort(value: unknown): value is number { @@ -255,6 +281,7 @@ export function launchForwardService( const isReachable = options.isReachable ?? probeLocalForwardListener; const processIsRunning = options.isProcessRunning ?? isProcessRunning; const readProcessIdentity = options.getProcessIdentity ?? getProcessIdentity; + const listenerIsOwned = options.isListenerOwned ?? isListenerOwned; if (isReachable(target.localPort)) { throw new Error(`Host port ${String(target.localPort)} is already occupied`); } @@ -294,11 +321,7 @@ export function launchForwardService( let ownershipLost = false; while (true) { if (childIdentity) { - const identityStatus = processIdentityStatus( - child.pid, - childIdentity, - readProcessIdentity, - ); + const identityStatus = processIdentityStatus(child.pid, childIdentity, readProcessIdentity); if (identityStatus === "exited") { exited = true; break; @@ -313,7 +336,37 @@ export function launchForwardService( break; } if (isReachable(target.localPort)) { - return; + const listenerOwnership = listenerIsOwned(child.pid, target.localPort); + if ( + listenerOwnership === true && + processIdentityStatus(child.pid, childIdentity, readProcessIdentity) === "owned" + ) { + return; + } + const stopResult = stopOwnedProcess( + child.pid, + childIdentity, + readProcessIdentity, + processIsRunning, + stopProcess, + sleep, + options.stopTimeoutMs ?? STOP_TIMEOUT_MS, + ); + const ownershipFailure = + listenerOwnership === false + ? "is owned by another process" + : "could not be verified as owned by the launched process"; + if (stopResult !== "stopped") { + throw new Error( + `Host port ${String(target.localPort)} became reachable but ${ownershipFailure}; ` + + `the launched process could not be stopped safely; refusing to report success or retry; ` + + `forward list: ${describeFailureState(options.describeState)}`, + ); + } + throw new Error( + `Host port ${String(target.localPort)} became reachable but ${ownershipFailure}; ` + + `stopped the launched process and refused to report success; forward list: ${describeFailureState(options.describeState)}`, + ); } if (Date.now() >= deadline) break; sleep(POLL_INTERVAL_MS); From f9fa06604eb416e83d761ae832d590513e6dd8c8 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Fri, 4 Sep 2026 22:39:41 -0700 Subject: [PATCH 08/43] fix(e2e): close forward retry validation gaps Signed-off-by: Prekshi Vyas --- .../openshell/forward-service.test.ts | 40 +- src/lib/adapters/openshell/forward-service.ts | 93 ++++- test/e2e/live/full-e2e.test.ts | 4 +- ...launch-agent-turn-session-evidence.test.ts | 286 ++++++++++++++ test/e2e/support/launch-agent-turn.test.ts | 363 +++++------------- 5 files changed, 508 insertions(+), 278 deletions(-) create mode 100644 test/e2e/support/launch-agent-turn-session-evidence.test.ts diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index a4bd48f66dd..73e49f5c345 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -1,11 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { createServer, type AddressInfo } from "node:net"; + import { describe, expect, it, vi } from "vitest"; import { buildForwardServiceArgs, + getForwardListenerOwnership, launchForwardService, + parseForwardInstanceIdentity, type ForwardServiceTarget, } from "./forward-service"; @@ -239,8 +243,41 @@ describe("OpenShell forward service", () => { }, ); + it.runIf(process.platform === "linux")( + "proves listener ownership from Linux procfs without lsof (#11084)", + async () => { + const server = createServer(); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + try { + const address = server.address() as AddressInfo; + expect(getForwardListenerOwnership(process.pid, address.port)).toBe(true); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }, + ); + + it("distinguishes same-second POSIX processes by their launch token (#11084)", () => { + const first = "11111111-1111-4111-8111-111111111111"; + const second = "22222222-2222-4222-8222-222222222222"; + + expect( + parseForwardInstanceIdentity( + `openshell ${"lstart=same ".repeat(2)}NEMOCLAW_FORWARD_INSTANCE_ID=${first}`, + ), + ).toBe(`${process.platform}:${first}`); + expect( + parseForwardInstanceIdentity( + `openshell ${"lstart=same ".repeat(2)}NEMOCLAW_FORWARD_INSTANCE_ID=${second}`, + ), + ).toBe(`${process.platform}:${second}`); + }); + it.runIf(process.platform === "darwin")( - "stops and retries a spawned process using its macOS start time (#11084)", + "stops and retries a spawned process after macOS identity verification (#11084)", () => { let running = true; let spawnCount = 0; @@ -254,6 +291,7 @@ describe("OpenShell forward service", () => { }); launchForwardService(target, { + getProcessIdentity: stableProcessIdentity, isListenerOwned: () => true, isProcessRunning: () => running, isReachable: () => spawnCount === 2, diff --git a/src/lib/adapters/openshell/forward-service.ts b/src/lib/adapters/openshell/forward-service.ts index 9e0c820a264..b856a99ebf8 100644 --- a/src/lib/adapters/openshell/forward-service.ts +++ b/src/lib/adapters/openshell/forward-service.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { spawn, spawnSync } from "node:child_process"; +import { randomUUID } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; @@ -14,6 +15,7 @@ const START_RETRY_DELAY_MS = 1_000; const START_ATTEMPTS = 2; const STOP_TIMEOUT_MS = 5_000; const POLL_INTERVAL_MS = 100; +const FORWARD_INSTANCE_ENV = "NEMOCLAW_FORWARD_INSTANCE_ID"; const sleepBuffer = new Int32Array(new SharedArrayBuffer(4)); type ForwardServiceChild = { @@ -64,25 +66,96 @@ function readLinuxProcessStat(pid: number): string[] | null | undefined { } } +export function parseForwardInstanceIdentity( + output: string, + platform = process.platform, +): string | undefined { + const match = new RegExp( + `(?:^|\\s)${FORWARD_INSTANCE_ENV}=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:\\s|$)`, + "iu", + ).exec(output); + return match?.[1] ? `${platform}:${match[1].toLowerCase()}` : undefined; +} + function getProcessIdentity(pid: number): string | null | undefined { const stat = readLinuxProcessStat(pid); const startTime = stat?.[19]; if (startTime && /^\d+$/u.test(startTime)) return `linux:${startTime}`; if (stat === null) return null; if (process.platform === "linux") return undefined; - const result = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], { + const result = spawnSync("ps", ["eww", "-p", String(pid), "-o", "command="], { encoding: "utf8", env: buildOpenShellSubprocessEnv(process.env), stdio: ["ignore", "pipe", "ignore"], timeout: 1_000, }); if (result.error) return undefined; - const startedAt = result.status === 0 ? result.stdout.trim() : ""; - if (startedAt) return `${process.platform}:${startedAt}`; + const identity = result.status === 0 ? parseForwardInstanceIdentity(result.stdout) : undefined; + if (identity) return identity; return result.status === 1 ? null : undefined; } -function isListenerOwned(pid: number, port: number): boolean | null { +function readLinuxListeningSocketInodes(port: number): Set | null { + const expectedPort = port.toString(16).toUpperCase().padStart(4, "0"); + const inodes = new Set(); + let readTable = false; + for (const tablePath of ["/proc/net/tcp", "/proc/net/tcp6"]) { + let table: string; + try { + table = fs.readFileSync(tablePath, "utf8"); + readTable = true; + } catch (error) { + const code = + typeof error === "object" && error !== null && "code" in error ? error.code : undefined; + if (code === "ENOENT") continue; + return null; + } + for (const line of table.split(/\r?\n/u).slice(1)) { + const fields = line.trim().split(/\s+/u); + const localAddress = fields[1]; + const state = fields[3]; + const inode = fields[9]; + if ( + localAddress?.endsWith(`:${expectedPort}`) && + state === "0A" && + inode !== undefined && + /^\d+$/u.test(inode) + ) { + inodes.add(inode); + } + } + } + return readTable ? inodes : null; +} + +function isLinuxListenerOwned(pid: number, port: number): boolean | null { + const listenerInodes = readLinuxListeningSocketInodes(port); + if (!listenerInodes) return null; + let descriptors: string[]; + try { + descriptors = fs.readdirSync(`/proc/${String(pid)}/fd`); + } catch (error) { + const code = + typeof error === "object" && error !== null && "code" in error ? error.code : undefined; + return code === "ENOENT" || code === "ESRCH" ? false : null; + } + let unreadableDescriptor = false; + for (const descriptor of descriptors) { + try { + const target = fs.readlinkSync(`/proc/${String(pid)}/fd/${descriptor}`); + const match = /^socket:\[(\d+)\]$/u.exec(target); + if (match?.[1] && listenerInodes.has(match[1])) return true; + } catch (error) { + const code = + typeof error === "object" && error !== null && "code" in error ? error.code : undefined; + if (code !== "ENOENT" && code !== "ESRCH") unreadableDescriptor = true; + } + } + return unreadableDescriptor ? null : false; +} + +export function getForwardListenerOwnership(pid: number, port: number): boolean | null { + if (process.platform === "linux") return isLinuxListenerOwned(pid, port); const result = spawnSync( "lsof", ["-nP", "-a", "-p", String(pid), `-iTCP:${String(port)}`, "-sTCP:LISTEN", "-t"], @@ -281,7 +354,7 @@ export function launchForwardService( const isReachable = options.isReachable ?? probeLocalForwardListener; const processIsRunning = options.isProcessRunning ?? isProcessRunning; const readProcessIdentity = options.getProcessIdentity ?? getProcessIdentity; - const listenerIsOwned = options.isListenerOwned ?? isListenerOwned; + const listenerIsOwned = options.isListenerOwned ?? getForwardListenerOwnership; if (isReachable(target.localPort)) { throw new Error(`Host port ${String(target.localPort)} is already occupied`); } @@ -298,7 +371,7 @@ export function launchForwardService( throw new Error(`OpenShell forward service attempts must be between 1 and ${START_ATTEMPTS}`); } const args = buildForwardServiceArgs(target); - const environment = buildOpenShellSubprocessEnv(options.sourceEnvironment ?? process.env); + const baseEnvironment = buildOpenShellSubprocessEnv(options.sourceEnvironment ?? process.env); let finalFailure = "exited before binding"; for (let attempt = 1; attempt <= attempts; attempt += 1) { finalFailure = "exited before binding"; @@ -307,6 +380,8 @@ export function launchForwardService( `Host port ${String(target.localPort)} became occupied before forward retry; refusing to adopt its listener`, ); } + const instanceId = randomUUID(); + const environment = { ...baseEnvironment, [FORWARD_INSTANCE_ENV]: instanceId }; const child = spawnDetached(target.executable, args, environment); if (!isProcessIdentity(child.pid)) { throw new Error( @@ -314,7 +389,11 @@ export function launchForwardService( `refusing to start a duplicate service; forward list: ${describeFailureState(options.describeState)}`, ); } - const childIdentity = readProcessIdentity(child.pid); + const childIdentity = options.getProcessIdentity + ? readProcessIdentity(child.pid) + : process.platform === "linux" + ? readProcessIdentity(child.pid) + : `${process.platform}:${instanceId}`; child.unref(); const deadline = Date.now() + (options.timeoutMs ?? START_TIMEOUT_MS); let exited = false; diff --git a/test/e2e/live/full-e2e.test.ts b/test/e2e/live/full-e2e.test.ts index 49950d31841..9bc0f1a544e 100644 --- a/test/e2e/live/full-e2e.test.ts +++ b/test/e2e/live/full-e2e.test.ts @@ -56,7 +56,9 @@ const FULL_E2E_TARGET_ID = process.env.E2E_TARGET_ID ?? "full-e2e"; const SETUP_MODE = process.env.NEMOCLAW_E2E_SETUP_MODE ?? "source-install"; const USE_PREINSTALLED_LAUNCHABLE = SETUP_MODE === "preinstalled-launchable"; const PORTABLE_PROFILE = process.env.NEMOCLAW_EXPERIMENTAL_PROFILE === "portable"; -const LIVE_TIMEOUT_MS = testTimeout(50 * 60_000); +// Cold install plus two launch turns with one provider retry each can consume +// almost 50 minutes before the remaining assertions and cleanup run. +const LIVE_TIMEOUT_MS = testTimeout(70 * 60_000); const INSTALL_TIMEOUT_MS = execTimeout(25 * 60_000); const FIRST_TURN_TIMEOUT_MS = 240_000; const MAX_SILENCE_SECS = 60; diff --git a/test/e2e/support/launch-agent-turn-session-evidence.test.ts b/test/e2e/support/launch-agent-turn-session-evidence.test.ts new file mode 100644 index 00000000000..42aa6a5a9e4 --- /dev/null +++ b/test/e2e/support/launch-agent-turn-session-evidence.test.ts @@ -0,0 +1,286 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { + appendFileSync, + closeSync, + constants, + fstatSync, + fsyncSync, + ftruncateSync, + mkdtempSync, + mkdirSync, + openSync, + readFileSync, + rmSync, + type Stats, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { expect, it } from "vitest"; +import { OPENCLAW_SESSION_EVIDENCE_SCRIPT } from "../live/launch-agent-turn.ts"; + +type SessionRecords = Record; + +function message(role: "assistant" | "user", content = "nonempty"): string { + return JSON.stringify({ + message: { content: [{ text: content, type: "text" }], role }, + type: "message", + }); +} + +function emptyMessage(role: "assistant" | "user"): string { + return JSON.stringify({ message: { content: [], role }, type: "message" }); +} + +function writeSessionRecords( + root: string, + sessions: SessionRecords, + append: boolean, + finalNewline = true, +): void { + for (const [sessionId, records] of Object.entries(sessions)) { + const filePath = join(root, `${sessionId}.jsonl`); + const body = records.length > 0 ? `${records.join("\n")}${finalNewline ? "\n" : ""}` : ""; + const writeRecords = append ? appendFileSync : writeFileSync; + writeRecords(filePath, body); + } +} + +function withOwnedFixtureFile( + filePath: string, + flags: number, + action: (descriptor: number, stats: Stats) => T, +): T { + const descriptor = openSync(filePath, flags | constants.O_NOFOLLOW, 0o600); + try { + const stats = fstatSync(descriptor); + expect([stats.isFile(), stats.uid, stats.mode & 0o777, stats.nlink]).toEqual([ + true, + process.getuid?.(), + 0o600, + 1, + ]); + return action(descriptor, stats); + } finally { + closeSync(descriptor); + } +} + +function runEvidenceFixture(input: { + after: SessionRecords; + afterFinalNewline?: boolean; + before?: SessionRecords; + expectedTurns: number; +}) { + const fixtureRoot = mkdtempSync(join(tmpdir(), "nemoclaw-launch-evidence-")); + const runId = randomUUID().replaceAll("-", ""); + const baselinePath = `/tmp/nemoclaw-launch-session-${runId}.json`; + const ptyMonitorRoot = `/tmp/nemoclaw-launch-turn-${runId}`; + const sessionRoot = join(fixtureRoot, "sessions"); + mkdirSync(sessionRoot); + try { + writeSessionRecords(sessionRoot, input.before ?? {}, false); + const baseline = spawnSync( + process.execPath, + [ + "-e", + OPENCLAW_SESSION_EVIDENCE_SCRIPT, + "baseline", + sessionRoot, + baselinePath, + "", + ptyMonitorRoot, + runId, + ], + { encoding: "utf8" }, + ); + writeSessionRecords(sessionRoot, input.after, true, input.afterFinalNewline ?? true); + const qualification = spawnSync( + process.execPath, + [ + "-e", + OPENCLAW_SESSION_EVIDENCE_SCRIPT, + "qualify", + sessionRoot, + baselinePath, + String(input.expectedTurns), + ptyMonitorRoot, + runId, + ], + { encoding: "utf8" }, + ); + const baselineFile = withOwnedFixtureFile( + baselinePath, + constants.O_RDONLY, + (descriptor, stats) => ({ body: readFileSync(descriptor, "utf8"), stats }), + ); + return { + baseline, + baselineKeys: Object.keys(JSON.parse(baselineFile.body)).sort(), + baselineMode: baselineFile.stats.mode & 0o777, + baselineNlink: baselineFile.stats.nlink, + baselineUid: baselineFile.stats.uid, + qualification, + }; + } finally { + rmSync(fixtureRoot, { force: true, recursive: true }); + rmSync(baselinePath, { force: true }); + rmSync(`${baselinePath}.tmp`, { force: true }); + rmSync(ptyMonitorRoot, { force: true, recursive: true }); + } +} + +function runBaselineMutationFixture(mutation: "invalid" | "removed" | "rewritten" | "truncated") { + const fixtureRoot = mkdtempSync(join(tmpdir(), "nemoclaw-launch-baseline-")); + const runId = randomUUID().replaceAll("-", ""); + const baselinePath = `/tmp/nemoclaw-launch-session-${runId}.json`; + const ptyMonitorRoot = `/tmp/nemoclaw-launch-turn-${runId}`; + const sessionRoot = join(fixtureRoot, "sessions"); + const sessionPath = join(sessionRoot, "session-a.jsonl"); + mkdirSync(sessionRoot); + writeSessionRecords(sessionRoot, { "session-a": [message("user"), message("assistant")] }, false); + try { + const baseline = spawnSync( + process.execPath, + [ + "-e", + OPENCLAW_SESSION_EVIDENCE_SCRIPT, + "baseline", + sessionRoot, + baselinePath, + "", + ptyMonitorRoot, + runId, + ], + { encoding: "utf8" }, + ); + const applyMutation: Record void> = { + invalid: () => + withOwnedFixtureFile(baselinePath, constants.O_WRONLY, (descriptor) => { + ftruncateSync(descriptor, 0); + writeFileSync(descriptor, "{}"); + fsyncSync(descriptor); + }), + removed: () => rmSync(sessionPath), + rewritten: () => + writeFileSync( + sessionPath, + readFileSync(sessionPath, "utf8").replace("nonempty", "changed!"), + ), + truncated: () => writeFileSync(sessionPath, ""), + }; + applyMutation[mutation](); + const qualification = spawnSync( + process.execPath, + [ + "-e", + OPENCLAW_SESSION_EVIDENCE_SCRIPT, + "qualify", + sessionRoot, + baselinePath, + "1", + ptyMonitorRoot, + runId, + ], + { encoding: "utf8" }, + ); + return { baseline, qualification }; + } finally { + rmSync(fixtureRoot, { force: true, recursive: true }); + rmSync(baselinePath, { force: true }); + rmSync(`${baselinePath}.tmp`, { force: true }); + rmSync(ptyMonitorRoot, { force: true, recursive: true }); + } +} + +it("qualifies two ordered structured turns without comparing message content (#9160)", () => { + const { baseline, baselineKeys, baselineMode, baselineNlink, baselineUid, qualification } = + runEvidenceFixture({ + after: { + "session-a": [ + message("user", "first arbitrary input"), + message("assistant", "first arbitrary response"), + message("user", "different second input"), + message("assistant", "different second response"), + ], + }, + expectedTurns: 2, + }); + + expect(baseline.status).toBe(0); + expect(baselineKeys).toEqual(["schemaVersion", "sessions"]); + expect(baselineMode).toBe(0o600); + expect(baselineNlink).toBe(1); + expect(baselineUid).toBe(process.getuid?.()); + expect(qualification.status).toBe(0); +}); + +it("keeps a partial structured turn pending (#9160)", () => { + const { baseline, qualification } = runEvidenceFixture({ + after: { "session-a": [message("user")] }, + expectedTurns: 1, + }); + + expect(baseline.status).toBe(0); + expect(qualification.status).toBe(1); +}); + +it("does not qualify structured turns recorded before the baseline (#9160)", () => { + const { baseline, qualification } = runEvidenceFixture({ + before: { "session-a": [message("user"), message("assistant")] }, + after: {}, + expectedTurns: 1, + }); + + expect(baseline.status).toBe(0); + expect(qualification.status).toBe(1); +}); + +it.each([ + { "session-a": [message("assistant"), message("user")] }, + { "session-a": [message("user"), message("user"), message("assistant")] }, + { "session-a": [message("user"), message("assistant"), message("assistant")] }, + { "session-a": [message("user"), "not-json", message("assistant")] }, + { "session-a": [emptyMessage("user"), message("assistant")] }, + { "session-a": [message("user"), message("assistant")], "session-b": [message("user")] }, +] as SessionRecords[])( + "rejects malformed, empty, duplicated, extra, out-of-order, or cross-session records [case %#] (#9160)", + (after) => { + const { baseline, qualification } = runEvidenceFixture({ after, expectedTurns: 1 }); + expect(baseline.status).toBe(0); + expect(qualification.status).toBe(2); + }, +); + +it("rejects an unterminated appended session record (#9160)", () => { + const { baseline, qualification } = runEvidenceFixture({ + after: { + "session-a": [ + message("user"), + message("assistant"), + message("user"), + message("assistant"), + message("user"), + ], + }, + afterFinalNewline: false, + expectedTurns: 2, + }); + + expect(baseline.status).toBe(0); + expect(qualification.status).toBe(2); +}); + +it.each(["invalid", "removed", "rewritten", "truncated"] as const)( + "rejects an invalid baseline or a removed, rewritten, or truncated session [case %#] (#9160)", + (mutation) => { + const { baseline, qualification } = runBaselineMutationFixture(mutation); + expect(baseline.status).toBe(0); + expect(qualification.status).toBe(2); + }, +); diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index 39aa4bc5bc7..41c9ddbefc0 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -4,21 +4,13 @@ import { spawnSync } from "node:child_process"; import { randomUUID } from "node:crypto"; import { - appendFileSync, chmodSync, - closeSync, - constants, existsSync, - fstatSync, - fsyncSync, - ftruncateSync, mkdtempSync, mkdirSync, - openSync, readFileSync, readdirSync, rmSync, - type Stats, statSync, writeFileSync, } from "node:fs"; @@ -43,7 +35,6 @@ import { runOpenClawLaunchReadinessLeaseTurns, } from "../live/launch-agent-turn.ts"; const PROCESS_EXIT_WAIT = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)); -type SessionRecords = Record; type FixtureMode = | "cleanup-failure" | "delayed-input-attachment" @@ -66,178 +57,6 @@ type FixtureMode = | "restored-canonical-timeout" | "valid"; -function message(role: "assistant" | "user", content = "nonempty"): string { - return JSON.stringify({ - message: { content: [{ text: content, type: "text" }], role }, - type: "message", - }); -} - -function emptyMessage(role: "assistant" | "user"): string { - return JSON.stringify({ message: { content: [], role }, type: "message" }); -} - -function writeSessionRecords( - root: string, - sessions: SessionRecords, - append: boolean, - finalNewline = true, -): void { - for (const [sessionId, records] of Object.entries(sessions)) { - const filePath = join(root, `${sessionId}.jsonl`); - const body = records.length > 0 ? `${records.join("\n")}${finalNewline ? "\n" : ""}` : ""; - const writeRecords = append ? appendFileSync : writeFileSync; - writeRecords(filePath, body); - } -} - -function withOwnedFixtureFile( - filePath: string, - flags: number, - action: (descriptor: number, stats: Stats) => T, -): T { - const descriptor = openSync(filePath, flags | constants.O_NOFOLLOW, 0o600); - try { - const stats = fstatSync(descriptor); - expect([stats.isFile(), stats.uid, stats.mode & 0o777, stats.nlink]).toEqual([ - true, - process.getuid?.(), - 0o600, - 1, - ]); - return action(descriptor, stats); - } finally { - closeSync(descriptor); - } -} - -function runEvidenceFixture(input: { - after: SessionRecords; - afterFinalNewline?: boolean; - before?: SessionRecords; - expectedTurns: number; -}) { - const fixtureRoot = mkdtempSync(join(tmpdir(), "nemoclaw-launch-evidence-")); - const runId = randomUUID().replaceAll("-", ""); - const baselinePath = `/tmp/nemoclaw-launch-session-${runId}.json`; - const ptyMonitorRoot = `/tmp/nemoclaw-launch-turn-${runId}`; - const sessionRoot = join(fixtureRoot, "sessions"); - mkdirSync(sessionRoot); - try { - writeSessionRecords(sessionRoot, input.before ?? {}, false); - const baseline = spawnSync( - process.execPath, - [ - "-e", - OPENCLAW_SESSION_EVIDENCE_SCRIPT, - "baseline", - sessionRoot, - baselinePath, - "", - ptyMonitorRoot, - runId, - ], - { encoding: "utf8" }, - ); - writeSessionRecords(sessionRoot, input.after, true, input.afterFinalNewline ?? true); - const qualification = spawnSync( - process.execPath, - [ - "-e", - OPENCLAW_SESSION_EVIDENCE_SCRIPT, - "qualify", - sessionRoot, - baselinePath, - String(input.expectedTurns), - ptyMonitorRoot, - runId, - ], - { encoding: "utf8" }, - ); - const baselineFile = withOwnedFixtureFile( - baselinePath, - constants.O_RDONLY, - (descriptor, stats) => ({ body: readFileSync(descriptor, "utf8"), stats }), - ); - return { - baseline, - baselineKeys: Object.keys(JSON.parse(baselineFile.body)).sort(), - baselineMode: baselineFile.stats.mode & 0o777, - baselineNlink: baselineFile.stats.nlink, - baselineUid: baselineFile.stats.uid, - qualification, - }; - } finally { - rmSync(fixtureRoot, { force: true, recursive: true }); - rmSync(baselinePath, { force: true }); - rmSync(`${baselinePath}.tmp`, { force: true }); - rmSync(ptyMonitorRoot, { force: true, recursive: true }); - } -} - -function runBaselineMutationFixture(mutation: "invalid" | "removed" | "rewritten" | "truncated") { - const fixtureRoot = mkdtempSync(join(tmpdir(), "nemoclaw-launch-baseline-")); - const runId = randomUUID().replaceAll("-", ""); - const baselinePath = `/tmp/nemoclaw-launch-session-${runId}.json`; - const ptyMonitorRoot = `/tmp/nemoclaw-launch-turn-${runId}`; - const sessionRoot = join(fixtureRoot, "sessions"); - const sessionPath = join(sessionRoot, "session-a.jsonl"); - mkdirSync(sessionRoot); - writeSessionRecords(sessionRoot, { "session-a": [message("user"), message("assistant")] }, false); - try { - const baseline = spawnSync( - process.execPath, - [ - "-e", - OPENCLAW_SESSION_EVIDENCE_SCRIPT, - "baseline", - sessionRoot, - baselinePath, - "", - ptyMonitorRoot, - runId, - ], - { encoding: "utf8" }, - ); - const applyMutation: Record void> = { - invalid: () => - withOwnedFixtureFile(baselinePath, constants.O_WRONLY, (descriptor) => { - ftruncateSync(descriptor, 0); - writeFileSync(descriptor, "{}"); - fsyncSync(descriptor); - }), - removed: () => rmSync(sessionPath), - rewritten: () => - writeFileSync( - sessionPath, - readFileSync(sessionPath, "utf8").replace("nonempty", "changed!"), - ), - truncated: () => writeFileSync(sessionPath, ""), - }; - applyMutation[mutation](); - const qualification = spawnSync( - process.execPath, - [ - "-e", - OPENCLAW_SESSION_EVIDENCE_SCRIPT, - "qualify", - sessionRoot, - baselinePath, - "1", - ptyMonitorRoot, - runId, - ], - { encoding: "utf8" }, - ); - return { baseline, qualification }; - } finally { - rmSync(fixtureRoot, { force: true, recursive: true }); - rmSync(baselinePath, { force: true }); - rmSync(`${baselinePath}.tmp`, { force: true }); - rmSync(ptyMonitorRoot, { force: true, recursive: true }); - } -} - it("reports a residual PTY monitor socket without removing it (#9384)", async () => { const fixtureRoot = mkdtempSync(join(tmpdir(), "nemoclaw-monitor-cleanup-")); const runId = randomUUID().replaceAll("-", ""); @@ -278,7 +97,10 @@ it("reports a residual PTY monitor socket without removing it (#9384)", async () } }); -function runLaunchSessionFixture(mode: FixtureMode, terminalCopy: "absent" | "ansi" | "reordered") { +function runLaunchSessionFixture( + mode: FixtureMode, + terminalCopy: "absent" | "ansi" | "auth" | "reordered", +) { const fixtureRoot = mkdtempSync(join(tmpdir(), "nemoclaw-launch-turn-")); const canonicalRestoredMarker = join(fixtureRoot, "canonical-restored"); const earlyInputMarker = join(fixtureRoot, "early-input"); @@ -498,6 +320,9 @@ if (process.argv[2] !== "tui") { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true }); const ask = () => new Promise((resolve) => rl.question("", resolve)); if (terminalCopy === "ansi") process.stdout.write("\u001b[2KServiceUnavailableError\r"); + if (terminalCopy === "auth") { + process.stdout.write("\u001b[2KServiceUnavailableError: HTTP 503; authentication failed: invalid API key\r"); + } if (terminalCopy === "reordered") process.stdout.write("idle | gateway connected\n"); if (mode === "delayed-recording") { @@ -855,93 +680,6 @@ require("node:fs").appendFileSync( } } -it("qualifies two ordered structured turns without comparing message content (#9160)", () => { - const { baseline, baselineKeys, baselineMode, baselineNlink, baselineUid, qualification } = - runEvidenceFixture({ - after: { - "session-a": [ - message("user", "first arbitrary input"), - message("assistant", "first arbitrary response"), - message("user", "different second input"), - message("assistant", "different second response"), - ], - }, - expectedTurns: 2, - }); - - expect(baseline.status).toBe(0); - expect(baselineKeys).toEqual(["schemaVersion", "sessions"]); - expect(baselineMode).toBe(0o600); - expect(baselineNlink).toBe(1); - expect(baselineUid).toBe(process.getuid?.()); - expect(qualification.status).toBe(0); -}); - -it("keeps a partial structured turn pending (#9160)", () => { - const { baseline, qualification } = runEvidenceFixture({ - after: { "session-a": [message("user")] }, - expectedTurns: 1, - }); - - expect(baseline.status).toBe(0); - expect(qualification.status).toBe(1); -}); - -it("does not qualify structured turns recorded before the baseline (#9160)", () => { - const { baseline, qualification } = runEvidenceFixture({ - before: { "session-a": [message("user"), message("assistant")] }, - after: {}, - expectedTurns: 1, - }); - - expect(baseline.status).toBe(0); - expect(qualification.status).toBe(1); -}); - -it.each([ - { "session-a": [message("assistant"), message("user")] }, - { "session-a": [message("user"), message("user"), message("assistant")] }, - { "session-a": [message("user"), message("assistant"), message("assistant")] }, - { "session-a": [message("user"), "not-json", message("assistant")] }, - { "session-a": [emptyMessage("user"), message("assistant")] }, - { "session-a": [message("user"), message("assistant")], "session-b": [message("user")] }, -] as SessionRecords[])( - "rejects malformed, empty, duplicated, extra, out-of-order, or cross-session records [case %#] (#9160)", - (after) => { - const { baseline, qualification } = runEvidenceFixture({ after, expectedTurns: 1 }); - expect(baseline.status).toBe(0); - expect(qualification.status).toBe(2); - }, -); - -it("rejects an unterminated appended session record (#9160)", () => { - const { baseline, qualification } = runEvidenceFixture({ - after: { - "session-a": [ - message("user"), - message("assistant"), - message("user"), - message("assistant"), - message("user"), - ], - }, - afterFinalNewline: false, - expectedTurns: 2, - }); - - expect(baseline.status).toBe(0); - expect(qualification.status).toBe(2); -}); - -it.each(["invalid", "removed", "rewritten", "truncated"] as const)( - "rejects an invalid baseline or a removed, rewritten, or truncated session [case %#] (#9160)", - (mutation) => { - const { baseline, qualification } = runBaselineMutationFixture(mutation); - expect(baseline.status).toBe(0); - expect(qualification.status).toBe(2); - }, -); - it.each([[], ["-g", "fixture-gateway"]].map((gatewayArgs) => [gatewayArgs] as const))( "intercepts one OpenClaw launch, preserves pass-through argv, and strips launch authority from filtered and inherited environments [case %#] (#9160)", (gatewayArgs) => { @@ -1264,6 +1002,93 @@ it.runIf(process.platform === "linux")( }, ); +it.runIf(process.platform === "linux")( + "retries the provider marker emitted by the real launch producer (#10978)", + async () => { + const produced = runLaunchSessionFixture("recording-timeout", "ansi").result; + const firstResult = { + exitCode: produced.status ?? 1, + signal: produced.signal, + stderr: produced.stderr, + stdout: produced.stdout, + }; + const calls: Array<{ artifactName?: string; runId?: string }> = []; + const host = { + command: async ( + _command: string, + _args: string[], + options?: { artifactName?: string; env?: NodeJS.ProcessEnv }, + ) => { + calls.push({ + artifactName: options?.artifactName, + runId: options?.env?.NEMOCLAW_LAUNCH_RUN_ID, + }); + return calls.length === 1 + ? firstResult + : { exitCode: 0, signal: null, stderr: "", stdout: "" }; + }, + openshellCommandPath: "/usr/bin/openshell", + }; + vi.useFakeTimers(); + try { + const launch = runOpenClawLaunchSession({ + artifactName: "producer-handoff", + cliCommand: "node", + env: {}, + host: host as never, + redactionValues: [], + sandboxName: "alpha", + }); + await vi.advanceTimersByTimeAsync(1_000); + await expect(launch).resolves.toMatchObject({ exitCode: 0 }); + expect(calls.map((call) => call.artifactName)).toEqual([ + "producer-handoff", + "producer-handoff-provider-retry-02", + ]); + expect(new Set(calls.map((call) => call.runId)).size).toBe(2); + } finally { + vi.useRealTimers(); + } + }, + testTimeout(30_000), +); + +it.runIf(process.platform === "linux")( + "does not retry real provider output that also reports authentication failure (#10978)", + async () => { + const produced = runLaunchSessionFixture("recording-timeout", "auth").result; + const firstResult = { + exitCode: produced.status ?? 1, + signal: produced.signal, + stderr: produced.stderr, + stdout: produced.stdout, + }; + let calls = 0; + const host = { + command: async () => { + calls += 1; + return firstResult; + }, + openshellCommandPath: "/usr/bin/openshell", + }; + + expect(firstResult.stderr).toContain("authentication failed"); + expect(firstResult.stderr).not.toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); + await expect( + runOpenClawLaunchSession({ + artifactName: "producer-auth-handoff", + cliCommand: "node", + env: {}, + host: host as never, + redactionValues: [], + sandboxName: "alpha", + }), + ).rejects.toThrow("launch session failed"); + expect(calls).toBe(1); + }, + testTimeout(30_000), +); + it.runIf(process.platform === "linux")( "rejects out-of-order structured records even when the PTY process remains active (#9160)", () => { From 57f938e3d350d5bb278a526b6b8a66beb2125b99 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 00:22:24 -0700 Subject: [PATCH 09/43] fix(forward): avoid activating readiness probes Signed-off-by: Prekshi Vyas --- .../openshell/forward-service.test.ts | 30 +++++++---- src/lib/adapters/openshell/forward-service.ts | 51 +++++++------------ 2 files changed, 37 insertions(+), 44 deletions(-) diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index 73e49f5c345..7a26a0951a2 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -50,15 +50,22 @@ describe("OpenShell forward service", () => { ); }); - it("detaches the OpenShell child and waits for its local port", () => { + it("accepts an owned listener without opening a ForwardTcp connection (#11084)", () => { const unref = vi.fn(); - const spawnDetached = vi.fn(() => ({ pid: 41, unref })); - let probes = 0; + let spawned = false; + const spawnDetached = vi.fn(() => { + spawned = true; + return { pid: 41, unref }; + }); + const isReachable = vi.fn(() => { + expect(spawned).toBe(false); + return false; + }); launchForwardService(target, { getProcessIdentity: stableProcessIdentity, isListenerOwned: () => true, - isReachable: () => ++probes >= 3, + isReachable, isProcessRunning: () => true, sleep: () => {}, spawnDetached, @@ -71,6 +78,7 @@ describe("OpenShell forward service", () => { expect.any(Object), ); expect(unref).toHaveBeenCalledOnce(); + expect(isReachable).toHaveBeenCalledTimes(2); }); it("refuses an occupied port without launching or adopting its listener", () => { @@ -113,7 +121,7 @@ describe("OpenShell forward service", () => { getProcessIdentity: stableProcessIdentity, isListenerOwned: () => true, isProcessRunning: (pid) => pid === 52, - isReachable: () => spawnDetached.mock.calls.length === 2, + isReachable: () => false, retryDelayMs: 0, sleep: () => {}, spawnDetached, @@ -224,22 +232,22 @@ describe("OpenShell forward service", () => { stopProcess, timeoutMs: 1_000, }), - ).toThrow(/became reachable.*owned by another process.*refused to report success/u); + ).toThrow(/remained reachable.*refusing to adopt its listener or retry/u); expect(stopProcess).toHaveBeenCalledWith(72, "SIGTERM"); }); it.runIf(process.platform === "linux")( "tracks the spawned process by its Linux start time (#11084)", () => { - let probes = 0; + const isReachable = vi.fn(() => false); launchForwardService(target, { isListenerOwned: () => true, - isReachable: () => ++probes >= 3, + isReachable, spawnDetached: () => ({ pid: process.pid, unref: vi.fn() }), }); - expect(probes).toBe(3); + expect(isReachable).toHaveBeenCalledTimes(2); }, ); @@ -292,9 +300,9 @@ describe("OpenShell forward service", () => { launchForwardService(target, { getProcessIdentity: stableProcessIdentity, - isListenerOwned: () => true, + isListenerOwned: () => spawnCount === 2, isProcessRunning: () => running, - isReachable: () => spawnCount === 2, + isReachable: () => false, retryDelayMs: 0, sleep: () => {}, spawnDetached, diff --git a/src/lib/adapters/openshell/forward-service.ts b/src/lib/adapters/openshell/forward-service.ts index b856a99ebf8..87e0fc7a30a 100644 --- a/src/lib/adapters/openshell/forward-service.ts +++ b/src/lib/adapters/openshell/forward-service.ts @@ -414,39 +414,18 @@ export function launchForwardService( exited = true; break; } - if (isReachable(target.localPort)) { - const listenerOwnership = listenerIsOwned(child.pid, target.localPort); - if ( - listenerOwnership === true && - processIdentityStatus(child.pid, childIdentity, readProcessIdentity) === "owned" - ) { - return; - } - const stopResult = stopOwnedProcess( - child.pid, - childIdentity, - readProcessIdentity, - processIsRunning, - stopProcess, - sleep, - options.stopTimeoutMs ?? STOP_TIMEOUT_MS, - ); - const ownershipFailure = - listenerOwnership === false - ? "is owned by another process" - : "could not be verified as owned by the launched process"; - if (stopResult !== "stopped") { - throw new Error( - `Host port ${String(target.localPort)} became reachable but ${ownershipFailure}; ` + - `the launched process could not be stopped safely; refusing to report success or retry; ` + - `forward list: ${describeFailureState(options.describeState)}`, - ); - } - throw new Error( - `Host port ${String(target.localPort)} became reachable but ${ownershipFailure}; ` + - `stopped the launched process and refused to report success; forward list: ${describeFailureState(options.describeState)}`, - ); + const listenerOwnership = listenerIsOwned(child.pid, target.localPort); + if ( + listenerOwnership === true && + processIdentityStatus(child.pid, childIdentity, readProcessIdentity) === "owned" + ) { + return; } + // OpenShell opens the host listener before it creates a sandbox relay. + // Connecting here is not a passive readiness check: the accepted socket + // starts ForwardTcp, and a sandbox that is still settling can reject that + // first relay and make the foreground service exit. Inspect the launched + // process's listener ownership without connecting to the service. if (Date.now() >= deadline) break; sleep(POLL_INTERVAL_MS); } @@ -473,7 +452,13 @@ export function launchForwardService( : "could not stop that process"; throw new Error( `OpenShell forward service process ${String(child.pid)} remained unbound after ${String(options.timeoutMs ?? START_TIMEOUT_MS)}ms and ${reason}; ` + - `refusing to signal or retry; forward list: ${describeFailureState(options.describeState)}`, + `refusing to signal or retry; forward list: ${describeFailureState(options.describeState)}`, + ); + } + if (isReachable(target.localPort)) { + throw new Error( + `Host port ${String(target.localPort)} remained reachable after the launched process stopped; ` + + `refusing to adopt its listener or retry; forward list: ${describeFailureState(options.describeState)}`, ); } finalFailure = "was stopped after failing to bind"; From 741c539702223c39c83d03002de8afb8ed58ce8c Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 01:31:02 -0700 Subject: [PATCH 10/43] fix(forward): restore readiness handoff retries Signed-off-by: Prekshi Vyas --- docs/get-started/quickstart-hermes.mdx | 7 +- docs/get-started/quickstart.mdx | 7 +- .../openshell/forward-service.test.ts | 96 +++++++++++ src/lib/adapters/openshell/forward-service.ts | 160 ++++++++++++++++-- 4 files changed, 251 insertions(+), 19 deletions(-) diff --git a/docs/get-started/quickstart-hermes.mdx b/docs/get-started/quickstart-hermes.mdx index b8859078630..88ce6cea653 100644 --- a/docs/get-started/quickstart-hermes.mdx +++ b/docs/get-started/quickstart-hermes.mdx @@ -381,10 +381,11 @@ Use these details when your first-run path needs more control. The onboard flow starts both port forwards automatically. For a new sandbox, NemoClaw reserves the selected dashboard loopback port through sandbox preparation and creation. If another listener claims the port before NemoClaw binds the reservation, NemoClaw selects another port before changing sandbox resources. - NemoClaw waits up to 90 seconds for each forward to bind. - If the exact forward process exits before it binds, NemoClaw waits 1 second and retries once. + NemoClaw waits up to 90 seconds for each forward to bind and remain owned through OpenShell's first post-bind sandbox check. + If OpenShell reports that the sandbox is still completing its readiness handoff, NemoClaw waits 5 seconds and retries up to 12 times. + An exact forward process that exits for another reason receives one retry. If the process remains unbound at the deadline, NemoClaw stops that exact process and confirms its exit before retrying. - The complete two-attempt sequence can take just over 3 minutes for each forward. + The ordinary two-attempt sequence can take just over 3 minutes for each forward; readiness-handoff retries use a separate one-minute delay budget. NemoClaw accepts each forward only when its spawned process owns the listener. It does not adopt an unrelated listener or start another forward while it cannot confirm that the prior process stopped. NemoClaw releases the reservation immediately before OpenShell starts the dashboard forward. diff --git a/docs/get-started/quickstart.mdx b/docs/get-started/quickstart.mdx index b3ea3c9b4bd..2e9de54329c 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -458,10 +458,11 @@ Use these details when your first-run path needs more control. When that port is occupied, NemoClaw uses the next free dashboard port, such as `18790`, and includes the port in the URL. For a new sandbox, NemoClaw reserves the selected loopback port through sandbox preparation and creation. If another listener claims the port before NemoClaw binds the reservation, NemoClaw selects another port before changing sandbox resources. - NemoClaw waits up to 90 seconds for the dashboard forward to bind. - If the exact forward process exits before it binds, NemoClaw waits 1 second and retries once. + NemoClaw waits up to 90 seconds for the dashboard forward to bind and remain owned through OpenShell's first post-bind sandbox check. + If OpenShell reports that the sandbox is still completing its readiness handoff, NemoClaw waits 5 seconds and retries up to 12 times. + An exact forward process that exits for another reason receives one retry. If the process remains unbound at the deadline, NemoClaw stops that exact process and confirms its exit before retrying. - The complete two-attempt sequence can take just over 3 minutes. + The ordinary two-attempt sequence can take just over 3 minutes; readiness-handoff retries use a separate one-minute delay budget. NemoClaw accepts the forward only when the spawned process owns the listener. It does not adopt an unrelated listener or start another forward while it cannot confirm that the prior process stopped. NemoClaw releases the reservation immediately before OpenShell starts the dashboard forward. diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index 7a26a0951a2..c5a8b61153e 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -81,6 +81,27 @@ describe("OpenShell forward service", () => { expect(isReachable).toHaveBeenCalledTimes(2); }); + it("requires the owned listener to remain stable before callers connect (#11084)", () => { + let ownershipChecks = 0; + const sleep = vi.fn(); + + launchForwardService(target, { + getProcessIdentity: stableProcessIdentity, + isListenerOwned: () => { + ownershipChecks += 1; + return ownershipChecks !== 10; + }, + isProcessRunning: () => true, + isReachable: () => false, + sleep, + spawnDetached: () => ({ pid: 43, unref: vi.fn() }), + timeoutMs: 10_000, + }); + + expect(ownershipChecks).toBe(36); + expect(sleep).toHaveBeenCalledTimes(35); + }); + it("refuses an occupied port without launching or adopting its listener", () => { const spawnDetached = vi.fn(); @@ -131,6 +152,54 @@ describe("OpenShell forward service", () => { expect(spawnDetached).toHaveBeenCalledTimes(2); }); + it("retries the exact OpenShell sandbox readiness handoff on its bounded schedule (#11084)", () => { + const spawnDetached = vi + .fn() + .mockReturnValueOnce({ + pid: 53, + readOutput: () => + "Error: sandbox 'demo' is no longer ready (phase: creating); stopping service forward", + removeOutput: vi.fn(), + unref: vi.fn(), + }) + .mockReturnValueOnce({ pid: 54, unref: vi.fn() }); + const sleep = vi.fn(); + + launchForwardService(target, { + getProcessIdentity: stableProcessIdentity, + isListenerOwned: (pid) => pid === 54, + isProcessRunning: (pid) => pid === 54, + isReachable: () => false, + maxSandboxReadyRetries: 1, + sleep, + spawnDetached, + }); + + expect(spawnDetached).toHaveBeenCalledTimes(2); + expect(sleep).toHaveBeenCalledWith(5_000); + }); + + it("does not classify a missing sandbox as a readiness handoff (#11084)", () => { + const sleep = vi.fn(); + + expect(() => + launchForwardService(target, { + getProcessIdentity: stableProcessIdentity, + isProcessRunning: () => false, + isReachable: () => false, + maxAttempts: 1, + sleep, + spawnDetached: () => ({ + pid: 55, + readOutput: () => "Error: sandbox 'demo' no longer exists; stopping service forward", + removeOutput: vi.fn(), + unref: vi.fn(), + }), + }), + ).toThrow(/forward start: non-readiness OpenShell diagnostic/u); + expect(sleep).not.toHaveBeenCalledWith(5_000); + }); + it("does not retry when the timed-out service cannot be stopped (#11084)", () => { const settlingTarget = { ...target, localPort: 18_790, targetPort: 18_790 }; const spawnDetached = vi.fn(() => ({ pid: 61, unref: vi.fn() })); @@ -331,4 +400,31 @@ describe("OpenShell forward service", () => { ).toThrow(/no process identity.*forward list: /u); expect(spawnDetached).toHaveBeenCalledOnce(); }); + + it("classifies OpenShell start output without exposing its contents (#11084)", () => { + const removeOutput = vi.fn(); + let error: unknown; + + try { + launchForwardService(target, { + isProcessRunning: () => false, + isReachable: () => false, + maxAttempts: 1, + sleep: () => {}, + spawnDetached: () => ({ + pid: 81, + readOutput: () => "sandbox is not ready API_KEY=secret-value", + removeOutput, + unref: vi.fn(), + }), + }); + } catch (caught) { + error = caught; + } + + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toMatch(/forward start: non-readiness OpenShell diagnostic/u); + expect((error as Error).message).not.toContain("secret-value"); + expect(removeOutput).toHaveBeenCalledOnce(); + }); }); diff --git a/src/lib/adapters/openshell/forward-service.ts b/src/lib/adapters/openshell/forward-service.ts index 87e0fc7a30a..95b4270881d 100644 --- a/src/lib/adapters/openshell/forward-service.ts +++ b/src/lib/adapters/openshell/forward-service.ts @@ -4,7 +4,9 @@ import { spawn, spawnSync } from "node:child_process"; import { randomUUID } from "node:crypto"; import fs from "node:fs"; +import os from "node:os"; import path from "node:path"; +import { stripVTControlCharacters } from "node:util"; import { isValidName } from "../../name-validation"; import { buildOpenShellSubprocessEnv } from "./resolve-shared"; @@ -13,13 +15,20 @@ import { probeLocalForwardListener } from "./local-forward-listener"; const START_TIMEOUT_MS = 90_000; const START_RETRY_DELAY_MS = 1_000; const START_ATTEMPTS = 2; +const SANDBOX_READY_RETRY_DELAY_MS = 5_000; +const SANDBOX_READY_MAX_RETRIES = 12; const STOP_TIMEOUT_MS = 5_000; const POLL_INTERVAL_MS = 100; +// OpenShell checks the sandbox every two seconds after binding. Keep the +// listener owned through one complete post-bind check before callers connect. +const STABLE_LISTENER_OBSERVATIONS = 26; const FORWARD_INSTANCE_ENV = "NEMOCLAW_FORWARD_INSTANCE_ID"; const sleepBuffer = new Int32Array(new SharedArrayBuffer(4)); type ForwardServiceChild = { readonly pid?: number; + readonly readOutput?: () => string; + readonly removeOutput?: () => void; unref(): void; }; @@ -41,6 +50,7 @@ export interface ForwardServiceLaunchOptions { readonly isListenerOwned?: (pid: number, port: number) => boolean | null; readonly isReachable?: (port: number) => boolean; readonly maxAttempts?: number; + readonly maxSandboxReadyRetries?: number; readonly retryDelayMs?: number; readonly sleep?: (milliseconds: number) => void; readonly sourceEnvironment?: NodeJS.ProcessEnv; @@ -206,6 +216,90 @@ function describeFailureState(describe: (() => string | null | undefined) | unde } } +function spawnForwardService( + executable: string, + args: readonly string[], + environment: NodeJS.ProcessEnv, +): ForwardServiceChild { + const outputDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-forward-service-")); + fs.chmodSync(outputDirectory, 0o700); + const outputPath = path.join(outputDirectory, "start.log"); + const outputDescriptor = fs.openSync(outputPath, "wx", 0o600); + let child: ReturnType; + try { + child = spawn(executable, [...args], { + detached: true, + env: environment, + stdio: ["ignore", outputDescriptor, outputDescriptor], + }); + } catch (error) { + try { + fs.closeSync(outputDescriptor); + } catch { + // Preserve the spawn failure if closing its diagnostic file also fails. + } + try { + fs.rmSync(outputDirectory, { force: true, recursive: true }); + } catch { + // Preserve the spawn failure if removing its diagnostic file also fails. + } + throw error; + } + try { + fs.closeSync(outputDescriptor); + } catch { + // The child owns its inherited descriptor; the parent no longer needs it. + } + return { + pid: child.pid, + unref: () => child.unref(), + readOutput: () => { + try { + return fs.readFileSync(outputPath, "utf8"); + } catch { + return ""; + } + }, + removeOutput: () => { + try { + fs.rmSync(outputDirectory, { force: true, recursive: true }); + } catch { + // The detached child may still hold the file on non-POSIX hosts. + } + }, + }; +} + +function readForwardStartState(child: ForwardServiceChild): { + readonly diagnostic: string; + readonly sandboxReadinessHandoff: boolean; +} { + const output = child.readOutput?.() ?? ""; + const sandboxReadinessHandoff = isSandboxReadinessHandoff(stripVTControlCharacters(output)); + return { + diagnostic: sandboxReadinessHandoff + ? "sandbox readiness handoff" + : output.trim() + ? "non-readiness OpenShell diagnostic" + : "", + sandboxReadinessHandoff, + }; +} + +function isSandboxReadinessHandoff(output: string): boolean { + const compact = output.replace(/\s+/gu, " ").trim(); + return ( + /message: ["']sandbox is not ready["']/iu.test(compact) || + /sandbox ["'][^"']+["'] is no longer ready \(phase: [^)]+\); stopping service forward/iu.test( + compact, + ) + ); +} + +function removeForwardStartOutput(child: ForwardServiceChild): void { + child.removeOutput?.(); +} + function isProcessIdentity(pid: number | undefined): pid is number { return Number.isSafeInteger(pid) && Number(pid) > 0; } @@ -360,8 +454,7 @@ export function launchForwardService( } const spawnDetached = options.spawnDetached ?? - ((executable, args, environment) => - spawn(executable, [...args], { detached: true, env: environment, stdio: "ignore" })); + ((executable, args, environment) => spawnForwardService(executable, args, environment)); const sleep = options.sleep ?? ((milliseconds: number) => Atomics.wait(sleepBuffer, 0, 0, milliseconds)); const stopProcess = @@ -370,10 +463,25 @@ export function launchForwardService( if (!Number.isSafeInteger(attempts) || attempts < 1 || attempts > START_ATTEMPTS) { throw new Error(`OpenShell forward service attempts must be between 1 and ${START_ATTEMPTS}`); } + const maxSandboxReadyRetries = options.maxSandboxReadyRetries ?? SANDBOX_READY_MAX_RETRIES; + if ( + !Number.isSafeInteger(maxSandboxReadyRetries) || + maxSandboxReadyRetries < 0 || + maxSandboxReadyRetries > SANDBOX_READY_MAX_RETRIES + ) { + throw new Error( + `OpenShell sandbox readiness retries must be between 0 and ${SANDBOX_READY_MAX_RETRIES}`, + ); + } const args = buildForwardServiceArgs(target); const baseEnvironment = buildOpenShellSubprocessEnv(options.sourceEnvironment ?? process.env); let finalFailure = "exited before binding"; - for (let attempt = 1; attempt <= attempts; attempt += 1) { + let finalStartState = { diagnostic: "", sandboxReadinessHandoff: false }; + let attempt = 0; + let standardFailures = 0; + let sandboxReadyRetries = 0; + while (true) { + attempt += 1; finalFailure = "exited before binding"; if (isReachable(target.localPort)) { throw new Error( @@ -384,9 +492,11 @@ export function launchForwardService( const environment = { ...baseEnvironment, [FORWARD_INSTANCE_ENV]: instanceId }; const child = spawnDetached(target.executable, args, environment); if (!isProcessIdentity(child.pid)) { + finalStartState = readForwardStartState(child); + removeForwardStartOutput(child); throw new Error( `OpenShell forward service returned no process identity for ${target.localHost}:${String(target.localPort)}; ` + - `refusing to start a duplicate service; forward list: ${describeFailureState(options.describeState)}`, + `refusing to start a duplicate service; forward start: ${finalStartState.diagnostic}; forward list: ${describeFailureState(options.describeState)}`, ); } const childIdentity = options.getProcessIdentity @@ -398,6 +508,7 @@ export function launchForwardService( const deadline = Date.now() + (options.timeoutMs ?? START_TIMEOUT_MS); let exited = false; let ownershipLost = false; + let stableListenerObservations = 0; while (true) { if (childIdentity) { const identityStatus = processIdentityStatus(child.pid, childIdentity, readProcessIdentity); @@ -419,20 +530,31 @@ export function launchForwardService( listenerOwnership === true && processIdentityStatus(child.pid, childIdentity, readProcessIdentity) === "owned" ) { - return; + stableListenerObservations += 1; + if (stableListenerObservations >= STABLE_LISTENER_OBSERVATIONS) { + removeForwardStartOutput(child); + return; + } + } else { + stableListenerObservations = 0; } // OpenShell opens the host listener before it creates a sandbox relay. // Connecting here is not a passive readiness check: the accepted socket // starts ForwardTcp, and a sandbox that is still settling can reject that // first relay and make the foreground service exit. Inspect the launched // process's listener ownership without connecting to the service. - if (Date.now() >= deadline) break; + // The bind deadline governs the first owned-listener observation. Once + // binding starts, finish the short stability window instead of timing + // out a service that bound at the edge of the deadline. + if (Date.now() >= deadline && stableListenerObservations === 0) break; sleep(POLL_INTERVAL_MS); } if (ownershipLost) { + finalStartState = readForwardStartState(child); + removeForwardStartOutput(child); throw new Error( `OpenShell forward service process ${String(child.pid)} changed identity before binding ${target.localHost}:${String(target.localPort)}; ` + - `refusing to signal or retry; forward list: ${describeFailureState(options.describeState)}`, + `refusing to signal or retry; forward start: ${finalStartState.diagnostic}; forward list: ${describeFailureState(options.describeState)}`, ); } if (!exited) { @@ -446,29 +568,41 @@ export function launchForwardService( options.stopTimeoutMs ?? STOP_TIMEOUT_MS, ); if (stopResult !== "stopped") { + finalStartState = readForwardStartState(child); + removeForwardStartOutput(child); const reason = stopResult === "unverified" ? "could not verify that it still owned that process" : "could not stop that process"; throw new Error( `OpenShell forward service process ${String(child.pid)} remained unbound after ${String(options.timeoutMs ?? START_TIMEOUT_MS)}ms and ${reason}; ` + - `refusing to signal or retry; forward list: ${describeFailureState(options.describeState)}`, + `refusing to signal or retry; forward start: ${finalStartState.diagnostic}; forward list: ${describeFailureState(options.describeState)}`, ); } if (isReachable(target.localPort)) { + finalStartState = readForwardStartState(child); + removeForwardStartOutput(child); throw new Error( `Host port ${String(target.localPort)} remained reachable after the launched process stopped; ` + - `refusing to adopt its listener or retry; forward list: ${describeFailureState(options.describeState)}`, + `refusing to adopt its listener or retry; forward start: ${finalStartState.diagnostic}; forward list: ${describeFailureState(options.describeState)}`, ); } finalFailure = "was stopped after failing to bind"; } - if (attempt < attempts) { - sleep(options.retryDelayMs ?? START_RETRY_DELAY_MS); + finalStartState = readForwardStartState(child); + removeForwardStartOutput(child); + if (exited && finalStartState.sandboxReadinessHandoff) { + if (sandboxReadyRetries >= maxSandboxReadyRetries) break; + sandboxReadyRetries += 1; + sleep(SANDBOX_READY_RETRY_DELAY_MS); + continue; } + standardFailures += 1; + if (standardFailures >= attempts) break; + sleep(options.retryDelayMs ?? START_RETRY_DELAY_MS); } throw new Error( - `OpenShell forward service ${finalFailure} ${target.localHost}:${String(target.localPort)} after ${String(attempts)} attempts; ` + - `forward list: ${describeFailureState(options.describeState)}`, + `OpenShell forward service ${finalFailure} ${target.localHost}:${String(target.localPort)} after ${String(attempt)} attempts; ` + + `forward start: ${finalStartState.diagnostic}; forward list: ${describeFailureState(options.describeState)}`, ); } From 7de1f1701a3611f6d607c98b1e8cde028c5b85b0 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 03:17:25 -0700 Subject: [PATCH 11/43] fix(forward): normalize wrapped readiness errors Signed-off-by: Prekshi Vyas --- src/lib/adapters/openshell/forward-service.test.ts | 2 +- src/lib/adapters/openshell/forward-service.ts | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index c5a8b61153e..29f9fea27cb 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -158,7 +158,7 @@ describe("OpenShell forward service", () => { .mockReturnValueOnce({ pid: 53, readOutput: () => - "Error: sandbox 'demo' is no longer ready (phase: creating); stopping service forward", + "Error:\n × sandbox 'demo' is no longer ready (phase: creating); stopping service\n │ forward", removeOutput: vi.fn(), unref: vi.fn(), }) diff --git a/src/lib/adapters/openshell/forward-service.ts b/src/lib/adapters/openshell/forward-service.ts index 95b4270881d..1e64f10f9f3 100644 --- a/src/lib/adapters/openshell/forward-service.ts +++ b/src/lib/adapters/openshell/forward-service.ts @@ -275,7 +275,7 @@ function readForwardStartState(child: ForwardServiceChild): { readonly sandboxReadinessHandoff: boolean; } { const output = child.readOutput?.() ?? ""; - const sandboxReadinessHandoff = isSandboxReadinessHandoff(stripVTControlCharacters(output)); + const sandboxReadinessHandoff = isSandboxReadinessHandoff(output); return { diagnostic: sandboxReadinessHandoff ? "sandbox readiness handoff" @@ -287,7 +287,13 @@ function readForwardStartState(child: ForwardServiceChild): { } function isSandboxReadinessHandoff(output: string): boolean { - const compact = output.replace(/\s+/gu, " ").trim(); + // Miette wraps long OpenShell errors with box-drawing continuation markers. + // Normalize those display-only characters so classification does not depend + // on the sandbox name length or terminal width. + const compact = stripVTControlCharacters(output) + .replace(/[×│]/gu, " ") + .replace(/\s+/gu, " ") + .trim(); return ( /message: ["']sandbox is not ready["']/iu.test(compact) || /sandbox ["'][^"']+["'] is no longer ready \(phase: [^)]+\); stopping service forward/iu.test( From 3cdb354efeace3bef5cfcedd2919176fe99e33ac Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 04:23:05 -0700 Subject: [PATCH 12/43] fix(forward): normalize diagnostic layout Signed-off-by: Prekshi Vyas --- src/lib/adapters/openshell/forward-service.test.ts | 2 +- src/lib/adapters/openshell/forward-service.ts | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index 29f9fea27cb..ca5fdf73a4a 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -158,7 +158,7 @@ describe("OpenShell forward service", () => { .mockReturnValueOnce({ pid: 53, readOutput: () => - "Error:\n × sandbox 'demo' is no longer ready (phase: creating); stopping service\n │ forward", + "Error:\n × sandbox 'demo' is no longer ready (phase: creating); stopping service\n ╰─▶ forward", removeOutput: vi.fn(), unref: vi.fn(), }) diff --git a/src/lib/adapters/openshell/forward-service.ts b/src/lib/adapters/openshell/forward-service.ts index 1e64f10f9f3..3a6d78df390 100644 --- a/src/lib/adapters/openshell/forward-service.ts +++ b/src/lib/adapters/openshell/forward-service.ts @@ -287,11 +287,11 @@ function readForwardStartState(child: ForwardServiceChild): { } function isSandboxReadinessHandoff(output: string): boolean { - // Miette wraps long OpenShell errors with box-drawing continuation markers. - // Normalize those display-only characters so classification does not depend - // on the sandbox name length or terminal width. + // Miette adds box-drawing lines and arrows around OpenShell errors. Retain + // only characters that can belong to the two readiness messages so the + // classification does not depend on its renderer or terminal width. const compact = stripVTControlCharacters(output) - .replace(/[×│]/gu, " ") + .replace(/[^\p{L}\p{N}\s'"():;._-]+/gu, " ") .replace(/\s+/gu, " ") .trim(); return ( From 45c5a1876a0396563a286268b1bf64828820f5d7 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 04:50:42 -0700 Subject: [PATCH 13/43] fix(e2e): require provider outage evidence Signed-off-by: Prekshi Vyas --- test/e2e/live/launch-agent-turn.ts | 41 ++++++++++++------- ...h-agent-turn-provider-availability.test.ts | 4 +- test/e2e/support/launch-agent-turn.test.ts | 31 +++++++++----- 3 files changed, 49 insertions(+), 27 deletions(-) diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index 232588bbed4..797cd1c16bf 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -13,17 +13,10 @@ const OPENCLAW_LAUNCH_PROVIDER_ATTEMPTS = 2; const OPENCLAW_LAUNCH_PROVIDER_RETRY_DELAY_MS = 1_000; export const OPENCLAW_PROVIDER_UNAVAILABLE_MARKER = "nemoclaw.e2e.launch-failure=provider-unavailable"; -const TERMINAL_LAUNCH_FAILURE_RE = - /authentication failed|authorization failed|unauthorized|forbidden|HTTP(?: status)?[:= ]+40[13]\b|\b40[13]\b|invalid[^\r\n]*(?:api[_ -]?key|credential|JSON|response)|denied by network policy|network policy denied|policy [^\r\n]*failed|routing [^\r\n]*failed|route [^\r\n]*failed|proxy [^\r\n]*failed|malformed|structured session evidence was invalid|launch final structured session evidence did not qualify|message_(?:content_empty|order_invalid)|session_(?:record_incomplete|removed|rewritten|truncated)|multiple_sessions_changed|extra_message|verifier_failed|PTY [^\r\n]*(?:failed|invalid|unavailable)|structured session baseline cleanup failed|launch host session cleanup failed|launch PTY monitor cleanup failed|launch could not remove/iu; - -function isTransientProviderAvailabilityFailure( - result: Pick, -): boolean { - const output = resultText(result); - return ( - output.split(/\r?\n/u).includes(OPENCLAW_PROVIDER_UNAVAILABLE_MARKER) && - !TERMINAL_LAUNCH_FAILURE_RE.test(output) - ); +const OPENCLAW_PROVIDER_UNAVAILABLE_PREFIX = `launch did not record the required structured session turns\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\n`; + +function isTransientProviderAvailabilityFailure(result: Pick): boolean { + return result.stderr.startsWith(OPENCLAW_PROVIDER_UNAVAILABLE_PREFIX); } export const OPENCLAW_LAUNCH_RUNTIME_ENV_SCRIPT = @@ -1131,10 +1124,18 @@ terminal_diagnostic() { transient_provider_availability_failure() { local diagnostic diagnostic="$(tail -c 4096 "$capture" 2>/dev/null || true)" - printf '%s\n' "$diagnostic" | grep -Eiq \ - 'ServiceUnavailable(Error)?|HTTP( status( code)?)?[:= ]+5[0-9]{2}|status( code)?[:= ]+5[0-9]{2}|5[0-9]{2} (Bad Gateway|Gateway Timeout|Internal Server Error|Service Unavailable)' || return 1 + printf '%s\n' "$diagnostic" | grep -Fq \ + 'run error: litellm.ServiceUnavailableError: ServiceUnavailableError:' || return 1 + printf '%s\n' "$diagnostic" | grep -Fq \ + 'OpenAIException - . Received Model Group=' || return 1 + printf '%s\n' "$diagnostic" | grep -Fq \ + 'Available Model Group Fallbacks=' || return 1 ! printf '%s\n' "$diagnostic" | grep -Eiq \ - 'authentication failed|authorization failed|unauthorized|forbidden|HTTP( status)?[:= ]+40[13]|invalid.*(api[_ -]?key|credential|JSON|response)|denied by network policy|network policy denied|policy .*failed|routing .*failed|route .*failed|proxy .*failed|malformed' + 'authentication failed|authorization failed|unauthorized|forbidden|HTTP( status)?[:= ]+40[13]|invalid.*(api[_ -]?key|credential|JSON|response)|\b(egress|request|connection|certificate|TLS|network|route|routing|policy|proxy)[^\r\n]*(blocked|denied|failed|invalid)\b|malformed' +} + +provider_empty_message_evidence() { + grep -Eq '^\{"reason":"message_content_empty","sessionId":"[^"]+"\}$' "$evidence_error" } fail_launch_session() { @@ -1185,7 +1186,17 @@ wait_for_turn_count() { evidence_status=$? fi if [[ "$evidence_status" != 1 ]]; then - fail_launch_session "structured session evidence was invalid or unavailable (status $evidence_status)" + case "$evidence_status" in + 2) + provider_empty_message_evidence && \ + transient_provider_availability_failure && \ + fail_launch_session \ + "launch did not record the required structured session turns" \ + "${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}" + ;; + esac + fail_launch_session \ + "structured session evidence was invalid or unavailable (status $evidence_status)" fi if ! kill -0 "$session_pid" 2>/dev/null; then break diff --git a/test/e2e/support/launch-agent-turn-provider-availability.test.ts b/test/e2e/support/launch-agent-turn-provider-availability.test.ts index a3230f852ba..b724717aac6 100644 --- a/test/e2e/support/launch-agent-turn-provider-availability.test.ts +++ b/test/e2e/support/launch-agent-turn-provider-availability.test.ts @@ -33,7 +33,7 @@ it("retries a transient provider failure in a fresh launch session (#10978)", as ? { exitCode: 1, signal: null, - stderr: `${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nlitellm.ServiceUnavailableError: NVIDIA upstream unavailable`, + stderr: `launch did not record the required structured session turns\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nlitellm.ServiceUnavailableError: NVIDIA upstream unavailable`, stdout: "", } : { exitCode: 0, signal: null, stderr: "", stdout: "" }; @@ -71,7 +71,7 @@ it("classifies exhausted transient launch attempts as provider unavailable (#109 return { exitCode: 1, signal: null, - stderr: `${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nlaunch did not record the required structured session turns\nHTTP ${calls.length === 1 ? "503" : "502"}`, + stderr: `launch did not record the required structured session turns\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nHTTP ${calls.length === 1 ? "503" : "502"}`, stdout: "", }; }, diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index 41c9ddbefc0..c125f7f4bcd 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -53,6 +53,7 @@ type FixtureMode = | "pty-socket-timeout" | "pty-path-unreadable" | "pty-termios-unavailable" + | "provider-empty-message" | "recording-timeout" | "restored-canonical-timeout" | "valid"; @@ -99,7 +100,7 @@ it("reports a residual PTY monitor socket without removing it (#9384)", async () function runLaunchSessionFixture( mode: FixtureMode, - terminalCopy: "absent" | "ansi" | "auth" | "reordered", + terminalCopy: "absent" | "ansi" | "provider" | "reordered" | "security", ) { const fixtureRoot = mkdtempSync(join(tmpdir(), "nemoclaw-launch-turn-")); const canonicalRestoredMarker = join(fixtureRoot, "canonical-restored"); @@ -320,8 +321,15 @@ if (process.argv[2] !== "tui") { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true }); const ask = () => new Promise((resolve) => rl.question("", resolve)); if (terminalCopy === "ansi") process.stdout.write("\u001b[2KServiceUnavailableError\r"); - if (terminalCopy === "auth") { - process.stdout.write("\u001b[2KServiceUnavailableError: HTTP 503; authentication failed: invalid API key\r"); + if (terminalCopy === "provider") { + process.stdout.write("\u001b[2Krun error: litellm.ServiceUnavailableError: ServiceUnavailableError:\r\n"); + process.stdout.write("\u001b[2KOpenAIException - . Received Model Group=nvidia/model\r\n"); + process.stdout.write("\u001b[2KAvailable Model Group Fallbacks=None\r"); + } + if (terminalCopy === "security") { + process.stdout.write("\u001b[2Krun error: litellm.ServiceUnavailableError: ServiceUnavailableError:\r\n"); + process.stdout.write("\u001b[2KOpenAIException - . Received Model Group=nvidia/model\r\n"); + process.stdout.write("\u001b[2KAvailable Model Group Fallbacks=None; egress blocked by sandbox guard\r"); } if (terminalCopy === "reordered") process.stdout.write("idle | gateway connected\n"); @@ -336,6 +344,9 @@ if (process.argv[2] !== "tui") { if (mode === "invalid-order") { append("assistant", "response before input"); append("user", firstInput); + } else if (mode === "provider-empty-message") { + append("user", firstInput); + append("assistant", ""); } else { append("user", firstInput); append("assistant", "first response"); @@ -987,11 +998,11 @@ it.runIf(process.platform === "linux")( ); it.runIf(process.platform === "linux")( - "marks provider unavailability when structured turns remain missing (#9160, #10978)", + "marks provider unavailability when it leaves an empty structured turn (#9160, #10978)", () => { const { baselineRemoved, result, ttyObserved } = runLaunchSessionFixture( - "recording-timeout", - "ansi", + "provider-empty-message", + "provider", ); expect(ttyObserved).toBe(true); @@ -1005,7 +1016,7 @@ it.runIf(process.platform === "linux")( it.runIf(process.platform === "linux")( "retries the provider marker emitted by the real launch producer (#10978)", async () => { - const produced = runLaunchSessionFixture("recording-timeout", "ansi").result; + const produced = runLaunchSessionFixture("provider-empty-message", "provider").result; const firstResult = { exitCode: produced.status ?? 1, signal: produced.signal, @@ -1054,9 +1065,9 @@ it.runIf(process.platform === "linux")( ); it.runIf(process.platform === "linux")( - "does not retry real provider output that also reports authentication failure (#10978)", + "does not retry real provider output that also reports a security denial (#10978)", async () => { - const produced = runLaunchSessionFixture("recording-timeout", "auth").result; + const produced = runLaunchSessionFixture("provider-empty-message", "security").result; const firstResult = { exitCode: produced.status ?? 1, signal: produced.signal, @@ -1072,7 +1083,7 @@ it.runIf(process.platform === "linux")( openshellCommandPath: "/usr/bin/openshell", }; - expect(firstResult.stderr).toContain("authentication failed"); + expect(firstResult.stderr).toContain("egress blocked by sandbox guard"); expect(firstResult.stderr).not.toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); await expect( runOpenClawLaunchSession({ From 2d0df5eedd269d7e90cda03c7cee13ec1b707f31 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 05:16:27 -0700 Subject: [PATCH 14/43] fix(e2e): preserve retry cleanup budget Signed-off-by: Prekshi Vyas --- .github/workflows/portable-profile-e2e.yaml | 2 +- docs/manage-sandboxes/recover-rebuild-sandboxes.mdx | 12 ++++++++++-- src/lib/actions/sandbox/forward-recovery.ts | 3 ++- ...ortable-profile-rootless-runtime-workflow.test.ts | 1 + .../security-posture-workflow-boundary.test.ts | 3 +++ tools/e2e/target-catalogue.mts | 4 ++-- 6 files changed, 19 insertions(+), 6 deletions(-) diff --git a/.github/workflows/portable-profile-e2e.yaml b/.github/workflows/portable-profile-e2e.yaml index abd93622d5c..21207eb3e8b 100644 --- a/.github/workflows/portable-profile-e2e.yaml +++ b/.github/workflows/portable-profile-e2e.yaml @@ -150,7 +150,7 @@ jobs: portable-launch: if: ${{ github.ref == 'refs/heads/main' }} runs-on: ubuntu-26.04 - timeout-minutes: 75 + timeout-minutes: 90 env: E2E_JOB: "1" E2E_TARGET_ID: portable-launch diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 9aa70105449..0ed4131ff13 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -68,7 +68,11 @@ If `$$nemoclaw status` reports the sandbox container or gateway is not ru $$nemoclaw recover ``` -The command repairs a stopped in-sandbox gateway and re-establishes the dashboard port-forward in one step. It is idempotent and safe to script. If the gateway is already healthy, `recover` exits after the probe and does not restart it. If the host forward is already active, recovery accepts it only after OpenShell ownership is reconciled and the local endpoint is reachable. +The command repairs a stopped in-sandbox gateway and re-establishes the dashboard port-forward in one step. +It is idempotent and safe to script. +If the gateway is already healthy, `recover` exits after the probe and does not restart it. +If the host forward is already active, recovery accepts it only after OpenShell ownership is reconciled and the local endpoint is reachable. +If recovery launches a new forward, it accepts the forward after the OpenShell process owns the listener through the startup stability window without opening a connection to the endpoint. Use `gateway restart` when you intentionally need a supported OpenClaw gateway to reload runtime configuration or plugins. @@ -87,7 +91,11 @@ If `$$nemoclaw status` reports the sandbox container or Hermes gateway is $$nemoclaw recover ``` -The command repairs a stopped in-sandbox gateway and re-establishes the dashboard port-forward in one step. It is idempotent and safe to script. If the gateway is already healthy, `recover` does not restart it. If the host forward is already active, recovery accepts it only after OpenShell ownership is reconciled and the local endpoint is reachable. +The command repairs a stopped in-sandbox gateway and re-establishes the dashboard port-forward in one step. +It is idempotent and safe to script. +If the gateway is already healthy, `recover` does not restart it. +If the host forward is already active, recovery accepts it only after OpenShell ownership is reconciled and the local endpoint is reachable. +If recovery launches a new forward, it accepts the forward after the OpenShell process owns the listener through the startup stability window without opening a connection to the endpoint. Before it repairs the gateway, `recover` checks for a NemoClaw cron restore gate or release recovery record left by an interrupted rebuild. The gate continues to block new Hermes turns and cron dispatch across gateway and container restarts in the same sandbox. If release rollback could not restore the gate, `recover` uses the root-owned recovery record to reacquire it before gateway repair can start dispatch. After gateway repair, `recover` waits for active agent work to finish and validates the restored cron jobs and scripts. It clears NemoClaw-owned gate and release recovery state only after validation succeeds. If no independent operator drain exists, successful recovery prints `Hermes cron dispatch resumed after restored jobs and scripts were validated.` If an operator drain exists, recovery prints `Hermes cron restore gate cleared; the independent operator drain remains active.` The command does not own or clear the Hermes operator drain, so new Hermes turns and cron dispatch remain blocked while that drain is active. If gate reacquisition or cron validation fails, `recover` exits nonzero and retains the recovery state for another attempt. diff --git a/src/lib/actions/sandbox/forward-recovery.ts b/src/lib/actions/sandbox/forward-recovery.ts index 72d078565b1..ea5b51cc506 100644 --- a/src/lib/actions/sandbox/forward-recovery.ts +++ b/src/lib/actions/sandbox/forward-recovery.ts @@ -301,7 +301,8 @@ export function teardownSandboxDashboardForward( * Re-establish the dashboard port forward to the sandbox. * Uses the recorded dashboard port when available, including custom ports for * non-OpenClaw agents, then falls back to the active agent's declared port. - * Returns true when the detached OpenShell service makes the port reachable. + * Returns true when an existing forward is reachable or a newly launched + * OpenShell service owns the listener through its startup stability window. */ export function ensureSandboxPortForward( sandboxName: string, diff --git a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts index 60a75b8cbb6..72443defcb9 100644 --- a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts +++ b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts @@ -244,6 +244,7 @@ ${serviceIdentityCheck}`, expect(upload?.if).toBe("always()"); expect(upload?.with?.name).toContain(revisionExpression); expect(workflow.jobs["portable-launch"]?.if).toBe("${{ github.ref == 'refs/heads/main' }}"); + expect(workflow.jobs["portable-launch"]?.["timeout-minutes"]).toBe(90); expect(liveSource).toContain('run("git", ["rev-parse", "HEAD"])'); expect(liveSource).toContain('"network", "rm", disposableNetworkId'); expect(liveSource).not.toContain('"network", "rm", "--force"'); diff --git a/test/e2e/support/security-posture-workflow-boundary.test.ts b/test/e2e/support/security-posture-workflow-boundary.test.ts index 907d83d49b4..1c6228f7314 100644 --- a/test/e2e/support/security-posture-workflow-boundary.test.ts +++ b/test/e2e/support/security-posture-workflow-boundary.test.ts @@ -17,6 +17,8 @@ describe("security-posture catalogue boundary", () => { const openclaw = catalogueTarget("security-posture-openclaw"); const hermes = catalogueTarget("security-posture-hermes"); + expect(catalogueTarget("full-e2e").timeoutMinutes).toBe(90); + const target = ({ OpenClaw: openclaw, Hermes: hermes } as const)[scenario]!; expect(target).toMatchObject({ targetId: "security-posture", @@ -33,6 +35,7 @@ describe("security-posture catalogue boundary", () => { expect(openclaw).toMatchObject({ shard: "openclaw", testFile: "test/e2e/live/full-e2e.test.ts", + timeoutMinutes: 90, }); expect(hermes).toMatchObject({ shard: "hermes", diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index e094a3980a6..e49228a7410 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -811,7 +811,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ agentRuntime: "openclaw", environmentOrInferenceEndpoint: "Ubuntu; NVIDIA hosted inference", profile: "nvidia-inference", - timeoutMinutes: 75, + timeoutMinutes: 90, installMode: "authenticated", restoreCli: true, exposeCliBin: true, @@ -1383,7 +1383,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ profile: "nvidia-inference", prAdvisorSelectable: true, testFile: "test/e2e/live/full-e2e.test.ts", - timeoutMinutes: 75, + timeoutMinutes: 90, installMode: "credential-free", installNonInteractive: true, restoreCli: true, From 7ebb655220517db1a816386e2e1aa63d62b62a56 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 05:38:55 -0700 Subject: [PATCH 15/43] test(e2e): model empty provider turns Signed-off-by: Prekshi Vyas --- test/e2e/support/launch-agent-turn.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index c125f7f4bcd..f05ffe6ca43 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -291,6 +291,10 @@ if (process.argv[2] !== "tui") { sessionFile, JSON.stringify({ message: { content: [{ text: content, type: "text" }], role }, type: "message" }) + "\n", ); + const appendEmpty = (role) => fs.appendFileSync( + sessionFile, + JSON.stringify({ message: { content: [], role }, type: "message" }) + "\n", + ); if (mode === "restored-canonical-timeout") { process.stdin.setRawMode(true); await new Promise((resolve) => setTimeout(resolve, 750)); @@ -346,7 +350,7 @@ if (process.argv[2] !== "tui") { append("user", firstInput); } else if (mode === "provider-empty-message") { append("user", firstInput); - append("assistant", ""); + appendEmpty("assistant"); } else { append("user", firstInput); append("assistant", "first response"); From 312b2eeb7b2591eaca2ee30abc5c3a29f15bfd08 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 05:54:45 -0700 Subject: [PATCH 16/43] fix(forward): report scoped recovery state Signed-off-by: Prekshi Vyas --- docs/changelog/2026-09-04.mdx | 2 +- .../forward-recovery-declared-ports.test.ts | 36 +++++++++++- src/lib/actions/sandbox/forward-recovery.ts | 46 ++++++++++++++- .../openshell/forward-service.test.ts | 56 +++++++++++-------- 4 files changed, 111 insertions(+), 29 deletions(-) diff --git a/docs/changelog/2026-09-04.mdx b/docs/changelog/2026-09-04.mdx index 6586a41eb51..e141bea0044 100644 --- a/docs/changelog/2026-09-04.mdx +++ b/docs/changelog/2026-09-04.mdx @@ -33,7 +33,7 @@ It also hardens sandbox recovery, onboarding, inference validation, MCP lifecycl Related changes: [PR #10722](https://github.com/NVIDIA/NemoClaw/pull/10722) and [PR #10996](https://github.com/NVIDIA/NemoClaw/pull/10996). For more information, refer to [Recover and Rebuild Sandboxes](/user-guide/openclaw/manage-sandboxes/operate-sandboxes/recover-and-rebuild-sandboxes) and [Security Best Practices](/user-guide/openclaw/security/best-practices). - NemoClaw now uses detached `openshell forward service` processes for managed dashboard, messaging, and MCP host forwards instead of owning SSH forwarding processes and receipt state. - The forward lifecycle follows sandbox and gateway availability, refuses an occupied host port, verifies reachability before success, and relaunches through normal recovery. + The forward lifecycle follows sandbox and gateway availability, refuses an occupied host port, verifies reachability for an existing forward, verifies ownership and startup stability for a newly launched forward, and relaunches through normal recovery. MCP lifecycle work and typed policy reads also retain the sandbox's recorded gateway, workspace, TLS, and mTLS authority instead of inheriting ambient selectors. Related changes: [PR #10695](https://github.com/NVIDIA/NemoClaw/pull/10695), [PR #10814](https://github.com/NVIDIA/NemoClaw/pull/10814), [PR #10815](https://github.com/NVIDIA/NemoClaw/pull/10815), and [PR #10810](https://github.com/NVIDIA/NemoClaw/pull/10810). For more information, refer to [Understand Gateway Lifecycle Control](/user-guide/openclaw/manage-sandboxes/configure-sandboxes/understand-gateway-lifecycle-control) and [About Managed MCP Servers](/user-guide/openclaw/manage-sandboxes/mcp-servers/about-managed-mcp-servers). diff --git a/src/lib/actions/sandbox/forward-recovery-declared-ports.test.ts b/src/lib/actions/sandbox/forward-recovery-declared-ports.test.ts index 112f2a384c0..c1e737f42cc 100644 --- a/src/lib/actions/sandbox/forward-recovery-declared-ports.test.ts +++ b/src/lib/actions/sandbox/forward-recovery-declared-ports.test.ts @@ -113,7 +113,7 @@ describe("ensureDeclaredAgentForwardPortsHealthy", { timeout: 30_000 }, () => { expect(ensureDeclaredAgentForwardPortsHealthy("beta", 18790)).toBe(true); expect(mocks.launchForwardService).toHaveBeenCalledWith( expect.objectContaining({ localPort: 8643, targetPort: 8643 }), - {}, + { describeState: expect.any(Function) }, ); }); @@ -160,6 +160,7 @@ describe("ensureDeclaredAgentForwardPortsHealthy", { timeout: 30_000 }, () => { workspace: runtimeSelection.workspace, }), { + describeState: expect.any(Function), sourceEnvironment: expect.objectContaining({ OPENSHELL_GATEWAY: runtimeSelection.gatewayName, OPENSHELL_WORKSPACE: runtimeSelection.workspace, @@ -175,6 +176,39 @@ describe("ensureDeclaredAgentForwardPortsHealthy", { timeout: 30_000 }, () => { expect(sourceEnvironment).not.toHaveProperty("OPENSHELL_TOKEN"); }); + it("reports bounded selected-gateway state after a forward launch failure (#11084)", async () => { + mocks.isLocalForwardReachable.mockReturnValue(false); + mocks.getSandbox.mockReturnValue({ agent: "hermes", dashboardPort: 18790 }); + mocks.captureOpenshell + .mockReturnValueOnce(forwardList([])) + .mockReturnValueOnce( + forwardList(["beta 127.0.0.1 18790 101 failed OPENSHELL_TOKEN=opaque-test-token"]), + ); + mocks.launchForwardService.mockImplementation((_target, options) => { + expect(options?.describeState?.()).toBe("matching forward is malformed"); + throw new Error("fixture forward launch failure"); + }); + const runtimeSelection = { + gatewayName: "nemoclaw-19080", + workspace: "review-workspace", + localTlsDir: "/authority/tls", + }; + const { ensureSandboxPortForward } = await import("./forward-recovery"); + + expect(ensureSandboxPortForward("beta", { runtimeSelection })).toBe(false); + expect(mocks.captureOpenshell).toHaveBeenLastCalledWith( + ["forward", "list", "--gateway", runtimeSelection.gatewayName], + expect.objectContaining({ + env: expect.objectContaining({ + OPENSHELL_GATEWAY: runtimeSelection.gatewayName, + OPENSHELL_WORKSPACE: runtimeSelection.workspace, + OPENSHELL_LOCAL_TLS_DIR: runtimeSelection.localTlsDir, + }), + replaceEnv: true, + }), + ); + }); + it("keeps the default API port for a sandbox registered without one (#8543)", async () => { mocks.getSandbox.mockReturnValue({ agent: "hermes", dashboardPort: 18789 }); mocks.captureOpenshell.mockReturnValue(forwardList([])); diff --git a/src/lib/actions/sandbox/forward-recovery.ts b/src/lib/actions/sandbox/forward-recovery.ts index ea5b51cc506..cb2c57ef418 100644 --- a/src/lib/actions/sandbox/forward-recovery.ts +++ b/src/lib/actions/sandbox/forward-recovery.ts @@ -194,6 +194,30 @@ function isValidPort(value: unknown): value is number { return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535; } +function describeForwardListEntry(output: string, sandboxName: string, port: number): string { + const matchingLine = output + .replace(/\x1B\[[0-?]*[ -/]*[@-~]/gu, "") + .split("\n") + .map((line) => line.trim()) + .find((line) => { + const columns = line.split(/\s+/u); + return columns[0] === sandboxName && columns[2] === String(port); + }); + if (!matchingLine) return "no matching forward"; + const [sandbox, bind, listedPort, pid, status, ...extra] = matchingLine.split(/\s+/u); + if ( + extra.length > 0 || + sandbox !== sandboxName || + (bind !== "127.0.0.1" && bind !== "0.0.0.0") || + listedPort !== String(port) || + !/^\d+$/u.test(pid ?? "") || + !/^[a-z][a-z-]{0,31}$/iu.test(status ?? "") + ) { + return "matching forward is malformed"; + } + return `${sandbox} ${bind} ${listedPort} ${pid} ${status}`; +} + export function resolveSandboxDashboardPort( sandboxName: string, deps: SandboxPortDeps = {}, @@ -431,9 +455,25 @@ export function ensureSandboxPortForwardForPort( expectedBind ?? (forwardTarget.startsWith("0.0.0.0:") ? "0.0.0.0" : "127.0.0.1"), runtimeSelection?.workspace ?? "default", ), - runtimeSelection - ? { sourceEnvironment: buildSelectedOpenShellSubprocessEnv(runtimeSelection) } - : {}, + { + describeState: () => { + const listed = captureOpenshell( + ["forward", "list", "--gateway", gatewayName], + withSelectedOpenShellCommandOptions( + { + ignoreError: true, + includeStreams: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }, + runtimeSelection, + ), + ); + return describeForwardListEntry(listed.output, sandboxName, port); + }, + ...(runtimeSelection + ? { sourceEnvironment: buildSelectedOpenShellSubprocessEnv(runtimeSelection) } + : {}), + }, ); return acceptSuccessfulForward(); } catch (error) { diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index ca5fdf73a4a..c2790fb67f9 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -152,32 +152,40 @@ describe("OpenShell forward service", () => { expect(spawnDetached).toHaveBeenCalledTimes(2); }); - it("retries the exact OpenShell sandbox readiness handoff on its bounded schedule (#11084)", () => { - const spawnDetached = vi - .fn() - .mockReturnValueOnce({ - pid: 53, - readOutput: () => - "Error:\n × sandbox 'demo' is no longer ready (phase: creating); stopping service\n ╰─▶ forward", - removeOutput: vi.fn(), - unref: vi.fn(), - }) - .mockReturnValueOnce({ pid: 54, unref: vi.fn() }); - const sleep = vi.fn(); + it.each([ + [ + "phase transition", + "Error:\n × sandbox 'demo' is no longer ready (phase: creating); stopping service\n ╰─▶ forward", + ], + ["explicit message", 'Error:\n ╰─▶ message: "sandbox is not ready"'], + ])( + "retries an exact OpenShell sandbox readiness handoff on its bounded schedule [%s] (#11084)", + (_case, diagnostic) => { + const spawnDetached = vi + .fn() + .mockReturnValueOnce({ + pid: 53, + readOutput: () => diagnostic, + removeOutput: vi.fn(), + unref: vi.fn(), + }) + .mockReturnValueOnce({ pid: 54, unref: vi.fn() }); + const sleep = vi.fn(); - launchForwardService(target, { - getProcessIdentity: stableProcessIdentity, - isListenerOwned: (pid) => pid === 54, - isProcessRunning: (pid) => pid === 54, - isReachable: () => false, - maxSandboxReadyRetries: 1, - sleep, - spawnDetached, - }); + launchForwardService(target, { + getProcessIdentity: stableProcessIdentity, + isListenerOwned: (pid) => pid === 54, + isProcessRunning: (pid) => pid === 54, + isReachable: () => false, + maxSandboxReadyRetries: 1, + sleep, + spawnDetached, + }); - expect(spawnDetached).toHaveBeenCalledTimes(2); - expect(sleep).toHaveBeenCalledWith(5_000); - }); + expect(spawnDetached).toHaveBeenCalledTimes(2); + expect(sleep).toHaveBeenCalledWith(5_000); + }, + ); it("does not classify a missing sandbox as a readiness handoff (#11084)", () => { const sleep = vi.fn(); From 03be604b502d0a42a7ab4ad63571d8c291ae65aa Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 06:46:48 -0700 Subject: [PATCH 17/43] fix(forward): preserve OpenShell config authority Signed-off-by: Prekshi Vyas --- .../openshell/forward-service.test.ts | 27 +++++++++++++++++++ src/lib/adapters/openshell/resolve-shared.ts | 1 + .../adapters/openshell/sanitized-capture.ts | 2 +- 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index c2790fb67f9..d041fbf9bea 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -81,6 +81,33 @@ describe("OpenShell forward service", () => { expect(isReachable).toHaveBeenCalledTimes(2); }); + it("uses the selected OpenShell configuration without exposing credentials (#11084)", () => { + const spawnDetached = vi.fn(() => ({ pid: 42, unref: vi.fn() })); + + launchForwardService(target, { + getProcessIdentity: stableProcessIdentity, + isListenerOwned: () => true, + isProcessRunning: () => true, + isReachable: () => false, + sleep: () => {}, + sourceEnvironment: { + HOME: "/tmp/isolated-home", + NVIDIA_INFERENCE_API_KEY: "secret-value", + PATH: "/usr/bin", + XDG_CONFIG_HOME: "/home/runner/.config", + }, + spawnDetached, + }); + + const environment = spawnDetached.mock.calls[0]?.[2]; + expect(environment).toMatchObject({ + HOME: "/tmp/isolated-home", + PATH: "/usr/bin", + XDG_CONFIG_HOME: "/home/runner/.config", + }); + expect(environment).not.toHaveProperty("NVIDIA_INFERENCE_API_KEY"); + }); + it("requires the owned listener to remain stable before callers connect (#11084)", () => { let ownershipChecks = 0; const sleep = vi.fn(); diff --git a/src/lib/adapters/openshell/resolve-shared.ts b/src/lib/adapters/openshell/resolve-shared.ts index 317d63c0148..fe66d5dfdd8 100644 --- a/src/lib/adapters/openshell/resolve-shared.ts +++ b/src/lib/adapters/openshell/resolve-shared.ts @@ -190,6 +190,7 @@ export function buildOpenShellSubprocessEnv( "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "CURL_CA_BUNDLE", + "XDG_CONFIG_HOME", ]); const environment = Object.fromEntries( Object.entries(source).filter( diff --git a/src/lib/adapters/openshell/sanitized-capture.ts b/src/lib/adapters/openshell/sanitized-capture.ts index 633ca2bd89a..d3d5c9075cc 100644 --- a/src/lib/adapters/openshell/sanitized-capture.ts +++ b/src/lib/adapters/openshell/sanitized-capture.ts @@ -23,7 +23,7 @@ export function captureSanitizedResolvedOpenshell( opts: SanitizedCaptureOptions, ): CapturedOpenShellCommandResult { const env = buildOpenShellSubprocessEnv(); - for (const name of ["XDG_CONFIG_HOME", "OPENSHELL_WORKSPACE"] as const) { + for (const name of ["OPENSHELL_WORKSPACE"] as const) { const value = process.env[name]; if (value !== undefined) env[name] = value; } From 0d1cfc70f3038c2793850c6c87a5793746f44cfd Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 07:05:25 -0700 Subject: [PATCH 18/43] fix(e2e): keep provider retries fail closed Signed-off-by: Prekshi Vyas --- docs/changelog/2026-09-04.mdx | 2 +- docs/get-started/quickstart-hermes.mdx | 5 +-- docs/get-started/quickstart.mdx | 5 +-- .../recover-rebuild-sandboxes.mdx | 2 +- .../openshell/forward-service.test.ts | 7 +++- test/e2e/live/launch-agent-turn.ts | 6 +--- test/e2e/support/launch-agent-turn.test.ts | 34 +++++++++++++++---- 7 files changed, 42 insertions(+), 19 deletions(-) diff --git a/docs/changelog/2026-09-04.mdx b/docs/changelog/2026-09-04.mdx index e141bea0044..d8546611801 100644 --- a/docs/changelog/2026-09-04.mdx +++ b/docs/changelog/2026-09-04.mdx @@ -33,7 +33,7 @@ It also hardens sandbox recovery, onboarding, inference validation, MCP lifecycl Related changes: [PR #10722](https://github.com/NVIDIA/NemoClaw/pull/10722) and [PR #10996](https://github.com/NVIDIA/NemoClaw/pull/10996). For more information, refer to [Recover and Rebuild Sandboxes](/user-guide/openclaw/manage-sandboxes/operate-sandboxes/recover-and-rebuild-sandboxes) and [Security Best Practices](/user-guide/openclaw/security/best-practices). - NemoClaw now uses detached `openshell forward service` processes for managed dashboard, messaging, and MCP host forwards instead of owning SSH forwarding processes and receipt state. - The forward lifecycle follows sandbox and gateway availability, refuses an occupied host port, verifies reachability for an existing forward, verifies ownership and startup stability for a newly launched forward, and relaunches through normal recovery. + These service-managed forwards follow sandbox and gateway availability, refuse an occupied host port, verify reachability for an existing forward, verify ownership and startup stability for a newly launched forward, and relaunch through normal recovery. MCP lifecycle work and typed policy reads also retain the sandbox's recorded gateway, workspace, TLS, and mTLS authority instead of inheriting ambient selectors. Related changes: [PR #10695](https://github.com/NVIDIA/NemoClaw/pull/10695), [PR #10814](https://github.com/NVIDIA/NemoClaw/pull/10814), [PR #10815](https://github.com/NVIDIA/NemoClaw/pull/10815), and [PR #10810](https://github.com/NVIDIA/NemoClaw/pull/10810). For more information, refer to [Understand Gateway Lifecycle Control](/user-guide/openclaw/manage-sandboxes/configure-sandboxes/understand-gateway-lifecycle-control) and [About Managed MCP Servers](/user-guide/openclaw/manage-sandboxes/mcp-servers/about-managed-mcp-servers). diff --git a/docs/get-started/quickstart-hermes.mdx b/docs/get-started/quickstart-hermes.mdx index 88ce6cea653..9778b705c08 100644 --- a/docs/get-started/quickstart-hermes.mdx +++ b/docs/get-started/quickstart-hermes.mdx @@ -381,11 +381,12 @@ Use these details when your first-run path needs more control. The onboard flow starts both port forwards automatically. For a new sandbox, NemoClaw reserves the selected dashboard loopback port through sandbox preparation and creation. If another listener claims the port before NemoClaw binds the reservation, NemoClaw selects another port before changing sandbox resources. - NemoClaw waits up to 90 seconds for each forward to bind and remain owned through OpenShell's first post-bind sandbox check. + NemoClaw waits up to 90 seconds for each forward to bind under its spawned OpenShell process. + It then verifies listener ownership through OpenShell's first post-bind sandbox check. If OpenShell reports that the sandbox is still completing its readiness handoff, NemoClaw waits 5 seconds and retries up to 12 times. An exact forward process that exits for another reason receives one retry. If the process remains unbound at the deadline, NemoClaw stops that exact process and confirms its exit before retrying. - The ordinary two-attempt sequence can take just over 3 minutes for each forward; readiness-handoff retries use a separate one-minute delay budget. + The ordinary two-attempt sequence can take about 3 minutes and 15 seconds for each forward, including listener stability, cleanup, and retry delays; readiness-handoff retries use a separate one-minute delay budget. NemoClaw accepts each forward only when its spawned process owns the listener. It does not adopt an unrelated listener or start another forward while it cannot confirm that the prior process stopped. NemoClaw releases the reservation immediately before OpenShell starts the dashboard forward. diff --git a/docs/get-started/quickstart.mdx b/docs/get-started/quickstart.mdx index 2e9de54329c..86635aecdb0 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -458,11 +458,12 @@ Use these details when your first-run path needs more control. When that port is occupied, NemoClaw uses the next free dashboard port, such as `18790`, and includes the port in the URL. For a new sandbox, NemoClaw reserves the selected loopback port through sandbox preparation and creation. If another listener claims the port before NemoClaw binds the reservation, NemoClaw selects another port before changing sandbox resources. - NemoClaw waits up to 90 seconds for the dashboard forward to bind and remain owned through OpenShell's first post-bind sandbox check. + NemoClaw waits up to 90 seconds for the dashboard forward to bind under the spawned OpenShell process. + It then verifies listener ownership through OpenShell's first post-bind sandbox check. If OpenShell reports that the sandbox is still completing its readiness handoff, NemoClaw waits 5 seconds and retries up to 12 times. An exact forward process that exits for another reason receives one retry. If the process remains unbound at the deadline, NemoClaw stops that exact process and confirms its exit before retrying. - The ordinary two-attempt sequence can take just over 3 minutes; readiness-handoff retries use a separate one-minute delay budget. + The ordinary two-attempt sequence can take about 3 minutes and 15 seconds, including listener stability, cleanup, and retry delays; readiness-handoff retries use a separate one-minute delay budget. NemoClaw accepts the forward only when the spawned process owns the listener. It does not adopt an unrelated listener or start another forward while it cannot confirm that the prior process stopped. NemoClaw releases the reservation immediately before OpenShell starts the dashboard forward. diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 0ed4131ff13..911ce2f6fc1 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -95,7 +95,7 @@ The command repairs a stopped in-sandbox gateway and re-establishes the dashboar It is idempotent and safe to script. If the gateway is already healthy, `recover` does not restart it. If the host forward is already active, recovery accepts it only after OpenShell ownership is reconciled and the local endpoint is reachable. -If recovery launches a new forward, it accepts the forward after the OpenShell process owns the listener through the startup stability window without opening a connection to the endpoint. +For a standard Hermes sandbox, if recovery launches a new forward, it accepts the forward after the OpenShell process owns the listener through the startup stability window without opening a connection to the endpoint. Before it repairs the gateway, `recover` checks for a NemoClaw cron restore gate or release recovery record left by an interrupted rebuild. The gate continues to block new Hermes turns and cron dispatch across gateway and container restarts in the same sandbox. If release rollback could not restore the gate, `recover` uses the root-owned recovery record to reacquire it before gateway repair can start dispatch. After gateway repair, `recover` waits for active agent work to finish and validates the restored cron jobs and scripts. It clears NemoClaw-owned gate and release recovery state only after validation succeeds. If no independent operator drain exists, successful recovery prints `Hermes cron dispatch resumed after restored jobs and scripts were validated.` If an operator drain exists, recovery prints `Hermes cron restore gate cleared; the independent operator drain remains active.` The command does not own or clear the Hermes operator drain, so new Hermes turns and cron dispatch remain blocked while that drain is active. If gate reacquisition or cron validation fails, `recover` exits nonzero and retains the recovery state for another attempt. diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index d041fbf9bea..57c5f712476 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -82,7 +82,12 @@ describe("OpenShell forward service", () => { }); it("uses the selected OpenShell configuration without exposing credentials (#11084)", () => { - const spawnDetached = vi.fn(() => ({ pid: 42, unref: vi.fn() })); + const spawnDetached = vi.fn( + (_executable: string, _args: readonly string[], _environment: NodeJS.ProcessEnv) => ({ + pid: 42, + unref: vi.fn(), + }), + ); launchForwardService(target, { getProcessIdentity: stableProcessIdentity, diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index 797cd1c16bf..dae277a5b93 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -1131,7 +1131,7 @@ transient_provider_availability_failure() { printf '%s\n' "$diagnostic" | grep -Fq \ 'Available Model Group Fallbacks=' || return 1 ! printf '%s\n' "$diagnostic" | grep -Eiq \ - 'authentication failed|authorization failed|unauthorized|forbidden|HTTP( status)?[:= ]+40[13]|invalid.*(api[_ -]?key|credential|JSON|response)|\b(egress|request|connection|certificate|TLS|network|route|routing|policy|proxy)[^\r\n]*(blocked|denied|failed|invalid)\b|malformed' + 'authentication failed|authorization failed|unauthorized|forbidden|HTTP( status)?[:= ]+40[13]|invalid.*(api[_ -]?key|credential|JSON|response)|\b(egress|request|connection|certificate|TLS|network|route|routing|policy|proxy|transport)[^\r\n]*(blocked|denied|failed|invalid)\b|\b(blocked|denied|failed|invalid)[^\r\n]*(egress|request|connection|certificate|TLS|network|route|routing|policy|proxy|transport)\b|malformed' } provider_empty_message_evidence() { @@ -1203,10 +1203,6 @@ wait_for_turn_count() { fi sleep 1 done - transient_provider_availability_failure && \ - fail_launch_session \ - "launch did not record the required structured session turns" \ - "${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}" fail_launch_session "launch did not record the required structured session turns" } diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index f05ffe6ca43..608b770cd32 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -100,7 +100,7 @@ it("reports a residual PTY monitor socket without removing it (#9384)", async () function runLaunchSessionFixture( mode: FixtureMode, - terminalCopy: "absent" | "ansi" | "provider" | "reordered" | "security", + terminalCopy: "absent" | "ansi" | "policy" | "provider" | "reordered" | "security", ) { const fixtureRoot = mkdtempSync(join(tmpdir(), "nemoclaw-launch-turn-")); const canonicalRestoredMarker = join(fixtureRoot, "canonical-restored"); @@ -330,6 +330,11 @@ if (process.argv[2] !== "tui") { process.stdout.write("\u001b[2KOpenAIException - . Received Model Group=nvidia/model\r\n"); process.stdout.write("\u001b[2KAvailable Model Group Fallbacks=None\r"); } + if (terminalCopy === "policy") { + process.stdout.write("\u001b[2Krun error: litellm.ServiceUnavailableError: ServiceUnavailableError:\r\n"); + process.stdout.write("\u001b[2KOpenAIException - . Received Model Group=nvidia/model\r\n"); + process.stdout.write("\u001b[2KAvailable Model Group Fallbacks=None; denied by network policy\r"); + } if (terminalCopy === "security") { process.stdout.write("\u001b[2Krun error: litellm.ServiceUnavailableError: ServiceUnavailableError:\r\n"); process.stdout.write("\u001b[2KOpenAIException - . Received Model Group=nvidia/model\r\n"); @@ -1068,10 +1073,13 @@ it.runIf(process.platform === "linux")( testTimeout(30_000), ); -it.runIf(process.platform === "linux")( - "does not retry real provider output that also reports a security denial (#10978)", - async () => { - const produced = runLaunchSessionFixture("provider-empty-message", "security").result; +it.runIf(process.platform === "linux").each([ + { denial: "egress blocked by sandbox guard", terminalCopy: "security" }, + { denial: "denied by network policy", terminalCopy: "policy" }, +] as const)( + "does not retry real provider output that reports $denial (#10978)", + async ({ denial, terminalCopy }) => { + const produced = runLaunchSessionFixture("provider-empty-message", terminalCopy).result; const firstResult = { exitCode: produced.status ?? 1, signal: produced.signal, @@ -1087,11 +1095,11 @@ it.runIf(process.platform === "linux")( openshellCommandPath: "/usr/bin/openshell", }; - expect(firstResult.stderr).toContain("egress blocked by sandbox guard"); + expect(firstResult.stderr).toContain(denial); expect(firstResult.stderr).not.toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); await expect( runOpenClawLaunchSession({ - artifactName: "producer-auth-handoff", + artifactName: "producer-denial-handoff", cliCommand: "node", env: {}, host: host as never, @@ -1104,6 +1112,18 @@ it.runIf(process.platform === "linux")( testTimeout(30_000), ); +it.runIf(process.platform === "linux")( + "does not mark provider output without structured empty-message evidence (#10978)", + () => { + const produced = runLaunchSessionFixture("recording-timeout", "provider").result; + + expect(produced.status).toBe(1); + expect(produced.stderr).toContain("ServiceUnavailableError"); + expect(produced.stderr).not.toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); + }, + testTimeout(20_000), +); + it.runIf(process.platform === "linux")( "rejects out-of-order structured records even when the PTY process remains active (#9160)", () => { From 26933c7d5ce0a9475389cd8b80e90b7cc1f5ef7c Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 07:26:23 -0700 Subject: [PATCH 19/43] fix(forward): verify recovered listener identity Signed-off-by: Prekshi Vyas --- docs/get-started/quickstart-hermes.mdx | 2 +- docs/get-started/quickstart.mdx | 2 +- .../forward-recovery-declared-ports.test.ts | 19 +++ src/lib/actions/sandbox/forward-recovery.ts | 35 +++-- .../openshell/forward-service.test.ts | 44 +++++++ src/lib/adapters/openshell/forward-service.ts | 121 +++++++++++++++++- 6 files changed, 210 insertions(+), 13 deletions(-) diff --git a/docs/get-started/quickstart-hermes.mdx b/docs/get-started/quickstart-hermes.mdx index 9778b705c08..2371bb601ea 100644 --- a/docs/get-started/quickstart-hermes.mdx +++ b/docs/get-started/quickstart-hermes.mdx @@ -382,7 +382,7 @@ Use these details when your first-run path needs more control. For a new sandbox, NemoClaw reserves the selected dashboard loopback port through sandbox preparation and creation. If another listener claims the port before NemoClaw binds the reservation, NemoClaw selects another port before changing sandbox resources. NemoClaw waits up to 90 seconds for each forward to bind under its spawned OpenShell process. - It then verifies listener ownership through OpenShell's first post-bind sandbox check. + It then verifies that each spawned process owns its listener and keeps that ownership stable for one post-bind check interval. If OpenShell reports that the sandbox is still completing its readiness handoff, NemoClaw waits 5 seconds and retries up to 12 times. An exact forward process that exits for another reason receives one retry. If the process remains unbound at the deadline, NemoClaw stops that exact process and confirms its exit before retrying. diff --git a/docs/get-started/quickstart.mdx b/docs/get-started/quickstart.mdx index 86635aecdb0..e0c08e8a119 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -459,7 +459,7 @@ Use these details when your first-run path needs more control. For a new sandbox, NemoClaw reserves the selected loopback port through sandbox preparation and creation. If another listener claims the port before NemoClaw binds the reservation, NemoClaw selects another port before changing sandbox resources. NemoClaw waits up to 90 seconds for the dashboard forward to bind under the spawned OpenShell process. - It then verifies listener ownership through OpenShell's first post-bind sandbox check. + It then verifies that the spawned process owns the listener and keeps that ownership stable for one post-bind check interval. If OpenShell reports that the sandbox is still completing its readiness handoff, NemoClaw waits 5 seconds and retries up to 12 times. An exact forward process that exits for another reason receives one retry. If the process remains unbound at the deadline, NemoClaw stops that exact process and confirms its exit before retrying. diff --git a/src/lib/actions/sandbox/forward-recovery-declared-ports.test.ts b/src/lib/actions/sandbox/forward-recovery-declared-ports.test.ts index c1e737f42cc..4d770398414 100644 --- a/src/lib/actions/sandbox/forward-recovery-declared-ports.test.ts +++ b/src/lib/actions/sandbox/forward-recovery-declared-ports.test.ts @@ -10,11 +10,13 @@ const mocks = vi.hoisted(() => ({ getSandbox: vi.fn(), getHermesDashboardRecoveryConfig: vi.fn(() => null), isLocalForwardReachable: vi.fn(() => true), + isForwardServiceListenerOwned: vi.fn(() => true), launchForwardService: vi.fn(), })); vi.mock("../../adapters/openshell/forward-service", async (importOriginal) => ({ ...(await importOriginal()), + isForwardServiceListenerOwned: mocks.isForwardServiceListenerOwned, launchForwardService: mocks.launchForwardService, })); @@ -63,6 +65,7 @@ beforeEach(() => { vi.unstubAllEnvs(); mocks.runOpenshell.mockReturnValue({ status: 0 }); mocks.isLocalForwardReachable.mockReturnValue(true); + mocks.isForwardServiceListenerOwned.mockReturnValue(true); mocks.launchForwardService.mockImplementation(() => { mocks.isLocalForwardReachable.mockReturnValue(true); }); @@ -85,6 +88,22 @@ describe("ensureDeclaredAgentForwardPortsHealthy", { timeout: 30_000 }, () => { expect(mocks.launchForwardService).not.toHaveBeenCalled(); }); + it("rejects a reachable listener without the selected service-forward identity (#11084)", async () => { + const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); + mocks.getSandbox.mockReturnValue({ agent: "openclaw", dashboardPort: 18789 }); + mocks.captureOpenshell.mockReturnValue(forwardList([])); + mocks.isForwardServiceListenerOwned.mockReturnValue(false); + const { ensureSandboxPortForward } = await import("./forward-recovery"); + + expect(ensureSandboxPortForward("unknown-listener")).toBe(false); + expect(mocks.launchForwardService).not.toHaveBeenCalled(); + expect(consoleError).toHaveBeenCalledWith( + expect.stringContaining( + "host port 18789 is occupied by a listener that does not match the selected OpenShell service forward", + ), + ); + }); + it("does not demand the manifest dashboard port from a sandbox that owns a different dashboard port (#8543)", async () => { mocks.getSandbox.mockReturnValue({ agent: "hermes", diff --git a/src/lib/actions/sandbox/forward-recovery.ts b/src/lib/actions/sandbox/forward-recovery.ts index cb2c57ef418..17e0c5c4e23 100644 --- a/src/lib/actions/sandbox/forward-recovery.ts +++ b/src/lib/actions/sandbox/forward-recovery.ts @@ -6,6 +6,7 @@ import { withSelectedOpenShellCommandOptions, } from "../../adapters/openshell/command-argv"; import { + isForwardServiceListenerOwned, launchForwardService, type ForwardServiceTarget, } from "../../adapters/openshell/forward-service"; @@ -325,8 +326,8 @@ export function teardownSandboxDashboardForward( * Re-establish the dashboard port forward to the sandbox. * Uses the recorded dashboard port when available, including custom ports for * non-OpenClaw agents, then falls back to the active agent's declared port. - * Returns true when an existing forward is reachable or a newly launched - * OpenShell service owns the listener through its startup stability window. + * Returns true when an existing exact OpenShell service owns the reachable + * listener or a newly launched service owns it through the startup stability window. */ export function ensureSandboxPortForward( sandboxName: string, @@ -356,7 +357,7 @@ export function ensureSandboxPortForward( }); } -/** Probe local reachability for a registered sandbox port without claiming process ownership. */ +/** Verify local reachability and exact OpenShell service-forward process ownership. */ export function isSandboxForwardHealthy( sandboxName: string, options: { isWsl?: boolean; runtimeSelection?: OpenShellRuntimeSelection } = {}, @@ -375,7 +376,7 @@ export function isSandboxForwardHealthy( export function isSandboxPortForwardHealthy( sandboxName: string, port: number, - _expectedBind?: string, + expectedBind?: string, runtimeSelection?: OpenShellRuntimeSelection, ): SandboxForwardHealth { const sandbox = registry.getSandbox(sandboxName); @@ -394,14 +395,27 @@ export function isSandboxPortForwardHealthy( ), ); if ( - !listed.error && - !listed.signal && - listed.status === 0 && + listed.error || + listed.signal || + listed.status !== 0 || isLegacySandboxForwardListed(listed.output, sandboxName, port) ) { return false; } - return true; + const executable = resolveOpenshell(); + if (!executable) return false; + return ( + isForwardServiceListenerOwned( + forwardServiceTarget( + executable, + gatewayName, + sandboxName, + port, + expectedBind, + runtimeSelection?.workspace ?? "default", + ), + ) === true + ); } export function ensureSandboxPortForwardForPort( @@ -444,6 +458,11 @@ export function ensureSandboxPortForwardForPort( if (!sandbox) throw new Error(`Sandbox '${sandboxName}' is not registered`); const gatewayName = runtimeSelection?.gatewayName ?? resolveSandboxGatewayName(sandbox); retireLegacyForwardServiceMigration(sandboxName, gatewayName, [port], runtimeSelection); + if (isLocalForwardReachable(port)) { + throw new Error( + `host port ${String(port)} is occupied by a listener that does not match the selected OpenShell service forward`, + ); + } const executable = resolveOpenshell(); if (!executable) throw new Error("OpenShell is unavailable"); launchForwardService( diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index 57c5f712476..f0d1507b685 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -8,6 +8,7 @@ import { describe, expect, it, vi } from "vitest"; import { buildForwardServiceArgs, getForwardListenerOwnership, + isForwardServiceListenerOwned, launchForwardService, parseForwardInstanceIdentity, type ForwardServiceTarget, @@ -50,6 +51,32 @@ describe("OpenShell forward service", () => { ); }); + it("accepts only an exact same-user service-forward listener (#11084)", () => { + const currentUid = process.getuid?.(); + expect(currentUid).toBeDefined(); + if (currentUid === undefined) return; + const expectedArgv = [target.executable, ...buildForwardServiceArgs(target)]; + const options = { + findListenerOwnerPids: () => [42], + isListenerOwned: () => true, + readProcess: () => ({ argv: expectedArgv, uid: currentUid }), + }; + + expect(isForwardServiceListenerOwned(target, options)).toBe(true); + expect( + isForwardServiceListenerOwned(target, { + ...options, + readProcess: () => ({ argv: [...expectedArgv, "unexpected"], uid: currentUid }), + }), + ).toBe(false); + expect( + isForwardServiceListenerOwned(target, { + ...options, + readProcess: () => ({ argv: expectedArgv, uid: currentUid + 1 }), + }), + ).toBe(false); + }); + it("accepts an owned listener without opening a ForwardTcp connection (#11084)", () => { const unref = vi.fn(); let spawned = false; @@ -377,6 +404,23 @@ describe("OpenShell forward service", () => { }, ); + it.runIf(process.platform === "darwin")( + "proves listener ownership from macOS lsof (#11084)", + async () => { + const server = createServer(); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + try { + const address = server.address() as AddressInfo; + expect(getForwardListenerOwnership(process.pid, address.port)).toBe(true); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }, + ); + it("distinguishes same-second POSIX processes by their launch token (#11084)", () => { const first = "11111111-1111-4111-8111-111111111111"; const second = "22222222-2222-4222-8222-222222222222"; diff --git a/src/lib/adapters/openshell/forward-service.ts b/src/lib/adapters/openshell/forward-service.ts index 3a6d78df390..bc6d630f02a 100644 --- a/src/lib/adapters/openshell/forward-service.ts +++ b/src/lib/adapters/openshell/forward-service.ts @@ -32,6 +32,12 @@ type ForwardServiceChild = { unref(): void; }; +type ForwardServiceProcess = { + readonly argv?: readonly string[]; + readonly command?: string; + readonly uid: number; +}; + export interface ForwardServiceTarget { readonly executable: string; readonly gatewayName: string; @@ -64,6 +70,12 @@ export interface ForwardServiceLaunchOptions { readonly timeoutMs?: number; } +type ForwardServiceOwnershipOptions = { + readonly findListenerOwnerPids?: (port: number) => readonly number[] | null; + readonly isListenerOwned?: (pid: number, port: number) => boolean | null; + readonly readProcess?: (pid: number) => ForwardServiceProcess | null; +}; + function readLinuxProcessStat(pid: number): string[] | null | undefined { if (process.platform !== "linux") return undefined; try { @@ -138,9 +150,10 @@ function readLinuxListeningSocketInodes(port: number): Set | null { return readTable ? inodes : null; } -function isLinuxListenerOwned(pid: number, port: number): boolean | null { - const listenerInodes = readLinuxListeningSocketInodes(port); - if (!listenerInodes) return null; +function linuxProcessOwnsListenerInodes( + pid: number, + listenerInodes: ReadonlySet, +): boolean | null { let descriptors: string[]; try { descriptors = fs.readdirSync(`/proc/${String(pid)}/fd`); @@ -164,6 +177,80 @@ function isLinuxListenerOwned(pid: number, port: number): boolean | null { return unreadableDescriptor ? null : false; } +function findLinuxListenerOwnerPids(port: number): number[] | null { + const listenerInodes = readLinuxListeningSocketInodes(port); + if (!listenerInodes || listenerInodes.size === 0) return null; + let processes: fs.Dirent[]; + try { + processes = fs.readdirSync("/proc", { withFileTypes: true }); + } catch { + return null; + } + const owners: number[] = []; + for (const processEntry of processes) { + if (!processEntry.isDirectory() || !/^\d+$/u.test(processEntry.name)) continue; + const pid = Number(processEntry.name); + if (linuxProcessOwnsListenerInodes(pid, listenerInodes) === true) owners.push(pid); + } + return owners.length > 0 ? owners : null; +} + +function findLsofListenerOwnerPids(port: number): number[] | null { + const result = spawnSync("lsof", ["-nP", "-t", `-iTCP:${String(port)}`, "-sTCP:LISTEN"], { + encoding: "utf8", + env: buildOpenShellSubprocessEnv(process.env), + stdio: ["ignore", "pipe", "ignore"], + timeout: 1_000, + }); + if (result.error || (result.status !== 0 && result.status !== 1)) return null; + const owners = result.stdout + .split(/\r?\n/u) + .map((value) => value.trim()) + .filter((value) => /^\d+$/u.test(value)) + .map(Number); + return owners.length > 0 ? [...new Set(owners)] : null; +} + +function findListenerOwnerPids(port: number): number[] | null { + return process.platform === "linux" + ? findLinuxListenerOwnerPids(port) + : findLsofListenerOwnerPids(port); +} + +function readForwardServiceProcess(pid: number): ForwardServiceProcess | null { + const currentUid = process.getuid?.(); + if (currentUid === undefined) return null; + if (process.platform === "linux") { + try { + return { + argv: fs + .readFileSync(`/proc/${String(pid)}/cmdline`) + .toString("utf8") + .split("\0") + .filter(Boolean), + uid: fs.statSync(`/proc/${String(pid)}`).uid, + }; + } catch { + return null; + } + } + const result = spawnSync("ps", ["-ww", "-p", String(pid), "-o", "uid=", "-o", "command="], { + encoding: "utf8", + env: buildOpenShellSubprocessEnv(process.env), + stdio: ["ignore", "pipe", "ignore"], + timeout: 1_000, + }); + if (result.error || result.status !== 0) return null; + const match = /^\s*(\d+)\s+(.+)$/u.exec(result.stdout.trim()); + return match?.[1] && match[2] ? { command: match[2], uid: Number(match[1]) } : null; +} + +function isLinuxListenerOwned(pid: number, port: number): boolean | null { + const listenerInodes = readLinuxListeningSocketInodes(port); + if (!listenerInodes) return null; + return linuxProcessOwnsListenerInodes(pid, listenerInodes); +} + export function getForwardListenerOwnership(pid: number, port: number): boolean | null { if (process.platform === "linux") return isLinuxListenerOwned(pid, port); const result = spawnSync( @@ -445,6 +532,34 @@ export function buildForwardServiceArgs(target: ForwardServiceTarget): string[] ]; } +/** Verify that an existing listener belongs to the exact OpenShell service-forward command. */ +export function isForwardServiceListenerOwned( + target: ForwardServiceTarget, + options: ForwardServiceOwnershipOptions = {}, +): boolean | null { + validateForwardServiceTarget(target); + const ownerPids = (options.findListenerOwnerPids ?? findListenerOwnerPids)(target.localPort); + if (!ownerPids || ownerPids.length !== 1) return null; + const pid = ownerPids[0]; + if (pid === undefined) return null; + const listenerOwned = (options.isListenerOwned ?? getForwardListenerOwnership)( + pid, + target.localPort, + ); + if (listenerOwned !== true) return listenerOwned; + const owner = (options.readProcess ?? readForwardServiceProcess)(pid); + const currentUid = process.getuid?.(); + if (!owner || currentUid === undefined || owner.uid !== currentUid) return false; + const expectedArgv = [target.executable, ...buildForwardServiceArgs(target)]; + if (owner.argv) { + return ( + owner.argv.length === expectedArgv.length && + owner.argv.every((value, index) => value === expectedArgv[index]) + ); + } + return owner.command === expectedArgv.join(" "); +} + /** Launch one foreground OpenShell service forward as a detached host child. */ export function launchForwardService( target: ForwardServiceTarget, From e1fc11118f718993de67a3af2146a5b2a643d4e5 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 07:31:53 -0700 Subject: [PATCH 20/43] test(forward): use platform test gate Signed-off-by: Prekshi Vyas --- .../openshell/forward-service.test.ts | 51 ++++++++++--------- 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index f0d1507b685..774b1c9d455 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -51,31 +51,32 @@ describe("OpenShell forward service", () => { ); }); - it("accepts only an exact same-user service-forward listener (#11084)", () => { - const currentUid = process.getuid?.(); - expect(currentUid).toBeDefined(); - if (currentUid === undefined) return; - const expectedArgv = [target.executable, ...buildForwardServiceArgs(target)]; - const options = { - findListenerOwnerPids: () => [42], - isListenerOwned: () => true, - readProcess: () => ({ argv: expectedArgv, uid: currentUid }), - }; - - expect(isForwardServiceListenerOwned(target, options)).toBe(true); - expect( - isForwardServiceListenerOwned(target, { - ...options, - readProcess: () => ({ argv: [...expectedArgv, "unexpected"], uid: currentUid }), - }), - ).toBe(false); - expect( - isForwardServiceListenerOwned(target, { - ...options, - readProcess: () => ({ argv: expectedArgv, uid: currentUid + 1 }), - }), - ).toBe(false); - }); + it.runIf(process.getuid !== undefined)( + "accepts only an exact same-user service-forward listener (#11084)", + () => { + const currentUid = process.getuid?.() ?? -1; + const expectedArgv = [target.executable, ...buildForwardServiceArgs(target)]; + const options = { + findListenerOwnerPids: () => [42], + isListenerOwned: () => true, + readProcess: () => ({ argv: expectedArgv, uid: currentUid }), + }; + + expect(isForwardServiceListenerOwned(target, options)).toBe(true); + expect( + isForwardServiceListenerOwned(target, { + ...options, + readProcess: () => ({ argv: [...expectedArgv, "unexpected"], uid: currentUid }), + }), + ).toBe(false); + expect( + isForwardServiceListenerOwned(target, { + ...options, + readProcess: () => ({ argv: expectedArgv, uid: currentUid + 1 }), + }), + ).toBe(false); + }, + ); it("accepts an owned listener without opening a ForwardTcp connection (#11084)", () => { const unref = vi.fn(); From d4b602c0aafdefa14df130acb53bdf917ad1dcba Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 07:41:49 -0700 Subject: [PATCH 21/43] fix(forward): bound listener stability Signed-off-by: Prekshi Vyas --- .../openshell/forward-service.test.ts | 28 +++++++++++++++++++ src/lib/adapters/openshell/forward-service.ts | 27 ++++++++++++++---- 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/src/lib/adapters/openshell/forward-service.test.ts b/src/lib/adapters/openshell/forward-service.test.ts index 774b1c9d455..89670d1ba8d 100644 --- a/src/lib/adapters/openshell/forward-service.test.ts +++ b/src/lib/adapters/openshell/forward-service.test.ts @@ -162,6 +162,34 @@ describe("OpenShell forward service", () => { expect(sleep).toHaveBeenCalledTimes(35); }); + it("stops when listener ownership never stabilizes (#11084)", () => { + let now = 0; + let ownershipChecks = 0; + let running = true; + const stopProcess = vi.fn(() => { + running = false; + }); + vi.spyOn(Date, "now").mockImplementation(() => now); + + expect(() => + launchForwardService(target, { + getProcessIdentity: stableProcessIdentity, + isListenerOwned: () => ++ownershipChecks % 2 === 1, + isProcessRunning: () => running, + isReachable: () => false, + maxAttempts: 1, + sleep: (milliseconds) => { + now += milliseconds; + }, + spawnDetached: () => ({ pid: 44, unref: vi.fn() }), + stopProcess, + timeoutMs: 10_000, + }), + ).toThrow(/was stopped after listener ownership did not stabilize/u); + expect(ownershipChecks).toBeGreaterThan(1); + expect(stopProcess).toHaveBeenCalledWith(44, "SIGTERM"); + }); + it("refuses an occupied port without launching or adopting its listener", () => { const spawnDetached = vi.fn(); diff --git a/src/lib/adapters/openshell/forward-service.ts b/src/lib/adapters/openshell/forward-service.ts index bc6d630f02a..762fc217476 100644 --- a/src/lib/adapters/openshell/forward-service.ts +++ b/src/lib/adapters/openshell/forward-service.ts @@ -22,6 +22,7 @@ const POLL_INTERVAL_MS = 100; // OpenShell checks the sandbox every two seconds after binding. Keep the // listener owned through one complete post-bind check before callers connect. const STABLE_LISTENER_OBSERVATIONS = 26; +const STABLE_LISTENER_TIMEOUT_MS = STABLE_LISTENER_OBSERVATIONS * POLL_INTERVAL_MS; const FORWARD_INSTANCE_ENV = "NEMOCLAW_FORWARD_INSTANCE_ID"; const sleepBuffer = new Int32Array(new SharedArrayBuffer(4)); @@ -626,9 +627,12 @@ export function launchForwardService( ? readProcessIdentity(child.pid) : `${process.platform}:${instanceId}`; child.unref(); - const deadline = Date.now() + (options.timeoutMs ?? START_TIMEOUT_MS); + const timeoutMs = options.timeoutMs ?? START_TIMEOUT_MS; + const bindDeadline = Date.now() + timeoutMs; + let stabilityDeadline: number | undefined; let exited = false; let ownershipLost = false; + let stabilityTimedOut = false; let stableListenerObservations = 0; while (true) { if (childIdentity) { @@ -651,6 +655,7 @@ export function launchForwardService( listenerOwnership === true && processIdentityStatus(child.pid, childIdentity, readProcessIdentity) === "owned" ) { + stabilityDeadline ??= Date.now() + STABLE_LISTENER_TIMEOUT_MS; stableListenerObservations += 1; if (stableListenerObservations >= STABLE_LISTENER_OBSERVATIONS) { removeForwardStartOutput(child); @@ -665,9 +670,14 @@ export function launchForwardService( // first relay and make the foreground service exit. Inspect the launched // process's listener ownership without connecting to the service. // The bind deadline governs the first owned-listener observation. Once - // binding starts, finish the short stability window instead of timing - // out a service that bound at the edge of the deadline. - if (Date.now() >= deadline && stableListenerObservations === 0) break; + // binding starts, a separate fixed deadline prevents repeated ownership + // loss from resetting the stability window forever. + const now = Date.now(); + if (stabilityDeadline !== undefined && now >= stabilityDeadline) { + stabilityTimedOut = true; + break; + } + if (stabilityDeadline === undefined && now >= bindDeadline) break; sleep(POLL_INTERVAL_MS); } if (ownershipLost) { @@ -695,8 +705,11 @@ export function launchForwardService( stopResult === "unverified" ? "could not verify that it still owned that process" : "could not stop that process"; + const incompleteState = stabilityTimedOut + ? `did not retain listener ownership for ${String(STABLE_LISTENER_TIMEOUT_MS)}ms` + : `remained unbound after ${String(timeoutMs)}ms`; throw new Error( - `OpenShell forward service process ${String(child.pid)} remained unbound after ${String(options.timeoutMs ?? START_TIMEOUT_MS)}ms and ${reason}; ` + + `OpenShell forward service process ${String(child.pid)} ${incompleteState} and ${reason}; ` + `refusing to signal or retry; forward start: ${finalStartState.diagnostic}; forward list: ${describeFailureState(options.describeState)}`, ); } @@ -708,7 +721,9 @@ export function launchForwardService( `refusing to adopt its listener or retry; forward start: ${finalStartState.diagnostic}; forward list: ${describeFailureState(options.describeState)}`, ); } - finalFailure = "was stopped after failing to bind"; + finalFailure = stabilityTimedOut + ? "was stopped after listener ownership did not stabilize" + : "was stopped after failing to bind"; } finalStartState = readForwardStartState(child); removeForwardStartOutput(child); From 4f9126d7537c687b738e944acd6608236ac69b2b Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 07:57:23 -0700 Subject: [PATCH 22/43] fix(forward): verify launch listener authority Signed-off-by: Prekshi Vyas --- src/lib/actions/sandbox/forward-recovery.ts | 66 +++++++++++++++++-- ...unch-readiness-forward-observation.test.ts | 58 +++++++++++++++- 2 files changed, 117 insertions(+), 7 deletions(-) diff --git a/src/lib/actions/sandbox/forward-recovery.ts b/src/lib/actions/sandbox/forward-recovery.ts index 17e0c5c4e23..1d114b4638f 100644 --- a/src/lib/actions/sandbox/forward-recovery.ts +++ b/src/lib/actions/sandbox/forward-recovery.ts @@ -39,9 +39,10 @@ import { ensureHermesDashboardPortForwardIfEnabled as ensureHermesDashboardPortForward, getHermesDashboardRecoveryConfig, } from "./hermes-dashboard-recovery"; -import type { - HermesPortableForwardRecoveryInput, - HermesPortableForwardRecoveryTimingEvidence, +import { + verifyHermesPortableLaunchForwards, + type HermesPortableForwardRecoveryInput, + type HermesPortableForwardRecoveryTimingEvidence, } from "./probe/hermes-portable-forward-recovery"; export { HermesPortableForwardRecoveryError, @@ -624,10 +625,47 @@ export function ensureDeclaredAgentForwardPortsHealthy( * Observe every host forward that the interactive preflight would recover, * without starting, stopping, or rebinding one. */ +type SandboxLaunchForwardCapture = ( + args: string[], + options?: NonNullable[1]>, +) => ReturnType; + +function verifyPortableLaunchForwards( + sandboxName: string, + gatewayName: string, + ports: readonly number[], + capture: SandboxLaunchForwardCapture, +): boolean | null { + const captureList = (args: readonly string[], timeout: number) => + capture([...args], { ignoreError: true, includeStreams: true, timeout }); + try { + return ( + verifyHermesPortableLaunchForwards({ + intent: "connect-probe-only", + sandboxName, + gatewayName, + operationTimeoutMs: OPENSHELL_PROBE_TIMEOUT_MS, + ports, + probeTimeoutMs: OPENSHELL_PROBE_TIMEOUT_MS, + deps: { + assertCurrent: () => undefined, + assertRollbackCurrent: () => undefined, + captureCurrentList: captureList, + captureRollbackList: captureList, + runCurrentMutation: () => undefined, + isPortReachable: isLocalForwardReachable, + }, + }).kind === "healthy" + ); + } catch { + return null; + } +} + export function areSandboxLaunchForwardsHealthy( sandboxName: string, gatewayName?: string, - _capture?: unknown, + portableCapture?: SandboxLaunchForwardCapture, ): boolean | null { const sandbox = registry.getSandbox(sandboxName); if (!sandbox) return false; @@ -636,8 +674,26 @@ export function areSandboxLaunchForwardsHealthy( const agent = agentRuntime.getSessionAgent(sandboxName); const requiredPorts = resolveSandboxLaunchForwardPortsFromAuthority(sandboxName, sandbox, agent); if (requiredPorts.length === 0) return true; + if (portableCapture) { + return verifyPortableLaunchForwards( + sandboxName, + owningGatewayName, + requiredPorts, + portableCapture, + ); + } try { - return requiredPorts.every((port) => isLocalForwardReachable(port)); + const primaryPort = resolveSandboxDashboardPort(sandboxName); + const allInterfaceDashboard = sandbox.dashboardRemoteBindPrepared === true || isWsl(); + const runtimeSelection = { gatewayName: owningGatewayName, workspace: "default" }; + return requiredPorts.every((port) => + isSandboxPortForwardHealthy( + sandboxName, + port, + port === primaryPort && allInterfaceDashboard ? "0.0.0.0" : "127.0.0.1", + runtimeSelection, + ), + ); } catch { return null; } diff --git a/test/e2e-runtime/launch-readiness-forward-observation.test.ts b/test/e2e-runtime/launch-readiness-forward-observation.test.ts index 6cefb63cbdd..bbb067c6853 100644 --- a/test/e2e-runtime/launch-readiness-forward-observation.test.ts +++ b/test/e2e-runtime/launch-readiness-forward-observation.test.ts @@ -1,13 +1,42 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { afterEach, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + captureOpenshell: vi.fn(), + isForwardServiceListenerOwned: vi.fn(), +})); + +vi.mock("../../src/lib/adapters/openshell/forward-service.ts", async (importOriginal) => ({ + ...(await importOriginal()), + isForwardServiceListenerOwned: mocks.isForwardServiceListenerOwned, +})); + +vi.mock("../../src/lib/adapters/openshell/resolve.ts", async (importOriginal) => ({ + ...(await importOriginal()), + resolveOpenshell: () => "/usr/local/bin/openshell", +})); + +vi.mock("../../src/lib/adapters/openshell/runtime.ts", async (importOriginal) => ({ + ...(await importOriginal()), + captureOpenshell: mocks.captureOpenshell, +})); import * as forwardHealth from "../../src/lib/actions/sandbox/forward-health.ts"; import { areSandboxLaunchForwardsHealthy } from "../../src/lib/actions/sandbox/forward-recovery.ts"; import * as agentRuntime from "../../src/lib/agent/runtime.ts"; import * as registry from "../../src/lib/state/registry.ts"; +beforeEach(() => { + vi.clearAllMocks(); + mocks.captureOpenshell.mockReturnValue({ + status: 0, + output: "SANDBOX BIND PORT PID STATUS", + }); + mocks.isForwardServiceListenerOwned.mockReturnValue(true); +}); + afterEach(() => { vi.restoreAllMocks(); }); @@ -27,11 +56,36 @@ function mockLaunchForwardObservation(reachable = true, gatewayRuntime = true): vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(reachable); } -it("checks each registered launch-forward port without inspecting a process", () => { +it("requires exact service ownership for each registered launch-forward port (#11084)", () => { mockLaunchForwardObservation(); expect(areSandboxLaunchForwardsHealthy("beta")).toBe(true); expect(vi.mocked(forwardHealth.isLocalForwardReachable).mock.calls).toEqual([[18_789], [18_790]]); + expect(mocks.isForwardServiceListenerOwned).toHaveBeenCalledTimes(2); +}); + +it("rejects a reachable launch-forward port owned by another process (#11084)", () => { + mockLaunchForwardObservation(); + mocks.isForwardServiceListenerOwned.mockImplementation( + (forward: { localPort: number }) => forward.localPort === 18_789, + ); + + expect(areSandboxLaunchForwardsHealthy("beta", "nemoclaw")).toBe(false); +}); + +it("uses bound Hermes Portable forward-list authority (#11084)", () => { + mockLaunchForwardObservation(); + const capture = vi.fn(() => ({ + status: 0, + output: [ + "SANDBOX BIND PORT PID STATUS", + "beta 127.0.0.1 18789 101 running", + "beta 127.0.0.1 18790 102 running", + ].join("\n"), + })); + + expect(areSandboxLaunchForwardsHealthy("beta", "nemoclaw", capture)).toBe(true); + expect(mocks.isForwardServiceListenerOwned).not.toHaveBeenCalled(); }); it("checks sandbox-owned Hermes ports instead of manifest defaults", () => { From cebe90d50ba76aab4bae7aa3a3a89f99d72e5038 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 5 Sep 2026 08:13:13 -0700 Subject: [PATCH 23/43] fix(e2e): block retry after cleanup failure Signed-off-by: Prekshi Vyas --- test/e2e/live/launch-agent-turn.ts | 10 ++++- ...h-agent-turn-provider-availability.test.ts | 4 ++ test/e2e/support/launch-agent-turn.test.ts | 42 ++++++++++++++++++- 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index dae277a5b93..b502f658068 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -14,9 +14,17 @@ const OPENCLAW_LAUNCH_PROVIDER_RETRY_DELAY_MS = 1_000; export const OPENCLAW_PROVIDER_UNAVAILABLE_MARKER = "nemoclaw.e2e.launch-failure=provider-unavailable"; const OPENCLAW_PROVIDER_UNAVAILABLE_PREFIX = `launch did not record the required structured session turns\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\n`; +const OPENCLAW_LAUNCH_CLEANUP_FAILURES = [ + "structured session baseline cleanup failed", + "launch host session cleanup failed", + "launch PTY monitor cleanup failed", +] as const; function isTransientProviderAvailabilityFailure(result: Pick): boolean { - return result.stderr.startsWith(OPENCLAW_PROVIDER_UNAVAILABLE_PREFIX); + return ( + result.stderr.startsWith(OPENCLAW_PROVIDER_UNAVAILABLE_PREFIX) && + OPENCLAW_LAUNCH_CLEANUP_FAILURES.every((diagnostic) => !result.stderr.includes(diagnostic)) + ); } export const OPENCLAW_LAUNCH_RUNTIME_ENV_SCRIPT = diff --git a/test/e2e/support/launch-agent-turn-provider-availability.test.ts b/test/e2e/support/launch-agent-turn-provider-availability.test.ts index b724717aac6..769e25147ed 100644 --- a/test/e2e/support/launch-agent-turn-provider-availability.test.ts +++ b/test/e2e/support/launch-agent-turn-provider-availability.test.ts @@ -107,6 +107,10 @@ it.each([ "invalid response", `${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nServiceUnavailableError: HTTP 503\ninvalid provider response`, ], + [ + "cleanup failure", + `launch did not record the required structured session turns\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nServiceUnavailableError: HTTP 503\nstructured session baseline cleanup failed`, + ], ["unstructured provider output", "ServiceUnavailableError: HTTP 503"], ["unknown failure", "launch failed for an unknown reason"], ])("does not retry a %s (#10978)", async (_case, stderr) => { diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index 608b770cd32..b8d0f908e4b 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -53,6 +53,7 @@ type FixtureMode = | "pty-socket-timeout" | "pty-path-unreadable" | "pty-termios-unavailable" + | "provider-cleanup-failure" | "provider-empty-message" | "recording-timeout" | "restored-canonical-timeout" @@ -353,7 +354,7 @@ if (process.argv[2] !== "tui") { if (mode === "invalid-order") { append("assistant", "response before input"); append("user", firstInput); - } else if (mode === "provider-empty-message") { + } else if (mode === "provider-empty-message" || mode === "provider-cleanup-failure") { append("user", firstInput); appendEmpty("assistant"); } else { @@ -420,7 +421,7 @@ if [[ "$NEMOCLAW_FIXTURE_MODE" == "restored-canonical-timeout" && "$4" == "input done [[ -e "$NEMOCLAW_FIXTURE_CANONICAL_RESTORED_MARKER" ]] || exit 1 fi -if [[ "$NEMOCLAW_FIXTURE_MODE" == "cleanup-failure" && "$4" == "cleanup-baseline" ]]; then +if [[ ( "$NEMOCLAW_FIXTURE_MODE" == "cleanup-failure" || "$NEMOCLAW_FIXTURE_MODE" == "provider-cleanup-failure" ) && "$4" == "cleanup-baseline" ]]; then exit 71 fi if [[ ( "$NEMOCLAW_FIXTURE_MODE" == "pty-cleanup-failure" || "$NEMOCLAW_FIXTURE_MODE" == "nonzero-pty-cleanup-failure" ) && "$4" == "cleanup-pty" ]]; then @@ -1073,6 +1074,43 @@ it.runIf(process.platform === "linux")( testTimeout(30_000), ); +it.runIf(process.platform === "linux")( + "does not retry a provider failure when producer cleanup is incomplete (#10978)", + async () => { + const produced = runLaunchSessionFixture("provider-cleanup-failure", "provider").result; + let calls = 0; + const host = { + command: async () => { + calls += 1; + return calls === 1 + ? { + exitCode: produced.status ?? 1, + signal: produced.signal, + stderr: produced.stderr, + stdout: produced.stdout, + } + : { exitCode: 0, signal: null, stderr: "", stdout: "" }; + }, + openshellCommandPath: "/usr/bin/openshell", + }; + + expect(produced.stderr).toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); + expect(produced.stderr).toContain("structured session baseline cleanup failed"); + await expect( + runOpenClawLaunchSession({ + artifactName: "provider-cleanup-handoff", + cliCommand: "node", + env: {}, + host: host as never, + redactionValues: [], + sandboxName: "alpha", + }), + ).rejects.toThrow("launch session failed"); + expect(calls).toBe(1); + }, + testTimeout(30_000), +); + it.runIf(process.platform === "linux").each([ { denial: "egress blocked by sandbox guard", terminalCopy: "security" }, { denial: "denied by network policy", terminalCopy: "policy" }, From d0bd3f41126ef737d589dbeb26989be87b65e31a Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 13:08:51 -0700 Subject: [PATCH 24/43] fix(e2e): fail closed before provider retry Make the launch producer the sole owner of retry eligibility. Scan the complete PTY capture for veto evidence and emit a run-bound marker only after cleanup succeeds. Signed-off-by: Prekshi Vyas --- test/e2e/live/launch-agent-turn.ts | 40 ++++++----- ...h-agent-turn-provider-availability.test.ts | 16 +++-- test/e2e/support/launch-agent-turn.test.ts | 66 ++++++++++++++++--- 3 files changed, 91 insertions(+), 31 deletions(-) diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index b502f658068..b58917d6fca 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -13,17 +13,17 @@ const OPENCLAW_LAUNCH_PROVIDER_ATTEMPTS = 2; const OPENCLAW_LAUNCH_PROVIDER_RETRY_DELAY_MS = 1_000; export const OPENCLAW_PROVIDER_UNAVAILABLE_MARKER = "nemoclaw.e2e.launch-failure=provider-unavailable"; -const OPENCLAW_PROVIDER_UNAVAILABLE_PREFIX = `launch did not record the required structured session turns\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\n`; -const OPENCLAW_LAUNCH_CLEANUP_FAILURES = [ - "structured session baseline cleanup failed", - "launch host session cleanup failed", - "launch PTY monitor cleanup failed", -] as const; - -function isTransientProviderAvailabilityFailure(result: Pick): boolean { +const OPENCLAW_PROVIDER_UNAVAILABLE_FAILURE_PREFIX = + "launch did not record the required structured session turns\n"; + +function isTransientProviderAvailabilityFailure( + result: Pick, + runId: string, +): boolean { + const finalMarker = `${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${runId}\n`; return ( - result.stderr.startsWith(OPENCLAW_PROVIDER_UNAVAILABLE_PREFIX) && - OPENCLAW_LAUNCH_CLEANUP_FAILURES.every((diagnostic) => !result.stderr.includes(diagnostic)) + result.stderr.startsWith(OPENCLAW_PROVIDER_UNAVAILABLE_FAILURE_PREFIX) && + result.stderr.endsWith(`\n${finalMarker}`) ); } @@ -1068,6 +1068,7 @@ baseline_path="/tmp/nemoclaw-launch-session-$NEMOCLAW_LAUNCH_RUN_ID.json" pty_monitor_root="/tmp/nemoclaw-launch-turn-$NEMOCLAW_LAUNCH_RUN_ID" session_pid="" session_deadline="" +provider_unavailable_candidate=0 remove_session_baseline() { session_evidence cleanup-baseline @@ -1112,6 +1113,9 @@ cleanup() { cleanup_status=1 fi if [[ "$original_status" != 0 ]]; then + case "$provider_unavailable_candidate:$cleanup_status" in + 1:0) echo "${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:$NEMOCLAW_LAUNCH_RUN_ID" >&2 ;; + esac exit "$original_status" fi exit "$cleanup_status" @@ -1131,6 +1135,9 @@ terminal_diagnostic() { transient_provider_availability_failure() { local diagnostic + grep -Eiq \ + 'authentication failed|authorization failed|unauthorized|forbidden|HTTP( status)?[:= ]+40[13]|invalid.*(api[_ -]?key|credential|JSON|response)|\b(egress|request|connection|certificate|TLS|network|route|routing|policy|proxy|transport)[^\r\n]*(blocked|denied|failed|invalid)\b|\b(blocked|denied|failed|invalid)[^\r\n]*(egress|request|connection|certificate|TLS|network|route|routing|policy|proxy|transport)\b|malformed' \ + "$capture" && return 1 diagnostic="$(tail -c 4096 "$capture" 2>/dev/null || true)" printf '%s\n' "$diagnostic" | grep -Fq \ 'run error: litellm.ServiceUnavailableError: ServiceUnavailableError:' || return 1 @@ -1138,8 +1145,6 @@ transient_provider_availability_failure() { 'OpenAIException - . Received Model Group=' || return 1 printf '%s\n' "$diagnostic" | grep -Fq \ 'Available Model Group Fallbacks=' || return 1 - ! printf '%s\n' "$diagnostic" | grep -Eiq \ - 'authentication failed|authorization failed|unauthorized|forbidden|HTTP( status)?[:= ]+40[13]|invalid.*(api[_ -]?key|credential|JSON|response)|\b(egress|request|connection|certificate|TLS|network|route|routing|policy|proxy|transport)[^\r\n]*(blocked|denied|failed|invalid)\b|\b(blocked|denied|failed|invalid)[^\r\n]*(egress|request|connection|certificate|TLS|network|route|routing|policy|proxy|transport)\b|malformed' } provider_empty_message_evidence() { @@ -1148,7 +1153,6 @@ provider_empty_message_evidence() { fail_launch_session() { echo "$1" >&2 - echo "${"$"}{2:-}" >&2 if [[ -s "$evidence_error" ]]; then tail -c 2048 "$evidence_error" >&2 || true fi @@ -1198,9 +1202,8 @@ wait_for_turn_count() { 2) provider_empty_message_evidence && \ transient_provider_availability_failure && \ - fail_launch_session \ - "launch did not record the required structured session turns" \ - "${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}" + provider_unavailable_candidate=1 && \ + fail_launch_session "launch did not record the required structured session turns" ;; esac fail_launch_session \ @@ -1397,6 +1400,7 @@ export async function runOpenClawLaunchSession( let providerUnavailable = false; for (let attempt = 1; attempt <= OPENCLAW_LAUNCH_PROVIDER_ATTEMPTS; attempt += 1) { const inputs = uniqueTurnInputs(); + const runId = randomUUID().replaceAll("-", ""); const result = await options.host.command("bash", ["-lc", LAUNCH_TURN_SCRIPT], { artifactName: attempt === 1 @@ -1409,7 +1413,7 @@ export async function runOpenClawLaunchSession( NEMOCLAW_LAUNCH_EXIT_COMMAND: options.exitCommand ?? "", NEMOCLAW_LAUNCH_FIRST_INPUT: inputs.first, NEMOCLAW_LAUNCH_HOST_TMP_ROOT: resolve(options.env.TMPDIR || "/tmp"), - NEMOCLAW_LAUNCH_RUN_ID: randomUUID().replaceAll("-", ""), + NEMOCLAW_LAUNCH_RUN_ID: runId, NEMOCLAW_LAUNCH_SANDBOX: options.sandboxName, NEMOCLAW_LAUNCH_SESSION_BUDGET_SECONDS: "230", NEMOCLAW_LAUNCH_SECOND_INPUT: inputs.second, @@ -1426,7 +1430,7 @@ export async function runOpenClawLaunchSession( }); if (result.exitCode === 0) return result; finalFailure = result; - providerUnavailable = isTransientProviderAvailabilityFailure(result); + providerUnavailable = isTransientProviderAvailabilityFailure(result, runId); if (!providerUnavailable) break; if (attempt < OPENCLAW_LAUNCH_PROVIDER_ATTEMPTS) { await delay(OPENCLAW_LAUNCH_PROVIDER_RETRY_DELAY_MS); diff --git a/test/e2e/support/launch-agent-turn-provider-availability.test.ts b/test/e2e/support/launch-agent-turn-provider-availability.test.ts index 769e25147ed..4f024164fcd 100644 --- a/test/e2e/support/launch-agent-turn-provider-availability.test.ts +++ b/test/e2e/support/launch-agent-turn-provider-availability.test.ts @@ -33,7 +33,7 @@ it("retries a transient provider failure in a fresh launch session (#10978)", as ? { exitCode: 1, signal: null, - stderr: `launch did not record the required structured session turns\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nlitellm.ServiceUnavailableError: NVIDIA upstream unavailable`, + stderr: `launch did not record the required structured session turns\nlitellm.ServiceUnavailableError: NVIDIA upstream unavailable\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${options?.env?.NEMOCLAW_LAUNCH_RUN_ID}\n`, stdout: "", } : { exitCode: 0, signal: null, stderr: "", stdout: "" }; @@ -66,12 +66,16 @@ it("classifies exhausted transient launch attempts as provider unavailable (#109 vi.useFakeTimers(); const calls: string[] = []; const host = { - command: async (_command: string, _args: string[], options?: { artifactName?: string }) => { + command: async ( + _command: string, + _args: string[], + options?: { artifactName?: string; env?: NodeJS.ProcessEnv }, + ) => { calls.push(options?.artifactName ?? ""); return { exitCode: 1, signal: null, - stderr: `launch did not record the required structured session turns\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nHTTP ${calls.length === 1 ? "503" : "502"}`, + stderr: `launch did not record the required structured session turns\nHTTP ${calls.length === 1 ? "503" : "502"}\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${options?.env?.NEMOCLAW_LAUNCH_RUN_ID}\n`, stdout: "", }; }, @@ -91,6 +95,10 @@ it("classifies exhausted transient launch attempts as provider unavailable (#109 }); it.each([ + [ + "marker from another launch run", + `launch did not record the required structured session turns\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:different-run-id\n`, + ], [ "invalid structured session evidence", `${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nServiceUnavailableError\nlaunch final structured session evidence did not qualify (status 2)\n{"reason":"message_order_invalid"}`, @@ -109,7 +117,7 @@ it.each([ ], [ "cleanup failure", - `launch did not record the required structured session turns\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}\nServiceUnavailableError: HTTP 503\nstructured session baseline cleanup failed`, + "launch did not record the required structured session turns\nServiceUnavailableError: HTTP 503\nstructured session baseline cleanup failed", ], ["unstructured provider output", "ServiceUnavailableError: HTTP 503"], ["unknown failure", "launch failed for an unknown reason"], diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index b8d0f908e4b..d40f72143bd 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -29,6 +29,7 @@ import { LAUNCH_TURN_SCRIPT, OPENCLAW_LAUNCH_OPENSHELL_SHIM_SCRIPT, OPENCLAW_LAUNCH_RUNTIME_ENV_SCRIPT, + OPENCLAW_PROVIDER_UNAVAILABLE_MARKER, OPENCLAW_PTY_MONITOR_STARTER_SCRIPT, OPENCLAW_SESSION_EVIDENCE_SCRIPT, runOpenClawLaunchSession, @@ -101,7 +102,14 @@ it("reports a residual PTY monitor socket without removing it (#9384)", async () function runLaunchSessionFixture( mode: FixtureMode, - terminalCopy: "absent" | "ansi" | "policy" | "provider" | "reordered" | "security", + terminalCopy: + | "absent" + | "ansi" + | "long-policy" + | "policy" + | "provider" + | "reordered" + | "security", ) { const fixtureRoot = mkdtempSync(join(tmpdir(), "nemoclaw-launch-turn-")); const canonicalRestoredMarker = join(fixtureRoot, "canonical-restored"); @@ -331,6 +339,13 @@ if (process.argv[2] !== "tui") { process.stdout.write("\u001b[2KOpenAIException - . Received Model Group=nvidia/model\r\n"); process.stdout.write("\u001b[2KAvailable Model Group Fallbacks=None\r"); } + if (terminalCopy === "long-policy") { + process.stdout.write("denied by network policy\r\n"); + process.stdout.write("x".repeat(5_000) + "\r\n"); + process.stdout.write("run error: litellm.ServiceUnavailableError: ServiceUnavailableError:\r\n"); + process.stdout.write("OpenAIException - . Received Model Group=nvidia/model\r\n"); + process.stdout.write("Available Model Group Fallbacks=None\r"); + } if (terminalCopy === "policy") { process.stdout.write("\u001b[2Krun error: litellm.ServiceUnavailableError: ServiceUnavailableError:\r\n"); process.stdout.write("\u001b[2KOpenAIException - . Received Model Group=nvidia/model\r\n"); @@ -1027,12 +1042,8 @@ it.runIf(process.platform === "linux")( "retries the provider marker emitted by the real launch producer (#10978)", async () => { const produced = runLaunchSessionFixture("provider-empty-message", "provider").result; - const firstResult = { - exitCode: produced.status ?? 1, - signal: produced.signal, - stderr: produced.stderr, - stdout: produced.stdout, - }; + const markerOffset = produced.stderr.lastIndexOf(`\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:`); + const producedFailure = produced.stderr.slice(0, markerOffset); const calls: Array<{ artifactName?: string; runId?: string }> = []; const host = { command: async ( @@ -1045,7 +1056,12 @@ it.runIf(process.platform === "linux")( runId: options?.env?.NEMOCLAW_LAUNCH_RUN_ID, }); return calls.length === 1 - ? firstResult + ? { + exitCode: produced.status ?? 1, + signal: produced.signal, + stderr: `${producedFailure}\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${options?.env?.NEMOCLAW_LAUNCH_RUN_ID}\n`, + stdout: produced.stdout, + } : { exitCode: 0, signal: null, stderr: "", stdout: "" }; }, openshellCommandPath: "/usr/bin/openshell", @@ -1094,7 +1110,7 @@ it.runIf(process.platform === "linux")( openshellCommandPath: "/usr/bin/openshell", }; - expect(produced.stderr).toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); + expect(produced.stderr).not.toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); expect(produced.stderr).toContain("structured session baseline cleanup failed"); await expect( runOpenClawLaunchSession({ @@ -1111,6 +1127,38 @@ it.runIf(process.platform === "linux")( testTimeout(30_000), ); +it.runIf(process.platform === "linux")( + "does not retry when a policy denial precedes the bounded provider diagnostic (#10978)", + async () => { + const produced = runLaunchSessionFixture("provider-empty-message", "long-policy").result; + let calls = 0; + const host = { + command: async () => { + calls += 1; + return { + exitCode: produced.status ?? 1, + signal: produced.signal, + stderr: produced.stderr, + stdout: produced.stdout, + }; + }, + openshellCommandPath: "/usr/bin/openshell", + }; + + expect(produced.stderr).not.toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); + await runOpenClawLaunchSession({ + artifactName: "producer-long-policy-handoff", + cliCommand: "node", + env: {}, + host: host as never, + redactionValues: [], + sandboxName: "alpha", + }).catch(() => undefined); + expect(calls).toBe(1); + }, + testTimeout(30_000), +); + it.runIf(process.platform === "linux").each([ { denial: "egress blocked by sandbox guard", terminalCopy: "security" }, { denial: "denied by network policy", terminalCopy: "policy" }, From 7eb235e2aacb20e117ce0cbb08192da6dc47e7a9 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 14:10:38 -0700 Subject: [PATCH 25/43] test(e2e): close provider retry evidence gaps Execute the real launch producer for both provider retry attempts. Preserve the workflow artifact-upload timeout margin. Signed-off-by: Prekshi Vyas --- .github/workflows/portable-profile-e2e.yaml | 2 +- test/e2e/support/launch-agent-turn.test.ts | 73 ++++++++++++------- ...-profile-rootless-runtime-workflow.test.ts | 5 +- ...security-posture-workflow-boundary.test.ts | 4 +- tools/e2e/target-catalogue.mts | 4 +- 5 files changed, 54 insertions(+), 34 deletions(-) diff --git a/.github/workflows/portable-profile-e2e.yaml b/.github/workflows/portable-profile-e2e.yaml index 5a351b16738..323d628a8ee 100644 --- a/.github/workflows/portable-profile-e2e.yaml +++ b/.github/workflows/portable-profile-e2e.yaml @@ -155,7 +155,7 @@ jobs: portable-launch: if: ${{ github.ref == 'refs/heads/main' }} runs-on: ubuntu-26.04 - timeout-minutes: 90 + timeout-minutes: 95 env: E2E_JOB: "1" E2E_TARGET_ID: portable-launch diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index d40f72143bd..991e9fea00a 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -29,7 +29,6 @@ import { LAUNCH_TURN_SCRIPT, OPENCLAW_LAUNCH_OPENSHELL_SHIM_SCRIPT, OPENCLAW_LAUNCH_RUNTIME_ENV_SCRIPT, - OPENCLAW_PROVIDER_UNAVAILABLE_MARKER, OPENCLAW_PTY_MONITOR_STARTER_SCRIPT, OPENCLAW_SESSION_EVIDENCE_SCRIPT, runOpenClawLaunchSession, @@ -60,6 +59,12 @@ type FixtureMode = | "restored-canonical-timeout" | "valid"; +interface LaunchFixtureInvocation { + args: string[]; + command: string; + env?: NodeJS.ProcessEnv; +} + it("reports a residual PTY monitor socket without removing it (#9384)", async () => { const fixtureRoot = mkdtempSync(join(tmpdir(), "nemoclaw-monitor-cleanup-")); const runId = randomUUID().replaceAll("-", ""); @@ -110,6 +115,7 @@ function runLaunchSessionFixture( | "provider" | "reordered" | "security", + invocation?: LaunchFixtureInvocation, ) { const fixtureRoot = mkdtempSync(join(tmpdir(), "nemoclaw-launch-turn-")); const canonicalRestoredMarker = join(fixtureRoot, "canonical-restored"); @@ -125,7 +131,8 @@ function runLaunchSessionFixture( const pendingQualificationMarker = join(fixtureRoot, "pending-qualification-observed"); const ptyPathUnreadableMarker = join(fixtureRoot, "pty-path-unreadable"); const ptySocketReceiptPath = join(fixtureRoot, "pty-socket-receipt.json"); - const runId = randomUUID().replaceAll("-", ""); + const invocationEnv = invocation?.env ?? {}; + const runId = invocationEnv.NEMOCLAW_LAUNCH_RUN_ID ?? randomUUID().replaceAll("-", ""); const baselinePath = `/tmp/nemoclaw-launch-session-${runId}.json`; const ptyMonitorRoot = `/tmp/nemoclaw-launch-turn-${runId}`; mkdirSync(sessionRoot); @@ -470,11 +477,14 @@ exec "$@" ? unavailablePtyMonitorStarterScript : OPENCLAW_PTY_MONITOR_STARTER_SCRIPT; - const result = spawnSync("bash", ["-c", LAUNCH_TURN_SCRIPT], { + const launchCommand = invocation?.command ?? "bash"; + const launchArgs = invocation?.args ?? ["-c", LAUNCH_TURN_SCRIPT]; + const result = spawnSync(launchCommand, launchArgs, { encoding: "utf8", killSignal: "SIGKILL", env: { ...process.env, + ...invocationEnv, HOME: fixtureRoot, NEMOCLAW_FIXTURE_BIN_ROOT: fixtureRoot, NEMOCLAW_FIXTURE_CANONICAL_RESTORED_MARKER: canonicalRestoredMarker, @@ -491,16 +501,16 @@ exec "$@" NEMOCLAW_FIXTURE_RUN_ID: runId, NEMOCLAW_FIXTURE_TUI_PIDS: tuiPidsPath, NEMOCLAW_FIXTURE_TTY_MARKER: ttyMarker, - NEMOCLAW_LAUNCH_COMMAND: fakeLaunch, - NEMOCLAW_LAUNCH_ENTRYPOINT: "", - NEMOCLAW_LAUNCH_EXIT_COMMAND: "/exit", - NEMOCLAW_LAUNCH_FIRST_INPUT: "first input", + NEMOCLAW_LAUNCH_COMMAND: invocationEnv.NEMOCLAW_LAUNCH_COMMAND ?? fakeLaunch, + NEMOCLAW_LAUNCH_ENTRYPOINT: invocationEnv.NEMOCLAW_LAUNCH_ENTRYPOINT ?? "", + NEMOCLAW_LAUNCH_EXIT_COMMAND: invocationEnv.NEMOCLAW_LAUNCH_EXIT_COMMAND ?? "/exit", + NEMOCLAW_LAUNCH_FIRST_INPUT: invocationEnv.NEMOCLAW_LAUNCH_FIRST_INPUT ?? "first input", NEMOCLAW_LAUNCH_HOST_TMP_ROOT: fixtureRoot, NEMOCLAW_LAUNCH_OPENSHELL_SHIM_SCRIPT: OPENCLAW_LAUNCH_OPENSHELL_SHIM_SCRIPT, NEMOCLAW_LAUNCH_PTY_MONITOR_STARTER_SCRIPT: ptyMonitorStarterScript, NEMOCLAW_LAUNCH_RUN_ID: runId, NEMOCLAW_LAUNCH_RUNTIME_ENV_SCRIPT: OPENCLAW_LAUNCH_RUNTIME_ENV_SCRIPT, - NEMOCLAW_LAUNCH_SANDBOX: "sandbox", + NEMOCLAW_LAUNCH_SANDBOX: invocationEnv.NEMOCLAW_LAUNCH_SANDBOX ?? "sandbox", NEMOCLAW_LAUNCH_SESSION_BUDGET_SECONDS: mode === "restored-canonical-timeout" ? "10" @@ -508,13 +518,14 @@ exec "$@" ? "5" : mode.endsWith("-timeout") ? "2" - : "230", - NEMOCLAW_LAUNCH_SECOND_INPUT: "second input", + : (invocationEnv.NEMOCLAW_LAUNCH_SESSION_BUDGET_SECONDS ?? "230"), + NEMOCLAW_LAUNCH_SECOND_INPUT: + invocationEnv.NEMOCLAW_LAUNCH_SECOND_INPUT ?? "second input", NEMOCLAW_LAUNCH_SESSION_EVIDENCE_SCRIPT: OPENCLAW_SESSION_EVIDENCE_SCRIPT, NEMOCLAW_LAUNCH_SESSION_ROOT: sessionRoot, NEMOCLAW_OPENSHELL_COMMAND: fakeOpenshell, PATH: `${fixtureRoot}:${process.env.PATH ?? ""}`, - TERM: "xterm-256color", + TERM: invocationEnv.TERM ?? "xterm-256color", }, timeout: 15_000, }); @@ -1032,37 +1043,41 @@ it.runIf(process.platform === "linux")( expect(ttyObserved).toBe(true); expect(baselineRemoved).toBe(true); - expect(result.signal).toBeNull(); expect(result.status).toBe(1); expect(result.stderr).toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); }, ); it.runIf(process.platform === "linux")( - "retries the provider marker emitted by the real launch producer (#10978)", + "executes the real launch producer across a provider retry (#10978)", async () => { - const produced = runLaunchSessionFixture("provider-empty-message", "provider").result; - const markerOffset = produced.stderr.lastIndexOf(`\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:`); - const producedFailure = produced.stderr.slice(0, markerOffset); - const calls: Array<{ artifactName?: string; runId?: string }> = []; + const calls: Array<{ + artifactName?: string; + firstInput?: string; + runId?: string; + }> = []; const host = { command: async ( - _command: string, - _args: string[], + command: string, + args: string[], options?: { artifactName?: string; env?: NodeJS.ProcessEnv }, ) => { calls.push({ artifactName: options?.artifactName, + firstInput: options?.env?.NEMOCLAW_LAUNCH_FIRST_INPUT, runId: options?.env?.NEMOCLAW_LAUNCH_RUN_ID, }); - return calls.length === 1 - ? { - exitCode: produced.status ?? 1, - signal: produced.signal, - stderr: `${producedFailure}\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${options?.env?.NEMOCLAW_LAUNCH_RUN_ID}\n`, - stdout: produced.stdout, - } - : { exitCode: 0, signal: null, stderr: "", stdout: "" }; + const fixture = runLaunchSessionFixture( + calls.length === 1 ? "provider-empty-message" : "valid", + calls.length === 1 ? "provider" : "absent", + { args, command, env: options?.env }, + ).result; + return { + exitCode: fixture.status ?? 1, + signal: fixture.signal, + stderr: fixture.stderr, + stdout: fixture.stdout, + }; }, openshellCommandPath: "/usr/bin/openshell", }; @@ -1070,8 +1085,9 @@ it.runIf(process.platform === "linux")( try { const launch = runOpenClawLaunchSession({ artifactName: "producer-handoff", - cliCommand: "node", + cliCommand: "openclaw", env: {}, + exitCommand: "/exit", host: host as never, redactionValues: [], sandboxName: "alpha", @@ -1083,6 +1099,7 @@ it.runIf(process.platform === "linux")( "producer-handoff-provider-retry-02", ]); expect(new Set(calls.map((call) => call.runId)).size).toBe(2); + expect(new Set(calls.map((call) => call.firstInput)).size).toBe(2); } finally { vi.useRealTimers(); } diff --git a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts index e27264e92bc..ce254008374 100644 --- a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts +++ b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts @@ -256,6 +256,9 @@ ${serviceIdentityCheck}`, (step) => step.name === "Upload portable profile E2E artifacts", ); const liveSource = readRepoText("test/e2e/live/portable-profile-rootless-linux.test.ts"); + const fullE2eTimeoutMinutes = Number( + readRepoText("test/e2e/live/full-e2e.test.ts").match(/testTimeout\((\d+) \* 60_000\)/u)?.[1], + ); const revisionExpression = "${{ github.event.pull_request.head.sha || github.sha }}"; expect(workflow.on.pull_request.types).toEqual(["opened", "synchronize", "reopened"]); @@ -274,7 +277,7 @@ ${serviceIdentityCheck}`, expect(upload?.if).toBe("always()"); expect(upload?.with?.name).toContain(revisionExpression); expect(workflow.jobs["portable-launch"]?.if).toBe("${{ github.ref == 'refs/heads/main' }}"); - expect(workflow.jobs["portable-launch"]?.["timeout-minutes"]).toBe(90); + expect(workflow.jobs["portable-launch"]?.["timeout-minutes"]).toBe(fullE2eTimeoutMinutes + 25); expect(liveSource).toContain('run("git", ["rev-parse", "HEAD"])'); expect(liveSource).toContain('"network", "rm", disposableNetworkId'); expect(liveSource).not.toContain('"network", "rm", "--force"'); diff --git a/test/e2e/support/security-posture-workflow-boundary.test.ts b/test/e2e/support/security-posture-workflow-boundary.test.ts index 1c6228f7314..5c2dc62b132 100644 --- a/test/e2e/support/security-posture-workflow-boundary.test.ts +++ b/test/e2e/support/security-posture-workflow-boundary.test.ts @@ -17,7 +17,7 @@ describe("security-posture catalogue boundary", () => { const openclaw = catalogueTarget("security-posture-openclaw"); const hermes = catalogueTarget("security-posture-hermes"); - expect(catalogueTarget("full-e2e").timeoutMinutes).toBe(90); + expect(catalogueTarget("full-e2e").timeoutMinutes).toBe(95); const target = ({ OpenClaw: openclaw, Hermes: hermes } as const)[scenario]!; expect(target).toMatchObject({ @@ -35,7 +35,7 @@ describe("security-posture catalogue boundary", () => { expect(openclaw).toMatchObject({ shard: "openclaw", testFile: "test/e2e/live/full-e2e.test.ts", - timeoutMinutes: 90, + timeoutMinutes: 95, }); expect(hermes).toMatchObject({ shard: "hermes", diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 7aef1717225..c9cbea2c4ad 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -736,7 +736,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ agentRuntime: "openclaw", environmentOrInferenceEndpoint: "Ubuntu; NVIDIA hosted inference", profile: "nvidia-inference", - timeoutMinutes: 90, + timeoutMinutes: 95, installMode: "authenticated", restoreCli: true, exposeCliBin: true, @@ -1308,7 +1308,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ profile: "nvidia-inference", prAdvisorSelectable: true, testFile: "test/e2e/live/full-e2e.test.ts", - timeoutMinutes: 90, + timeoutMinutes: 95, installMode: "credential-free", installNonInteractive: true, restoreCli: true, From f5817d17f84fc0f85ac7c9e1eacbb14b7d8e5053 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 14:30:30 -0700 Subject: [PATCH 26/43] fix(e2e): delimit provider retry marker Keep the final run-bound marker on its own line after PTY diagnostics. Signed-off-by: Prekshi Vyas --- test/e2e/live/launch-agent-turn.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index b58917d6fca..73f5849ad8c 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -1114,7 +1114,7 @@ cleanup() { fi if [[ "$original_status" != 0 ]]; then case "$provider_unavailable_candidate:$cleanup_status" in - 1:0) echo "${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:$NEMOCLAW_LAUNCH_RUN_ID" >&2 ;; + 1:0) printf '\n%s\n' "${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:$NEMOCLAW_LAUNCH_RUN_ID" >&2 ;; esac exit "$original_status" fi From 86a13cced8f5ffd056e41759d7967d4ae776abf4 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 15:38:49 -0700 Subject: [PATCH 27/43] fix(e2e): trust structured provider failures --- test/e2e/live/launch-agent-turn.ts | 77 +++++++++------- .../launch-readiness-lease-acceptance.test.ts | 7 +- ...launch-agent-turn-session-evidence.test.ts | 61 ++++++++++--- test/e2e/support/launch-agent-turn.test.ts | 88 ++++++++++--------- 4 files changed, 148 insertions(+), 85 deletions(-) diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index 73f5849ad8c..dfd68d332a5 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -11,6 +11,14 @@ import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; const OPENCLAW_LAUNCH_PROVIDER_ATTEMPTS = 2; const OPENCLAW_LAUNCH_PROVIDER_RETRY_DELAY_MS = 1_000; +const OPENCLAW_LAUNCH_SESSION_TIMEOUT_MS = 280_000; +const OPENCLAW_LAUNCH_READINESS_PROBE_TIMEOUT_MS = 360_000; +export const OPENCLAW_LAUNCH_READINESS_LEASE_MAXIMUM_MS = + OPENCLAW_LAUNCH_READINESS_PROBE_TIMEOUT_MS + + 2 * + (OPENCLAW_LAUNCH_PROVIDER_ATTEMPTS * OPENCLAW_LAUNCH_SESSION_TIMEOUT_MS + + (OPENCLAW_LAUNCH_PROVIDER_ATTEMPTS - 1) * OPENCLAW_LAUNCH_PROVIDER_RETRY_DELAY_MS); +export const OPENCLAW_LAUNCH_READINESS_LEASE_ACCEPTANCE_TIMEOUT_MS = 30 * 60_000; export const OPENCLAW_PROVIDER_UNAVAILABLE_MARKER = "nemoclaw.e2e.launch-failure=provider-unavailable"; const OPENCLAW_PROVIDER_UNAVAILABLE_FAILURE_PREFIX = @@ -485,10 +493,10 @@ const replacement = [ runRealOpenShell(replacement); `; -// OpenClaw owns the JSONL session store and does not expose a structured -// result from `nemoclaw launch`. This verifier records an in-sandbox baseline, -// then qualifies only complete user and assistant records appended after that -// baseline. Session content never moves to the host. +// OpenClaw owns the JSONL session store and does not expose a structured result +// from `nemoclaw launch`. This verifier records an in-sandbox baseline, then +// qualifies complete turns and exact structured provider failures appended +// after that baseline. Session content never moves to the host. export const OPENCLAW_SESSION_EVIDENCE_SCRIPT = String.raw` const crypto = require("node:crypto"); const fs = require("node:fs"); @@ -963,6 +971,23 @@ function hasStructuredContent(message) { return Array.isArray(message.content) && message.content.length > 0; } +const providerUnavailableCodes = new Set(["502", "503", "504", "529"]); + +function isStructuredProviderUnavailable(message) { + const identity = [ + message.role, + hasStructuredContent(message), + message.stopReason, + message.api, + message.provider, + ].join("\n"); + return ( + identity === "assistant\nfalse\nerror\nopenai-completions\ninference" && + typeof message.errorCode === "string" && + providerUnavailableCodes.has(message.errorCode.trim()) + ); +} + function appendedMessages(fileName, baseline) { const { offset, complete, raw } = readCompleteSession(fileName); const prior = baseline[fileName]; @@ -987,7 +1012,11 @@ function appendedMessages(fileName, baseline) { if (!record || record.type !== "message" || !record.message) continue; const role = record.message.role; if (role !== "user" && role !== "assistant") continue; - messages.push({ role, hasStructuredContent: hasStructuredContent(record.message) }); + messages.push({ + role, + hasStructuredContent: hasStructuredContent(record.message), + providerUnavailable: isStructuredProviderUnavailable(record.message), + }); } return messages; } @@ -1022,7 +1051,13 @@ function qualifyTurns() { if (message.role !== expectedRoles[index]) { finish(2, "message_order_invalid", { sessionId }); } - if (!message.hasStructuredContent) finish(2, "message_content_empty", { sessionId }); + if (!message.hasStructuredContent) { + const emptyStatus = message.providerUnavailable ? 3 : 2; + const emptyReason = message.providerUnavailable + ? "provider_unavailable" + : "message_content_empty"; + finish(emptyStatus, emptyReason, { sessionId }); + } } if (messages.length < expectedRoles.length) finish(1); finish(0); @@ -1133,24 +1168,6 @@ terminal_diagnostic() { fi } -transient_provider_availability_failure() { - local diagnostic - grep -Eiq \ - 'authentication failed|authorization failed|unauthorized|forbidden|HTTP( status)?[:= ]+40[13]|invalid.*(api[_ -]?key|credential|JSON|response)|\b(egress|request|connection|certificate|TLS|network|route|routing|policy|proxy|transport)[^\r\n]*(blocked|denied|failed|invalid)\b|\b(blocked|denied|failed|invalid)[^\r\n]*(egress|request|connection|certificate|TLS|network|route|routing|policy|proxy|transport)\b|malformed' \ - "$capture" && return 1 - diagnostic="$(tail -c 4096 "$capture" 2>/dev/null || true)" - printf '%s\n' "$diagnostic" | grep -Fq \ - 'run error: litellm.ServiceUnavailableError: ServiceUnavailableError:' || return 1 - printf '%s\n' "$diagnostic" | grep -Fq \ - 'OpenAIException - . Received Model Group=' || return 1 - printf '%s\n' "$diagnostic" | grep -Fq \ - 'Available Model Group Fallbacks=' || return 1 -} - -provider_empty_message_evidence() { - grep -Eq '^\{"reason":"message_content_empty","sessionId":"[^"]+"\}$' "$evidence_error" -} - fail_launch_session() { echo "$1" >&2 if [[ -s "$evidence_error" ]]; then @@ -1199,11 +1216,9 @@ wait_for_turn_count() { fi if [[ "$evidence_status" != 1 ]]; then case "$evidence_status" in - 2) - provider_empty_message_evidence && \ - transient_provider_availability_failure && \ - provider_unavailable_candidate=1 && \ - fail_launch_session "launch did not record the required structured session turns" + 3) + provider_unavailable_candidate=1 + fail_launch_session "launch did not record the required structured session turns" ;; esac fail_launch_session \ @@ -1426,7 +1441,7 @@ export async function runOpenClawLaunchSession( TERM: "xterm-256color", }, redactionValues: options.redactionValues, - timeoutMs: 280_000, + timeoutMs: OPENCLAW_LAUNCH_SESSION_TIMEOUT_MS, }); if (result.exitCode === 0) return result; finalFailure = result; @@ -1454,7 +1469,7 @@ export async function runOpenClawLaunchReadinessLeaseTurns( artifactName: `${options.artifactName}-probe`, env: options.env, redactionValues: options.redactionValues, - timeoutMs: 360_000, + timeoutMs: OPENCLAW_LAUNCH_READINESS_PROBE_TIMEOUT_MS, }); if (probe.exitCode !== 0) { throw new Error(`launch readiness producer failed: ${resultText(probe)}`); diff --git a/test/e2e/live/launch-readiness-lease-acceptance.test.ts b/test/e2e/live/launch-readiness-lease-acceptance.test.ts index 5e72c8b1098..cebf2aa32ef 100644 --- a/test/e2e/live/launch-readiness-lease-acceptance.test.ts +++ b/test/e2e/live/launch-readiness-lease-acceptance.test.ts @@ -4,14 +4,17 @@ import { expect, test } from "../fixtures/e2e-test.ts"; import { CLI_ENTRYPOINT } from "../fixtures/paths.ts"; import { readRegistrySandboxEntry } from "../fixtures/phases/index.ts"; -import { runOpenClawLaunchReadinessLeaseTurns } from "./launch-agent-turn.ts"; +import { + OPENCLAW_LAUNCH_READINESS_LEASE_ACCEPTANCE_TIMEOUT_MS, + runOpenClawLaunchReadinessLeaseTurns, +} from "./launch-agent-turn.ts"; const SANDBOX_NAME = process.env.NEMOCLAW_ACCEPTANCE_SANDBOX?.trim() ?? ""; test.runIf(process.platform === "linux" && SANDBOX_NAME.length > 0)( "launch readiness locked-image acceptance", { - timeout: 15 * 60_000, + timeout: OPENCLAW_LAUNCH_READINESS_LEASE_ACCEPTANCE_TIMEOUT_MS, meta: { e2ePhases: [ "verify the existing locked-image sandbox", diff --git a/test/e2e/support/launch-agent-turn-session-evidence.test.ts b/test/e2e/support/launch-agent-turn-session-evidence.test.ts index 42aa6a5a9e4..6c96a79a4df 100644 --- a/test/e2e/support/launch-agent-turn-session-evidence.test.ts +++ b/test/e2e/support/launch-agent-turn-session-evidence.test.ts @@ -37,6 +37,23 @@ function emptyMessage(role: "assistant" | "user"): string { return JSON.stringify({ message: { content: [], role }, type: "message" }); } +function providerUnavailableMessage(overrides: Record = {}): string { + return JSON.stringify({ + message: { + api: "openai-completions", + content: [], + errorCode: "503", + errorMessage: "litellm.ServiceUnavailableError: upstream unavailable", + model: "nvidia/model", + provider: "inference", + role: "assistant", + stopReason: "error", + ...overrides, + }, + type: "message", + }); +} + function writeSessionRecords( root: string, sessions: SessionRecords, @@ -241,19 +258,41 @@ it("does not qualify structured turns recorded before the baseline (#9160)", () expect(qualification.status).toBe(1); }); -it.each([ - { "session-a": [message("assistant"), message("user")] }, - { "session-a": [message("user"), message("user"), message("assistant")] }, - { "session-a": [message("user"), message("assistant"), message("assistant")] }, - { "session-a": [message("user"), "not-json", message("assistant")] }, - { "session-a": [emptyMessage("user"), message("assistant")] }, - { "session-a": [message("user"), message("assistant")], "session-b": [message("user")] }, -] as SessionRecords[])( - "rejects malformed, empty, duplicated, extra, out-of-order, or cross-session records [case %#] (#9160)", - (after) => { +it.each<{ after: SessionRecords; status: number }>([ + { after: { "session-a": [message("assistant"), message("user")] }, status: 2 }, + { + after: { "session-a": [message("user"), message("user"), message("assistant")] }, + status: 2, + }, + { + after: { "session-a": [message("user"), message("assistant"), message("assistant")] }, + status: 2, + }, + { after: { "session-a": [message("user"), "not-json", message("assistant")] }, status: 2 }, + { after: { "session-a": [emptyMessage("user"), message("assistant")] }, status: 2 }, + { + after: { + "session-a": [message("user"), message("assistant")], + "session-b": [message("user")], + }, + status: 2, + }, + { + after: { "session-a": [message("user"), providerUnavailableMessage()] }, + status: 3, + }, + { + after: { + "session-a": [message("user"), providerUnavailableMessage({ errorCode: "400" })], + }, + status: 2, + }, +])( + "rejects invalid evidence or classifies a structured provider 5xx [case %#] (#9160, #10978)", + ({ after, status }) => { const { baseline, qualification } = runEvidenceFixture({ after, expectedTurns: 1 }); expect(baseline.status).toBe(0); - expect(qualification.status).toBe(2); + expect(qualification.status).toBe(status); }, ); diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index 991e9fea00a..7c392b31ec0 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -27,6 +27,8 @@ import { import { testTimeout } from "../../helpers/timeouts"; import { LAUNCH_TURN_SCRIPT, + OPENCLAW_LAUNCH_READINESS_LEASE_ACCEPTANCE_TIMEOUT_MS, + OPENCLAW_LAUNCH_READINESS_LEASE_MAXIMUM_MS, OPENCLAW_LAUNCH_OPENSHELL_SHIM_SCRIPT, OPENCLAW_LAUNCH_RUNTIME_ENV_SCRIPT, OPENCLAW_PTY_MONITOR_STARTER_SCRIPT, @@ -55,6 +57,9 @@ type FixtureMode = | "pty-termios-unavailable" | "provider-cleanup-failure" | "provider-empty-message" + | "provider-terminal-spoof" + | "provider-wrong-api" + | "provider-wrong-route" | "recording-timeout" | "restored-canonical-timeout" | "valid"; @@ -107,14 +112,7 @@ it("reports a residual PTY monitor socket without removing it (#9384)", async () function runLaunchSessionFixture( mode: FixtureMode, - terminalCopy: - | "absent" - | "ansi" - | "long-policy" - | "policy" - | "provider" - | "reordered" - | "security", + terminalCopy: "absent" | "ansi" | "provider" | "reordered", invocation?: LaunchFixtureInvocation, ) { const fixtureRoot = mkdtempSync(join(tmpdir(), "nemoclaw-launch-turn-")); @@ -307,9 +305,22 @@ if (process.argv[2] !== "tui") { sessionFile, JSON.stringify({ message: { content: [{ text: content, type: "text" }], role }, type: "message" }) + "\n", ); - const appendEmpty = (role) => fs.appendFileSync( + const appendProviderError = (overrides = {}) => fs.appendFileSync( sessionFile, - JSON.stringify({ message: { content: [], role }, type: "message" }) + "\n", + JSON.stringify({ + message: { + api: "openai-completions", + content: [], + errorCode: "503", + errorMessage: "litellm.ServiceUnavailableError: ServiceUnavailableError: OpenAIException - . Received Model Group=nvidia/model; Available Model Group Fallbacks=None", + model: "nvidia/model", + provider: "inference", + role: "assistant", + stopReason: "error", + ...overrides, + }, + type: "message", + }) + "\n", ); if (mode === "restored-canonical-timeout") { process.stdin.setRawMode(true); @@ -346,23 +357,6 @@ if (process.argv[2] !== "tui") { process.stdout.write("\u001b[2KOpenAIException - . Received Model Group=nvidia/model\r\n"); process.stdout.write("\u001b[2KAvailable Model Group Fallbacks=None\r"); } - if (terminalCopy === "long-policy") { - process.stdout.write("denied by network policy\r\n"); - process.stdout.write("x".repeat(5_000) + "\r\n"); - process.stdout.write("run error: litellm.ServiceUnavailableError: ServiceUnavailableError:\r\n"); - process.stdout.write("OpenAIException - . Received Model Group=nvidia/model\r\n"); - process.stdout.write("Available Model Group Fallbacks=None\r"); - } - if (terminalCopy === "policy") { - process.stdout.write("\u001b[2Krun error: litellm.ServiceUnavailableError: ServiceUnavailableError:\r\n"); - process.stdout.write("\u001b[2KOpenAIException - . Received Model Group=nvidia/model\r\n"); - process.stdout.write("\u001b[2KAvailable Model Group Fallbacks=None; denied by network policy\r"); - } - if (terminalCopy === "security") { - process.stdout.write("\u001b[2Krun error: litellm.ServiceUnavailableError: ServiceUnavailableError:\r\n"); - process.stdout.write("\u001b[2KOpenAIException - . Received Model Group=nvidia/model\r\n"); - process.stdout.write("\u001b[2KAvailable Model Group Fallbacks=None; egress blocked by sandbox guard\r"); - } if (terminalCopy === "reordered") process.stdout.write("idle | gateway connected\n"); if (mode === "delayed-recording") { @@ -378,7 +372,16 @@ if (process.argv[2] !== "tui") { append("user", firstInput); } else if (mode === "provider-empty-message" || mode === "provider-cleanup-failure") { append("user", firstInput); - appendEmpty("assistant"); + appendProviderError(); + } else if (mode === "provider-terminal-spoof") { + append("user", firstInput); + appendProviderError({ errorCode: "400" }); + } else if (mode === "provider-wrong-api") { + append("user", firstInput); + appendProviderError({ api: "openai-responses" }); + } else if (mode === "provider-wrong-route") { + append("user", firstInput); + appendProviderError({ provider: "attacker-controlled" }); } else { append("user", firstInput); append("assistant", "first response"); @@ -519,8 +522,7 @@ exec "$@" : mode.endsWith("-timeout") ? "2" : (invocationEnv.NEMOCLAW_LAUNCH_SESSION_BUDGET_SECONDS ?? "230"), - NEMOCLAW_LAUNCH_SECOND_INPUT: - invocationEnv.NEMOCLAW_LAUNCH_SECOND_INPUT ?? "second input", + NEMOCLAW_LAUNCH_SECOND_INPUT: invocationEnv.NEMOCLAW_LAUNCH_SECOND_INPUT ?? "second input", NEMOCLAW_LAUNCH_SESSION_EVIDENCE_SCRIPT: OPENCLAW_SESSION_EVIDENCE_SCRIPT, NEMOCLAW_LAUNCH_SESSION_ROOT: sessionRoot, NEMOCLAW_OPENSHELL_COMMAND: fakeOpenshell, @@ -1145,9 +1147,9 @@ it.runIf(process.platform === "linux")( ); it.runIf(process.platform === "linux")( - "does not retry when a policy denial precedes the bounded provider diagnostic (#10978)", + "does not retry when terminal output mimics provider unavailability (#10978)", async () => { - const produced = runLaunchSessionFixture("provider-empty-message", "long-policy").result; + const produced = runLaunchSessionFixture("provider-terminal-spoof", "provider").result; let calls = 0; const host = { command: async () => { @@ -1164,7 +1166,7 @@ it.runIf(process.platform === "linux")( expect(produced.stderr).not.toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); await runOpenClawLaunchSession({ - artifactName: "producer-long-policy-handoff", + artifactName: "producer-terminal-spoof-handoff", cliCommand: "node", env: {}, host: host as never, @@ -1177,12 +1179,12 @@ it.runIf(process.platform === "linux")( ); it.runIf(process.platform === "linux").each([ - { denial: "egress blocked by sandbox guard", terminalCopy: "security" }, - { denial: "denied by network policy", terminalCopy: "policy" }, + { mismatch: "API", mode: "provider-wrong-api" }, + { mismatch: "route", mode: "provider-wrong-route" }, ] as const)( - "does not retry real provider output that reports $denial (#10978)", - async ({ denial, terminalCopy }) => { - const produced = runLaunchSessionFixture("provider-empty-message", terminalCopy).result; + "does not retry a structured provider error with the wrong $mismatch identity (#10978)", + async ({ mode }) => { + const produced = runLaunchSessionFixture(mode, "provider").result; const firstResult = { exitCode: produced.status ?? 1, signal: produced.signal, @@ -1198,11 +1200,11 @@ it.runIf(process.platform === "linux").each([ openshellCommandPath: "/usr/bin/openshell", }; - expect(firstResult.stderr).toContain(denial); + expect(firstResult.stderr).toContain("ServiceUnavailableError"); expect(firstResult.stderr).not.toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); await expect( runOpenClawLaunchSession({ - artifactName: "producer-denial-handoff", + artifactName: "producer-identity-mismatch-handoff", cliCommand: "node", env: {}, host: host as never, @@ -1419,7 +1421,11 @@ it.runIf(process.platform === "linux")( }, }); - expect(launchPhaseStartedAtCallCount).toBe(1); + expect( + launchPhaseStartedAtCallCount === 1 && + OPENCLAW_LAUNCH_READINESS_LEASE_ACCEPTANCE_TIMEOUT_MS >= + OPENCLAW_LAUNCH_READINESS_LEASE_MAXIMUM_MS + 5 * 60_000, + ).toBe(true); expect(calls).toHaveLength(3); expect(calls[0]).toMatchObject({ command: "node", From 8892c3494ffc19591268ea26edf14bfd0a963acb Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 16:18:04 -0700 Subject: [PATCH 28/43] fix(ci): preserve macOS E2E timeout headroom --- .github/workflows/platform-vitest-main.yaml | 6 ++---- .../e2e/platform-vitest-main-workflow.test.ts | 20 +++++++++++++++++-- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/.github/workflows/platform-vitest-main.yaml b/.github/workflows/platform-vitest-main.yaml index 7a00d21c510..3c296933e47 100644 --- a/.github/workflows/platform-vitest-main.yaml +++ b/.github/workflows/platform-vitest-main.yaml @@ -89,7 +89,7 @@ jobs: matrix: include: - shard: 1 - timeout_minutes: 60 + timeout_minutes: 95 - shard: 2 timeout_minutes: 30 - shard: 3 @@ -192,9 +192,7 @@ jobs: NEMOCLAW_SANDBOX_NAME: "e2e-macos" NEMOCLAW_RUN_LIVE_E2E: "1" run: >- - npx vitest run --project e2e-live - test/e2e/live/full-e2e.test.ts - --silent=false --reporter=default + npx vitest run --project e2e-live test/e2e/live/full-e2e.test.ts --silent=false --reporter=default - name: Explain skipped macOS live E2E if: ${{ matrix.shard == 1 && (steps.macos_docker.outputs.docker_ok != 'true' || github.ref != 'refs/heads/main') }} diff --git a/test/automation/e2e/platform-vitest-main-workflow.test.ts b/test/automation/e2e/platform-vitest-main-workflow.test.ts index af34e3416ae..785cb1be518 100644 --- a/test/automation/e2e/platform-vitest-main-workflow.test.ts +++ b/test/automation/e2e/platform-vitest-main-workflow.test.ts @@ -12,9 +12,13 @@ import { } from "../../helpers/e2e-workflow-contract"; const WORKFLOW_PATH = ".github/workflows/platform-vitest-main.yaml"; +const FULL_E2E_PATH = "test/e2e/live/full-e2e.test.ts"; const WSL_HELPER_PATH = "tools/wsl/ci-helper.ps1"; const MACOS_REQUIREMENTS_PATH = "ci/platform-vitest-macos-requirements.lock"; const workflow = readYaml(WORKFLOW_PATH); +const fullE2eTimeoutMinutes = Number( + readRepoText(FULL_E2E_PATH).match(/testTimeout\((\d+) \* 60_000\)/u)?.[1], +); const wslHelperSource = readRepoText(WSL_HELPER_PATH); function job(name: string): WorkflowJob { @@ -49,12 +53,24 @@ describe("platform evidence workflow", () => { }, ])("limits credentialed $job E2E to the first main-branch shard", (workflowCase) => { const live = step(workflowCase.job, workflowCase.step); - expect(live.if).toContain("matrix.shard == 1"); - expect(live.if).toContain(workflowCase.dockerOutput); + expect([ + live.if?.includes("matrix.shard == 1"), + live.if?.includes(workflowCase.dockerOutput), + ]).toEqual([true, true]); expect(live.if).toContain("github.ref == 'refs/heads/main'"); expect(live.env).toMatchObject({ GITHUB_TOKEN: "${{ github.token }}", NVIDIA_INFERENCE_API_KEY: "${{ secrets.NVIDIA_INFERENCE_API_KEY }}", }); }); + + it("reserves macOS cleanup and artifact time beyond the full E2E deadline", () => { + const macosShards = job("macos-vitest").strategy?.matrix?.include as Array<{ + shard: number; + timeout_minutes: number; + }>; + const firstShard = macosShards.find(({ shard }) => shard === 1); + + expect(firstShard?.timeout_minutes).toBe(fullE2eTimeoutMinutes + 25); + }); }); From d730fe4a5e25657bcd993c340575884934b75d4f Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 16:52:28 -0700 Subject: [PATCH 29/43] refactor(e2e): centralize full E2E timeout budget --- .../automation/e2e/platform-vitest-main-workflow.test.ts | 7 ++----- test/e2e/live/full-e2e.test.ts | 3 ++- .../portable-profile-rootless-runtime-workflow.test.ts | 8 ++++---- .../support/security-posture-workflow-boundary.test.ts | 5 +++-- test/helpers/vitest-watch-triggers.ts | 8 ++++++++ test/repository/vitest-watch-triggers.test.ts | 6 ++++++ tools/e2e/full-e2e-timeout-contract.mts | 9 +++++++++ tools/e2e/target-catalogue.mts | 5 +++-- 8 files changed, 37 insertions(+), 14 deletions(-) create mode 100644 tools/e2e/full-e2e-timeout-contract.mts diff --git a/test/automation/e2e/platform-vitest-main-workflow.test.ts b/test/automation/e2e/platform-vitest-main-workflow.test.ts index 785cb1be518..36b81aaf11a 100644 --- a/test/automation/e2e/platform-vitest-main-workflow.test.ts +++ b/test/automation/e2e/platform-vitest-main-workflow.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest"; +import { FULL_E2E_TARGET_TIMEOUT_MINUTES } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { readRepoText, readYaml, @@ -12,13 +13,9 @@ import { } from "../../helpers/e2e-workflow-contract"; const WORKFLOW_PATH = ".github/workflows/platform-vitest-main.yaml"; -const FULL_E2E_PATH = "test/e2e/live/full-e2e.test.ts"; const WSL_HELPER_PATH = "tools/wsl/ci-helper.ps1"; const MACOS_REQUIREMENTS_PATH = "ci/platform-vitest-macos-requirements.lock"; const workflow = readYaml(WORKFLOW_PATH); -const fullE2eTimeoutMinutes = Number( - readRepoText(FULL_E2E_PATH).match(/testTimeout\((\d+) \* 60_000\)/u)?.[1], -); const wslHelperSource = readRepoText(WSL_HELPER_PATH); function job(name: string): WorkflowJob { @@ -71,6 +68,6 @@ describe("platform evidence workflow", () => { }>; const firstShard = macosShards.find(({ shard }) => shard === 1); - expect(firstShard?.timeout_minutes).toBe(fullE2eTimeoutMinutes + 25); + expect(firstShard?.timeout_minutes).toBe(FULL_E2E_TARGET_TIMEOUT_MINUTES); }); }); diff --git a/test/e2e/live/full-e2e.test.ts b/test/e2e/live/full-e2e.test.ts index 9bc0f1a544e..d444f5788c9 100644 --- a/test/e2e/live/full-e2e.test.ts +++ b/test/e2e/live/full-e2e.test.ts @@ -50,6 +50,7 @@ import { import { readFullE2eColdWorkloadEvidence } from "./full-e2e-workload-evidence.ts"; import { runOpenClawLaunchReadinessLeaseTurns } from "./launch-agent-turn.ts"; import { bindApprovedPrBaseForBaseImageComparison } from "./pr-base-comparison.ts"; +import { FULL_E2E_TEST_TIMEOUT_MS } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; const SANDBOX_NAME = process.env.NEMOCLAW_SANDBOX_NAME ?? "e2e-full"; const FULL_E2E_TARGET_ID = process.env.E2E_TARGET_ID ?? "full-e2e"; @@ -58,7 +59,7 @@ const USE_PREINSTALLED_LAUNCHABLE = SETUP_MODE === "preinstalled-launchable"; const PORTABLE_PROFILE = process.env.NEMOCLAW_EXPERIMENTAL_PROFILE === "portable"; // Cold install plus two launch turns with one provider retry each can consume // almost 50 minutes before the remaining assertions and cleanup run. -const LIVE_TIMEOUT_MS = testTimeout(70 * 60_000); +const LIVE_TIMEOUT_MS = testTimeout(FULL_E2E_TEST_TIMEOUT_MS); const INSTALL_TIMEOUT_MS = execTimeout(25 * 60_000); const FIRST_TURN_TIMEOUT_MS = 240_000; const MAX_SILENCE_SECS = 60; diff --git a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts index ce254008374..3ef771d8742 100644 --- a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts +++ b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts @@ -6,6 +6,7 @@ import fs from "node:fs"; import { describe, expect, it } from "vitest"; +import { FULL_E2E_TARGET_TIMEOUT_MINUTES } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { readRepoText, readYaml, type Workflow } from "../../helpers/e2e-workflow-contract"; type PortableProfileWorkflow = Workflow & { @@ -256,9 +257,6 @@ ${serviceIdentityCheck}`, (step) => step.name === "Upload portable profile E2E artifacts", ); const liveSource = readRepoText("test/e2e/live/portable-profile-rootless-linux.test.ts"); - const fullE2eTimeoutMinutes = Number( - readRepoText("test/e2e/live/full-e2e.test.ts").match(/testTimeout\((\d+) \* 60_000\)/u)?.[1], - ); const revisionExpression = "${{ github.event.pull_request.head.sha || github.sha }}"; expect(workflow.on.pull_request.types).toEqual(["opened", "synchronize", "reopened"]); @@ -277,7 +275,9 @@ ${serviceIdentityCheck}`, expect(upload?.if).toBe("always()"); expect(upload?.with?.name).toContain(revisionExpression); expect(workflow.jobs["portable-launch"]?.if).toBe("${{ github.ref == 'refs/heads/main' }}"); - expect(workflow.jobs["portable-launch"]?.["timeout-minutes"]).toBe(fullE2eTimeoutMinutes + 25); + expect(workflow.jobs["portable-launch"]?.["timeout-minutes"]).toBe( + FULL_E2E_TARGET_TIMEOUT_MINUTES, + ); expect(liveSource).toContain('run("git", ["rev-parse", "HEAD"])'); expect(liveSource).toContain('"network", "rm", disposableNetworkId'); expect(liveSource).not.toContain('"network", "rm", "--force"'); diff --git a/test/e2e/support/security-posture-workflow-boundary.test.ts b/test/e2e/support/security-posture-workflow-boundary.test.ts index 5c2dc62b132..a3fd720341a 100644 --- a/test/e2e/support/security-posture-workflow-boundary.test.ts +++ b/test/e2e/support/security-posture-workflow-boundary.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest"; +import { FULL_E2E_TARGET_TIMEOUT_MINUTES } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { catalogueTarget, E2E_TARGET_CATALOGUE, @@ -17,7 +18,7 @@ describe("security-posture catalogue boundary", () => { const openclaw = catalogueTarget("security-posture-openclaw"); const hermes = catalogueTarget("security-posture-hermes"); - expect(catalogueTarget("full-e2e").timeoutMinutes).toBe(95); + expect(catalogueTarget("full-e2e").timeoutMinutes).toBe(FULL_E2E_TARGET_TIMEOUT_MINUTES); const target = ({ OpenClaw: openclaw, Hermes: hermes } as const)[scenario]!; expect(target).toMatchObject({ @@ -35,7 +36,7 @@ describe("security-posture catalogue boundary", () => { expect(openclaw).toMatchObject({ shard: "openclaw", testFile: "test/e2e/live/full-e2e.test.ts", - timeoutMinutes: 95, + timeoutMinutes: FULL_E2E_TARGET_TIMEOUT_MINUTES, }); expect(hermes).toMatchObject({ shard: "hermes", diff --git a/test/helpers/vitest-watch-triggers.ts b/test/helpers/vitest-watch-triggers.ts index 149db5dd507..d283e7adcc9 100644 --- a/test/helpers/vitest-watch-triggers.ts +++ b/test/helpers/vitest-watch-triggers.ts @@ -366,6 +366,14 @@ export const vitestWatchTriggerPatterns: VitestWatchTriggerPattern[] = [ pattern: /(?:^|\/)ci\/platform-vitest-macos-requirements\.lock$/, testsToRun: runTests("test/automation/e2e/platform-vitest-main-workflow.test.ts"), }, + { + pattern: /(?:^|\/)tools\/e2e\/full-e2e-timeout-contract\.mts$/, + testsToRun: runTests( + "test/automation/e2e/platform-vitest-main-workflow.test.ts", + "test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts", + "test/e2e/support/security-posture-workflow-boundary.test.ts", + ), + }, { pattern: /(?:^|\/)\.agents\/skills\/(?:nemoclaw-maintainer-cut-release-tag\/SKILL\.md|nemoclaw-maintainer-evening\/SKILL\.md|nemoclaw-maintainer-release-notes\/SKILL\.md|nemoclaw-maintainer-policies\/references\/release-train\.md)$/, diff --git a/test/repository/vitest-watch-triggers.test.ts b/test/repository/vitest-watch-triggers.test.ts index 04263f3a1f6..32078fb8392 100644 --- a/test/repository/vitest-watch-triggers.test.ts +++ b/test/repository/vitest-watch-triggers.test.ts @@ -97,6 +97,7 @@ const OPAQUE_INPUTS = [ ".github/workflows/platform-vitest-main.yaml", "tools/wsl/ci-helper.ps1", "ci/platform-vitest-macos-requirements.lock", + "tools/e2e/full-e2e-timeout-contract.mts", ".agents/skills/nemoclaw-maintainer-cut-release-tag/SKILL.md", ".agents/skills/nemoclaw-maintainer-evening/SKILL.md", ".agents/skills/nemoclaw-maintainer-release-notes/SKILL.md", @@ -363,6 +364,11 @@ describe("Vitest opaque-input watch triggers", () => { expect(triggeredBy("ci/platform-vitest-macos-requirements.lock")).toEqual([ "test/automation/e2e/platform-vitest-main-workflow.test.ts", ]); + expect(triggeredBy("tools/e2e/full-e2e-timeout-contract.mts")).toEqual([ + "test/automation/e2e/platform-vitest-main-workflow.test.ts", + "test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts", + "test/e2e/support/security-posture-workflow-boundary.test.ts", + ]); expect(triggeredBy(".agents/skills/nemoclaw-maintainer-cut-release-tag/SKILL.md")).toEqual([ "test/automation/releases/release-post-tag-follow-through.test.ts", ]); diff --git a/tools/e2e/full-e2e-timeout-contract.mts b/tools/e2e/full-e2e-timeout-contract.mts new file mode 100644 index 00000000000..fb01c1de352 --- /dev/null +++ b/tools/e2e/full-e2e-timeout-contract.mts @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export const FULL_E2E_TEST_TIMEOUT_MINUTES = 70; +export const FULL_E2E_JOB_HEADROOM_MINUTES = 25; + +export const FULL_E2E_TEST_TIMEOUT_MS = FULL_E2E_TEST_TIMEOUT_MINUTES * 60_000; +export const FULL_E2E_TARGET_TIMEOUT_MINUTES = + FULL_E2E_TEST_TIMEOUT_MINUTES + FULL_E2E_JOB_HEADROOM_MINUTES; diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index c9cbea2c4ad..c039b7bcd40 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -18,6 +18,7 @@ import { runtimeCoverageVariant, runtimeExecutionId, } from "./gateway-runtime.mts"; +import { FULL_E2E_TARGET_TIMEOUT_MINUTES } from "./full-e2e-timeout-contract.mts"; import { ONBOARD_RESUME_TARGET_TIMEOUT_MINUTES, ONBOARD_SINGLE_FINAL_HANDOFF_TARGET_TIMEOUT_MINUTES, @@ -736,7 +737,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ agentRuntime: "openclaw", environmentOrInferenceEndpoint: "Ubuntu; NVIDIA hosted inference", profile: "nvidia-inference", - timeoutMinutes: 95, + timeoutMinutes: FULL_E2E_TARGET_TIMEOUT_MINUTES, installMode: "authenticated", restoreCli: true, exposeCliBin: true, @@ -1308,7 +1309,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ profile: "nvidia-inference", prAdvisorSelectable: true, testFile: "test/e2e/live/full-e2e.test.ts", - timeoutMinutes: 95, + timeoutMinutes: FULL_E2E_TARGET_TIMEOUT_MINUTES, installMode: "credential-free", installNonInteractive: true, restoreCli: true, From ced63a2823e4cfcbe6bc6691562aac1acccee522 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 17:07:03 -0700 Subject: [PATCH 30/43] test(e2e): stage timeout contract in advisor fixture --- test/automation/e2e/e2e-recommendations.test.ts | 1 + test/helpers/vitest-watch-triggers.ts | 1 + test/repository/vitest-watch-triggers.test.ts | 1 + 3 files changed, 3 insertions(+) diff --git a/test/automation/e2e/e2e-recommendations.test.ts b/test/automation/e2e/e2e-recommendations.test.ts index 546193187bd..a89beeb7ecc 100644 --- a/test/automation/e2e/e2e-recommendations.test.ts +++ b/test/automation/e2e/e2e-recommendations.test.ts @@ -128,6 +128,7 @@ describe("E2E recommendation normalizer", () => { "tools/advisors/risk-plan.mts", "tools/e2e/credential-free-tests.mts", "tools/e2e/execution-coverage.mts", + "tools/e2e/full-e2e-timeout-contract.mts", "tools/e2e/gateway-runtime.mts", "tools/e2e/onboard-timeout-contract.mts", "tools/e2e/openshell-gateway-upgrade-fixture.mts", diff --git a/test/helpers/vitest-watch-triggers.ts b/test/helpers/vitest-watch-triggers.ts index d283e7adcc9..4e5179e44ce 100644 --- a/test/helpers/vitest-watch-triggers.ts +++ b/test/helpers/vitest-watch-triggers.ts @@ -369,6 +369,7 @@ export const vitestWatchTriggerPatterns: VitestWatchTriggerPattern[] = [ { pattern: /(?:^|\/)tools\/e2e\/full-e2e-timeout-contract\.mts$/, testsToRun: runTests( + "test/automation/e2e/e2e-recommendations.test.ts", "test/automation/e2e/platform-vitest-main-workflow.test.ts", "test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts", "test/e2e/support/security-posture-workflow-boundary.test.ts", diff --git a/test/repository/vitest-watch-triggers.test.ts b/test/repository/vitest-watch-triggers.test.ts index 32078fb8392..80a83b59ff5 100644 --- a/test/repository/vitest-watch-triggers.test.ts +++ b/test/repository/vitest-watch-triggers.test.ts @@ -365,6 +365,7 @@ describe("Vitest opaque-input watch triggers", () => { "test/automation/e2e/platform-vitest-main-workflow.test.ts", ]); expect(triggeredBy("tools/e2e/full-e2e-timeout-contract.mts")).toEqual([ + "test/automation/e2e/e2e-recommendations.test.ts", "test/automation/e2e/platform-vitest-main-workflow.test.ts", "test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts", "test/e2e/support/security-posture-workflow-boundary.test.ts", From ea2d353834ff9f20267ae788136b7f3985718ee1 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 17:24:10 -0700 Subject: [PATCH 31/43] fix(deps): require patched js-yaml --- package-lock.json | 10 +++++----- package.json | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 08a05ee0a36..7017355f62f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,7 +17,7 @@ "@oclif/core": "^4.10.5", "ajv": "^8.17.0", "execa": "^9.6.1", - "js-yaml": "^4.1.1", + "js-yaml": "^4.3.2", "p-retry": "^4.6.2", "qrcode-terminal": "^0.12.0", "smol-toml": "1.7.0", @@ -1513,7 +1513,7 @@ "typebox": "1.1.38" }, "bin": { - "pi-ai": "dist/cli.js" + "pi-ai": "./dist/cli.js" }, "engines": { "node": ">=22.19.0" @@ -7069,9 +7069,9 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz", - "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "funding": [ { "type": "github", diff --git a/package.json b/package.json index 5922559ea83..55bf531582f 100644 --- a/package.json +++ b/package.json @@ -109,7 +109,7 @@ "@oclif/core": "^4.10.5", "ajv": "^8.17.0", "execa": "^9.6.1", - "js-yaml": "^4.1.1", + "js-yaml": "^4.3.2", "p-retry": "^4.6.2", "qrcode-terminal": "^0.12.0", "smol-toml": "1.7.0", From 4c7c717deef068a5fd42b5cabb8276bf337896f3 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 18:23:10 -0700 Subject: [PATCH 32/43] test(e2e): prove exhausted provider handoff --- test/e2e/README.md | 14 +++-- test/e2e/support/launch-agent-turn.test.ts | 66 ++++++++++++++++++++++ 2 files changed, 75 insertions(+), 5 deletions(-) diff --git a/test/e2e/README.md b/test/e2e/README.md index e95c6b3c2af..845d2620e10 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -479,11 +479,15 @@ The host must provide that user a secure, independently writable OS runtime auth The host must provide the util-linux `script` command and GNU `timeout` command. The helper rebuilds the candidate CLI, runs `connect --probe-only`, and then -runs two `launch` sessions during the same fixed lease. -Each real pseudo-terminal session sends two distinct messages and `/exit`, then -requires process exit status `0`. The OpenClaw session store must append two -nonempty `user` and `assistant` record pairs in one session. The helper does not -compare message content. Terminal output is a bounded failure diagnostic only. +runs two logical `launch` sessions during the same fixed lease. Each logical +session may retry once with a fresh run ID and input only when the OpenClaw +session store contains a structured transient provider-unavailability record +and cleanup succeeds. Authentication, authorization, policy, malformed-response, +cleanup, and unknown failures stop the acceptance test without retrying. +Each successful real pseudo-terminal attempt sends two distinct messages and +`/exit`, then requires process exit status `0`. The OpenClaw session store must +append two nonempty `user` and `assistant` record pairs in one session. The helper +does not compare message content. Terminal output is a bounded failure diagnostic only. Deterministic unit tests separately prove selection of the complete preflight and lease paths, stale-producer exclusion, the fixed time-unsafe quarantine, refusal to recover when prior evidence cannot be durably fenced, and the named diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index 7c392b31ec0..e1b420cec85 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -31,6 +31,7 @@ import { OPENCLAW_LAUNCH_READINESS_LEASE_MAXIMUM_MS, OPENCLAW_LAUNCH_OPENSHELL_SHIM_SCRIPT, OPENCLAW_LAUNCH_RUNTIME_ENV_SCRIPT, + OPENCLAW_PROVIDER_UNAVAILABLE_MARKER, OPENCLAW_PTY_MONITOR_STARTER_SCRIPT, OPENCLAW_SESSION_EVIDENCE_SCRIPT, runOpenClawLaunchSession, @@ -1109,6 +1110,71 @@ it.runIf(process.platform === "linux")( testTimeout(30_000), ); +it.runIf(process.platform === "linux")( + "executes two real provider failures before reporting exhausted availability (#10978)", + async () => { + const calls: Array<{ + artifactName?: string; + firstInput?: string; + runId?: string; + stderr: string; + }> = []; + const host = { + command: async ( + command: string, + args: string[], + options?: { artifactName?: string; env?: NodeJS.ProcessEnv }, + ) => { + const fixture = runLaunchSessionFixture("provider-empty-message", "provider", { + args, + command, + env: options?.env, + }).result; + calls.push({ + artifactName: options?.artifactName, + firstInput: options?.env?.NEMOCLAW_LAUNCH_FIRST_INPUT, + runId: options?.env?.NEMOCLAW_LAUNCH_RUN_ID, + stderr: fixture.stderr, + }); + return { + exitCode: fixture.status ?? 1, + signal: fixture.signal, + stderr: fixture.stderr, + stdout: fixture.stdout, + }; + }, + openshellCommandPath: "/usr/bin/openshell", + }; + vi.useFakeTimers(); + try { + const launch = runOpenClawLaunchSession({ + artifactName: "producer-exhaustion", + cliCommand: "openclaw", + env: {}, + exitCommand: "/exit", + host: host as never, + redactionValues: [], + sandboxName: "alpha", + }); + expect(calls).toHaveLength(1); + await vi.advanceTimersByTimeAsync(1_000); + await expect(launch).rejects.toThrow("OpenClaw launch provider unavailable after 2 attempts"); + expect(calls.map((call) => call.artifactName)).toEqual([ + "producer-exhaustion", + "producer-exhaustion-provider-retry-02", + ]); + expect(new Set(calls.map((call) => call.runId)).size).toBe(2); + expect(new Set(calls.map((call) => call.firstInput)).size).toBe(2); + for (const call of calls) { + expect(call.stderr).toContain(`${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${call.runId}`); + } + } finally { + vi.useRealTimers(); + } + }, + testTimeout(45_000), +); + it.runIf(process.platform === "linux")( "does not retry a provider failure when producer cleanup is incomplete (#10978)", async () => { From 005a9a0aca3cf36ecc0b9dcc758afc6f7d780c3e Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 18:29:35 -0700 Subject: [PATCH 33/43] test(e2e): keep provider proof within guardrails --- test/e2e/support/launch-agent-turn.test.ts | 112 +++++++-------------- 1 file changed, 38 insertions(+), 74 deletions(-) diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index e1b420cec85..f8d7de40eef 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -1051,13 +1051,27 @@ it.runIf(process.platform === "linux")( }, ); -it.runIf(process.platform === "linux")( - "executes the real launch producer across a provider retry (#10978)", - async () => { +it.runIf(process.platform === "linux").each([ + { + expectedError: null, + secondMarker: false, + secondMode: "valid", + secondTerminal: "absent", + }, + { + expectedError: "OpenClaw launch provider unavailable after 2 attempts", + secondMarker: true, + secondMode: "provider-empty-message", + secondTerminal: "provider", + }, +] as const)( + "executes the real launch producer through $secondMode (#10978)", + async ({ expectedError, secondMarker, secondMode, secondTerminal }) => { const calls: Array<{ artifactName?: string; firstInput?: string; runId?: string; + stderr: string; }> = []; const host = { command: async ( @@ -1065,71 +1079,11 @@ it.runIf(process.platform === "linux")( args: string[], options?: { artifactName?: string; env?: NodeJS.ProcessEnv }, ) => { - calls.push({ - artifactName: options?.artifactName, - firstInput: options?.env?.NEMOCLAW_LAUNCH_FIRST_INPUT, - runId: options?.env?.NEMOCLAW_LAUNCH_RUN_ID, - }); const fixture = runLaunchSessionFixture( - calls.length === 1 ? "provider-empty-message" : "valid", - calls.length === 1 ? "provider" : "absent", + calls.length === 0 ? "provider-empty-message" : secondMode, + calls.length === 0 ? "provider" : secondTerminal, { args, command, env: options?.env }, ).result; - return { - exitCode: fixture.status ?? 1, - signal: fixture.signal, - stderr: fixture.stderr, - stdout: fixture.stdout, - }; - }, - openshellCommandPath: "/usr/bin/openshell", - }; - vi.useFakeTimers(); - try { - const launch = runOpenClawLaunchSession({ - artifactName: "producer-handoff", - cliCommand: "openclaw", - env: {}, - exitCommand: "/exit", - host: host as never, - redactionValues: [], - sandboxName: "alpha", - }); - await vi.advanceTimersByTimeAsync(1_000); - await expect(launch).resolves.toMatchObject({ exitCode: 0 }); - expect(calls.map((call) => call.artifactName)).toEqual([ - "producer-handoff", - "producer-handoff-provider-retry-02", - ]); - expect(new Set(calls.map((call) => call.runId)).size).toBe(2); - expect(new Set(calls.map((call) => call.firstInput)).size).toBe(2); - } finally { - vi.useRealTimers(); - } - }, - testTimeout(30_000), -); - -it.runIf(process.platform === "linux")( - "executes two real provider failures before reporting exhausted availability (#10978)", - async () => { - const calls: Array<{ - artifactName?: string; - firstInput?: string; - runId?: string; - stderr: string; - }> = []; - const host = { - command: async ( - command: string, - args: string[], - options?: { artifactName?: string; env?: NodeJS.ProcessEnv }, - ) => { - const fixture = runLaunchSessionFixture("provider-empty-message", "provider", { - args, - command, - env: options?.env, - }).result; calls.push({ artifactName: options?.artifactName, firstInput: options?.env?.NEMOCLAW_LAUNCH_FIRST_INPUT, @@ -1148,7 +1102,7 @@ it.runIf(process.platform === "linux")( vi.useFakeTimers(); try { const launch = runOpenClawLaunchSession({ - artifactName: "producer-exhaustion", + artifactName: "producer-handoff", cliCommand: "openclaw", env: {}, exitCommand: "/exit", @@ -1156,23 +1110,33 @@ it.runIf(process.platform === "linux")( redactionValues: [], sandboxName: "alpha", }); - expect(calls).toHaveLength(1); + const outcome = launch.then( + (result) => ({ error: null, exitCode: result.exitCode }), + (error: unknown) => ({ + error: error instanceof Error ? error.message : String(error), + exitCode: null, + }), + ); await vi.advanceTimersByTimeAsync(1_000); - await expect(launch).rejects.toThrow("OpenClaw launch provider unavailable after 2 attempts"); + const expectedExitCode = expectedError === null ? 0 : null; + await expect(outcome).resolves.toEqual({ error: expectedError, exitCode: expectedExitCode }); expect(calls.map((call) => call.artifactName)).toEqual([ - "producer-exhaustion", - "producer-exhaustion-provider-retry-02", + "producer-handoff", + "producer-handoff-provider-retry-02", ]); expect(new Set(calls.map((call) => call.runId)).size).toBe(2); expect(new Set(calls.map((call) => call.firstInput)).size).toBe(2); - for (const call of calls) { - expect(call.stderr).toContain(`${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${call.runId}`); - } + expect(calls[0]?.stderr).toContain( + `${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${calls[0]?.runId}`, + ); + expect( + calls[1]?.stderr.includes(`${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${calls[1]?.runId}`), + ).toBe(secondMarker); } finally { vi.useRealTimers(); } }, - testTimeout(45_000), + testTimeout(30_000), ); it.runIf(process.platform === "linux")( From f6a376a8bf1081f40bac1436c24ff6d0d5cd2373 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 19:05:50 -0700 Subject: [PATCH 34/43] test(e2e): accept bounded provider diagnostics --- test/e2e/support/launch-agent-turn.test.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index f8d7de40eef..b0ec24e8f27 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -1054,19 +1054,17 @@ it.runIf(process.platform === "linux")( it.runIf(process.platform === "linux").each([ { expectedError: null, - secondMarker: false, secondMode: "valid", secondTerminal: "absent", }, { expectedError: "OpenClaw launch provider unavailable after 2 attempts", - secondMarker: true, secondMode: "provider-empty-message", secondTerminal: "provider", }, ] as const)( "executes the real launch producer through $secondMode (#10978)", - async ({ expectedError, secondMarker, secondMode, secondTerminal }) => { + async ({ expectedError, secondMode, secondTerminal }) => { const calls: Array<{ artifactName?: string; firstInput?: string; @@ -1118,8 +1116,10 @@ it.runIf(process.platform === "linux").each([ }), ); await vi.advanceTimersByTimeAsync(1_000); - const expectedExitCode = expectedError === null ? 0 : null; - await expect(outcome).resolves.toEqual({ error: expectedError, exitCode: expectedExitCode }); + await expect(outcome).resolves.toEqual({ + error: expectedError === null ? null : expect.stringContaining(expectedError), + exitCode: expectedError === null ? 0 : null, + }); expect(calls.map((call) => call.artifactName)).toEqual([ "producer-handoff", "producer-handoff-provider-retry-02", @@ -1131,7 +1131,7 @@ it.runIf(process.platform === "linux").each([ ); expect( calls[1]?.stderr.includes(`${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${calls[1]?.runId}`), - ).toBe(secondMarker); + ).toBe(expectedError !== null); } finally { vi.useRealTimers(); } From b7414a10ea3b2fd55f045015fd2263f162b65758 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 19:34:52 -0700 Subject: [PATCH 35/43] ci(e2e): bind portable timeout ownership --- .github/workflows/portable-profile-e2e.yaml | 1 + test/e2e/README.md | 3 ++- test/e2e/docs/README.md | 3 ++- .../support/portable-profile-rootless-runtime-workflow.test.ts | 1 + 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/portable-profile-e2e.yaml b/.github/workflows/portable-profile-e2e.yaml index 323d628a8ee..e43c111fd6e 100644 --- a/.github/workflows/portable-profile-e2e.yaml +++ b/.github/workflows/portable-profile-e2e.yaml @@ -41,6 +41,7 @@ on: - "test/e2e/live/portable-profile-gateway-proof.ts" - "test/e2e/live/portable-profile-rootless-linux.test.ts" - "tools/e2e/check-semantic-phases.mts" + - "tools/e2e/full-e2e-timeout-contract.mts" permissions: contents: read diff --git a/test/e2e/README.md b/test/e2e/README.md index 845d2620e10..fe50fbaa139 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -222,7 +222,8 @@ boundaries are the behavior under test. `.github/workflows/platform-vitest-main.yaml` publishes the `CI / Platform Compatibility` workflow. It runs the Ubuntu 26.04 compatibility contracts and the full Vitest suite in four shards on macOS and WSL. The matrix disables `fail-fast`. -The first macOS shard has a 60-minute budget for live E2E; the other shards have 30 minutes. +The first macOS shard has a 95-minute job budget: a 70-minute live-E2E deadline plus +25 minutes of setup, cleanup, and artifact headroom. The other shards have 30 minutes. The first WSL shard has a 180-minute budget for root-required contracts and live E2E; the other shards have 90 minutes. On shard 1, the workflow runs focused macOS and WSL live E2E only when the run tests `main` and Docker is available. diff --git a/test/e2e/docs/README.md b/test/e2e/docs/README.md index 73083a156ca..ebbec5376ef 100644 --- a/test/e2e/docs/README.md +++ b/test/e2e/docs/README.md @@ -352,7 +352,8 @@ test/e2e/ - `.github/workflows/platform-vitest-main.yaml` publishes `CI / Platform Compatibility`. It runs the Ubuntu 26.04 compatibility contracts and four full-suite Vitest shards on each of macOS and WSL. Each macOS shard installs the pinned OpenShell formula. - Shard 1 has a 60-minute budget for live E2E; the other shards have 30 minutes. + Shard 1 has a 95-minute job budget: a 70-minute live-E2E deadline plus 25 minutes of setup, cleanup, and artifact headroom. + The other shards have 30 minutes. WSL shard 1 has a 180-minute budget for root-required contracts and live E2E; the other shards have 90 minutes. On shard 1, the workflow runs focused macOS and WSL live E2E only when the run tests `main` and Docker is available. Otherwise, those live tests skip and the platform contracts remain as evidence. diff --git a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts index 3ef771d8742..ffde68f1ffc 100644 --- a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts +++ b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts @@ -260,6 +260,7 @@ ${serviceIdentityCheck}`, const revisionExpression = "${{ github.event.pull_request.head.sha || github.sha }}"; expect(workflow.on.pull_request.types).toEqual(["opened", "synchronize", "reopened"]); + expect(workflow.on.push.paths).toContain("tools/e2e/full-e2e-timeout-contract.mts"); expect(workflow.on.pull_request.paths).toEqual( expect.arrayContaining([ "src/lib/onboard/experimental/portable-host-preparation.ts", From a7dce15d539389409f3da4b7cc3a33d44d568cc9 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 20:08:49 -0700 Subject: [PATCH 36/43] fix(e2e): constrain provider retries and budgets --- .github/workflows/platform-vitest-main.yaml | 3 +- .github/workflows/portable-profile-e2e.yaml | 3 +- .../e2e/platform-vitest-main-workflow.test.ts | 14 ++- test/e2e/README.md | 5 +- test/e2e/docs/README.md | 2 +- test/e2e/live/launch-agent-turn.ts | 10 ++- ...h-agent-turn-provider-availability.test.ts | 85 ++++++++++--------- ...launch-agent-turn-session-evidence.test.ts | 17 ++++ ...-profile-rootless-runtime-workflow.test.ts | 14 ++- ...security-posture-workflow-boundary.test.ts | 8 +- ...standard-profile-workflow-boundary.test.ts | 26 ++++++ tools/e2e/full-e2e-timeout-contract.mts | 22 ++++- tools/e2e/target-catalogue.mts | 6 +- 13 files changed, 154 insertions(+), 61 deletions(-) diff --git a/.github/workflows/platform-vitest-main.yaml b/.github/workflows/platform-vitest-main.yaml index 3c296933e47..4fb3bda1e27 100644 --- a/.github/workflows/platform-vitest-main.yaml +++ b/.github/workflows/platform-vitest-main.yaml @@ -89,7 +89,8 @@ jobs: matrix: include: - shard: 1 - timeout_minutes: 95 + # 60m pre-live shard/setup + 70m live E2E + 20m cleanup/artifacts. + timeout_minutes: 150 - shard: 2 timeout_minutes: 30 - shard: 3 diff --git a/.github/workflows/portable-profile-e2e.yaml b/.github/workflows/portable-profile-e2e.yaml index e43c111fd6e..59400b388f8 100644 --- a/.github/workflows/portable-profile-e2e.yaml +++ b/.github/workflows/portable-profile-e2e.yaml @@ -156,7 +156,8 @@ jobs: portable-launch: if: ${{ github.ref == 'refs/heads/main' }} runs-on: ubuntu-26.04 - timeout-minutes: 95 + # 45m portable setup + 70m live E2E + 20m cleanup/artifacts. + timeout-minutes: 135 env: E2E_JOB: "1" E2E_TARGET_ID: portable-launch diff --git a/test/automation/e2e/platform-vitest-main-workflow.test.ts b/test/automation/e2e/platform-vitest-main-workflow.test.ts index 36b81aaf11a..fec8f610ad0 100644 --- a/test/automation/e2e/platform-vitest-main-workflow.test.ts +++ b/test/automation/e2e/platform-vitest-main-workflow.test.ts @@ -3,7 +3,12 @@ import { describe, expect, it } from "vitest"; -import { FULL_E2E_TARGET_TIMEOUT_MINUTES } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; +import { + FULL_E2E_MACOS_JOB_TIMEOUT_MINUTES, + FULL_E2E_MACOS_POST_TEST_MINUTES, + FULL_E2E_MACOS_PRE_TEST_MINUTES, + FULL_E2E_TEST_TIMEOUT_MINUTES, +} from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { readRepoText, readYaml, @@ -68,6 +73,11 @@ describe("platform evidence workflow", () => { }>; const firstShard = macosShards.find(({ shard }) => shard === 1); - expect(firstShard?.timeout_minutes).toBe(FULL_E2E_TARGET_TIMEOUT_MINUTES); + expect(firstShard?.timeout_minutes).toBe(FULL_E2E_MACOS_JOB_TIMEOUT_MINUTES); + expect(firstShard?.timeout_minutes).toBe( + FULL_E2E_MACOS_PRE_TEST_MINUTES + + FULL_E2E_TEST_TIMEOUT_MINUTES + + FULL_E2E_MACOS_POST_TEST_MINUTES, + ); }); }); diff --git a/test/e2e/README.md b/test/e2e/README.md index fe50fbaa139..71fded28f0c 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -222,8 +222,9 @@ boundaries are the behavior under test. `.github/workflows/platform-vitest-main.yaml` publishes the `CI / Platform Compatibility` workflow. It runs the Ubuntu 26.04 compatibility contracts and the full Vitest suite in four shards on macOS and WSL. The matrix disables `fail-fast`. -The first macOS shard has a 95-minute job budget: a 70-minute live-E2E deadline plus -25 minutes of setup, cleanup, and artifact headroom. The other shards have 30 minutes. +The first macOS shard has a 150-minute job budget: 60 minutes for the pre-live +shard and setup, a 70-minute live-E2E deadline, and 20 minutes for cleanup and +artifacts. The other shards have 30 minutes. The first WSL shard has a 180-minute budget for root-required contracts and live E2E; the other shards have 90 minutes. On shard 1, the workflow runs focused macOS and WSL live E2E only when the run tests `main` and Docker is available. diff --git a/test/e2e/docs/README.md b/test/e2e/docs/README.md index ebbec5376ef..ebc0f675ddc 100644 --- a/test/e2e/docs/README.md +++ b/test/e2e/docs/README.md @@ -352,7 +352,7 @@ test/e2e/ - `.github/workflows/platform-vitest-main.yaml` publishes `CI / Platform Compatibility`. It runs the Ubuntu 26.04 compatibility contracts and four full-suite Vitest shards on each of macOS and WSL. Each macOS shard installs the pinned OpenShell formula. - Shard 1 has a 95-minute job budget: a 70-minute live-E2E deadline plus 25 minutes of setup, cleanup, and artifact headroom. + Shard 1 has a 150-minute job budget: 60 minutes for the pre-live shard and setup, a 70-minute live-E2E deadline, and 20 minutes for cleanup and artifacts. The other shards have 30 minutes. WSL shard 1 has a 180-minute budget for root-required contracts and live E2E; the other shards have 90 minutes. On shard 1, the workflow runs focused macOS and WSL live E2E only when the run tests `main` and Docker is available. diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index dfd68d332a5..559ea3e6768 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -971,9 +971,13 @@ function hasStructuredContent(message) { return Array.isArray(message.content) && message.content.length > 0; } -const providerUnavailableCodes = new Set(["502", "503", "504", "529"]); +const providerUnavailableCodes = new Set(["500", "502", "503", "504", "529"]); +const providerUnavailableError = /^(?:litellm\.)?(?:InternalServerError|ServiceUnavailableError)(?::|$)/; +const providerAuthenticationError = + /(?:authenticat|authori[sz]|unauthori[sz]ed|forbidden|invalid (?:api )?key|credential)/i; function isStructuredProviderUnavailable(message) { + const errorMessage = typeof message.errorMessage === "string" ? message.errorMessage.trim() : ""; const identity = [ message.role, hasStructuredContent(message), @@ -984,7 +988,9 @@ function isStructuredProviderUnavailable(message) { return ( identity === "assistant\nfalse\nerror\nopenai-completions\ninference" && typeof message.errorCode === "string" && - providerUnavailableCodes.has(message.errorCode.trim()) + providerUnavailableCodes.has(message.errorCode.trim()) && + providerUnavailableError.test(errorMessage) && + !providerAuthenticationError.test(errorMessage) ); } diff --git a/test/e2e/support/launch-agent-turn-provider-availability.test.ts b/test/e2e/support/launch-agent-turn-provider-availability.test.ts index 4f024164fcd..f7c73cc1fea 100644 --- a/test/e2e/support/launch-agent-turn-provider-availability.test.ts +++ b/test/e2e/support/launch-agent-turn-provider-availability.test.ts @@ -18,48 +18,51 @@ function launchOptions(host: unknown) { }; } -it("retries a transient provider failure in a fresh launch session (#10978)", async () => { - const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); - vi.useFakeTimers(); - const calls: Array<{ artifactName?: string; env?: NodeJS.ProcessEnv }> = []; - const host = { - command: async ( - _command: string, - _args: string[], - options?: { artifactName?: string; env?: NodeJS.ProcessEnv }, - ) => { - calls.push({ artifactName: options?.artifactName, env: options?.env }); - return calls.length === 1 - ? { - exitCode: 1, - signal: null, - stderr: `launch did not record the required structured session turns\nlitellm.ServiceUnavailableError: NVIDIA upstream unavailable\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${options?.env?.NEMOCLAW_LAUNCH_RUN_ID}\n`, - stdout: "", - } - : { exitCode: 0, signal: null, stderr: "", stdout: "" }; - }, - openshellCommandPath: "/usr/bin/openshell", - }; +it.each(["500", "503"] as const)( + "retries a transient HTTP %s provider failure in a fresh launch session (#10978)", + async (status) => { + const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + vi.useFakeTimers(); + const calls: Array<{ artifactName?: string; env?: NodeJS.ProcessEnv }> = []; + const host = { + command: async ( + _command: string, + _args: string[], + options?: { artifactName?: string; env?: NodeJS.ProcessEnv }, + ) => { + calls.push({ artifactName: options?.artifactName, env: options?.env }); + return calls.length === 1 + ? { + exitCode: 1, + signal: null, + stderr: `launch did not record the required structured session turns\nlitellm.ServiceUnavailableError: HTTP ${status}; NVIDIA upstream unavailable\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${options?.env?.NEMOCLAW_LAUNCH_RUN_ID}\n`, + stdout: "", + } + : { exitCode: 0, signal: null, stderr: "", stdout: "" }; + }, + openshellCommandPath: "/usr/bin/openshell", + }; - try { - const launch = runOpenClawLaunchSession(launchOptions(host)); - expect(calls).toHaveLength(1); - await vi.advanceTimersByTimeAsync(999); - expect(calls).toHaveLength(1); - await vi.advanceTimersByTimeAsync(1); - const result = await launch; - expect(result.exitCode).toBe(0); - expect(calls.map((call) => call.artifactName)).toEqual([ - "provider-turn", - "provider-turn-provider-retry-02", - ]); - expect(new Set(calls.map((call) => call.env?.NEMOCLAW_LAUNCH_RUN_ID)).size).toBe(2); - expect(new Set(calls.map((call) => call.env?.NEMOCLAW_LAUNCH_FIRST_INPUT)).size).toBe(2); - } finally { - vi.useRealTimers(); - platform.mockRestore(); - } -}); + try { + const launch = runOpenClawLaunchSession(launchOptions(host)); + expect(calls).toHaveLength(1); + await vi.advanceTimersByTimeAsync(999); + expect(calls).toHaveLength(1); + await vi.advanceTimersByTimeAsync(1); + const result = await launch; + expect(result.exitCode).toBe(0); + expect(calls.map((call) => call.artifactName)).toEqual([ + "provider-turn", + "provider-turn-provider-retry-02", + ]); + expect(new Set(calls.map((call) => call.env?.NEMOCLAW_LAUNCH_RUN_ID)).size).toBe(2); + expect(new Set(calls.map((call) => call.env?.NEMOCLAW_LAUNCH_FIRST_INPUT)).size).toBe(2); + } finally { + vi.useRealTimers(); + platform.mockRestore(); + } + }, +); it("classifies exhausted transient launch attempts as provider unavailable (#10978)", async () => { const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); diff --git a/test/e2e/support/launch-agent-turn-session-evidence.test.ts b/test/e2e/support/launch-agent-turn-session-evidence.test.ts index 6c96a79a4df..624d5ff1137 100644 --- a/test/e2e/support/launch-agent-turn-session-evidence.test.ts +++ b/test/e2e/support/launch-agent-turn-session-evidence.test.ts @@ -281,6 +281,23 @@ it.each<{ after: SessionRecords; status: number }>([ after: { "session-a": [message("user"), providerUnavailableMessage()] }, status: 3, }, + { + after: { + "session-a": [message("user"), providerUnavailableMessage({ errorCode: "500" })], + }, + status: 3, + }, + { + after: { + "session-a": [ + message("user"), + providerUnavailableMessage({ + errorMessage: "litellm.AuthenticationError: invalid API key", + }), + ], + }, + status: 2, + }, { after: { "session-a": [message("user"), providerUnavailableMessage({ errorCode: "400" })], diff --git a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts index ffde68f1ffc..6ad6c7890fb 100644 --- a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts +++ b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts @@ -6,7 +6,12 @@ import fs from "node:fs"; import { describe, expect, it } from "vitest"; -import { FULL_E2E_TARGET_TIMEOUT_MINUTES } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; +import { + FULL_E2E_PORTABLE_JOB_TIMEOUT_MINUTES, + FULL_E2E_PORTABLE_POST_TEST_MINUTES, + FULL_E2E_PORTABLE_PRE_TEST_MINUTES, + FULL_E2E_TEST_TIMEOUT_MINUTES, +} from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { readRepoText, readYaml, type Workflow } from "../../helpers/e2e-workflow-contract"; type PortableProfileWorkflow = Workflow & { @@ -277,7 +282,12 @@ ${serviceIdentityCheck}`, expect(upload?.with?.name).toContain(revisionExpression); expect(workflow.jobs["portable-launch"]?.if).toBe("${{ github.ref == 'refs/heads/main' }}"); expect(workflow.jobs["portable-launch"]?.["timeout-minutes"]).toBe( - FULL_E2E_TARGET_TIMEOUT_MINUTES, + FULL_E2E_PORTABLE_JOB_TIMEOUT_MINUTES, + ); + expect(workflow.jobs["portable-launch"]?.["timeout-minutes"]).toBe( + FULL_E2E_PORTABLE_PRE_TEST_MINUTES + + FULL_E2E_TEST_TIMEOUT_MINUTES + + FULL_E2E_PORTABLE_POST_TEST_MINUTES, ); expect(liveSource).toContain('run("git", ["rev-parse", "HEAD"])'); expect(liveSource).toContain('"network", "rm", disposableNetworkId'); diff --git a/test/e2e/support/security-posture-workflow-boundary.test.ts b/test/e2e/support/security-posture-workflow-boundary.test.ts index a3fd720341a..61f75cbea92 100644 --- a/test/e2e/support/security-posture-workflow-boundary.test.ts +++ b/test/e2e/support/security-posture-workflow-boundary.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; -import { FULL_E2E_TARGET_TIMEOUT_MINUTES } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; +import { FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { catalogueTarget, E2E_TARGET_CATALOGUE, @@ -18,7 +18,9 @@ describe("security-posture catalogue boundary", () => { const openclaw = catalogueTarget("security-posture-openclaw"); const hermes = catalogueTarget("security-posture-hermes"); - expect(catalogueTarget("full-e2e").timeoutMinutes).toBe(FULL_E2E_TARGET_TIMEOUT_MINUTES); + expect(catalogueTarget("full-e2e").timeoutMinutes).toBe( + FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES, + ); const target = ({ OpenClaw: openclaw, Hermes: hermes } as const)[scenario]!; expect(target).toMatchObject({ @@ -36,7 +38,7 @@ describe("security-posture catalogue boundary", () => { expect(openclaw).toMatchObject({ shard: "openclaw", testFile: "test/e2e/live/full-e2e.test.ts", - timeoutMinutes: FULL_E2E_TARGET_TIMEOUT_MINUTES, + timeoutMinutes: FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES, }); expect(hermes).toMatchObject({ shard: "hermes", diff --git a/test/e2e/support/standard-profile-workflow-boundary.test.ts b/test/e2e/support/standard-profile-workflow-boundary.test.ts index d69b8c7c83e..bd2495ee55f 100644 --- a/test/e2e/support/standard-profile-workflow-boundary.test.ts +++ b/test/e2e/support/standard-profile-workflow-boundary.test.ts @@ -9,7 +9,14 @@ import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; import YAML from "yaml"; +import { + FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES, + FULL_E2E_STANDARD_PROFILE_POST_TEST_MINUTES, + FULL_E2E_STANDARD_PROFILE_PRE_TEST_MINUTES, + FULL_E2E_TEST_TIMEOUT_MINUTES, +} from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { validateStandardProfileWorkflowBoundary } from "../../../tools/e2e/standard-profile-workflow-boundary.mts"; +import { catalogueTarget } from "../../../tools/e2e/target-catalogue.mts"; import { readWorkflow } from "../../helpers/e2e-workflow-contract"; const REPO_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".."); @@ -19,6 +26,25 @@ describe("standard E2E execution profile", () => { expect(validateStandardProfileWorkflowBoundary(readWorkflow())).toEqual([]); }); + it("reserves the standard full-E2E setup, test, and artifact envelope", () => { + const profile = YAML.parse( + fs.readFileSync( + path.join(REPO_ROOT, ".github", "workflows", "e2e-standard-profile.yaml"), + "utf8", + ), + ) as { jobs: { run: { "timeout-minutes": string } } }; + + expect(profile.jobs.run["timeout-minutes"]).toBe("${{ inputs.timeout_minutes }}"); + expect(catalogueTarget("full-e2e").timeoutMinutes).toBe( + FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES, + ); + expect(FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES).toBe( + FULL_E2E_STANDARD_PROFILE_PRE_TEST_MINUTES + + FULL_E2E_TEST_TIMEOUT_MINUTES + + FULL_E2E_STANDARD_PROFILE_POST_TEST_MINUTES, + ); + }); + it("rejects a cloudflared PATH shortcut before package verification", () => { const profile = YAML.parse( fs.readFileSync( diff --git a/tools/e2e/full-e2e-timeout-contract.mts b/tools/e2e/full-e2e-timeout-contract.mts index fb01c1de352..beb7f39e1a5 100644 --- a/tools/e2e/full-e2e-timeout-contract.mts +++ b/tools/e2e/full-e2e-timeout-contract.mts @@ -2,8 +2,24 @@ // SPDX-License-Identifier: Apache-2.0 export const FULL_E2E_TEST_TIMEOUT_MINUTES = 70; -export const FULL_E2E_JOB_HEADROOM_MINUTES = 25; + +export const FULL_E2E_STANDARD_PROFILE_PRE_TEST_MINUTES = 30; +export const FULL_E2E_STANDARD_PROFILE_POST_TEST_MINUTES = 15; +export const FULL_E2E_MACOS_PRE_TEST_MINUTES = 60; +export const FULL_E2E_MACOS_POST_TEST_MINUTES = 20; +export const FULL_E2E_PORTABLE_PRE_TEST_MINUTES = 45; +export const FULL_E2E_PORTABLE_POST_TEST_MINUTES = 20; export const FULL_E2E_TEST_TIMEOUT_MS = FULL_E2E_TEST_TIMEOUT_MINUTES * 60_000; -export const FULL_E2E_TARGET_TIMEOUT_MINUTES = - FULL_E2E_TEST_TIMEOUT_MINUTES + FULL_E2E_JOB_HEADROOM_MINUTES; +export const FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES = + FULL_E2E_STANDARD_PROFILE_PRE_TEST_MINUTES + + FULL_E2E_TEST_TIMEOUT_MINUTES + + FULL_E2E_STANDARD_PROFILE_POST_TEST_MINUTES; +export const FULL_E2E_MACOS_JOB_TIMEOUT_MINUTES = + FULL_E2E_MACOS_PRE_TEST_MINUTES + + FULL_E2E_TEST_TIMEOUT_MINUTES + + FULL_E2E_MACOS_POST_TEST_MINUTES; +export const FULL_E2E_PORTABLE_JOB_TIMEOUT_MINUTES = + FULL_E2E_PORTABLE_PRE_TEST_MINUTES + + FULL_E2E_TEST_TIMEOUT_MINUTES + + FULL_E2E_PORTABLE_POST_TEST_MINUTES; diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index c039b7bcd40..967700c0bdb 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -18,7 +18,7 @@ import { runtimeCoverageVariant, runtimeExecutionId, } from "./gateway-runtime.mts"; -import { FULL_E2E_TARGET_TIMEOUT_MINUTES } from "./full-e2e-timeout-contract.mts"; +import { FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES } from "./full-e2e-timeout-contract.mts"; import { ONBOARD_RESUME_TARGET_TIMEOUT_MINUTES, ONBOARD_SINGLE_FINAL_HANDOFF_TARGET_TIMEOUT_MINUTES, @@ -737,7 +737,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ agentRuntime: "openclaw", environmentOrInferenceEndpoint: "Ubuntu; NVIDIA hosted inference", profile: "nvidia-inference", - timeoutMinutes: FULL_E2E_TARGET_TIMEOUT_MINUTES, + timeoutMinutes: FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES, installMode: "authenticated", restoreCli: true, exposeCliBin: true, @@ -1309,7 +1309,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ profile: "nvidia-inference", prAdvisorSelectable: true, testFile: "test/e2e/live/full-e2e.test.ts", - timeoutMinutes: FULL_E2E_TARGET_TIMEOUT_MINUTES, + timeoutMinutes: FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES, installMode: "credential-free", installNonInteractive: true, restoreCli: true, From 80cb7c155ce9741b55f12b797618ef27de15c9b8 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 20:13:54 -0700 Subject: [PATCH 37/43] test(e2e): use typed standard timeout contract --- .../support/standard-profile-workflow-boundary.test.ts | 8 -------- 1 file changed, 8 deletions(-) diff --git a/test/e2e/support/standard-profile-workflow-boundary.test.ts b/test/e2e/support/standard-profile-workflow-boundary.test.ts index bd2495ee55f..30cddbe864c 100644 --- a/test/e2e/support/standard-profile-workflow-boundary.test.ts +++ b/test/e2e/support/standard-profile-workflow-boundary.test.ts @@ -27,14 +27,6 @@ describe("standard E2E execution profile", () => { }); it("reserves the standard full-E2E setup, test, and artifact envelope", () => { - const profile = YAML.parse( - fs.readFileSync( - path.join(REPO_ROOT, ".github", "workflows", "e2e-standard-profile.yaml"), - "utf8", - ), - ) as { jobs: { run: { "timeout-minutes": string } } }; - - expect(profile.jobs.run["timeout-minutes"]).toBe("${{ inputs.timeout_minutes }}"); expect(catalogueTarget("full-e2e").timeoutMinutes).toBe( FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES, ); From 66cd7e04f0d365a950a4431ed2ec7e71f15a527e Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 20:45:39 -0700 Subject: [PATCH 38/43] fix(e2e): route timeout contract evidence --- .github/workflows/portable-profile-e2e.yaml | 1 + .../e2e/platform-vitest-main-workflow.test.ts | 13 +------------ ...ble-profile-rootless-runtime-workflow.test.ts | 16 ++-------------- test/e2e/support/workflow-plan.test.ts | 9 +++++++++ tools/e2e/full-e2e-timeout-contract.mts | 12 ------------ tools/e2e/target-catalogue.mts | 2 ++ 6 files changed, 15 insertions(+), 38 deletions(-) diff --git a/.github/workflows/portable-profile-e2e.yaml b/.github/workflows/portable-profile-e2e.yaml index 59400b388f8..873b4f3b1f6 100644 --- a/.github/workflows/portable-profile-e2e.yaml +++ b/.github/workflows/portable-profile-e2e.yaml @@ -21,6 +21,7 @@ on: - "src/lib/onboard/experimental/portable-retired-subnet-recovery.test.ts" - "test/e2e/live/portable-profile-rootless-linux.test.ts" - "test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts" + - "tools/e2e/full-e2e-timeout-contract.mts" push: branches: - main diff --git a/test/automation/e2e/platform-vitest-main-workflow.test.ts b/test/automation/e2e/platform-vitest-main-workflow.test.ts index fec8f610ad0..63c4dc12a5f 100644 --- a/test/automation/e2e/platform-vitest-main-workflow.test.ts +++ b/test/automation/e2e/platform-vitest-main-workflow.test.ts @@ -3,12 +3,6 @@ import { describe, expect, it } from "vitest"; -import { - FULL_E2E_MACOS_JOB_TIMEOUT_MINUTES, - FULL_E2E_MACOS_POST_TEST_MINUTES, - FULL_E2E_MACOS_PRE_TEST_MINUTES, - FULL_E2E_TEST_TIMEOUT_MINUTES, -} from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { readRepoText, readYaml, @@ -73,11 +67,6 @@ describe("platform evidence workflow", () => { }>; const firstShard = macosShards.find(({ shard }) => shard === 1); - expect(firstShard?.timeout_minutes).toBe(FULL_E2E_MACOS_JOB_TIMEOUT_MINUTES); - expect(firstShard?.timeout_minutes).toBe( - FULL_E2E_MACOS_PRE_TEST_MINUTES + - FULL_E2E_TEST_TIMEOUT_MINUTES + - FULL_E2E_MACOS_POST_TEST_MINUTES, - ); + expect(firstShard?.timeout_minutes).toBe(150); }); }); diff --git a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts index 6ad6c7890fb..0724246d027 100644 --- a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts +++ b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts @@ -6,12 +6,6 @@ import fs from "node:fs"; import { describe, expect, it } from "vitest"; -import { - FULL_E2E_PORTABLE_JOB_TIMEOUT_MINUTES, - FULL_E2E_PORTABLE_POST_TEST_MINUTES, - FULL_E2E_PORTABLE_PRE_TEST_MINUTES, - FULL_E2E_TEST_TIMEOUT_MINUTES, -} from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { readRepoText, readYaml, type Workflow } from "../../helpers/e2e-workflow-contract"; type PortableProfileWorkflow = Workflow & { @@ -273,6 +267,7 @@ ${serviceIdentityCheck}`, "src/lib/onboard/experimental/portable-retired-subnet-recovery.test.ts", "test/e2e/live/portable-profile-rootless-linux.test.ts", "test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts", + "tools/e2e/full-e2e-timeout-contract.mts", ]), ); expect(job?.env?.E2E_SOURCE_REVISION).toBe(revisionExpression); @@ -281,14 +276,7 @@ ${serviceIdentityCheck}`, expect(upload?.if).toBe("always()"); expect(upload?.with?.name).toContain(revisionExpression); expect(workflow.jobs["portable-launch"]?.if).toBe("${{ github.ref == 'refs/heads/main' }}"); - expect(workflow.jobs["portable-launch"]?.["timeout-minutes"]).toBe( - FULL_E2E_PORTABLE_JOB_TIMEOUT_MINUTES, - ); - expect(workflow.jobs["portable-launch"]?.["timeout-minutes"]).toBe( - FULL_E2E_PORTABLE_PRE_TEST_MINUTES + - FULL_E2E_TEST_TIMEOUT_MINUTES + - FULL_E2E_PORTABLE_POST_TEST_MINUTES, - ); + expect(workflow.jobs["portable-launch"]?.["timeout-minutes"]).toBe(135); expect(liveSource).toContain('run("git", ["rev-parse", "HEAD"])'); expect(liveSource).toContain('"network", "rm", disposableNetworkId'); expect(liveSource).not.toContain('"network", "rm", "--force"'); diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 711bc8e2569..0e70fe118d2 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -663,6 +663,15 @@ describe("E2E workflow plan", () => { expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-standard", "jetson-nvmap-gpu"]); }); + it("selects only full E2E consumers when the timeout contract changes", () => { + const changedFile = "tools/e2e/full-e2e-timeout-contract.mts"; + + expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toEqual([ + "full-e2e", + "security-posture-openclaw", + ]); + }); + it.each([ "test/e2e/e2e-cloud-experimental/features/skill/add-sandbox-skill.sh", "test/e2e/e2e-cloud-experimental/features/skill/verify-sandbox-skill-via-agent.sh", diff --git a/tools/e2e/full-e2e-timeout-contract.mts b/tools/e2e/full-e2e-timeout-contract.mts index beb7f39e1a5..e488231d6aa 100644 --- a/tools/e2e/full-e2e-timeout-contract.mts +++ b/tools/e2e/full-e2e-timeout-contract.mts @@ -5,21 +5,9 @@ export const FULL_E2E_TEST_TIMEOUT_MINUTES = 70; export const FULL_E2E_STANDARD_PROFILE_PRE_TEST_MINUTES = 30; export const FULL_E2E_STANDARD_PROFILE_POST_TEST_MINUTES = 15; -export const FULL_E2E_MACOS_PRE_TEST_MINUTES = 60; -export const FULL_E2E_MACOS_POST_TEST_MINUTES = 20; -export const FULL_E2E_PORTABLE_PRE_TEST_MINUTES = 45; -export const FULL_E2E_PORTABLE_POST_TEST_MINUTES = 20; export const FULL_E2E_TEST_TIMEOUT_MS = FULL_E2E_TEST_TIMEOUT_MINUTES * 60_000; export const FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES = FULL_E2E_STANDARD_PROFILE_PRE_TEST_MINUTES + FULL_E2E_TEST_TIMEOUT_MINUTES + FULL_E2E_STANDARD_PROFILE_POST_TEST_MINUTES; -export const FULL_E2E_MACOS_JOB_TIMEOUT_MINUTES = - FULL_E2E_MACOS_PRE_TEST_MINUTES + - FULL_E2E_TEST_TIMEOUT_MINUTES + - FULL_E2E_MACOS_POST_TEST_MINUTES; -export const FULL_E2E_PORTABLE_JOB_TIMEOUT_MINUTES = - FULL_E2E_PORTABLE_PRE_TEST_MINUTES + - FULL_E2E_TEST_TIMEOUT_MINUTES + - FULL_E2E_PORTABLE_POST_TEST_MINUTES; diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 967700c0bdb..2758062d844 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -745,6 +745,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ "test/e2e/live/launch-agent-turn.ts", "test/e2e/live/pr-base-comparison.ts", "src/lib/tunnel/gateway-stop-script.ts", + "tools/e2e/full-e2e-timeout-contract.mts", ], environment: { ...hostedInference, @@ -1316,6 +1317,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ exposeCliBin: true, shard: "openclaw", artifactLayout: "flat-shard", + owningPaths: ["tools/e2e/full-e2e-timeout-contract.mts"], environment: { ...hostedInference, ...nonInteractive, From 18befcf75208de2f572e2246d34459be57c0c6d4 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 21:26:13 -0700 Subject: [PATCH 39/43] test(e2e): cover accepted provider variants --- .github/workflows/platform-vitest-main.yaml | 2 +- .github/workflows/portable-profile-e2e.yaml | 2 +- test/e2e/README.md | 6 +-- test/e2e/docs/README.md | 2 +- test/e2e/support/launch-agent-turn.test.ts | 52 ++++++++++----------- 5 files changed, 32 insertions(+), 32 deletions(-) diff --git a/.github/workflows/platform-vitest-main.yaml b/.github/workflows/platform-vitest-main.yaml index 4fb3bda1e27..982bf26a462 100644 --- a/.github/workflows/platform-vitest-main.yaml +++ b/.github/workflows/platform-vitest-main.yaml @@ -89,7 +89,7 @@ jobs: matrix: include: - shard: 1 - # 60m pre-live shard/setup + 70m live E2E + 20m cleanup/artifacts. + # The live E2E has a 70m timeout; every other step shares the remaining job time. timeout_minutes: 150 - shard: 2 timeout_minutes: 30 diff --git a/.github/workflows/portable-profile-e2e.yaml b/.github/workflows/portable-profile-e2e.yaml index 873b4f3b1f6..904b82a9d48 100644 --- a/.github/workflows/portable-profile-e2e.yaml +++ b/.github/workflows/portable-profile-e2e.yaml @@ -157,7 +157,7 @@ jobs: portable-launch: if: ${{ github.ref == 'refs/heads/main' }} runs-on: ubuntu-26.04 - # 45m portable setup + 70m live E2E + 20m cleanup/artifacts. + # The live E2E has a 70m timeout; every other step shares the remaining job time. timeout-minutes: 135 env: E2E_JOB: "1" diff --git a/test/e2e/README.md b/test/e2e/README.md index 71fded28f0c..da0d8b0ea68 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -222,9 +222,9 @@ boundaries are the behavior under test. `.github/workflows/platform-vitest-main.yaml` publishes the `CI / Platform Compatibility` workflow. It runs the Ubuntu 26.04 compatibility contracts and the full Vitest suite in four shards on macOS and WSL. The matrix disables `fail-fast`. -The first macOS shard has a 150-minute job budget: 60 minutes for the pre-live -shard and setup, a 70-minute live-E2E deadline, and 20 minutes for cleanup and -artifacts. The other shards have 30 minutes. +The first macOS shard has a 150-minute job timeout. Its live E2E has a +70-minute timeout, and every other step shares the remaining job time. The +other shards have 30 minutes. The first WSL shard has a 180-minute budget for root-required contracts and live E2E; the other shards have 90 minutes. On shard 1, the workflow runs focused macOS and WSL live E2E only when the run tests `main` and Docker is available. diff --git a/test/e2e/docs/README.md b/test/e2e/docs/README.md index ebc0f675ddc..26a959eb285 100644 --- a/test/e2e/docs/README.md +++ b/test/e2e/docs/README.md @@ -352,7 +352,7 @@ test/e2e/ - `.github/workflows/platform-vitest-main.yaml` publishes `CI / Platform Compatibility`. It runs the Ubuntu 26.04 compatibility contracts and four full-suite Vitest shards on each of macOS and WSL. Each macOS shard installs the pinned OpenShell formula. - Shard 1 has a 150-minute job budget: 60 minutes for the pre-live shard and setup, a 70-minute live-E2E deadline, and 20 minutes for cleanup and artifacts. + Shard 1 has a 150-minute job timeout. Its live E2E has a 70-minute timeout, and every other step shares the remaining job time. The other shards have 30 minutes. WSL shard 1 has a 180-minute budget for root-required contracts and live E2E; the other shards have 90 minutes. On shard 1, the workflow runs focused macOS and WSL live E2E only when the run tests `main` and Docker is available. diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index b0ec24e8f27..b411e4923de 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -312,8 +312,8 @@ if (process.argv[2] !== "tui") { message: { api: "openai-completions", content: [], - errorCode: "503", - errorMessage: "litellm.ServiceUnavailableError: ServiceUnavailableError: OpenAIException - . Received Model Group=nvidia/model; Available Model Group Fallbacks=None", + errorCode: process.env.NEMOCLAW_FIXTURE_PROVIDER_ERROR_CODE || "503", + errorMessage: process.env.NEMOCLAW_FIXTURE_PROVIDER_ERROR_MESSAGE || "litellm.ServiceUnavailableError: ServiceUnavailableError: OpenAIException - . Received Model Group=nvidia/model; Available Model Group Fallbacks=None", model: "nvidia/model", provider: "inference", role: "assistant", @@ -1052,19 +1052,18 @@ it.runIf(process.platform === "linux")( ); it.runIf(process.platform === "linux").each([ - { - expectedError: null, - secondMode: "valid", - secondTerminal: "absent", - }, - { - expectedError: "OpenClaw launch provider unavailable after 2 attempts", - secondMode: "provider-empty-message", - secondTerminal: "provider", - }, + ["500", "ServiceUnavailableError", "valid"], + ["502", "ServiceUnavailableError", "valid"], + ["503", "ServiceUnavailableError", "valid"], + ["504", "ServiceUnavailableError", "valid"], + ["529", "ServiceUnavailableError", "valid"], + ["500", "InternalServerError", "valid"], + ["503", "ServiceUnavailableError", "provider-empty-message"], ] as const)( - "executes the real launch producer through $secondMode (#10978)", - async ({ expectedError, secondMode, secondTerminal }) => { + "executes the real $1 HTTP $0 launch producer through $2 (#10978)", + async (providerCode, providerError, secondMode) => { + const expectedError = secondMode === "valid" ? null : "provider unavailable after 2 attempts"; + const secondTerminal = secondMode === "valid" ? "absent" : "provider"; const calls: Array<{ artifactName?: string; firstInput?: string; @@ -1080,7 +1079,15 @@ it.runIf(process.platform === "linux").each([ const fixture = runLaunchSessionFixture( calls.length === 0 ? "provider-empty-message" : secondMode, calls.length === 0 ? "provider" : secondTerminal, - { args, command, env: options?.env }, + { + args, + command, + env: { + ...options?.env, + NEMOCLAW_FIXTURE_PROVIDER_ERROR_CODE: providerCode, + NEMOCLAW_FIXTURE_PROVIDER_ERROR_MESSAGE: `litellm.${providerError}: ${providerError}: upstream unavailable`, + }, + }, ).result; calls.push({ artifactName: options?.artifactName, @@ -1108,18 +1115,11 @@ it.runIf(process.platform === "linux").each([ redactionValues: [], sandboxName: "alpha", }); - const outcome = launch.then( - (result) => ({ error: null, exitCode: result.exitCode }), - (error: unknown) => ({ - error: error instanceof Error ? error.message : String(error), - exitCode: null, - }), - ); await vi.advanceTimersByTimeAsync(1_000); - await expect(outcome).resolves.toEqual({ - error: expectedError === null ? null : expect.stringContaining(expectedError), - exitCode: expectedError === null ? 0 : null, - }); + const outcome = launch.then(({ exitCode }) => exitCode).catch(String); + await expect(outcome).resolves.toEqual( + expectedError === null ? 0 : expect.stringContaining(expectedError), + ); expect(calls.map((call) => call.artifactName)).toEqual([ "producer-handoff", "producer-handoff-provider-retry-02", From 8e8fdc9aab2405ca915c938b5858affbe32b4ee1 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 21:30:54 -0700 Subject: [PATCH 40/43] chore(deps): drop unrelated lockfile drift --- package-lock.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package-lock.json b/package-lock.json index 7017355f62f..c8b0a7ecae5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1513,7 +1513,7 @@ "typebox": "1.1.38" }, "bin": { - "pi-ai": "./dist/cli.js" + "pi-ai": "dist/cli.js" }, "engines": { "node": ">=22.19.0" From 4fe9f99ccb6257da887b42069a05ff3330c77aaa Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 22:04:42 -0700 Subject: [PATCH 41/43] fix(e2e): complete timeout evidence routing --- .github/workflows/portable-profile-e2e.yaml | 1 - test/e2e-runtime/brev-launchable-e2e.test.ts | 11 +++++++++++ ...portable-profile-rootless-runtime-workflow.test.ts | 2 +- .../security-posture-workflow-boundary.test.ts | 4 ---- tools/e2e/brev-launchable-e2e.sh | 3 ++- 5 files changed, 14 insertions(+), 7 deletions(-) diff --git a/.github/workflows/portable-profile-e2e.yaml b/.github/workflows/portable-profile-e2e.yaml index 904b82a9d48..968ae36f99c 100644 --- a/.github/workflows/portable-profile-e2e.yaml +++ b/.github/workflows/portable-profile-e2e.yaml @@ -21,7 +21,6 @@ on: - "src/lib/onboard/experimental/portable-retired-subnet-recovery.test.ts" - "test/e2e/live/portable-profile-rootless-linux.test.ts" - "test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts" - - "tools/e2e/full-e2e-timeout-contract.mts" push: branches: - main diff --git a/test/e2e-runtime/brev-launchable-e2e.test.ts b/test/e2e-runtime/brev-launchable-e2e.test.ts index 1768298a417..8d609250055 100644 --- a/test/e2e-runtime/brev-launchable-e2e.test.ts +++ b/test/e2e-runtime/brev-launchable-e2e.test.ts @@ -5,6 +5,7 @@ import fs from "node:fs"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { FULL_E2E_TEST_TIMEOUT_MINUTES } from "../../tools/e2e/full-e2e-timeout-contract.mts"; import { candidateSha, cleanupFixtures, @@ -28,6 +29,16 @@ function identitySmokeEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { } describe("focused staging Brev Launchable lane", () => { + it("keeps the staging SSH wrapper outside the full E2E deadline", () => { + const source = fs.readFileSync( + path.resolve(import.meta.dirname, "../../tools/e2e/brev-launchable-e2e.sh"), + "utf8", + ); + const defaultTimeout = source.match(/FULL_E2E_TIMEOUT_SECONDS:-([0-9]+)\}/u)?.[1]; + + expect(Number(defaultTimeout)).toBe(FULL_E2E_TEST_TIMEOUT_MINUTES * 60 + 300); + }); + it("runs the strict lane without inherited lane controls (#9925)", () => { vi.stubEnv("BREV_CREATE_RECONCILE_SECONDS", "0"); vi.stubEnv("NEMOCLAW_BREV_DEFER_CLEANUP", "1"); diff --git a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts index 0724246d027..479eff317f7 100644 --- a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts +++ b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts @@ -260,6 +260,7 @@ ${serviceIdentityCheck}`, expect(workflow.on.pull_request.types).toEqual(["opened", "synchronize", "reopened"]); expect(workflow.on.push.paths).toContain("tools/e2e/full-e2e-timeout-contract.mts"); + expect(workflow.on.pull_request.paths).not.toContain("tools/e2e/full-e2e-timeout-contract.mts"); expect(workflow.on.pull_request.paths).toEqual( expect.arrayContaining([ "src/lib/onboard/experimental/portable-host-preparation.ts", @@ -267,7 +268,6 @@ ${serviceIdentityCheck}`, "src/lib/onboard/experimental/portable-retired-subnet-recovery.test.ts", "test/e2e/live/portable-profile-rootless-linux.test.ts", "test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts", - "tools/e2e/full-e2e-timeout-contract.mts", ]), ); expect(job?.env?.E2E_SOURCE_REVISION).toBe(revisionExpression); diff --git a/test/e2e/support/security-posture-workflow-boundary.test.ts b/test/e2e/support/security-posture-workflow-boundary.test.ts index 61f75cbea92..d94139b653b 100644 --- a/test/e2e/support/security-posture-workflow-boundary.test.ts +++ b/test/e2e/support/security-posture-workflow-boundary.test.ts @@ -18,10 +18,6 @@ describe("security-posture catalogue boundary", () => { const openclaw = catalogueTarget("security-posture-openclaw"); const hermes = catalogueTarget("security-posture-hermes"); - expect(catalogueTarget("full-e2e").timeoutMinutes).toBe( - FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES, - ); - const target = ({ OpenClaw: openclaw, Hermes: hermes } as const)[scenario]!; expect(target).toMatchObject({ targetId: "security-posture", diff --git a/tools/e2e/brev-launchable-e2e.sh b/tools/e2e/brev-launchable-e2e.sh index 30f54965d24..1709f75a034 100755 --- a/tools/e2e/brev-launchable-e2e.sh +++ b/tools/e2e/brev-launchable-e2e.sh @@ -1000,7 +1000,8 @@ export NEMOCLAW_SANDBOX_NAME=e2e-staging ./node_modules/.bin/vitest run --project e2e-live test/e2e/live/full-e2e.test.ts --silent=false --reporter=default printf 'NEMOCLAW_FULL_E2E_PASSED\n' REMOTE -} | timeout "${FULL_E2E_TIMEOUT_SECONDS:-3000}" ssh -T -o ConnectTimeout=10 -o LogLevel=ERROR \ + # The wrapper adds five minutes for remote-shell and Vitest lifecycle overhead beyond the test. +} | timeout "${FULL_E2E_TIMEOUT_SECONDS:-4500}" ssh -T -o ConnectTimeout=10 -o LogLevel=ERROR \ "$INSTANCE_NAME" 'bash -s' >"$raw_log" 2>&1 e2e_status=$? set -e From 8e0f75b0d180060090a21fa1657eb185f478786c Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 8 Sep 2026 23:58:33 -0700 Subject: [PATCH 42/43] fix(e2e): validate provider retry evidence Signed-off-by: Prekshi Vyas --- test/e2e/live/launch-agent-turn.ts | 26 ++++++++++++------- ...launch-agent-turn-session-evidence.test.ts | 24 +++++++++++++++++ 2 files changed, 40 insertions(+), 10 deletions(-) diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index 559ea3e6768..b47af8c8eba 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -978,15 +978,16 @@ const providerAuthenticationError = function isStructuredProviderUnavailable(message) { const errorMessage = typeof message.errorMessage === "string" ? message.errorMessage.trim() : ""; + const validEmptyContent = JSON.stringify(message.content) === "[]"; const identity = [ message.role, - hasStructuredContent(message), + validEmptyContent, message.stopReason, message.api, message.provider, ].join("\n"); return ( - identity === "assistant\nfalse\nerror\nopenai-completions\ninference" && + identity === "assistant\ntrue\nerror\nopenai-completions\ninference" && typeof message.errorCode === "string" && providerUnavailableCodes.has(message.errorCode.trim()) && providerUnavailableError.test(errorMessage) && @@ -1052,20 +1053,25 @@ function qualifyTurns() { const { messages, sessionId } = changedSessions[0]; const expectedRoles = Array.from({ length: expectedTurns }, () => ["user", "assistant"]).flat(); + const providerUnavailableIndex = messages.findIndex((message) => message.providerUnavailable); for (const [index, message] of messages.entries()) { - if (index >= expectedRoles.length) finish(2, "extra_message", { sessionId }); + if (index >= expectedRoles.length || (providerUnavailableIndex !== -1 && index > providerUnavailableIndex)) { + const reason = index >= expectedRoles.length ? "extra_message" : "message_after_provider_unavailable"; + finish(2, reason, { sessionId }); + } if (message.role !== expectedRoles[index]) { finish(2, "message_order_invalid", { sessionId }); } - if (!message.hasStructuredContent) { - const emptyStatus = message.providerUnavailable ? 3 : 2; - const emptyReason = message.providerUnavailable - ? "provider_unavailable" - : "message_content_empty"; - finish(emptyStatus, emptyReason, { sessionId }); + if (!message.hasStructuredContent && !message.providerUnavailable) { + finish(2, "message_content_empty", { sessionId }); } } - if (messages.length < expectedRoles.length) finish(1); + const providerUnavailable = providerUnavailableIndex !== -1; + if (providerUnavailable || messages.length < expectedRoles.length) { + finish(providerUnavailable ? 3 : 1, providerUnavailable ? "provider_unavailable" : undefined, { + sessionId, + }); + } finish(0); } diff --git a/test/e2e/support/launch-agent-turn-session-evidence.test.ts b/test/e2e/support/launch-agent-turn-session-evidence.test.ts index 624d5ff1137..5cc3f1eb0cd 100644 --- a/test/e2e/support/launch-agent-turn-session-evidence.test.ts +++ b/test/e2e/support/launch-agent-turn-session-evidence.test.ts @@ -258,6 +258,30 @@ it("does not qualify structured turns recorded before the baseline (#9160)", () expect(qualification.status).toBe(1); }); +it.each([ + { content: undefined, contentShape: "missing" }, + { content: null, contentShape: "null" }, + { content: {}, contentShape: "object-valued" }, +])("rejects a provider error with $contentShape content (#10978)", ({ content }) => { + const after = { + "session-a": [message("user"), providerUnavailableMessage({ content })], + }; + const { baseline, qualification } = runEvidenceFixture({ after, expectedTurns: 1 }); + + expect(baseline.status).toBe(0); + expect(qualification.status).toBe(2); +}); + +it("rejects a provider error when later messages are appended (#10978)", () => { + const after = { + "session-a": [message("user"), providerUnavailableMessage(), message("assistant")], + }; + const { baseline, qualification } = runEvidenceFixture({ after, expectedTurns: 1 }); + + expect(baseline.status).toBe(0); + expect(qualification.status).toBe(2); +}); + it.each<{ after: SessionRecords; status: number }>([ { after: { "session-a": [message("assistant"), message("user")] }, status: 2 }, { From 49e86588c9ee1146e525b9e597355fb05b8269d9 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 9 Sep 2026 01:22:58 -0700 Subject: [PATCH 43/43] fix(e2e): preserve fail-closed provider retries Signed-off-by: Prekshi Vyas --- test/e2e/live/launch-agent-turn.ts | 25 +++++++++++++------ ...launch-agent-turn-session-evidence.test.ts | 11 ++++++++ test/e2e/support/launch-agent-turn.test.ts | 22 ++++++++-------- 3 files changed, 38 insertions(+), 20 deletions(-) diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index b47af8c8eba..db2a8a99a45 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -973,8 +973,8 @@ function hasStructuredContent(message) { const providerUnavailableCodes = new Set(["500", "502", "503", "504", "529"]); const providerUnavailableError = /^(?:litellm\.)?(?:InternalServerError|ServiceUnavailableError)(?::|$)/; -const providerAuthenticationError = - /(?:authenticat|authori[sz]|unauthori[sz]ed|forbidden|invalid (?:api )?key|credential)/i; +const providerNonRetryableError = + /(?:authenticat|authori[sz]|unauthori[sz]ed|forbidden|invalid (?:api )?key|credential|\b(?:policy|permission)\b|\b(?:denied|blocked|prohibited)\b)/i; function isStructuredProviderUnavailable(message) { const errorMessage = typeof message.errorMessage === "string" ? message.errorMessage.trim() : ""; @@ -991,7 +991,7 @@ function isStructuredProviderUnavailable(message) { typeof message.errorCode === "string" && providerUnavailableCodes.has(message.errorCode.trim()) && providerUnavailableError.test(errorMessage) && - !providerAuthenticationError.test(errorMessage) + !providerNonRetryableError.test(errorMessage) ); } @@ -1189,6 +1189,11 @@ fail_launch_session() { exit 1 } +fail_provider_unavailable() { + provider_unavailable_candidate=1 + fail_launch_session "launch did not record the required structured session turns" +} + session_evidence() { local mode="$1" local expected_turns="" @@ -1220,7 +1225,11 @@ session_evidence() { wait_for_turn_count() { local expected_turns="$1" local evidence_status + local session_active while (( SECONDS < session_deadline )); do + # Sample liveness first so an exited child receives one final evidence qualification. + session_active=1 + kill -0 "$session_pid" 2>/dev/null || session_active=0 if session_evidence qualify "$expected_turns" >/dev/null 2>"$evidence_error"; then return 0 else @@ -1228,15 +1237,12 @@ wait_for_turn_count() { fi if [[ "$evidence_status" != 1 ]]; then case "$evidence_status" in - 3) - provider_unavailable_candidate=1 - fail_launch_session "launch did not record the required structured session turns" - ;; + 3) fail_provider_unavailable ;; esac fail_launch_session \ "structured session evidence was invalid or unavailable (status $evidence_status)" fi - if ! kill -0 "$session_pid" 2>/dev/null; then + if [[ "$session_active" != 1 ]]; then break fi sleep 1 @@ -1383,6 +1389,9 @@ if session_evidence qualify 2 >/dev/null 2>"$evidence_error"; then : else evidence_status=$? + case "$evidence_status" in + 3) fail_provider_unavailable ;; + esac fail_launch_session "launch final structured session evidence did not qualify (status $evidence_status)" fi if ! remove_session_baseline >/dev/null 2>"$evidence_error"; then diff --git a/test/e2e/support/launch-agent-turn-session-evidence.test.ts b/test/e2e/support/launch-agent-turn-session-evidence.test.ts index 5cc3f1eb0cd..9fdfe3ee785 100644 --- a/test/e2e/support/launch-agent-turn-session-evidence.test.ts +++ b/test/e2e/support/launch-agent-turn-session-evidence.test.ts @@ -322,6 +322,17 @@ it.each<{ after: SessionRecords; status: number }>([ }, status: 2, }, + { + after: { + "session-a": [ + message("user"), + providerUnavailableMessage({ + errorMessage: "litellm.ServiceUnavailableError: network policy denied", + }), + ], + }, + status: 2, + }, { after: { "session-a": [message("user"), providerUnavailableMessage({ errorCode: "400" })], diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index b411e4923de..651aed844f9 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -56,14 +56,9 @@ type FixtureMode = | "pty-socket-timeout" | "pty-path-unreadable" | "pty-termios-unavailable" - | "provider-cleanup-failure" - | "provider-empty-message" - | "provider-terminal-spoof" - | "provider-wrong-api" - | "provider-wrong-route" - | "recording-timeout" - | "restored-canonical-timeout" - | "valid"; + | "provider-cleanup-failure" | "provider-empty-message" | "provider-exit-after-recording" + | "provider-terminal-spoof" | "provider-wrong-api" | "provider-wrong-route" + | "recording-timeout" | "restored-canonical-timeout" | "valid"; interface LaunchFixtureInvocation { args: string[]; @@ -166,6 +161,7 @@ const net = require("node:net"); const readline = require("node:readline"); const mode = process.env.NEMOCLAW_FIXTURE_MODE; +const exitWithStatus = process.exit.bind(process); if (process.argv[2] !== "tui") { const allowedNames = new Set(${JSON.stringify(SUBPROCESS_ENV_ALLOWED_NAMES)}); const allowedPrefixes = ${JSON.stringify(SUBPROCESS_ENV_ALLOWED_PREFIXES)}; @@ -360,7 +356,7 @@ if (process.argv[2] !== "tui") { } if (terminalCopy === "reordered") process.stdout.write("idle | gateway connected\n"); - if (mode === "delayed-recording") { + if (mode === "delayed-recording" || mode === "provider-exit-after-recording") { const publicationDeadline = Date.now() + 2_000; while (!fs.existsSync(process.env.NEMOCLAW_FIXTURE_PENDING_QUALIFICATION_MARKER)) { if (Date.now() >= publicationDeadline) process.exit(68); @@ -371,9 +367,10 @@ if (process.argv[2] !== "tui") { if (mode === "invalid-order") { append("assistant", "response before input"); append("user", firstInput); - } else if (mode === "provider-empty-message" || mode === "provider-cleanup-failure") { + } else if (mode === "provider-empty-message" || mode === "provider-cleanup-failure" || mode === "provider-exit-after-recording") { append("user", firstInput); appendProviderError(); + new Map([["provider-exit-after-recording", () => exitWithStatus(23)]]).get(mode)?.(); } else if (mode === "provider-terminal-spoof") { append("user", firstInput); appendProviderError({ errorCode: "400" }); @@ -456,12 +453,13 @@ fi if [[ "$NEMOCLAW_FIXTURE_MODE" == "pty-socket-timeout" && "$4" == "$NEMOCLAW_FIXTURE_RUN_ID" ]]; then exec node -e 'setTimeout(() => process.exit(0), 10_000)' fi -if [[ "$NEMOCLAW_FIXTURE_MODE" == "delayed-recording" && "$4" == "qualify" && "$7" == "1" ]]; then +if [[ ( "$NEMOCLAW_FIXTURE_MODE" == "delayed-recording" || "$NEMOCLAW_FIXTURE_MODE" == "provider-exit-after-recording" ) && "$4" == "qualify" && "$7" == "1" ]]; then set +e "$@" status=$? set -e [[ "$status" != "1" ]] || : > "$NEMOCLAW_FIXTURE_PENDING_QUALIFICATION_MARKER" + [[ "$NEMOCLAW_FIXTURE_MODE" != "provider-exit-after-recording" ]] || sleep 0.2 exit "$status" fi exec "$@" @@ -1077,7 +1075,7 @@ it.runIf(process.platform === "linux").each([ options?: { artifactName?: string; env?: NodeJS.ProcessEnv }, ) => { const fixture = runLaunchSessionFixture( - calls.length === 0 ? "provider-empty-message" : secondMode, + calls.length === 0 ? "provider-exit-after-recording" : secondMode, calls.length === 0 ? "provider" : secondTerminal, { args,