Skip to content
TypeScript

fix(server): a macOS setTypeOfService EINVAL no longer kills the backend (#20414)

Victor Vogel6ae65e129cb9
diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts
index 4e01009c77c..03b282a3838 100644
--- a/apps/server/src/bin.ts
+++ b/apps/server/src/bin.ts
@@ -14,6 +14,9 @@ if (
})
) {
const command = process.argv[2];
+ // Guard sockets before either dispatch path can load outbound-capable modules.
+ const { ignoreMacosTypeOfServiceEinval } = await import("./outboundHttp.ts");
+ ignoreMacosTypeOfServiceEinval();
if (command === "acp-mcp-bridge" || command === "acp-mcp-call") {
const { runAcpMcpCliFastPath } = await import("./mcp/AcpMcpStdioBridge.ts");
await runAcpMcpCliFastPath(command, process.argv.slice(3));
diff --git a/apps/server/src/outboundHttp.test.ts b/apps/server/src/outboundHttp.test.ts
index e6afa46095c..a4f8a926061 100644
--- a/apps/server/src/outboundHttp.test.ts
+++ b/apps/server/src/outboundHttp.test.ts
@@ -2,9 +2,13 @@
import * as NodeHttp2 from "node:http2";
import * as NodeNet from "node:net";
import * as NodeTls from "node:tls";
+import * as NodeURL from "node:url";
+import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
+import * as Stream from "effect/Stream";
+import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { FetchHttpClient, HttpClient } from "effect/http";
import * as Undici from "undici";
import { afterAll, afterEach, beforeAll, describe, expect } from "vite-plus/test";
@@ -12,6 +16,7 @@ import { afterAll, afterEach, beforeAll, describe, expect } from "vite-plus/test
import {
builtinFetchUsesHttp2,
extendConnectionAttemptTimeout,
+ ignoreMacosTypeOfServiceEinval,
installHttp1FetchDispatcher,
} from "./outboundHttp.ts";
@@ -97,6 +102,141 @@ describe("installHttp1FetchDispatcher", () => {
);
});
+const runNode = Effect.fnUntraced(function* (args: Array<string>) {
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const child = yield* spawner.spawn(ChildProcess.make(process.execPath, args));
+ return yield* Effect.all(
+ {
+ stdout: child.stdout.pipe(Stream.decodeText(), Stream.mkString),
+ stderr: child.stderr.pipe(Stream.decodeText(), Stream.mkString),
+ exitCode: child.exitCode.pipe(Effect.map(Number)),
+ },
+ { concurrency: "unbounded" },
+ );
+}, Effect.scoped);
+
+describe("ignoreMacosTypeOfServiceEinval", () => {
+ const errnoError = (code: string) =>
+ Object.assign(new Error(`setTypeOfService ${code}`), { code, syscall: "setTypeOfService" });
+
+ it("swallows only an Error with code EINVAL on macOS", () => {
+ let error: unknown = errnoError("EINVAL");
+ const prototype = {
+ setTypeOfService(this: NodeNet.Socket, _typeOfService: number): NodeNet.Socket {
+ throw error;
+ },
+ };
+ ignoreMacosTypeOfServiceEinval("darwin", prototype);
+
+ const socket = new NodeNet.Socket();
+ expect(prototype.setTypeOfService.call(socket, 0)).toBe(socket);
+
+ error = errnoError("EPERM");
+ expect(() => prototype.setTypeOfService.call(socket, 0)).toThrow(error);
+
+ error = { code: "EINVAL" };
+ expect(() => prototype.setTypeOfService.call(socket, 0)).toThrow();
+ });
+
+ it("changes nothing off macOS or on a runtime without setTypeOfService", () => {
+ const error = errnoError("EINVAL");
+ const prototype = {
+ setTypeOfService() {
+ throw error;
+ },
+ };
+ const original = prototype.setTypeOfService;
+ ignoreMacosTypeOfServiceEinval("linux", prototype);
+ ignoreMacosTypeOfServiceEinval("win32", prototype);
+ expect(prototype.setTypeOfService).toBe(original);
+ expect(() => prototype.setTypeOfService()).toThrow(error);
+
+ const withoutTypeOfService = {};
+ ignoreMacosTypeOfServiceEinval("darwin", withoutTypeOfService);
+ expect(withoutTypeOfService).not.toHaveProperty("setTypeOfService");
+ });
+
+ // Bundled undici 7 calls this API from a socket callback. Keep the real fetch
+ // in a child so an escaped EINVAL exits that process instead of breaking Vitest.
+ it.effect.runIf(
+ typeof (NodeNet.Socket.prototype as { setTypeOfService?: unknown }).setTypeOfService ===
+ "function" && process.versions.undici?.startsWith("7.") === true,
+ )("keeps built-in fetch working when setTypeOfService throws EINVAL", () =>
+ Effect.gen(function* () {
+ const child = yield* runNode([
+ "--input-type=module",
+ "--eval",
+ `
+import * as NodeNet from "node:net";
+import * as NodeTls from "node:tls";
+import { ignoreMacosTypeOfServiceEinval } from ${JSON.stringify(new URL("./outboundHttp.ts", import.meta.url).href)};
+
+NodeTls.setDefaultCACertificates([${JSON.stringify(TEST_CERT)}]);
+let calls = 0;
+NodeNet.Socket.prototype.setTypeOfService = () => {
+ calls++;
+ throw Object.assign(new Error("setTypeOfService EINVAL"), { code: "EINVAL" });
+};
+ignoreMacosTypeOfServiceEinval("darwin");
+console.log(await (await fetch(${JSON.stringify(origin)})).text());
+if (calls === 0) throw new Error("fetch did not call setTypeOfService");
+`,
+ ]);
+ expect(child.exitCode, child.stderr).toBe(0);
+ expect(child.stdout.trim()).toBe("1.1");
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("guards ordinary CLI and both ACP fast paths before their imports run", () =>
+ Effect.gen(function* () {
+ const dispatchModules = ["mcp/AcpMcpStdioBridge.ts", "cli/consoleStdin.ts", "binCli.ts"];
+ // Load the real entrypoint, but replace dispatch modules to avoid starting
+ // the app. Probe at import time, when those modules could first open sockets.
+ const preload = `
+import * as NodeModule from "node:module";
+import * as NodeNet from "node:net";
+
+Object.defineProperty(process, "platform", { value: "darwin" });
+NodeNet.Socket.prototype.setTypeOfService = () => {
+ throw Object.assign(new Error("setTypeOfService EINVAL"), { code: "EINVAL" });
+};
+NodeModule.registerHooks({
+ load(url, context, nextLoad) {
+ const path = ${JSON.stringify(dispatchModules)}.find((path) => url.endsWith("/src/" + path));
+ if (path === undefined) return nextLoad(url, context);
+ NodeNet.Socket.prototype.setTypeOfService.call(new NodeNet.Socket(), 0);
+ console.log(path);
+ return {
+ format: "module",
+ source: "export const runAcpMcpCliFastPath = async () => {}; export const attachConsoleStdin = () => {}; export const runCli = () => {};",
+ shortCircuit: true,
+ };
+ },
+});
+`;
+ const children = yield* Effect.forEach(
+ ["--version", "acp-mcp-bridge", "acp-mcp-call"],
+ (command) =>
+ runNode([
+ "--import",
+ `data:text/javascript,${encodeURIComponent(preload)}`,
+ NodeURL.fileURLToPath(new URL("./bin.ts", import.meta.url)),
+ command,
+ ]),
+ );
+ expect(
+ children.map((child) => child.exitCode),
+ children.map((child) => child.stderr).join("\n"),
+ ).toEqual([0, 0, 0]);
+ expect(children.map((child) => child.stdout.trim().split("\n"))).toEqual([
+ ["cli/consoleStdin.ts", "binCli.ts"],
+ ["mcp/AcpMcpStdioBridge.ts"],
+ ["mcp/AcpMcpStdioBridge.ts"],
+ ]);
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+});
+
describe("extendConnectionAttemptTimeout", () => {
it("raises a default below the floor to 1000 ms", () => {
NodeNet.setDefaultAutoSelectFamilyAttemptTimeout(50);
diff --git a/apps/server/src/outboundHttp.ts b/apps/server/src/outboundHttp.ts
index f4463ba1d2c..aeb7f69aba9 100644
--- a/apps/server/src/outboundHttp.ts
+++ b/apps/server/src/outboundHttp.ts
@@ -43,6 +43,31 @@ export function keepOutboundFetchOnHttp1(): void {
if (builtinFetchUsesHttp2(process.versions.undici)) installHttp1FetchDispatcher();
}
+// @types/node does not declare setTypeOfService yet.
+type TypeOfServiceSocket = {
+ setTypeOfService?: (this: NodeNet.Socket, typeOfService: number) => NodeNet.Socket;
+};
+
+// Bundled undici calls this from a socket callback without catching. On macOS,
+// EINVAL after a peer reset must not exit the server over an optional QoS hint.
+export function ignoreMacosTypeOfServiceEinval(
+ // oxlint-disable-next-line t3code/no-global-process-runtime -- Runs before ACP dispatch without loading the Effect graph.
+ platform = process.platform,
+ socketPrototype: TypeOfServiceSocket = NodeNet.Socket.prototype as TypeOfServiceSocket,
+): void {
+ if (platform !== "darwin") return;
+ const setTypeOfService = socketPrototype.setTypeOfService;
+ if (typeof setTypeOfService !== "function") return;
+ socketPrototype.setTypeOfService = function (...args) {
+ try {
+ return setTypeOfService.apply(this, args);
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "EINVAL") return this;
+ throw error;
+ }
+ };
+}
+
/**
* Node's 250 ms Happy Eyeballs attempt timeout abandons a working-but-slow IPv4
* connect when IPv6 is advertised but unroutable, which broke the ACP registry