Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
82926df
fix(sandbox): retry forward start through OpenShell's readiness handoff
gaveezy Aug 31, 2026
255429e
chore(sandbox): format added forward-recovery tests
gaveezy Aug 31, 2026
58bad8f
merge: refresh PR #10675 from main
apurvvkumaria Aug 31, 2026
1dfe96d
fix(sandbox): harden forward readiness recovery
apurvvkumaria Aug 31, 2026
57444a2
merge: refresh PR #10675 from main
apurvvkumaria Aug 31, 2026
d8584a4
test(sandbox): cover classified forward recovery failure
apurvvkumaria Aug 31, 2026
f3df51e
fix(sandbox): tailor forward recovery guidance
apurvvkumaria Aug 31, 2026
8521d52
merge: refresh PR #10675 from main
apurvvkumaria Aug 31, 2026
0b863f1
test(sandbox): name forward recovery guidance directly
apurvvkumaria Aug 31, 2026
8785d95
fix(sandbox): use supported readiness command
apurvvkumaria Aug 31, 2026
9d058f5
merge: refresh PR #10675 from main
apurvvkumaria Aug 31, 2026
4e5be89
fix(sandbox): clarify forward readiness recovery
apurvvkumaria Aug 31, 2026
bf34fda
fix(sandbox): scope forward recovery diagnostics
apurvvkumaria Aug 31, 2026
36171ee
fix(sandbox): secure forward recovery resources
apurvvkumaria Aug 31, 2026
97b4934
test(sandbox): expect gateway-scoped recovery
apurvvkumaria Aug 31, 2026
d2e8bf8
fix(sandbox): report forward ownership failures
apurvvkumaria Aug 31, 2026
79d9540
test(sandbox): expect scoped recovery guidance
apurvvkumaria Aug 31, 2026
d59b3e4
test(sandbox): expect scoped recovery commands
apurvvkumaria Aug 31, 2026
5299b82
merge: sync main into fix/10640-stop-start-dashboard-forward
apurvvkumaria Aug 31, 2026
bbf3f3e
fix(sandbox): scope auxiliary recovery guidance
apurvvkumaria Aug 31, 2026
3177dff
test(sandbox): expect auxiliary recovery scope
apurvvkumaria Aug 31, 2026
e5aadae
merge: sync main into fix/10640-stop-start-dashboard-forward
apurvvkumaria Aug 31, 2026
814e25f
merge: resolve conflicts with main
github-actions[bot] Sep 1, 2026
5f4212f
merge: sync main into fix/10640-stop-start-dashboard-forward
apurvvkumaria Sep 1, 2026
8983034
test(sandbox): use synthetic remote-bind fixture
apurvvkumaria Sep 1, 2026
b449645
merge: sync main into fix/10640-stop-start-dashboard-forward
apurvvkumaria Sep 1, 2026
142b922
test(sandbox): remove shipped Dockerfile test coupling
apurvvkumaria Sep 1, 2026
2d2c0bf
merge: resolve conflicts with main
github-actions[bot] Sep 3, 2026
e566b38
merge: resolve conflicts with main
github-actions[bot] Sep 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ci/source-architecture-budget.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"src/lib/actions/sandbox/connect.ts": 43,
"src/lib/actions/sandbox/destroy.ts": 29,
"src/lib/actions/sandbox/doctor.ts": 27,
"src/lib/actions/sandbox/forward-recovery.ts": 21,
"src/lib/actions/sandbox/gateway-state.ts": 21,
"src/lib/actions/sandbox/status-snapshot.ts": 19,
"src/lib/actions/sandbox/policy-channel.ts": 30,
Expand Down
99 changes: 99 additions & 0 deletions src/lib/actions/sandbox/connect-forward-recovery-guidance.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest";

import { createConnectHarness } from "../../../../test/support/connect-flow-test-harness";

describe("connect forward recovery guidance", () => {
let exitSpy: MockInstance;

beforeEach(() => {
vi.stubEnv("NEMOCLAW_TEST_NO_SLEEP", "1");
exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number | string | null) => {
throw new Error(`process.exit(${code ?? 0})`);
}) as never);
});

afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
});

it.each([
[
"readiness retry exhaustion",
"forward-readiness-retry-limit",
"openshell sandbox status alpha` reports Ready",
false,
],
[
"port ownership conflict",
"port-ownership-conflict",
"identify the current owner of port 18789 before you change either sandbox",
false,
],
[
"unavailable forward state",
"forward-state-unavailable",
"After OpenShell reports forward state",
false,
],
[
"unverified forward ownership",
"forward-ownership-unverified",
"confirm that 'alpha' owns port 18789",
false,
],
[
"listener retry exhaustion",
"forward-listener-retry-limit",
"If port 18789 has no owner",
true,
],
[
"rejected forward start",
"forward-start-failure",
"to read the OpenShell error. Correct the error",
true,
],
] as const)(
"gives safe guidance for %s (#10640)",
async (_caseName, reason, expectedGuidance, includesManualStart) => {
const processCheck = {
checked: true,
wasRunning: true,
recovered: false,
forwardRecovered: false,
forwardRecoveryFailed: true,
forwardRecoveryFailureDetail: `classified ${reason}`,
};
const harness = createConnectHarness({ processCheck });
harness.checkAndRecoverSpy.mockImplementation((_sandboxName: unknown, options: unknown) => {
(
options as {
onForwardRecoveryFailure?: (failure: {
port: number;
reason: typeof reason;
sandboxName: string;
}) => void;
}
).onForwardRecoveryFailure?.({ port: 18789, reason, sandboxName: "alpha" });
return processCheck;
});

await expect(harness.connectSandbox("alpha", { probeOnly: true })).rejects.toThrow(
"process.exit(1)",
);

const errorOutput = harness.errorSpy.mock.calls
.map((call) => String(call[0] ?? ""))
.join("\n");
expect(errorOutput).toContain(expectedGuidance);
expect(errorOutput.includes("openshell forward start --background 18789 alpha")).toBe(
includesManualStart,
);
expect(exitSpy).toHaveBeenCalledWith(1);
},
);
});
17 changes: 10 additions & 7 deletions src/lib/actions/sandbox/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,15 @@ import {
type HermesPortableForwardRecoveryFailure,
type HermesPortableForwardRecoveryTimingEvidence,
type ManagedGatewayControlCompletion,
primaryForwardRecoveryGuidance,
prepareHermesPortableLaunchForwards,
verifyHermesPortableLaunchForwards,
type PreparedHermesPortableForwardRecovery,
resolveSandboxDashboardPort,
resolveSandboxLaunchForwardPorts,
waitForManagedGatewaySupervisor,
} from "./process-recovery";
import type { SandboxForwardRecoveryFailureReason } from "./forward-recovery";
import {
classifyHermesPortableInferenceConnectRecoveryFailure,
inspectHermesPortableInferenceReadinessRuntimeForConnectProbe,
Expand Down Expand Up @@ -276,14 +278,13 @@ function exitOnForwardRecoveryFailure(
agentName: string,
port: number,
detail?: string,
reason?: SandboxForwardRecoveryFailureReason,
): never {
console.error("");
console.error(
` Probe failed: ${agentName} gateway is running in '${sandboxName}', but ${detail ?? "the dashboard/API host forward could not be restored"}.`,
);
console.error(
` Run \`openshell forward start --background ${port} ${sandboxName}\` manually and re-run \`nemoclaw ${sandboxName} recover\`.`,
);
console.error(` ${primaryForwardRecoveryGuidance(sandboxName, port, reason)}`);
process.exit(1);
}

Expand Down Expand Up @@ -392,10 +393,14 @@ async function runSandboxConnectProbe(
// Managed recovery runs quiet here, so its classified failure layer is the
// only way this path can tell a retryable wedge apart from a deterministic
// integrity refusal that no restart, recover, or connect can clear (#7801).
let forwardRecoveryFailureReason: SandboxForwardRecoveryFailureReason | undefined;
let recoveryFailureLayer: GatewayRestartFailureLayer | null = null;
const processCheck = checkAndRecoverSandboxProcesses(sandboxName, {
quiet: true,
probeTiming,
onForwardRecoveryFailure: (failure) => {
forwardRecoveryFailureReason = failure.reason;
},
onRecoveryFailureLayer: (layer) => {
recoveryFailureLayer = layer;
},
Expand Down Expand Up @@ -426,6 +431,7 @@ async function runSandboxConnectProbe(
agentName,
resolveSandboxDashboardPort(sandboxName),
detail,
forwardRecoveryFailureReason,
);
}
if ("recoveryFailureDetail" in processCheck && processCheck.recoveryFailureDetail) {
Expand Down Expand Up @@ -2238,10 +2244,7 @@ async function prepareConnectSandboxWithinLifecycleFence(
let initialPortableAuthority: ReturnType<typeof qualifyPortableAgentLifecycleAuthority>;
try {
initialPortableAuthority = probeTiming!.measure("authority", () =>
qualifyPortableAgentLifecycleAuthority(
sandboxName,
portableAgentLifecycleAuthorityDeps(),
),
qualifyPortableAgentLifecycleAuthority(sandboxName, portableAgentLifecycleAuthorityDeps()),
);
} catch {
probeTiming!.markFailureStage("authority");
Expand Down
76 changes: 62 additions & 14 deletions src/lib/actions/sandbox/forward-recovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
waitForForwardRecoveryState,
waitForStoppedForwardPortRelease,
} from "../../onboard/forward-cleanup";
import { runBackgroundForwardStartWithReadinessRetry } from "../../onboard/forward-start";
import {
resolveSandboxHermesApiPort,
retargetHermesApiPortInUrl,
Expand Down Expand Up @@ -67,10 +68,25 @@ type SandboxPortDeps = {
getSessionAgent?: (sandboxName?: string) => SandboxPortAgent;
};

export type SandboxForwardRecoveryFailureReason =
| "forward-listener-retry-limit"
| "forward-ownership-unverified"
| "forward-readiness-retry-limit"
| "forward-start-failure"
| "forward-state-unavailable"
| "port-ownership-conflict";

export type SandboxForwardRecoveryFailure = {
readonly port: number;
readonly reason: SandboxForwardRecoveryFailureReason;
readonly sandboxName: string;
};

type SandboxForwardRecoveryOptions = {
afterSuccess?: () => boolean;
beforeStart?: () => boolean;
isWsl?: boolean;
onFailure?: (failure: SandboxForwardRecoveryFailure) => void;
};

type DashboardForwardStopRunner = (
Expand Down Expand Up @@ -209,6 +225,7 @@ export function ensureSandboxPortForward(
forceRestart: remoteBindRequested,
expectedBind: allInterfaceBindRequired ? "0.0.0.0" : "127.0.0.1",
afterSuccess: options.afterSuccess,
onFailure: options.onFailure,
beforeStart: () =>
(!remoteBindRequested ||
registry.getSandbox(sandboxName)?.dashboardRemoteBindPrepared === true) &&
Expand Down Expand Up @@ -273,6 +290,8 @@ export function ensureSandboxPortForwardForPort(
forceRestart?: boolean;
expectedBind?: string;
beforeStart?: () => boolean;
onFailure?: (failure: SandboxForwardRecoveryFailure) => void;
sleepMs?: (milliseconds: number) => void;
} = {},
): boolean {
const {
Expand Down Expand Up @@ -350,33 +369,62 @@ export function ensureSandboxPortForwardForPort(
}

if (!beforeStart()) return false;
const startResult = runOpenshell(
["forward", "start", "--background", forwardTarget, sandboxName],
{
ignoreError: true,
// OpenShell 0.0.85 leaves the background SSH forward attached to the
// caller's inherited descriptors. Detach them so a scripted `recover`
// can finish after the foreground OpenShell command exits. Keep this
// until every supported OpenShell release redirects those descriptors.
stdio: "ignore",
// After a sandbox restart, OpenShell can reject `forward start` during its
// readiness handoff. Before #7227, the retained host listener hid this
// rejection. Recovery retries the recognized transient diagnostic and fails
// closed when another sandbox owns the port.
let retryHealth: SandboxForwardHealth = forwardHealth;
const startResult = runBackgroundForwardStartWithReadinessRetry({
runForwardStart: (stdio) =>
runOpenshell(["forward", "start", "--background", forwardTarget, sandboxName], {
ignoreError: true,
stdio,
}),
isListenerReachable: () => isLocalForwardReachable(port),
isRetryAllowed: () => {
retryHealth = isSandboxPortForwardHealthy(sandboxName, port, expectedBind);
return retryHealth === false;
},
);
...(options.sleepMs ? { sleepMs: options.sleepMs } : {}),
});

const reportStartFailure = (health: SandboxForwardHealth): false => {
let reason: SandboxForwardRecoveryFailureReason;
if (health === "occupied") {
reason = "port-ownership-conflict";
} else if (health === null) {
reason = "forward-state-unavailable";
} else if (startResult.failureReason === "readiness-retry-limit") {
reason = "forward-readiness-retry-limit";
} else if (startResult.failureReason === "listener-retry-limit") {
reason = "forward-listener-retry-limit";
} else if (startResult.status === 0 || startResult.failureReason === "listener-reachable") {
reason = "forward-ownership-unverified";
} else {
reason = "forward-start-failure";
}
options.onFailure?.({ port, reason, sandboxName });
return false;
};

// OpenShell 0.0.85 returns an error when start preflight finds a validated
// live forward for the requested port. Recovery cannot change that upstream
// CLI contract, so a reachable listener settles against the authoritative
// forward list below; an absent listener still fails fast. Remove this
// tolerance once every supported OpenShell release makes `forward start`
// idempotent for an already-tracked live forward.
if (startResult.status !== 0 && !isLocalForwardReachable(port)) return false;
if (startResult.status !== 0 && !isLocalForwardReachable(port)) {
return reportStartFailure(retryHealth);
}

// `forward start --background` can return before its authoritative list
// entry becomes visible. Poll for the exact live sandbox+port owner instead
// of accepting an arbitrary reachable listener or failing on the first
// metadata refresh.
let health = isSandboxPortForwardHealthy(sandboxName, port, expectedBind);
if (health === true) return acceptSuccessfulForward();
if (health === "occupied") return false;
if (waitMs === 0) return false;
if (health === "occupied") return reportStartFailure(health);
if (waitMs === 0) return reportStartFailure(health);

let occupied = false;
const settled = waitForForwardRecoveryState(() => {
Expand All @@ -387,7 +435,7 @@ export function ensureSandboxPortForwardForPort(
}
return health === true;
}, waitMs);
return settled && !occupied && acceptSuccessfulForward();
return settled && !occupied ? acceptSuccessfulForward() : reportStartFailure(health);
}

export function ensureHermesDashboardPortForwardIfEnabled(sandboxName: string): boolean | null {
Expand Down
Loading
Loading