fix(hopper): diagnose MCP provider failures with stage, state, and request context (#1044)

* fix(hopper): diagnose MCP provider failures with stage, state, and request context

* fix(hopper): retain health at the actual provider lifecycle boundary

* test(hopper): distinguish socket loss from later observed process exit

* test(hopper): cover observed exit separately from socket-first replies

---------

Co-authored-by: N0zoM1z0 <1705004398@qq.com>
This commit is contained in:
Alan Vo
2026-10-09 00:33:56 +08:00
committed by GitHub
co-authored by N0zoM1z0
parent b5c2954ad6
commit 5a67c7fc54
20 changed files with 990 additions and 62 deletions
@@ -0,0 +1,178 @@
import { EventEmitter } from "node:events";
import { describe, expect, it, onTestFinished, vi } from "vitest";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { ok } from "../../../../src/domain/result.js";
import type {
BridgeLauncher,
BridgeSession,
} from "../../../../src/hopper/BridgeLauncher.js";
import { HopperClient } from "../../../../src/hopper/HopperClient.js";
import { HopperFixtureLauncher } from "./hopperClient.fixture.js";
class ObservedProcess extends EventEmitter {
readonly stdout = null;
readonly stderr = null;
exitCode: number | null = null;
readonly signalCode = null;
exit(code: number): void {
this.exitCode = code;
this.emit("exit", code, null);
this.emit("close", code, null);
}
kill(): boolean {
this.exit(0);
return true;
}
}
class LifecycleLauncher implements BridgeLauncher {
readonly fixture = new HopperFixtureLauncher();
observed = new ObservedProcess();
constructor(readonly owned: boolean) {}
async launch(session: BridgeSession) {
this.observed = new ObservedProcess();
await this.fixture.launch(session);
return ok({
process: this.observed,
ownsProcessLifetime: this.owned,
shutdownMode: "bridge-request" as const,
});
}
}
const start = async (owned: boolean) => {
const launcher = new LifecycleLauncher(owned);
const client = new HopperClient({ launcher, startupTimeoutMs: 10_000 });
onTestFinished(async () => {
await client.close();
for (const child of launcher.fixture.processes) child.kill();
});
expect((await client.start()).ok).toBe(true);
return { client, launcher };
};
describe("Hopper provider lifecycle health", () => {
it("keeps a live bridge healthy after a non-owning launcher helper exits", async () => {
const { client, launcher } = await start(false);
launcher.observed.exit(0);
expect(client.operationHealth().state).toBe("idle");
expect(await client.callTool("echo", { label: "GUI still alive" })).toEqual(
{
ok: true,
value: { label: "GUI still alive" },
},
);
expect(client.operationHealth().state).toBe("idle");
});
it("settles disconnected requests without attributing the helper exit to the GUI", async () => {
const { client, launcher } = await start(false);
launcher.observed.exit(0);
const pending = client.callTool("hang");
await launcher.fixture.waitForRequest("hang");
launcher.fixture.processes.at(-1)?.kill("SIGKILL");
await vi.waitFor(() =>
expect(client.operationHealth().state).toBe("unreachable"),
);
expect(await pending).toMatchObject({
ok: false,
error: {
providerState: "unreachable",
exitCode: null,
operation: "hang",
},
});
expect(client.operationHealth()).toMatchObject({
state: "unreachable",
exitCode: null,
});
expect(
await client.callTool("procedure_pseudo_code", { procedure: "main" }),
).toMatchObject({
ok: false,
error: {
providerState: "unreachable",
stage: "decompilation",
operation: "procedure_pseudo_code",
},
});
});
it("projects the exit code when the owned process exit is observed before disconnection", async () => {
const { client, launcher } = await start(true);
const pending = client.callTool("hang");
const request = await launcher.fixture.waitForRequest("hang");
launcher.observed.exit(7);
const result = await pending;
expect(result).toMatchObject({
ok: false,
error: {
_tag: "HopperProcessError",
exitCode: 7,
providerState: "exited",
requestId: request.id,
},
});
if (!result.ok)
expect(projectAnalysisError(result.error)).toMatchObject({
message: expect.stringContaining(
"Hopper exited during hang (exit code 7)",
),
details: {
provider_state: "exited",
exit_code: 7,
stage: "analysis",
operation: "hang",
request_id: request.id,
},
});
});
it("retains an observed exit when an earlier successful reply resumes afterward", async () => {
const { client, launcher } = await start(true);
const first = client.callTool("echo", { gate: "before-exit" });
const request = await launcher.fixture.waitForRequest(
"echo",
"before-exit",
);
const controller = new AbortController();
const second = client.callTool(
"hang",
{},
{
signal: controller.signal,
progress: {
report: (update) => {
if (update.message === "hang started on Hopper's serial bridge") {
controller.abort();
launcher.observed.exit(7);
}
return Promise.resolve();
},
},
},
);
await vi.waitFor(() =>
expect(client.requestActivity()?.queuedRequests).toBe(1),
);
await launcher.fixture.release(request);
expect((await first).ok).toBe(true);
expect(await second).toMatchObject({
ok: false,
error: { _tag: "HopperCancelledError" },
});
expect(client.operationHealth()).toMatchObject({
state: "exited",
exitCode: 7,
});
await client.close();
expect((await client.start()).ok).toBe(true);
expect(client.operationHealth().state).toBe("idle");
});
});
@@ -1,9 +1,13 @@
import { once } from "node:events";
import { describe, expect, it, onTestFinished, vi } from "vitest";
import { HopperProcessError } from "../../../../src/domain/hopperErrors.js";
import { HOPPER_OPERATIONS } from "../../../../src/hopper/HopperProvider.js";
import { HopperClient } from "../../../../src/hopper/HopperClient.js";
import type { HopperDiagnostic } from "../../../../src/hopper/HopperDiagnostics.js";
import { providerCleanupFailure } from "../../../../src/hopper/HopperDiagnostics.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import {
HopperFixtureLauncher as FixtureLauncher,
@@ -192,3 +196,125 @@ describe("HopperClient response lifecycle", () => {
});
});
});
describe("HopperClient operational diagnostics", () => {
it("records process exit code, stage, and restart guidance on unexpected exit", async () => {
const launcher = new FixtureLauncher();
const client = await startClient(launcher);
const child = launcher.processes.at(-1);
if (child === undefined) throw new Error("Missing fixture process");
const exited = once(child, "exit");
const result = await client.callTool("exit");
await exited;
expect(result.ok).toBe(false);
if (!result.ok) {
if (!(result.error instanceof HopperProcessError))
throw new Error("Expected a provider process error");
expect(["unreachable", "exited"]).toContain(result.error.providerState);
expect(result.error.exitCode).toBe(
result.error.providerState === "exited" ? 7 : null,
);
expect(result.error).toMatchObject({
_tag: "HopperProcessError",
operation: "exit",
});
const projected = projectAnalysisError(result.error);
expect(projected).toMatchObject({
code: "provider_unavailable",
retryable: true,
details: {
stage: "analysis",
provider_state: result.error.providerState,
retry_action: "restart_provider",
operation: "exit",
exit_code: result.error.exitCode,
},
});
expect(projected.remediation.action).toContain("close_binary");
}
expect(client.operationHealth()).toMatchObject({
state: "exited",
stage: "analysis",
retryAction: "restart_provider",
exitCode: 7,
requests: [
expect.objectContaining({
operation: "exit",
stage: "analysis",
}),
],
});
});
it("retains request correlation and health across concurrent requests when the bridge process terminates", async () => {
const launcher = new FixtureLauncher();
const client = await startClient(launcher);
const hanging = client.callTool("hang");
const inFlight = await launcher.waitForRequest("hang");
const queued = client.callTool("echo", { label: "queued" });
const child = launcher.processes.at(-1);
if (child === undefined) throw new Error("Missing fixture process");
const exited = once(child, "exit");
child.kill("SIGKILL");
await exited;
const [hangingResult, queuedResult] = await Promise.all([hanging, queued]);
expect(hangingResult.ok).toBe(false);
expect(queuedResult.ok).toBe(false);
if (!hangingResult.ok && !queuedResult.ok) {
if (
!(hangingResult.error instanceof HopperProcessError) ||
!(queuedResult.error instanceof HopperProcessError)
)
throw new Error("Expected correlated provider process errors");
// Socket loss may be observed before the separate child-exit event.
// The immutable reply must preserve what was known when it settled.
expect(["unreachable", "exited"]).toContain(
hangingResult.error.providerState,
);
expect(["unreachable", "exited"]).toContain(
queuedResult.error.providerState,
);
expect(hangingResult.error).toMatchObject({
_tag: "HopperProcessError",
operation: "hang",
requestId: inFlight.id,
});
expect(queuedResult.error).toMatchObject({
_tag: "HopperProcessError",
operation: "echo",
requestId: inFlight.id + 1,
});
const hangingProjected = projectAnalysisError(hangingResult.error);
const queuedProjected = projectAnalysisError(queuedResult.error);
expect(hangingProjected.details).toMatchObject({
stage: "analysis",
provider_state: hangingResult.error.providerState,
retry_action: "restart_provider",
operation: "hang",
request_id: inFlight.id,
});
expect(queuedProjected.details).toMatchObject({
stage: "analysis",
provider_state: queuedResult.error.providerState,
retry_action: "restart_provider",
operation: "echo",
request_id: inFlight.id + 1,
});
expect(hangingProjected.remediation.action).toContain("close_binary");
expect(queuedProjected.remediation.action).toContain("close_binary");
}
expect(client.operationHealth()).toMatchObject({
state: "exited",
retryAction: "restart_provider",
});
expect(client.operationHealth().requests).toEqual([
expect.objectContaining({ requestId: inFlight.id, operation: "hang" }),
expect.objectContaining({
requestId: inFlight.id + 1,
operation: "echo",
}),
]);
});
});
@@ -122,6 +122,40 @@ afterEach(async () => {
await Promise.all(clients.splice(0).map((client) => client.close()));
});
describe("HopperClient startup deadline", () => {
it("applies one deadline to launcher, socket, and health startup phases", async () => {
const launcher = new LateSilentLauncher();
const client = new HopperClient({ launcher, startupTimeoutMs: 500 });
clients.push(client);
const result = await client.start();
expect(result).toMatchObject({
ok: false,
error: { _tag: "HopperTimeoutError", timeoutMs: 500 },
});
expect(client.operationHealth()).toMatchObject({
state: "not_started",
stage: "launch",
retryAction: "retry",
exitCode: null,
});
if (!result.ok)
expect(projectAnalysisError(result.error).details).toMatchObject({
stage: "startup",
});
expect(launcher.directories).toHaveLength(1);
await expect(access(launcher.directories[0] ?? "")).rejects.toMatchObject({
code: "ENOENT",
});
const process = launcher.processes[0];
expect(
process !== undefined &&
(process.exitCode !== null || process.signalCode !== null),
).toBe(true);
});
});
describe("HopperClient startup failures", () => {
it("cancels bridge startup without waiting for the startup timeout", async () => {
const launcher = new CancelThenFixtureLauncher();
@@ -183,28 +217,6 @@ describe("HopperClient startup failures", () => {
});
});
it("applies one deadline to launcher, socket, and health startup phases", async () => {
const launcher = new LateSilentLauncher();
const client = new HopperClient({ launcher, startupTimeoutMs: 500 });
clients.push(client);
const result = await client.start();
expect(result).toMatchObject({
ok: false,
error: { _tag: "HopperTimeoutError", timeoutMs: 500 },
});
expect(launcher.directories).toHaveLength(1);
await expect(access(launcher.directories[0] ?? "")).rejects.toMatchObject({
code: "ENOENT",
});
const process = launcher.processes[0];
expect(
process !== undefined &&
(process.exitCode !== null || process.signalCode !== null),
).toBe(true);
});
it.each([70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80])(
"reports Linux adapter exit %i during bridge startup",
async (exitCode) => {
@@ -158,6 +158,76 @@ describe("detached provider and target metadata", () => {
await session.close();
});
it("exposes provider operational health in session status", async () => {
const [first] = await createBinarySessionTargets();
let healthState: "idle" | "busy" | "exited" = "busy";
const provider: AnalysisProvider = {
identity: () => ({ id: "fixture", name: "Fixture", version: "1" }),
capabilities: () => [],
createClient: () => ({
execute: () => Promise.resolve(ok("ok")),
operationHealthSnapshot: () => ({
state: healthState,
stage: "analysis",
retryAction: healthState === "exited" ? "restart_provider" : "wait",
exitCode: healthState === "exited" ? 7 : null,
requests: [
{
requestId: 1,
operation: "find_code_for_string",
stage: "analysis",
},
],
}),
close: () => Promise.resolve(),
}),
};
const session = createTestBinarySession(provider);
expect(session.status()).toMatchObject({
open: false,
provider_operation_health: null,
});
expect((await session.open(first)).ok).toBe(true);
expect(session.status()).toMatchObject({
open: true,
provider_operation_health: {
state: "busy",
stage: "analysis",
retry_action: "wait",
exit_code: null,
requests: [
{
request_id: 1,
operation: "find_code_for_string",
stage: "analysis",
},
],
},
});
healthState = "exited";
expect(session.status()).toMatchObject({
open: true,
provider_operation_health: {
state: "exited",
stage: "analysis",
retry_action: "restart_provider",
exit_code: 7,
requests: [
{
request_id: 1,
operation: "find_code_for_string",
stage: "analysis",
},
],
},
});
await session.close();
expect(session.status()).toMatchObject({
open: false,
provider_operation_health: null,
});
});
});
describe("opening previewed targets", () => {