diff --git a/.github/workflows/platform-vitest-main.yaml b/.github/workflows/platform-vitest-main.yaml index 7a00d21c510..982bf26a462 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: 60 + # The live E2E has a 70m timeout; every other step shares the remaining job time. + timeout_minutes: 150 - shard: 2 timeout_minutes: 30 - shard: 3 @@ -192,9 +193,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/.github/workflows/portable-profile-e2e.yaml b/.github/workflows/portable-profile-e2e.yaml index 7c6900ee7b3..968ae36f99c 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 @@ -155,7 +156,8 @@ jobs: portable-launch: if: ${{ github.ref == 'refs/heads/main' }} runs-on: ubuntu-26.04 - timeout-minutes: 75 + # The live E2E has a 70m timeout; every other step shares the remaining job time. + timeout-minutes: 135 env: E2E_JOB: "1" E2E_TARGET_ID: portable-launch 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/automation/e2e/platform-vitest-main-workflow.test.ts b/test/automation/e2e/platform-vitest-main-workflow.test.ts index af34e3416ae..63c4dc12a5f 100644 --- a/test/automation/e2e/platform-vitest-main-workflow.test.ts +++ b/test/automation/e2e/platform-vitest-main-workflow.test.ts @@ -49,12 +49,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(150); + }); }); 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/README.md b/test/e2e/README.md index 6109cffd242..364c00f09cd 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -240,7 +240,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 60-minute budget for live E2E; 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. @@ -497,11 +499,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/docs/README.md b/test/e2e/docs/README.md index 73083a156ca..26a959eb285 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 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. Otherwise, those live tests skip and the platform contracts remain as evidence. diff --git a/test/e2e/live/full-e2e.test.ts b/test/e2e/live/full-e2e.test.ts index 8b95a7f186c..22eb26fa1d8 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"; import { parseOpenClawJsonDocuments } from "../../../src/lib/openclaw/agent-json-provenance.ts"; const SANDBOX_NAME = process.env.NEMOCLAW_SANDBOX_NAME ?? "e2e-full"; @@ -57,7 +58,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(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/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index 9519aea10e2..db2a8a99a45 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -3,11 +3,38 @@ 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 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 = + "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_FAILURE_PREFIX) && + result.stderr.endsWith(`\n${finalMarker}`) + ); +} + 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 -- "$@"'; @@ -466,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"); @@ -944,6 +971,30 @@ function hasStructuredContent(message) { return Array.isArray(message.content) && message.content.length > 0; } +const providerUnavailableCodes = new Set(["500", "502", "503", "504", "529"]); +const providerUnavailableError = /^(?:litellm\.)?(?:InternalServerError|ServiceUnavailableError)(?::|$)/; +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() : ""; + const validEmptyContent = JSON.stringify(message.content) === "[]"; + const identity = [ + message.role, + validEmptyContent, + message.stopReason, + message.api, + message.provider, + ].join("\n"); + return ( + identity === "assistant\ntrue\nerror\nopenai-completions\ninference" && + typeof message.errorCode === "string" && + providerUnavailableCodes.has(message.errorCode.trim()) && + providerUnavailableError.test(errorMessage) && + !providerNonRetryableError.test(errorMessage) + ); +} + function appendedMessages(fileName, baseline) { const { offset, complete, raw } = readCompleteSession(fileName); const prior = baseline[fileName]; @@ -968,7 +1019,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; } @@ -998,14 +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) finish(2, "message_content_empty", { sessionId }); + if (!message.hasStructuredContent && !message.providerUnavailable) { + finish(2, "message_content_empty", { sessionId }); + } + } + const providerUnavailable = providerUnavailableIndex !== -1; + if (providerUnavailable || messages.length < expectedRoles.length) { + finish(providerUnavailable ? 3 : 1, providerUnavailable ? "provider_unavailable" : undefined, { + sessionId, + }); } - if (messages.length < expectedRoles.length) finish(1); finish(0); } @@ -1049,6 +1115,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 @@ -1093,6 +1160,9 @@ cleanup() { cleanup_status=1 fi if [[ "$original_status" != 0 ]]; then + case "$provider_unavailable_candidate:$cleanup_status" in + 1:0) printf '\n%s\n' "${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:$NEMOCLAW_LAUNCH_RUN_ID" >&2 ;; + esac exit "$original_status" fi exit "$cleanup_status" @@ -1119,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="" @@ -1150,16 +1225,24 @@ 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 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 + 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 @@ -1306,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 @@ -1346,35 +1432,52 @@ 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 runId = randomUUID().replaceAll("-", ""); + 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: runId, + 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: OPENCLAW_LAUNCH_SESSION_TIMEOUT_MS, + }); + if (result.exitCode === 0) return result; + finalFailure = result; + providerUnavailable = isTransientProviderAvailabilityFailure(result, runId); + if (!providerUnavailable) break; + if (attempt < OPENCLAW_LAUNCH_PROVIDER_ATTEMPTS) { + await delay(OPENCLAW_LAUNCH_PROVIDER_RETRY_DELAY_MS); + } } - 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( @@ -1387,7 +1490,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/mock-parity.json b/test/e2e/mock-parity.json index f70ad0bfa11..b92ae6ab466 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -159,12 +159,14 @@ "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/runtime/sandbox/sandbox-provisioning.test.ts", "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", @@ -175,10 +177,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" ] 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..f7c73cc1fea --- /dev/null +++ b/test/e2e/support/launch-agent-turn-provider-availability.test.ts @@ -0,0 +1,146 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { expect, it, vi } from "vitest"; +import { + OPENCLAW_PROVIDER_UNAVAILABLE_MARKER, + 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.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(); + } + }, +); + +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; env?: NodeJS.ProcessEnv }, + ) => { + 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"}\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${options?.env?.NEMOCLAW_LAUNCH_RUN_ID}\n`, + stdout: "", + }; + }, + openshellCommandPath: "/usr/bin/openshell", + }; + + try { + 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(); + } +}); + +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"}`, + ], + [ + "authentication failure", + `${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`, + ], + [ + "cleanup failure", + "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"], +])("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(); + } +}); 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..9fdfe3ee785 --- /dev/null +++ b/test/e2e/support/launch-agent-turn-session-evidence.test.ts @@ -0,0 +1,377 @@ +// 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 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, + 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([ + { 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 }, + { + 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: "500" })], + }, + status: 3, + }, + { + after: { + "session-a": [ + message("user"), + providerUnavailableMessage({ + errorMessage: "litellm.AuthenticationError: invalid API key", + }), + ], + }, + status: 2, + }, + { + after: { + "session-a": [ + message("user"), + providerUnavailableMessage({ + errorMessage: "litellm.ServiceUnavailableError: network policy denied", + }), + ], + }, + status: 2, + }, + { + 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(status); + }, +); + +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 ff96afb4a73..651aed844f9 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"; @@ -35,15 +27,17 @@ 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_PROVIDER_UNAVAILABLE_MARKER, OPENCLAW_PTY_MONITOR_STARTER_SCRIPT, OPENCLAW_SESSION_EVIDENCE_SCRIPT, runOpenClawLaunchSession, 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" @@ -62,180 +56,14 @@ type FixtureMode = | "pty-socket-timeout" | "pty-path-unreadable" | "pty-termios-unavailable" - | "recording-timeout" - | "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 }); - } + | "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[]; + command: string; + env?: NodeJS.ProcessEnv; } it("reports a residual PTY monitor socket without removing it (#9384)", async () => { @@ -278,7 +106,11 @@ 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" | "provider" | "reordered", + invocation?: LaunchFixtureInvocation, +) { const fixtureRoot = mkdtempSync(join(tmpdir(), "nemoclaw-launch-turn-")); const canonicalRestoredMarker = join(fixtureRoot, "canonical-restored"); const earlyInputMarker = join(fixtureRoot, "early-input"); @@ -293,7 +125,8 @@ function runLaunchSessionFixture(mode: FixtureMode, terminalCopy: "absent" | "an 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); @@ -328,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)}; @@ -468,6 +302,23 @@ if (process.argv[2] !== "tui") { sessionFile, JSON.stringify({ message: { content: [{ text: content, type: "text" }], role }, type: "message" }) + "\n", ); + const appendProviderError = (overrides = {}) => fs.appendFileSync( + sessionFile, + JSON.stringify({ + message: { + api: "openai-completions", + content: [], + 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", + stopReason: "error", + ...overrides, + }, + type: "message", + }) + "\n", + ); if (mode === "restored-canonical-timeout") { process.stdin.setRawMode(true); await new Promise((resolve) => setTimeout(resolve, 750)); @@ -497,10 +348,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[2Kgateway connected | idle\r"); + if (terminalCopy === "ansi") process.stdout.write("\u001b[2KServiceUnavailableError\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 === "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); @@ -511,6 +367,19 @@ 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" || 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" }); + } 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"); @@ -575,7 +444,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 @@ -584,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 "$@" @@ -609,11 +479,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, @@ -630,29 +503,30 @@ 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_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_SANDBOX: invocationEnv.NEMOCLAW_LAUNCH_SANDBOX ?? "sandbox", + NEMOCLAW_LAUNCH_SESSION_BUDGET_SECONDS: + mode === "restored-canonical-timeout" + ? "10" + : mode === "pty-socket-timeout" + ? "5" + : mode.endsWith("-timeout") + ? "2" + : (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, }); @@ -854,93 +728,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) => { @@ -1248,19 +1035,226 @@ it.runIf(process.platform === "linux")( ); it.runIf(process.platform === "linux")( - "reports missing structured turns before the PTY child timeout (#9160)", + "marks provider unavailability when it leaves an empty structured turn (#9160, #10978)", () => { const { baselineRemoved, result, ttyObserved } = runLaunchSessionFixture( - "recording-timeout", - "absent", + "provider-empty-message", + "provider", ); 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"); + }, +); + +it.runIf(process.platform === "linux").each([ + ["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 $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; + runId?: string; + stderr: string; + }> = []; + const host = { + command: async ( + command: string, + args: string[], + options?: { artifactName?: string; env?: NodeJS.ProcessEnv }, + ) => { + const fixture = runLaunchSessionFixture( + calls.length === 0 ? "provider-exit-after-recording" : secondMode, + calls.length === 0 ? "provider" : secondTerminal, + { + 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, + 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-handoff", + cliCommand: "openclaw", + env: {}, + exitCommand: "/exit", + host: host as never, + redactionValues: [], + sandboxName: "alpha", + }); + await vi.advanceTimersByTimeAsync(1_000); + 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", + ]); + expect(new Set(calls.map((call) => call.runId)).size).toBe(2); + expect(new Set(calls.map((call) => call.firstInput)).size).toBe(2); + 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(expectedError !== null); + } finally { + vi.useRealTimers(); + } + }, + 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).not.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")( + "does not retry when terminal output mimics provider unavailability (#10978)", + async () => { + const produced = runLaunchSessionFixture("provider-terminal-spoof", "provider").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-terminal-spoof-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([ + { mismatch: "API", mode: "provider-wrong-api" }, + { mismatch: "route", mode: "provider-wrong-route" }, +] as const)( + "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, + 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("ServiceUnavailableError"); + expect(firstResult.stderr).not.toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); + await expect( + runOpenClawLaunchSession({ + artifactName: "producer-identity-mismatch-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")( + "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")( @@ -1455,7 +1449,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", 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 5809e004755..479eff317f7 100644 --- a/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts +++ b/test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts @@ -259,6 +259,8 @@ ${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).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", @@ -274,6 +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(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/security-posture-workflow-boundary.test.ts b/test/e2e/support/security-posture-workflow-boundary.test.ts index 907d83d49b4..d94139b653b 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_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { catalogueTarget, E2E_TARGET_CATALOGUE, @@ -33,6 +34,7 @@ describe("security-posture catalogue boundary", () => { expect(openclaw).toMatchObject({ shard: "openclaw", testFile: "test/e2e/live/full-e2e.test.ts", + 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..30cddbe864c 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,17 @@ describe("standard E2E execution profile", () => { expect(validateStandardProfileWorkflowBoundary(readWorkflow())).toEqual([]); }); + it("reserves the standard full-E2E setup, test, and artifact envelope", () => { + 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/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/test/helpers/vitest-watch-triggers.ts b/test/helpers/vitest-watch-triggers.ts index efcf098760c..639aa5656cb 100644 --- a/test/helpers/vitest-watch-triggers.ts +++ b/test/helpers/vitest-watch-triggers.ts @@ -375,6 +375,15 @@ 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/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", + ), + }, { 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 bc44a83d6a4..280a6ced6d0 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", @@ -366,6 +367,12 @@ 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/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", + ]); 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/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 diff --git a/tools/e2e/full-e2e-timeout-contract.mts b/tools/e2e/full-e2e-timeout-contract.mts new file mode 100644 index 00000000000..e488231d6aa --- /dev/null +++ b/tools/e2e/full-e2e-timeout-contract.mts @@ -0,0 +1,13 @@ +// 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_STANDARD_PROFILE_PRE_TEST_MINUTES = 30; +export const FULL_E2E_STANDARD_PROFILE_POST_TEST_MINUTES = 15; + +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; diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index a9cb9f0b9de..2758062d844 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_STANDARD_PROFILE_JOB_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: 75, + timeoutMinutes: FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES, installMode: "authenticated", restoreCli: true, exposeCliBin: true, @@ -744,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, @@ -1308,13 +1310,14 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ profile: "nvidia-inference", prAdvisorSelectable: true, testFile: "test/e2e/live/full-e2e.test.ts", - timeoutMinutes: 75, + timeoutMinutes: FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES, installMode: "credential-free", installNonInteractive: true, restoreCli: true, exposeCliBin: true, shard: "openclaw", artifactLayout: "flat-shard", + owningPaths: ["tools/e2e/full-e2e-timeout-contract.mts"], environment: { ...hostedInference, ...nonInteractive,