From 2f8c27a5f3b2a4062adc0d1367b12ede59b79af0 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 31 Aug 2026 01:05:46 +0800 Subject: [PATCH 1/2] fix: surface raw-dump failures and rate-limit telemetry path noise (#362) - Raw dumps (INCOMING/REQ/RES/SSE) that fail now log a rate-limited warn (first failure immediate, repeats suppressed within a 60s window, cumulative count) instead of failing silently. A stopped raw/ dump (disk full, locked dir) was previously invisible. - The 'unrecognized path' telemetry warn (client event-report endpoints forwarded unchanged) is now rate-limited per path (first 3 at warn, one 'suppressed' notice, then silent) instead of logging every hit (~20k lines in one user's capture). - No change to forwarding behavior; observability only. typecheck clean; 845 tests pass; build success. --- src/server.ts | 45 +++++++++++++++++++---- tests/dump-observability.test.ts | 61 ++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 7 deletions(-) create mode 100644 tests/dump-observability.test.ts diff --git a/src/server.ts b/src/server.ts index d23c0ecdaa..2650e5f855 100644 --- a/src/server.ts +++ b/src/server.ts @@ -77,6 +77,37 @@ function bodyDumpEnabled(): boolean { return process.env.ACP_DUMP_BODY === "1"; } +// Raw dumps are best-effort: a failure (disk full, locked dir, EPERM) must not +// break the request, but a silently-stopped dump hides real problems (#362). +// Rate-limited so a stuck dir doesn't spam the log. +let dumpFailCount = 0; +let lastDumpFailLog = 0; +export function logDumpFailure(where: string, err: unknown): void { + dumpFailCount++; + const now = Date.now(); + if (dumpFailCount === 1 || now - lastDumpFailLog >= 60_000) { + lastDumpFailLog = now; + const msg = err instanceof Error ? err.message : String(err); + loggerLog("warn", `[dump] ${where} failed (total ${dumpFailCount}x): ${msg}`); + } +} + +// Non-protocol paths (client telemetry like /api/v1/event/report, ...) are +// forwarded unchanged — expected, not an error. Logging every hit spammed the +// log (~20k lines in one user's capture, #362). Per-path: first 3 at warn, one +// "suppressed" notice, then silent. +const unrecognizedPathCounts = new Map(); +export function logUnrecognizedPath(log: (level: string, msg: string) => void, url: string): void { + const key = maskUrlsInText(url); + const n = (unrecognizedPathCounts.get(key) ?? 0) + 1; + unrecognizedPathCounts.set(key, n); + if (n <= 3) { + log("warn", `unrecognized path ${key} — not a known protocol (/chat/completions, /v1/messages, /responses, /responses/compact); forwarding unchanged`); + } else if (n === 4) { + log("info", `unrecognized path ${key}: forwarding unchanged; further occurrences suppressed`); + } +} + // #300: bili→bili chain marker. When a bili instance forwards a request it has // processed upstream, it stamps this header with its own instance id. A bili // instance that RECEIVES a request already carrying it knows an upstream bili @@ -747,7 +778,7 @@ async function handle( ); const hdrText = Object.entries(hdrs).map(([k, v]) => `${k}: ${v}`).join("\n"); fs.writeFileSync(`${rawDir}/${Date.now()}-INCOMING.txt`, `${req.method} ${maskUrlsInText(req.url ?? "")}\n${hdrText}\n\n${bodyBuffer.toString("utf8")}`); - } catch { /* best-effort dump */ } + } catch (err) { logDumpFailure("INCOMING dump", err); } } // Per-request context limit + compression tuning: look up body.model against // the per-route model declaration first, then the built-in table / registry. @@ -1186,7 +1217,7 @@ async function handle( } if (!prepared) { if (protocol === null && !opts.passthrough) { - log("warn", `unrecognized path ${maskUrlsInText(req.url ?? "")} — not a known protocol (/chat/completions, /v1/messages, /responses, /responses/compact); forwarding unchanged`); + logUnrecognizedPath(log, req.url ?? ""); } await forward(req, res, opts, bodyBuffer, null, core, reqConfig, log, route, instanceId, undefined); } @@ -2212,7 +2243,7 @@ async function forward( const reqPath = `${rawBase}-REQ.txt`; fs.writeFileSync(reqPath, `${req.method ?? "POST"} ${maskUrlForLog(upstreamUrl)}\n${hdrText}\n\n${bodyText}`); log("info", `[debug] RAW request dump: ${reqPath}`); - } catch { /* best-effort */ } + } catch (err) { logDumpFailure("REQ dump", err); } } const dispatcher = proxyDispatcher(proxyUrl); const init: Omit & { dispatcher?: object } = { @@ -2263,7 +2294,7 @@ async function forward( const resPath = `${rawBase}-RES.txt`; fs.writeFileSync(resPath, `${upstream.status}\n${hdrText}\n`); log("info", `[debug] RAW response dump: ${resPath}`); - } catch { /* best-effort */ } + } catch (err) { logDumpFailure("RES dump", err); } } // P1.2: if the upstream returned a non-2xx (auth, rate-limit, context too // long, ...), do NOT route the error body through the SSE rewriter — it has @@ -2607,7 +2638,7 @@ async function dumpStreamToFile(stream: ReadableStream, dir: string, try { mkdirSync(dir, { recursive: true }); const ws = createWriteStream(join(dir, name)); - ws.on("error", (e) => { loggerLog("debug", `[dump] write stream error: ${(e as Error).message ?? e}`); }); + ws.on("error", (e) => { logDumpFailure("SSE stream dump", e); }); const reader = stream.getReader(); try { for (;;) { @@ -2619,8 +2650,8 @@ async function dumpStreamToFile(stream: ReadableStream, dir: string, reader.releaseLock(); ws.end(); } - } catch { - // best-effort dump + } catch (err) { + logDumpFailure("SSE stream dump", err); } } diff --git a/tests/dump-observability.test.ts b/tests/dump-observability.test.ts new file mode 100644 index 0000000000..ba0332a0a7 --- /dev/null +++ b/tests/dump-observability.test.ts @@ -0,0 +1,61 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +process.env.NODE_ENV = "test"; + +import { setLogCapture } from "../src/logger.ts"; +import { logDumpFailure, logUnrecognizedPath } from "../src/server.ts"; + +interface Line { level: string; msg: string; } + +// #362 noise: client telemetry paths (/api/v1/event/report, ...) are forwarded +// unchanged — expected, not an error. Logging every hit produced ~20k warn lines +// in one user's capture. Per-path: first 3 at warn, one "suppressed" notice, +// then silent. +test("logUnrecognizedPath: per-path warn x3, then one suppression notice, then silent", () => { + const lines: Line[] = []; + const log = (level: string, msg: string) => { lines.push({ level, msg }); }; + const url = "https://client.example/api/v1/event/report"; + for (let i = 0; i < 5; i++) logUnrecognizedPath(log, url); + assert.equal(lines.length, 4); + assert.equal(lines[0].level, "warn"); + assert.ok(lines[0].msg.includes("unrecognized path")); + assert.equal(lines[1].level, "warn"); + assert.equal(lines[2].level, "warn"); + assert.equal(lines[3].level, "info"); + assert.ok(lines[3].msg.includes("suppressed")); +}); + +test("logUnrecognizedPath: distinct paths are counted independently", () => { + const lines: Line[] = []; + const log = (level: string, msg: string) => { lines.push({ level, msg }); }; + logUnrecognizedPath(log, "https://a.example/p1"); + logUnrecognizedPath(log, "https://b.example/p2"); + assert.equal(lines.length, 2); + assert.ok(lines[0].msg.includes("/p1")); + assert.ok(lines[1].msg.includes("/p2")); +}); + +// #362: a raw dump that fails (disk full, locked dir, EPERM) must not break the +// request, but a silently-stopped dump hides real problems. First failure logs +// immediately, repeats within the window are suppressed, and it re-logs after +// the window with a cumulative count. +test("logDumpFailure: first failure logs, repeat suppressed, re-logs after window", (t) => { + const lines: Line[] = []; + setLogCapture((level, msg) => { lines.push({ level, msg }); }); + t.after(() => { setLogCapture(null); }); + let now = Date.now(); + t.mock.method(Date, "now", () => now); + logDumpFailure("SSE stream dump", new Error("ENOSPC: no space left on device")); + assert.equal(lines.length, 1); + assert.equal(lines[0].level, "warn"); + assert.ok(lines[0].msg.includes("SSE stream dump")); + assert.ok(lines[0].msg.includes("total 1x")); + assert.ok(lines[0].msg.includes("ENOSPC")); + logDumpFailure("SSE stream dump", new Error("ENOSPC: no space left on device")); + assert.equal(lines.length, 1); + now += 61_000; + logDumpFailure("SSE stream dump", new Error("ENOSPC: no space left on device")); + assert.equal(lines.length, 2); + assert.ok(lines[1].msg.includes("total 3x")); +}); From e6fd645a35700d6057f41e2c2bf443b265c2a35d Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Mon, 31 Aug 2026 09:23:26 +0800 Subject: [PATCH 2/2] fix: strip query string from the unrecognized-path rate-limit key A varying query (?ts=...) would split one endpoint into unbounded keys, defeating the suppression and growing the map without bound. --- src/server.ts | 4 +++- tests/dump-observability.test.ts | 9 +++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/server.ts b/src/server.ts index 2650e5f855..64b0760391 100644 --- a/src/server.ts +++ b/src/server.ts @@ -98,7 +98,9 @@ export function logDumpFailure(where: string, err: unknown): void { // "suppressed" notice, then silent. const unrecognizedPathCounts = new Map(); export function logUnrecognizedPath(log: (level: string, msg: string) => void, url: string): void { - const key = maskUrlsInText(url); + // Strip the query before masking: a varying query (?ts=…) would otherwise + // split one endpoint into unbounded keys and defeat the rate limit. + const key = maskUrlsInText(url.split("?")[0]); const n = (unrecognizedPathCounts.get(key) ?? 0) + 1; unrecognizedPathCounts.set(key, n); if (n <= 3) { diff --git a/tests/dump-observability.test.ts b/tests/dump-observability.test.ts index ba0332a0a7..7829885178 100644 --- a/tests/dump-observability.test.ts +++ b/tests/dump-observability.test.ts @@ -36,6 +36,15 @@ test("logUnrecognizedPath: distinct paths are counted independently", () => { assert.ok(lines[1].msg.includes("/p2")); }); +test("logUnrecognizedPath: a varying query string does not split the per-path key", () => { + const lines: Line[] = []; + const log = (level: string, msg: string) => { lines.push({ level, msg }); }; + for (let i = 0; i < 4; i++) logUnrecognizedPath(log, `/api/v1/event/report?ts=${i}`); + assert.equal(lines.length, 4); + assert.equal(lines[3].level, "info"); + assert.ok(lines[3].msg.includes("suppressed")); +}); + // #362: a raw dump that fails (disk full, locked dir, EPERM) must not break the // request, but a silently-stopped dump hides real problems. First failure logs // immediately, repeats within the window are suppressed, and it re-logs after