Skip to content

Commit 06944d7

Browse files
fix(server): ACP requests whose handler dies get their own error
The ACP client and agent RPC servers also sent a handler defect as a socket-level error with id -32603, so the peer's request never got an answer. They now use disableFatalDefects too. DefectReporter moves from the global observability layer to the WS RPC handlers. Installed globally it logged MCP tool defects a second time, since McpServer already logs them. It now logs only dies, so the HttpApi fail-then-die bookkeeping is gone. The RPC test pairs a real client with the server: with fatal defects the client ended the sibling subscription, which the server-only test could not see. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 3d26833 commit 06944d7

8 files changed

Lines changed: 135 additions & 106 deletions

File tree

Lines changed: 40 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
import { assert, describe, it } from "@effect/vitest";
22
import * as Cause from "effect/Cause";
3-
import * as Deferred from "effect/Deferred";
43
import * as Effect from "effect/Effect";
54
import * as ErrorReporter from "effect/ErrorReporter";
5+
import * as Exit from "effect/Exit";
6+
import * as Fiber from "effect/Fiber";
67
import * as Layer from "effect/Layer";
78
import * as Logger from "effect/Logger";
89
import * as Queue from "effect/Queue";
910
import * as Schema from "effect/Schema";
1011
import * as Stream from "effect/Stream";
11-
import { Rpc, RpcGroup, RpcMessage, RpcSerialization, RpcServer } from "effect/unstable/rpc";
12+
import { Rpc, RpcClient, RpcGroup, RpcServer } from "effect/unstable/rpc";
1213

1314
import { WS_RPC_SERVER_OPTIONS } from "../ws.ts";
1415
import * as DefectReporter from "./DefectReporter.ts";
@@ -17,8 +18,9 @@ class TestRpcs extends RpcGroup.make(
1718
Rpc.make("subscribe", { success: Schema.Number, stream: true }),
1819
Rpc.make("boom", { success: Schema.Void }),
1920
) {}
21+
type TestRpc = RpcGroup.Rpcs<typeof TestRpcs>;
2022

21-
/** Runs `body` with the defect reporter installed and every error log captured. */
23+
/** Runs `body` with every error log captured. */
2224
const withErrorLogs = <A, E, R>(
2325
body: (logs: Queue.Queue<Cause.Cause<unknown>>) => Effect.Effect<A, E, R>,
2426
) =>
@@ -28,9 +30,7 @@ const withErrorLogs = <A, E, R>(
2830
if (logLevel === "Error") Queue.offerUnsafe(logs, cause);
2931
});
3032
return yield* body(logs).pipe(
31-
Effect.provide(
32-
Layer.merge(DefectReporter.layer, Logger.layer([logger], { mergeWithExisting: false })),
33-
),
33+
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
3434
);
3535
});
3636

@@ -41,83 +41,63 @@ describe("DefectReporter", () => {
4141
withErrorLogs((logs) =>
4242
Effect.gen(function* () {
4343
const subscription = yield* Queue.unbounded<number>();
44-
const responses = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
45-
const receive = yield* Deferred.make<Parameters<RpcServer.Protocol["Service"]["run"]>[0]>();
46-
const protocol = yield* RpcServer.Protocol.make((write) =>
47-
Effect.gen(function* () {
48-
yield* Deferred.succeed(receive, write);
49-
const serialization = yield* RpcSerialization.RpcSerialization;
50-
return {
51-
disconnects: yield* Queue.unbounded<number>(),
52-
send: (_clientId, response) => Queue.offer(responses, response),
53-
end: () => Effect.void,
54-
clientIds: Effect.succeed(new Set([0])),
55-
initialMessage: Effect.succeedNone,
56-
supportsAck: true,
57-
supportsTransferables: false,
58-
supportsSpanPropagation: false,
59-
supportsNotifications: true,
60-
codecFor: serialization.codecFor,
61-
};
62-
}),
63-
);
64-
yield* RpcServer.make(TestRpcs, WS_RPC_SERVER_OPTIONS).pipe(
44+
// The same client/server pairing as RpcTest.makeClient, with ws.ts's options.
45+
// oxlint-disable-next-line prefer-const
46+
let client!: Effect.Success<
47+
ReturnType<typeof RpcClient.makeNoSerialization<TestRpc, never>>
48+
>;
49+
const server = yield* RpcServer.makeNoSerialization(TestRpcs, {
50+
...WS_RPC_SERVER_OPTIONS,
51+
onFromServer: (response) => client.write(response),
52+
}).pipe(
53+
// Provided to the handlers, as ws.ts does.
6554
Effect.provide(
6655
TestRpcs.toLayer({
6756
subscribe: () => Stream.fromQueue(subscription),
6857
boom: () => Effect.die(new Error("handler bug")),
69-
}),
58+
}).pipe(Layer.provide(DefectReporter.layer)),
7059
),
71-
Effect.provideService(RpcServer.Protocol, protocol),
72-
Effect.forkScoped,
7360
);
74-
const write = yield* Deferred.await(receive);
61+
client = yield* RpcClient.makeNoSerialization(TestRpcs, {
62+
supportsAck: true,
63+
onFromClient: ({ message }) => server.write(0, message),
64+
});
7565

76-
yield* write(0, { _tag: "Request", id: "1", tag: "subscribe", payload: null, headers: [] });
66+
const received = yield* Queue.unbounded<number>();
67+
const sibling = yield* client.client.subscribe().pipe(
68+
Stream.runForEach((value) => Queue.offer(received, value)),
69+
Effect.forkScoped,
70+
);
7771
yield* Queue.offer(subscription, 1);
78-
assert.deepEqual(yield* Queue.take(responses), {
79-
_tag: "Chunk",
80-
requestId: "1",
81-
values: [1],
82-
});
83-
yield* write(0, { _tag: "Ack", requestId: "1" });
72+
assert.equal(yield* Queue.take(received), 1);
8473

85-
yield* write(0, { _tag: "Request", id: "2", tag: "boom", payload: null, headers: [] });
86-
const boom = yield* Queue.take(responses);
87-
assert.equal(boom._tag, "Exit");
88-
if (boom._tag === "Exit") {
89-
assert.equal(boom.requestId, "2");
90-
assert.equal(boom.exit._tag, "Failure");
91-
}
92-
const logged = yield* Queue.take(logs);
93-
assert.isTrue(Cause.hasDies(logged));
94-
assert.equal(errorMessage(logged), "handler bug");
74+
const boom = yield* Effect.exit(client.client.boom());
75+
assert.isTrue(Exit.hasDies(boom));
76+
// The server reports before it answers, so the log is already written.
77+
const logged = yield* Queue.clear(logs);
78+
assert.deepEqual(logged.map(errorMessage), ["handler bug"]);
9579

9680
// The sibling subscription on the same client keeps delivering.
9781
yield* Queue.offer(subscription, 2);
98-
assert.deepEqual(yield* Queue.take(responses), {
99-
_tag: "Chunk",
100-
requestId: "1",
101-
values: [2],
102-
});
82+
const next = yield* Queue.take(received).pipe(
83+
Effect.raceFirst(Fiber.await(sibling).pipe(Effect.as("subscription ended"))),
84+
);
85+
assert.equal(next, 2);
10386
assert.equal(yield* Queue.size(logs), 0);
10487
}),
105-
).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped),
88+
).pipe(Effect.scoped),
10689
);
10790

108-
it.effect("does not log typed failures, or a typed failure rethrown as a defect", () =>
91+
it.effect("logs defects, not typed failures or interrupts", () =>
10992
withErrorLogs((logs) =>
11093
Effect.gen(function* () {
111-
// HttpApi reports a schema failure, then rethrows the same error as a defect.
112-
const badRequest = new Error("bad request");
113-
yield* ErrorReporter.report(Cause.fail(badRequest));
114-
yield* ErrorReporter.report(Cause.die(badRequest));
11594
yield* ErrorReporter.report(Cause.fail(new Error("expected")));
95+
yield* ErrorReporter.report(Cause.interrupt());
11696
yield* ErrorReporter.report(Cause.die(new Error("bug")));
11797

11898
assert.equal(errorMessage(yield* Queue.take(logs)), "bug");
11999
assert.equal(yield* Queue.size(logs), 0);
120-
}),
100+
}).pipe(Effect.provide(DefectReporter.layer)),
121101
),
122102
);
123103
});

‎apps/server/src/observability/DefectReporter.ts‎

Lines changed: 16 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,39 +3,22 @@ import * as Effect from "effect/Effect";
33
import * as ErrorReporter from "effect/ErrorReporter";
44

55
/**
6-
* Logs defects that reach a reporting boundary: RPC handlers, HTTP routes and
7-
* HttpApi endpoints. Typed failures are expected responses, and HttpApi reports
8-
* every one of them, so they are not logged.
9-
*
10-
* Errors first seen as typed failures are remembered. HttpApi reports a bad
11-
* request as a failure and then rethrows it as a defect so the HTTP layer answers
12-
* 400, and that second report must not be logged. Ignored errors, such as the
13-
* response HttpEffect attaches to every failed request, are skipped.
6+
* Logs the defects of WebSocket RPC handlers. RpcServer reports every failed
7+
* handler exit; typed failures are expected responses, so only dies are logged.
148
*/
15-
const make = (): ErrorReporter.ErrorReporter => {
16-
const seen = new WeakSet<object>();
17-
return {
18-
[ErrorReporter.TypeId]: ErrorReporter.TypeId,
19-
report: ({ cause, fiber }) => {
20-
if (seen.has(cause)) return;
21-
seen.add(cause);
22-
for (const reason of cause.reasons) {
23-
if (reason._tag === "Interrupt") continue;
24-
const value = reason._tag === "Fail" ? reason.error : reason.defect;
25-
if (typeof value === "object" && value !== null) {
26-
if (seen.has(value)) continue;
27-
seen.add(value);
28-
}
29-
if (reason._tag === "Fail" || ErrorReporter.isIgnored(value)) continue;
30-
// Reporters are called synchronously from the failing fiber. Logging with
31-
// its context keeps its loggers and annotations, and a fork cannot throw
32-
// back into the boundary that reported.
33-
Effect.runForkWith(fiber.context)(
34-
Effect.logError("Unhandled defect", Cause.fromReasons([reason])),
35-
);
36-
}
37-
},
38-
};
9+
const reporter: ErrorReporter.ErrorReporter = {
10+
[ErrorReporter.TypeId]: ErrorReporter.TypeId,
11+
report: ({ cause, fiber }) => {
12+
for (const reason of cause.reasons) {
13+
if (reason._tag !== "Die" || ErrorReporter.isIgnored(reason.defect)) continue;
14+
// Reporters are called synchronously from the failing fiber. Logging with
15+
// its context keeps its loggers and annotations, and a fork cannot throw
16+
// back into the server that reported.
17+
Effect.runForkWith(fiber.context)(
18+
Effect.logError("Unhandled defect", Cause.fromReasons([reason])),
19+
);
20+
}
21+
},
3922
};
4023

41-
export const layer = ErrorReporter.layer([Effect.sync(make)]);
24+
export const layer = ErrorReporter.layer([reporter]);

‎apps/server/src/observability/Layers/Observability.ts‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import * as ServerConfig from "../../config.ts";
1717
import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
1818
import { ServerLoggerLive } from "../../serverLogger.ts";
1919
import * as BrowserTraceCollector from "../BrowserTraceCollector.ts";
20-
import * as DefectReporter from "../DefectReporter.ts";
2120

2221
export const ObservabilityLive = Layer.unwrap(
2322
Effect.gen(function* () {
@@ -96,13 +95,7 @@ export const ObservabilityLive = Layer.unwrap(
9695

9796
return otelWarningsLayer.pipe(
9897
Layer.provideMerge(
99-
Layer.mergeAll(
100-
ServerLoggerLive,
101-
traceReferencesLayer,
102-
tracerLayer,
103-
metricsLayer,
104-
DefectReporter.layer,
105-
),
98+
Layer.mergeAll(ServerLoggerLive, traceReferencesLayer, tracerLayer, metricsLayer),
10699
),
107100
Layer.provide(
108101
OtelEnvironment.layerResourceAttributes(config.otelEnvironment.resourceAttributes),

‎apps/server/src/ws.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolve
205205
import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts";
206206
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
207207
import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
208+
import * as DefectReporter from "./observability/DefectReporter.ts";
208209
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
209210
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
210211
import {
@@ -3763,9 +3764,9 @@ const makeWsRpcLayer = (
37633764
}),
37643765
);
37653766

3766-
// A handler defect fails only its own request. RpcServer's default sends a
3767-
// socket-level Defect frame instead, and the client ends every pending request on
3768-
// the socket with it. DefectReporter logs the defect either way.
3767+
// A defect in a handler's effect fails only its own request. RpcServer's default
3768+
// sends a socket-level Defect frame instead, and the client ends every pending
3769+
// request on the socket with it. DefectReporter logs these defects.
37693770
export const WS_RPC_SERVER_OPTIONS = {
37703771
disableTracing: true,
37713772
disableFatalDefects: true,
@@ -3829,6 +3830,9 @@ export const websocketRpcRouteLayer = Layer.unwrap(
38293830
previewAutomationBroker,
38303831
).pipe(
38313832
Layer.provideMerge(RpcSerialization.layerJson),
3833+
// Request fibers run in the handlers' context, so this reporter sees
3834+
// their defects and nothing else on the server.
3835+
Layer.provide(DefectReporter.layer),
38323836
Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)),
38333837
Layer.provide(AgentSessionScanner.layer),
38343838
Layer.provide(ProviderMaintenanceRunner.layer),

‎packages/effect-acp/src/agent.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ const SessionCancelNotification = jsonRpcNotification(
3535
const ExtPingNotification = jsonRpcNotification("x/ping", Schema.Struct({ count: Schema.Number }));
3636
const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
3737
const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
38+
/** A JSON-RPC error response; only its id and the presence of an error matter here. */
39+
const ErrorResponse = Schema.Struct({ id: Schema.Number, error: Schema.Unknown });
3840
const decodeRequestPermissionRequest = Schema.decodeEffect(
3941
Schema.fromJsonString(RequestPermissionRequest),
4042
);
@@ -296,3 +298,34 @@ it.effect("effect-acp agent uses distinct ids for RPC calls and extension reques
296298
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
297299
}),
298300
);
301+
302+
it.effect("effect-acp agent answers a request whose handler dies with an error for it", () =>
303+
Effect.gen(function* () {
304+
const { stdio, input, output } = yield* makeInMemoryStdio();
305+
const scope = yield* Scope.make();
306+
const context = yield* Layer.buildWithScope(AcpAgent.layer(stdio), scope);
307+
const agent = yield* Effect.service(AcpAgent.AcpAgent).pipe(Effect.provide(context));
308+
yield* agent.handleInitialize(() => Effect.die(new Error("handler bug")));
309+
310+
yield* Queue.offer(
311+
input,
312+
yield* encodeJsonl(InitializeRequest, {
313+
jsonrpc: "2.0",
314+
id: 7,
315+
method: "initialize",
316+
params: {
317+
protocolVersion: 2,
318+
capabilities: {},
319+
info: { name: "effect-acp-test", version: "0.0.0" },
320+
},
321+
headers: [],
322+
}),
323+
);
324+
const response = yield* Queue.take(output).pipe(
325+
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(ErrorResponse))),
326+
);
327+
assert.equal(response.id, 7);
328+
assert.isNotNull(response.error);
329+
yield* Scope.close(scope, Exit.void);
330+
}),
331+
);

‎packages/effect-acp/src/agent.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -421,7 +421,7 @@ export const make = Effect.fn("effect-acp/AcpAgent.make")(function* (
421421
}),
422422
);
423423

424-
yield* RpcServer.make(AcpRpcs.AgentRpcs).pipe(
424+
yield* RpcServer.make(AcpRpcs.AgentRpcs, { disableFatalDefects: true }).pipe(
425425
Effect.provideService(RpcServer.Protocol, transport.serverProtocol),
426426
Effect.provide(agentHandlerLayer),
427427
Effect.forkScoped,

‎packages/effect-acp/src/client.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ const PermissionRequest = jsonRpcRequest(
5050
const PermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
5151
const ElicitationRequest = jsonRpcRequest("elicitation/create", AcpSchema.CreateElicitationRequest);
5252
const ElicitationResponse = jsonRpcResponse(AcpSchema.CreateElicitationResponse);
53+
/** A JSON-RPC error response; only its id and the presence of an error matter here. */
54+
const ErrorResponse = Schema.Struct({ id: Schema.String, error: Schema.Unknown });
5355
const decodePromptRequestLine = Schema.decodeEffect(Schema.fromJsonString(PromptRequest));
5456
const XAiPromptCompleteNotification = jsonRpcNotification(
5557
"_x.ai/session/prompt_complete",
@@ -1130,6 +1132,40 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
11301132
}),
11311133
);
11321134

1135+
it.effect("answers a request whose handler dies with an error for that request", () =>
1136+
Effect.gen(function* () {
1137+
const { stdio, input, output } = yield* makeInMemoryStdio();
1138+
const scope = yield* Scope.make();
1139+
const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
1140+
yield* acp.handleRequestPermission(() => Effect.die(new Error("handler bug")));
1141+
1142+
yield* Queue.offer(
1143+
input,
1144+
yield* encodeJsonl(PermissionRequest, {
1145+
jsonrpc: "2.0",
1146+
id: "permission-a",
1147+
method: "session/request_permission",
1148+
params: {
1149+
sessionId: "session-1",
1150+
title: "Tool",
1151+
subject: {
1152+
type: "tool_call" as const,
1153+
toolCall: { toolCallId: "tool-1", title: "Tool" },
1154+
},
1155+
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" as const }],
1156+
},
1157+
headers: [],
1158+
}),
1159+
);
1160+
const response = yield* Queue.take(output).pipe(
1161+
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(ErrorResponse))),
1162+
);
1163+
assert.equal(response.id, "permission-a");
1164+
assert.isNotNull(response.error);
1165+
yield* Scope.close(scope, Exit.void);
1166+
}),
1167+
);
1168+
11331169
it.effect("answers elicitation/create with the flat action shape", () =>
11341170
Effect.gen(function* () {
11351171
const { stdio, input, output } = yield* makeInMemoryStdio();

‎packages/effect-acp/src/client.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1099,7 +1099,7 @@ export const make = Effect.fn("effect-acp/AcpClient.make")(function* (
10991099
}),
11001100
);
11011101

1102-
yield* RpcServer.make(AcpRpcs.CompatClientRpcs).pipe(
1102+
yield* RpcServer.make(AcpRpcs.CompatClientRpcs, { disableFatalDefects: true }).pipe(
11031103
Effect.provideService(RpcServer.Protocol, transport.serverProtocol),
11041104
Effect.provide(clientHandlerLayer),
11051105
Effect.forkScoped,

0 commit comments

Comments
 (0)