Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,50 @@ describe("Hermes Portable connect recovery errors", () => {
expect(output).not.toContain("Hermes Portable inference recovery for 'alpha' failed");
});

it("verifies a compatible-endpoint route without Ollama recovery", async () => {
const entry = {
name: "alpha",
agent: "hermes",
provider: "compatible-endpoint",
model: "descriptor/model",
policies: [],
openshellDriver: "docker",
gatewayName: "nemoclaw",
lifecycleGeneration: "generation-1",
} as never;
const harness = createConnectHarness({
agentName: "hermes",
sessionAgent: { name: "hermes" },
registryEntry: entry,
inferenceGetOutput:
"Gateway inference:\n Provider: compatible-endpoint\n Model: descriptor/model\n",
inferenceProbeResponses: ["OK 200"],
portableReceiptDisposition: { kind: "hermes", phase: "active" },
portableRecoveryResult: { kind: "already-running" },
readinessDecision: {
kind: "accepted",
category: "accepted",
agent: { name: "hermes" },
sb: entry,
},
});

await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined();

expect(harness.registryEntries[0]?.hostLocalInferenceReceipt).toBeUndefined();
expect(harness.recoverHermesPortableOllamaInferenceSpy).not.toHaveBeenCalled();
expect(harness.captureResolvedOpenshellSpy).toHaveBeenCalledWith(
["inference", "get", "-g", "nemoclaw"],
expect.objectContaining({ openshellBinary: "/usr/bin/openshell" }),
);
expect(
harness.captureResolvedOpenshellSpy.mock.calls.some(
([args]) => Array.isArray(args) && args[0] === "sandbox" && args[1] === "exec",
),
).toBe(true);
expect(harness.publishLaunchReadinessSpy).not.toHaveBeenCalled();
});

it.each([
[
"authority drift",
Expand Down
11 changes: 7 additions & 4 deletions src/lib/actions/sandbox/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ async function runSandboxConnectProbe(
if (hermesPortable) {
if (probeOnly !== true) throw new Error("Hermes inference recovery requires probe-only mode");
measure("inference", () =>
recoverHermesPortableInferenceRouteForProbeOnlyOrExit(sandboxName, agent),
verifyOrRecoverHermesPortableInferenceRouteForProbeOnlyOrExit(sandboxName, agent),
);
let authority: HermesPortableActiveLifecycleAuthority;
try {
Expand Down Expand Up @@ -743,8 +743,8 @@ function verifyHermesPortableInferenceRouteOrExit(
}
}

/** Resume published Ollama authority only for the explicit probe-only command. */
function recoverHermesPortableInferenceRouteForProbeOnlyOrExit(
/** Verify the recorded route and resume published Ollama only for probe-only recovery. */
function verifyOrRecoverHermesPortableInferenceRouteForProbeOnlyOrExit(
sandboxName: string,
agent: InferenceRouteProbeAgent,
expectedAuthority?: HermesPortableActiveLifecycleAuthority,
Expand All @@ -759,6 +759,9 @@ function recoverHermesPortableInferenceRouteForProbeOnlyOrExit(
} catch {
failHermesPortableInferenceRoute(sandboxName, "missing or incomplete");
}
if (authority.entry.provider !== "ollama-local") {
return verifyHermesPortableInferenceRouteOrExit(sandboxName, agent, authority);
}
let verified: SandboxEntry | null = null;
try {
recoverHermesPortableInferenceForConnectProbe({
Expand Down Expand Up @@ -2016,7 +2019,7 @@ async function prepareConnectSandboxWithinLifecycleFence(
throw new Error("Hermes inference recovery requires probe-only mode");
}
const verified = probeTiming!.measure("inference", () =>
recoverHermesPortableInferenceRouteForProbeOnlyOrExit(
verifyOrRecoverHermesPortableInferenceRouteForProbeOnlyOrExit(
sandboxName,
acceptedReadiness.agent,
activeAuthority,
Expand Down
7 changes: 6 additions & 1 deletion src/lib/actions/sandbox/forward-health.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,16 @@ export type SandboxForwardListEntry = {

export type SandboxForwardHealth = boolean | "occupied" | null;

/** Whether OpenShell reports a forward as live in either supported CLI vocabulary. */
export function isLiveSandboxForwardStatus(status: string): boolean {
return status === "running" || status === "active";
}

function liveEntriesForPort(
entries: SandboxForwardListEntry[],
port: string,
): SandboxForwardListEntry[] {
return entries.filter((entry) => entry.port === port && entry.status === "running");
return entries.filter((entry) => entry.port === port && isLiveSandboxForwardStatus(entry.status));
}

export function classifySandboxForwardHealth(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,31 @@ describe("Hermes Portable probe-only forward recovery", () => {
expect(fixture.rollbackCalls).toEqual([]);
});

it("keeps exact active forwards verification-only", () => {
const fixture = createRecoveryFixture({ ports: [18_789, 8_642], active: [18_789, 8_642] });

expect(recoverHermesPortableLaunchForwards(fixture.input)).toEqual({
kind: "verified",
restoredPorts: [],
});
expect(fixture.currentCalls).toEqual([["forward", "list", "--gateway", "nemoclaw"]]);
expect(fixture.rollbackCalls).toEqual([]);
});

it.each([
["stopped", { stopped: [18_789] }],
["dead after the host session ends", { dead: [18_789] }],
])("restores an exact %s forward", (_state, options) => {
const fixture = createRecoveryFixture(options);

expect(recoverHermesPortableLaunchForwards(fixture.input)).toEqual({
kind: "restored",
restoredPorts: [18_789],
});
expect(fixture.currentCalls.filter((args) => args[1] === "start")).toHaveLength(1);
expect(fixture.rollbackCalls).toEqual([]);
});

it("accepts a returned nonzero start only after the exact owner settles healthy", () => {
const fixture = createRecoveryFixture({ startStatus: 1 });

Expand Down Expand Up @@ -80,7 +105,8 @@ describe("Hermes Portable probe-only forward recovery", () => {
});

it.each([
["PID", "alpha 127.0.0.1 18789 not-a-pid running"],
["active PID", "alpha 127.0.0.1 18789 not-a-pid active"],
["dead PID", "alpha 127.0.0.1 18789 not-a-pid dead"],
["bind", "alpha not-an-address 18789 12345 running"],
["port", "alpha 127.0.0.1 70000 12345 running"],
["status", "alpha 127.0.0.1 18789 12345 uncertain"],
Expand Down Expand Up @@ -108,14 +134,14 @@ describe("Hermes Portable probe-only forward recovery", () => {
});

it("rejects ambiguous duplicate rows before mutation", () => {
const fixture = createRecoveryFixture({ running: [18_789] });
const fixture = createRecoveryFixture({ active: [18_789] });
Object.assign(fixture.input.deps, {
captureCurrent: () => ({
status: 0,
output:
"SANDBOX BIND PORT PID STATUS\n" +
"alpha 127.0.0.1 18789 12345 running\n" +
"alpha 127.0.0.1 18789 12346 running",
"alpha 127.0.0.1 18789 12345 active\n" +
"alpha 127.0.0.1 18789 12346 active",
}),
});

Expand All @@ -125,6 +151,18 @@ describe("Hermes Portable probe-only forward recovery", () => {
expect(fixture.rollbackCalls).toEqual([]);
});

it("rejects a foreign active owner before mutation", () => {
const fixture = createRecoveryFixture({
listOutput: "SANDBOX BIND PORT PID STATUS\nbeta 127.0.0.1 18789 12345 active",
});

expect(() => recoverHermesPortableLaunchForwards(fixture.input)).toThrow(
expect.objectContaining({ failure: "forward-occupied" }),
);
expect(fixture.currentCalls.some((args) => ["start", "stop"].includes(args[1]!))).toBe(false);
expect(fixture.rollbackCalls).toEqual([]);
});

it("restores the exact missing state when authority drifts after start", () => {
const fixture = createRecoveryFixture({ driftCurrentAfterStart: true });

Expand Down Expand Up @@ -230,6 +268,32 @@ describe("Hermes Portable connect composition", () => {
);
});

it("restores an exact dead forward once before launch-readiness publication (#10423)", async () => {
const harness = createConnectHarness({
agentName: "hermes",
sessionAgent: { name: "hermes" },
portableReceiptDisposition: { kind: "hermes", phase: "active" },
portableRecoveryResult: { kind: "already-running" },
});
configureMissingHermesForwardCapture(harness, { initialStatus: "dead" });

await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined();

const mutations = harness.captureResolvedOpenshellSpy.mock.calls
.filter(
([args]) =>
Array.isArray(args) &&
args[0] === "forward" &&
["start", "stop"].includes(String(args[1])),
)
.map(([args]) => (args as string[])[1]);
expect(mutations).toEqual(["stop", "start"]);
expect(harness.publishLaunchReadinessSpy).toHaveBeenCalledOnce();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
expect(harness.logSpy.mock.calls.flat().join("\n")).toMatch(
/forwardAction=restored result=ready/,
);
});

it("stops before publication when the owning gateway forward list is malformed", async () => {
const harness = createConnectHarness({
agentName: "hermes",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
import { isIP } from "node:net";

import { parseForwardList } from "../../../state/sandbox-session";
import { classifySandboxForwardHealth, isLocalForwardReachable } from "../forward-health";
import {
classifySandboxForwardHealth,
isLiveSandboxForwardStatus,
isLocalForwardReachable,
} from "../forward-health";

const FORWARD_SETTLEMENT_TIMEOUT_MS = 3_000;
const FORWARD_SETTLEMENT_INTERVAL_MS = 100;
Expand Down Expand Up @@ -92,7 +96,8 @@ function isSupportedForwardRow(parts: readonly string[]): boolean {
/^\d+$/u.test(pidValue) &&
Number.isSafeInteger(pid) &&
pid > 0 &&
["running", "stopped"].includes(status.toLowerCase())
(isLiveSandboxForwardStatus(status.toLowerCase()) ||
["dead", "stopped"].includes(status.toLowerCase()))
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,32 @@ function createHarness(initiallyRunning = false, registryInitiallyRunning = fals
}

describe("Hermes Portable Ollama inference recovery", () => {
it.each([
["missing", undefined, "sandbox registry host-local inference receipt is missing"],
["malformed", "not-json\n", "serialized receipt is not valid JSON"],
] as const)(
"rejects an ollama-local registry receipt that is %s before registry recovery",
(_label, serializedReceipt, expectedError) => {
const harness = createHarness();
const entry = {
...harness.input.entry,
hostLocalInferenceReceipt: serializedReceipt,
} as SandboxEntry;

expect(() =>
recoverHermesPortableOllamaInference(
{
...harness.input,
entry,
readRegistry: vi.fn(() => entry),
},
harness.overrides as never,
),
).toThrow(expectedError);
expect(harness.overrides.prepareRegistryRecovery).not.toHaveBeenCalled();
},
);

it("resumes one stopped published runtime and commits only after final route proof", () => {
const harness = createHarness();

Expand Down
39 changes: 34 additions & 5 deletions test/process-recovery/process-recovery-primitives.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -473,20 +473,33 @@ describe("resolveSandboxDashboardPort", () => {
});

describe("classifySandboxForwardHealth", () => {
it("returns true for a running forward owned by the target sandbox", () => {
it.each(["running", "active"])(
"returns true for a %s forward owned by the target sandbox",
(status) => {
expect(
classifySandboxForwardHealth(
[{ sandboxName: "beta", port: "18790", status }],
"beta",
"18790",
),
).toBe(true);
},
);

it("returns occupied when another sandbox owns the expected port", () => {
expect(
classifySandboxForwardHealth(
[{ sandboxName: "beta", port: "18790", status: "running" }],
[{ sandboxName: "alpha", port: "18790", status: "running" }],
"beta",
"18790",
),
).toBe(true);
).toBe("occupied");
});

it("returns occupied when another sandbox owns the expected port", () => {
it("returns occupied when another sandbox owns an active forward on the expected port", () => {
expect(
classifySandboxForwardHealth(
[{ sandboxName: "alpha", port: "18790", status: "running" }],
[{ sandboxName: "alpha", port: "18790", status: "active" }],
"beta",
"18790",
),
Expand Down Expand Up @@ -576,6 +589,22 @@ describe("classifySandboxForwardHealth", () => {
});

describe("classifyForwardHealthWithReachability", () => {
it("requires an exact active owner to answer before reporting healthy", () => {
let probed = false;
const result = classifyForwardHealthWithReachability(
[{ sandboxName: "beta", port: "18790", status: "active" }],
"beta",
"18790",
() => {
probed = true;
return true;
},
);

expect(result).toBe(true);
expect(probed).toBe(true);
});

it("does not trust an arbitrary local listener for a non-running owned entry", () => {
let probed = false;
const result = classifyForwardHealthWithReachability(
Expand Down
Loading
Loading