From 1a2be868d3d1265e3061b75a074edb4893c39ad1 Mon Sep 17 00:00:00 2001 From: TutorLink Dev Date: Sun, 4 Oct 2026 20:54:17 +0530 Subject: [PATCH 1/2] fix(worker): ignore Canceled unhandled rejections VS Code promise-cancellation races surface as Canceled rejections (e.g. a pending ptyHost resolved-variables RPC cancelled on extension-host restart). Treating them as fatal crashed the worker on every restart, and the respawn loop re-triggered the same race. Canceled rejections (by name or message) are now logged and ignored; all others still forward { type: error } to the parent and exit 1, so the respawn contract is unchanged. Adds lib/worker.test.ts: forks the actual worker.mjs against a stubbed dist entry in a temp dir and covers both Canceled shapes plus the forward-and-exit path end-to-end over IPC. --- README.md | 2 +- lib/worker.mjs | 18 +++++- lib/worker.test.ts | 150 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 168 insertions(+), 2 deletions(-) create mode 100644 lib/worker.test.ts diff --git a/README.md b/README.md index 5be180e..9a15779 120000 --- a/README.md +++ b/README.md @@ -1 +1 @@ -lib/README.md \ No newline at end of file +lib/README.md diff --git a/lib/worker.mjs b/lib/worker.mjs index dc466d6..04df972 100644 --- a/lib/worker.mjs +++ b/lib/worker.mjs @@ -61,4 +61,20 @@ const forwardFatal = (kind) => (err) => { }; process.on("uncaughtException", forwardFatal("uncaughtException")); -process.on("unhandledRejection", forwardFatal("unhandledRejection")); + +// VS Code's promise-cancellation races surface as `Canceled` rejections — for +// example a pending ptyHost resolved-variables RPC cancelled when the +// extension host restarts. Those are by design, not bugs: treating them as +// fatal makes every extension-host restart crash the worker, and because the +// parent respawns us and the browser reconnects, the same race fires again — +// a self-sustaining crash loop. Log and keep going; every other rejection +// still forwards to the parent and exits. +const isCanceled = (err) => err?.name === "Canceled" || err?.message === "Canceled"; + +process.on("unhandledRejection", (err) => { + if (isCanceled(err)) { + console.error("[coderaft worker] ignoring Canceled rejection:", err); + return; + } + forwardFatal("unhandledRejection")(err); +}); diff --git a/lib/worker.test.ts b/lib/worker.test.ts new file mode 100644 index 0000000..8283a9e --- /dev/null +++ b/lib/worker.test.ts @@ -0,0 +1,150 @@ +// Integration coverage for the worker's `Canceled`-rejection filter +// (lib/worker.mjs). +// +// The worker is a forked entry that imports the built code-server from +// ./dist/index.mjs, so these tests run the *actual shipped* worker.mjs bytes +// against a stubbed code-server entry in a temp dir — no build required, and +// the fork/IPC contract with lib/src/spawn.ts (forward `{ type: "error" }`, +// then exit 1) is exercised end-to-end. +// +// Cases mirror the production crash loop: +// - a `Canceled` rejection (by name OR message — the cancelled ptyHost +// resolved-variables RPC shape) must NOT terminate the worker; +// - any other rejection must still be forwarded to the parent and exit 1, +// so SpawnedCodeServer's respawn contract is unchanged. + +import { fork, type ChildProcess } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterEach, describe, expect, it } from "vitest"; + +const workerSource = readFileSync(fileURLToPath(new URL("./worker.mjs", import.meta.url)), "utf8"); + +type WorkerMessage = { type: string } & Record; + +interface WorkerHarness { + child: ChildProcess; + messages: WorkerMessage[]; + /** Mutable container — the `data` callback fills it after `fork()` returns. */ + stderr: { text: string }; + exit: Promise<{ code: number | null; signal: NodeJS.Signals | null }>; + dir: string; +} + +function spawnWorker(serverBody: string): WorkerHarness { + const dir = mkdtempSync(join(tmpdir(), "coderaft-worker-test-")); + mkdirSync(join(dir, "dist"), { recursive: true }); + writeFileSync(join(dir, "worker.mjs"), workerSource); + writeFileSync( + join(dir, "dist", "index.mjs"), + `export function startCodeServer() { ${serverBody} }`, + ); + + const child = fork(join(dir, "worker.mjs"), { + stdio: ["ignore", "pipe", "pipe", "ipc"], + }); + const messages: WorkerMessage[] = []; + const stderr: { text: string } = { text: "" }; + child.on("message", (msg) => messages.push(msg as WorkerMessage)); + child.stderr?.on("data", (chunk: Buffer) => { + stderr.text += chunk.toString(); + }); + const exit = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => { + child.once("exit", (code, signal) => resolve({ code, signal })); + }); + return { child, messages, stderr, exit, dir }; +} + +const READY_HANDLE = + `return { url: "http://127.0.0.1:8080", port: 8080, ` + + `socketPath: undefined, connectionToken: "test" };`; + +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +async function startWorker(serverBody: string): Promise { + const harness = spawnWorker(serverBody); + harness.child.send({ type: "start", opts: {} }); + await waitForReady(harness); + return harness; +} + +function waitForReady(harness: WorkerHarness, timeoutMs = 2000): Promise { + return new Promise((resolve, reject) => { + const started = Date.now(); + const poll = () => { + if (harness.messages.some((m) => m.type === "ready")) { + resolve(); + } else if (Date.now() - started > timeoutMs) { + reject(new Error("worker did not become ready")); + } else { + setTimeout(poll, 10); + } + }; + poll(); + }); +} + +describe("worker unhandledRejection filter", () => { + const running: WorkerHarness[] = []; + + afterEach(async () => { + for (const harness of running) { + harness.child.kill("SIGTERM"); + await Promise.race([harness.exit, delay(1000)]); + rmSync(harness.dir, { recursive: true, force: true }); + } + running.length = 0; + }); + + it("does not terminate on a Canceled rejection (by name)", async () => { + const harness = await startWorker(` + setTimeout(() => { + Promise.reject(Object.assign(new Error("canceled"), { name: "Canceled" })); + }, 20); + ${READY_HANDLE} + `); + running.push(harness); + + await delay(200); + + expect(harness.messages.some((m) => m.type === "error")).toBe(false); + expect(harness.child.exitCode).toBeNull(); + expect(harness.stderr.text).toContain("ignoring Canceled rejection"); + }); + + it("does not terminate on a Canceled rejection (by message)", async () => { + const harness = await startWorker(` + setTimeout(() => { + Promise.reject(new Error("Canceled")); + }, 20); + ${READY_HANDLE} + `); + running.push(harness); + + await delay(200); + + expect(harness.messages.some((m) => m.type === "error")).toBe(false); + expect(harness.child.exitCode).toBeNull(); + expect(harness.stderr.text).toContain("ignoring Canceled rejection"); + }); + + it("forwards a non-Canceled rejection to the parent and exits 1", async () => { + const harness = await startWorker(` + setTimeout(() => { + Promise.reject(new Error("ptyHost resolve failed")); + }, 20); + ${READY_HANDLE} + `); + running.push(harness); + + const result = await Promise.race([harness.exit, delay(2000).then(() => null)]); + + expect(result?.code).toBe(1); + const forwarded = harness.messages.find((m) => m.type === "error"); + expect(forwarded).toBeDefined(); + expect(String(forwarded?.message)).toContain("unhandledRejection"); + expect(String(forwarded?.message)).toContain("ptyHost resolve failed"); + }); +}); From 6c52eaad32f6c211eb2787c0545cdadbb15b2388 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Sun, 22 Nov 2026 14:53:09 +0000 Subject: [PATCH 2/2] fix(worker): tighten Canceled filter and harden fatal-error handling - Restore README.md symlink target (a trailing newline broke it). - Match VS Code's isCancellationError (Error with name AND message "Canceled") instead of name OR message. - Apply the filter to uncaughtException too (--unhandled-rejections=strict). - Log only the first ignored Canceled error, and none during shutdown. - Give unhandled rejections a 1s grace period (cancelled on rejectionHandled) before treating them as fatal, like VS Code. - Tests: register harness before awaiting ready, SIGKILL stragglers, poll instead of fixed sleeps, cover the new cases. --- README.md | 2 +- lib/worker.mjs | 62 +++++++++++++++----- lib/worker.test.ts | 139 +++++++++++++++++++++++++++------------------ 3 files changed, 133 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index 9a15779..5be180e 120000 --- a/README.md +++ b/README.md @@ -1 +1 @@ -lib/README.md +lib/README.md \ No newline at end of file diff --git a/lib/worker.mjs b/lib/worker.mjs index 04df972..930b5c2 100644 --- a/lib/worker.mjs +++ b/lib/worker.mjs @@ -60,21 +60,53 @@ const forwardFatal = (kind) => (err) => { } }; -process.on("uncaughtException", forwardFatal("uncaughtException")); +// VS Code's promise-cancellation races surface as `CancellationError`s — for +// example RequestStore's timeout promise rejecting when a pending ptyHost +// resolved-variables request is cancelled on extension-host restart (it has +// no rejection handler). Those are by design, not bugs: VS Code's own +// handlers ignore them. Treating them as fatal makes every extension-host +// restart crash the worker, and because the parent respawns us and the +// browser reconnects, the same race fires again — a self-sustaining crash +// loop. Mirrors VS Code's `isCancellationError` (src/vs/base/common/errors.ts). +const isCanceled = (err) => + err instanceof Error && err.name === "Canceled" && err.message === "Canceled"; -// VS Code's promise-cancellation races surface as `Canceled` rejections — for -// example a pending ptyHost resolved-variables RPC cancelled when the -// extension host restarts. Those are by design, not bugs: treating them as -// fatal makes every extension-host restart crash the worker, and because the -// parent respawns us and the browser reconnects, the same race fires again — -// a self-sustaining crash loop. Log and keep going; every other rejection -// still forwards to the parent and exits. -const isCanceled = (err) => err?.name === "Canceled" || err?.message === "Canceled"; +// RequestStore cancels its timeout on every successful reply, so these are +// frequent in normal operation. Log the first one only. +let loggedCanceled = false; +const ignoreCanceled = (err) => { + if (loggedCanceled || shuttingDown) return; + loggedCanceled = true; + console.error( + "[coderaft worker] ignoring Canceled error (further ones will not be logged):", + err, + ); +}; -process.on("unhandledRejection", (err) => { - if (isCanceled(err)) { - console.error("[coderaft worker] ignoring Canceled rejection:", err); - return; - } - forwardFatal("unhandledRejection")(err); +// With `--unhandled-rejections=strict` (e.g. via NODE_OPTIONS), rejections +// arrive here instead of `unhandledRejection`, so filter in both places. +process.on("uncaughtException", (err) => { + if (isCanceled(err)) return ignoreCanceled(err); + forwardFatal("uncaughtException")(err); +}); + +// Node emits `unhandledRejection` as soon as a rejected promise has no handler +// at the end of a microtask drain, even if one is attached a tick later. Like +// VS Code, give it a grace period and only treat it as fatal if it is still +// unhandled afterwards. +const UNHANDLED_REJECTION_GRACE_MS = 1000; +const pendingRejections = new Map(); + +process.on("unhandledRejection", (reason, promise) => { + if (shuttingDown) return; + if (isCanceled(reason)) return ignoreCanceled(reason); + pendingRejections.set(promise, reason); + setTimeout(() => { + if (!pendingRejections.delete(promise)) return; + forwardFatal("unhandledRejection")(reason); + }, UNHANDLED_REJECTION_GRACE_MS); +}); + +process.on("rejectionHandled", (promise) => { + pendingRejections.delete(promise); }); diff --git a/lib/worker.test.ts b/lib/worker.test.ts index 8283a9e..73d0389 100644 --- a/lib/worker.test.ts +++ b/lib/worker.test.ts @@ -1,5 +1,4 @@ -// Integration coverage for the worker's `Canceled`-rejection filter -// (lib/worker.mjs). +// Integration coverage for the worker's fatal-error filtering (lib/worker.mjs). // // The worker is a forked entry that imports the built code-server from // ./dist/index.mjs, so these tests run the *actual shipped* worker.mjs bytes @@ -8,8 +7,9 @@ // then exit 1) is exercised end-to-end. // // Cases mirror the production crash loop: -// - a `Canceled` rejection (by name OR message — the cancelled ptyHost -// resolved-variables RPC shape) must NOT terminate the worker; +// - a VS Code `CancellationError` (name AND message "Canceled") must NOT +// terminate the worker, whether it arrives as a rejection or an exception; +// - a rejection that gets a handler within the grace period is not fatal; // - any other rejection must still be forwarded to the parent and exit 1, // so SpawnedCodeServer's respawn contract is unchanged. @@ -23,16 +23,20 @@ import { afterEach, describe, expect, it } from "vitest"; const workerSource = readFileSync(fileURLToPath(new URL("./worker.mjs", import.meta.url)), "utf8"); type WorkerMessage = { type: string } & Record; +type ExitResult = { code: number | null; signal: NodeJS.Signals | null }; interface WorkerHarness { child: ChildProcess; messages: WorkerMessage[]; /** Mutable container — the `data` callback fills it after `fork()` returns. */ stderr: { text: string }; - exit: Promise<{ code: number | null; signal: NodeJS.Signals | null }>; + exit: Promise; + exited: boolean; dir: string; } +const running: WorkerHarness[] = []; + function spawnWorker(serverBody: string): WorkerHarness { const dir = mkdtempSync(join(tmpdir(), "coderaft-worker-test-")); mkdirSync(join(dir, "dist"), { recursive: true }); @@ -44,107 +48,134 @@ function spawnWorker(serverBody: string): WorkerHarness { const child = fork(join(dir, "worker.mjs"), { stdio: ["ignore", "pipe", "pipe", "ipc"], + env: { ...process.env, NODE_OPTIONS: "" }, }); - const messages: WorkerMessage[] = []; - const stderr: { text: string } = { text: "" }; - child.on("message", (msg) => messages.push(msg as WorkerMessage)); + const harness: WorkerHarness = { + child, + messages: [], + stderr: { text: "" }, + exit: undefined as unknown as Promise, + exited: false, + dir, + }; + // Register before anything can fail so afterEach always cleans up. + running.push(harness); + child.on("message", (msg) => harness.messages.push(msg as WorkerMessage)); child.stderr?.on("data", (chunk: Buffer) => { - stderr.text += chunk.toString(); + harness.stderr.text += chunk.toString(); }); - const exit = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => { - child.once("exit", (code, signal) => resolve({ code, signal })); + harness.exit = new Promise((resolve) => { + child.once("exit", (code, signal) => { + harness.exited = true; + resolve({ code, signal }); + }); }); - return { child, messages, stderr, exit, dir }; + return harness; } const READY_HANDLE = `return { url: "http://127.0.0.1:8080", port: 8080, ` + - `socketPath: undefined, connectionToken: "test" };`; + `socketPath: undefined, connectionToken: "test", close: async () => {} };`; + +/** A VS Code `CancellationError` — name and message are both "Canceled". */ +const CANCELLATION_ERROR = `Object.assign(new Error("Canceled"), { name: "Canceled" })`; const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); async function startWorker(serverBody: string): Promise { const harness = spawnWorker(serverBody); harness.child.send({ type: "start", opts: {} }); - await waitForReady(harness); + await waitFor(() => harness.messages.some((m) => m.type === "ready"), "worker ready"); return harness; } -function waitForReady(harness: WorkerHarness, timeoutMs = 2000): Promise { - return new Promise((resolve, reject) => { - const started = Date.now(); - const poll = () => { - if (harness.messages.some((m) => m.type === "ready")) { - resolve(); - } else if (Date.now() - started > timeoutMs) { - reject(new Error("worker did not become ready")); - } else { - setTimeout(poll, 10); - } - }; - poll(); - }); +async function waitFor(check: () => boolean, what: string, timeoutMs = 3000): Promise { + const deadline = Date.now() + timeoutMs; + while (!check()) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`); + await delay(10); + } } -describe("worker unhandledRejection filter", () => { - const running: WorkerHarness[] = []; +async function expectStaysAlive(harness: WorkerHarness): Promise { + // Outlast the worker's 1s unhandled-rejection grace period. + await delay(1300); + expect(harness.messages.some((m) => m.type === "error")).toBe(false); + expect(harness.exited).toBe(false); +} +describe("worker fatal-error filter", () => { afterEach(async () => { for (const harness of running) { - harness.child.kill("SIGTERM"); - await Promise.race([harness.exit, delay(1000)]); + if (!harness.exited) { + harness.child.kill("SIGTERM"); + await Promise.race([harness.exit, delay(1000)]); + if (!harness.exited) { + harness.child.kill("SIGKILL"); + await harness.exit; + } + } rmSync(harness.dir, { recursive: true, force: true }); } running.length = 0; }); - it("does not terminate on a Canceled rejection (by name)", async () => { + it("does not terminate on a Canceled rejection, and logs it once", async () => { const harness = await startWorker(` setTimeout(() => { - Promise.reject(Object.assign(new Error("canceled"), { name: "Canceled" })); + Promise.reject(${CANCELLATION_ERROR}); + Promise.reject(${CANCELLATION_ERROR}); }, 20); ${READY_HANDLE} `); - running.push(harness); - await delay(200); + await waitFor(() => harness.stderr.text.includes("ignoring Canceled error"), "log line"); + await expectStaysAlive(harness); + expect(harness.stderr.text.split("ignoring Canceled error").length - 1).toBe(1); + }); - expect(harness.messages.some((m) => m.type === "error")).toBe(false); - expect(harness.child.exitCode).toBeNull(); - expect(harness.stderr.text).toContain("ignoring Canceled rejection"); + it("does not terminate on a Canceled uncaught exception", async () => { + const harness = await startWorker(` + setTimeout(() => { throw ${CANCELLATION_ERROR}; }, 20); + ${READY_HANDLE} + `); + + await waitFor(() => harness.stderr.text.includes("ignoring Canceled error"), "log line"); + await expectStaysAlive(harness); }); - it("does not terminate on a Canceled rejection (by message)", async () => { + it("does not terminate when a rejection is handled within the grace period", async () => { const harness = await startWorker(` setTimeout(() => { - Promise.reject(new Error("Canceled")); + const p = Promise.reject(new Error("handled later")); + setTimeout(() => p.catch(() => {}), 100); }, 20); ${READY_HANDLE} `); - running.push(harness); - await delay(200); - - expect(harness.messages.some((m) => m.type === "error")).toBe(false); - expect(harness.child.exitCode).toBeNull(); - expect(harness.stderr.text).toContain("ignoring Canceled rejection"); + await expectStaysAlive(harness); }); - it("forwards a non-Canceled rejection to the parent and exits 1", async () => { + it.each([ + ["a non-Canceled error", `new Error("ptyHost resolve failed")`, "ptyHost resolve failed"], + ["an Error whose message alone is Canceled", `new Error("Canceled")`, "Canceled"], + [ + "an Error named Canceled with a real message", + `Object.assign(new Error("disk full"), { name: "Canceled" })`, + "disk full", + ], + ])("forwards %s to the parent and exits 1", async (_label, error, expected) => { const harness = await startWorker(` - setTimeout(() => { - Promise.reject(new Error("ptyHost resolve failed")); - }, 20); + setTimeout(() => { Promise.reject(${error}); }, 20); ${READY_HANDLE} `); - running.push(harness); - const result = await Promise.race([harness.exit, delay(2000).then(() => null)]); + const result = await Promise.race([harness.exit, delay(3000).then(() => null)]); expect(result?.code).toBe(1); const forwarded = harness.messages.find((m) => m.type === "error"); expect(forwarded).toBeDefined(); expect(String(forwarded?.message)).toContain("unhandledRejection"); - expect(String(forwarded?.message)).toContain("ptyHost resolve failed"); + expect(String(forwarded?.message)).toContain(expected); }); });