diff --git a/src/external-summary-runtime.ts b/src/external-summary-runtime.ts index 038aeabbb9..a5e05402a0 100644 --- a/src/external-summary-runtime.ts +++ b/src/external-summary-runtime.ts @@ -3,10 +3,15 @@ import { SummaryCredentialStore } from "./external-summary-credentials.js"; import { createSummaryHttpCandidate } from "./external-summary-http.js"; import { parseExternalSummarySettings, type ExternalSummarySettings } from "./external-summary-settings.js"; import { ExternalSummaryExecutor, type ExternalSummaryBatchResult, type SummaryCandidate, type SummaryWork } from "./external-summary.js"; +import { log as loggerLog } from "./logger.js"; // One shared queue across all sessions and all compression entry points. const executor = new ExternalSummaryExecutor(4); +// The plan is rebuilt on every request, so a persistently-misconfigured chain +// must not spam a warn line per request — dedupe by (candidate, reason). +const seenCandidateWarnings = new Set(); + export class ConfiguredSummaryPlan { private readonly candidates: readonly SummaryCandidate[]; private readonly settings: ExternalSummarySettings; @@ -25,13 +30,22 @@ export class ConfiguredSummaryPlan { this.candidates = this.settings.targets.map((target) => { try { const key = target.apiKey !== undefined ? target.apiKey : store.resolve(target.credentialRef ?? "", env); - if (!key) throw new Error(); + if (!key) throw new Error(`credential ${target.credentialRef || "(none)"} did not resolve to a value`); const headers: Record = target.protocol === "anthropic" ? { "x-api-key": key } : target.protocol === "google" ? { "x-goog-api-key": key } : { authorization: `Bearer ${key}` }; return createSummaryHttpCandidate({ ...target, headers, proxyUrl }, this.settings.budget.maxSummaryBytes * 4 + 65536); - } catch { - // Preserve order without leaking private errors or borrowing main auth. + } catch (error) { + // Log WHY this target is unusable (once per signature) so a + // misconfigured chain is diagnosable instead of silently degrading + // every fold to main-model summaries (#2484). The placeholder keeps + // its generic message so no private detail leaks into results/wire. + const reason = error instanceof Error ? error.message : String(error); + const signature = `${target.name}|${reason}`; + if (!seenCandidateWarnings.has(signature)) { + seenCandidateWarnings.add(signature); + loggerLog("warn", `[external-summary] candidate ${target.name} unavailable: ${reason} — it will be skipped until fixed`); + } return { async summarize(): Promise { throw new Error("External summary candidate unavailable"); } }; } }); diff --git a/src/external-summary-settings.ts b/src/external-summary-settings.ts index f753456f3a..13890fd50f 100644 --- a/src/external-summary-settings.ts +++ b/src/external-summary-settings.ts @@ -66,7 +66,11 @@ function text(value: unknown, limit: number): string { function parseBudget(raw: unknown): SummaryBudget { const rawBudget = raw === undefined ? {} : object(raw); knownKeys(rawBudget, ["totalTimeoutMs", "targetTimeoutMs", "maxSummaryBytes"]); - const totalTimeoutMs = integer(rawBudget.totalTimeoutMs, SUMMARY_DEFAULT_BUDGET.totalTimeoutMs, 100, 50_000); + // totalTimeoutMs bounds the WHOLE batch (one shared deadline across every + // chunk); a big-session fold runs a dozen or more chunks, so the cap needs + // real headroom. Long waits are safe — preflight holds the client with SSE + // keep-alives past its undici body timeout (#2484/#1647). + const totalTimeoutMs = integer(rawBudget.totalTimeoutMs, SUMMARY_DEFAULT_BUDGET.totalTimeoutMs, 100, 600_000); const targetTimeoutMs = integer(rawBudget.targetTimeoutMs, Math.min(SUMMARY_DEFAULT_BUDGET.targetTimeoutMs, totalTimeoutMs), 100, totalTimeoutMs); const maxSummaryBytes = integer(rawBudget.maxSummaryBytes, SUMMARY_DEFAULT_BUDGET.maxSummaryBytes, 128, 1024 * 1024); return { totalTimeoutMs, targetTimeoutMs, maxSummaryBytes }; diff --git a/src/preflight.ts b/src/preflight.ts index c614b301fd..9b229e4d53 100644 --- a/src/preflight.ts +++ b/src/preflight.ts @@ -21,6 +21,7 @@ import { peekRegistryOutputLimit } from "./registry.js"; import { safePrefix } from "./text-safe.js"; import { applyEstimateCalibration, currentCalibrationFactor } from "./util.js"; import { configuredSummaryPlan, type ConfiguredSummaryPlan } from "./external-summary-runtime.js"; +import type { ExternalSummaryBatchResult } from "./external-summary.js"; import type { ResolvedKernelConfig } from "./compress-settings.js"; // #247: proactive pre-forward compression. When the session's real context @@ -869,6 +870,20 @@ function emptyCompletionDetail(json: Record): string | null { return parts.length > 0 ? ` (${parts.join(", ")})` : ""; } +/** Describe why an external-summary batch yielded no usable summary (#2484): + * the batch stop reason plus each candidate attempt's outcome, so an operator + * can tell timeout / error / cancelled / invalid-plan apart instead of seeing + * one opaque "failed or exceeded their budget" line. */ +export function describeExternalSummaryFailure(batch: ExternalSummaryBatchResult): string { + if (batch.status === "failed") return `batch=failed reason=${batch.reason}`; + const result = batch.results[0]; + if (!result) return `batch=${batch.status} (no result)`; + const parts = [`batch=${batch.status}`, `result=${result.status}`]; + if (result.status === "failed") parts.push(`reason=${result.reason}`); + parts.push(`attempts=[${result.attempts.map((a) => `t${a.targetIndex}:${a.outcome}`).join(",")}]`); + return parts.join(" "); +} + async function summarizeRange(deps: PreflightDeps, content: string, startRef: string, endRef: string, lengthBudget?: number): Promise { // #1775: the cap used to be enforced only after the fact — an over-cap // assembly was discarded wholesale (the #1775 incident). Tell the model the @@ -886,7 +901,7 @@ async function summarizeRange(deps: PreflightDeps, content: string, startRef: st maxSummaryChars: deps.config.compress.maxSummaryLength }], deps.signal); const result = batch.results[0]; return result?.status === "success" ? { summary: result.summary } - : { unusable: "configured external summary candidates failed or exceeded their budget", transient: false }; + : { unusable: describeExternalSummaryFailure(batch), transient: false }; } // #626: the session remembers upstreams that require stream:true, so the // extra 400 round-trip is paid at most once per session (persisted with diff --git a/src/server/relay.ts b/src/server/relay.ts index 89d3234f3f..d3ba89742f 100644 --- a/src/server/relay.ts +++ b/src/server/relay.ts @@ -87,6 +87,12 @@ function inferWireProtocol(path: string): "openai" | "responses" | "google" | nu function armFailureShrink(prepared: Prepared, log: (level: string, msg: string) => void, reason: string, est: number): void { const s = prepared.session; if (!Number.isFinite(est) || est <= 0) return; + // An upstream-proven ceiling (overflow-arm) plus its route-origin evidence + // must never be demoted by a local payload estimate: demoting it back to + // "estimate" drops baselineFloorRaw below the probe threshold and re-fires + // the forward-probe loop every turn (#2484). usage→estimate overwrite stays + // the intended #604 behavior for generic failures with no overflow marker. + if (s.stats.lastInputTokensSource === "overflow-arm") return; if (est > s.stats.lastInputTokens) { s.stats.lastInputTokens = est; s.stats.lastInputTokensSource = "estimate"; @@ -832,11 +838,11 @@ export async function forward( } // #604: relay/gateway 5xx — no usage report will arrive, so arm the // emergency shrink with a local estimate of the wire body we just sent - // (see armFailureShrink for the deadlock this breaks). Generic relay - // errors (new_api_error etc.) are not overflow signatures and carry no - // window number, so this is the only self-heal path for them; - // inspectContextOverflow never matches 5xx (400/413 only), so the - // overflow path above could not have handled this response. + // (see armFailureShrink for the deadlock this breaks). A generic relay + // error carries no overflow marker or window number, so this is its only + // self-heal path; a 5xx whose body DOES match an overflow marker was + // already armed by the overflow path above, and armFailureShrink's + // overflow-arm guard keeps this estimate from demoting that ceiling (#2484). if (prepared?.session && upstream.status >= 500) { armFailureShrink(prepared, log, `upstream ${upstream.status}`, outboundPayloadBreakdown(prepared, opts, route, req.url ?? "").armEstimate); } diff --git a/src/util.ts b/src/util.ts index ed6e3e58cd..9585123718 100644 --- a/src/util.ts +++ b/src/util.ts @@ -300,11 +300,15 @@ function parseOverflowWindow(text: string): number | undefined { } /** Inspect an upstream response for a context-overflow error. `status` is the - * HTTP status; `bodyText` is the (usually small) error body. Only 400/413 with - * a recognized context-too-long marker counts. */ + * HTTP status; `bodyText` is the (usually small) error body. 400/413 and any + * 5xx are checked against the recognized context-too-long markers; the marker + * match is the real gate, so a generic server error (no marker) never counts. + * 5xx is included because some gateways relay the model provider's overflow + * rejection under 502/503 rather than 400 (#2484). */ export function inspectContextOverflow(status: number, bodyText: string): ContextOverflowInfo { const message = (bodyText ?? "").slice(0, 300); - if (status !== 400 && status !== 413) return { isOverflow: false, message }; + const plausible = status === 400 || status === 413 || status >= 500; + if (!plausible) return { isOverflow: false, message }; if (!bodyText) return { isOverflow: false, message }; const isOverflow = CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(bodyText)); if (!isOverflow) return { isOverflow: false, message }; diff --git a/tests/context-overflow.test.ts b/tests/context-overflow.test.ts index 2b38cac576..77ac2fe9ea 100644 --- a/tests/context-overflow.test.ts +++ b/tests/context-overflow.test.ts @@ -139,9 +139,16 @@ test("2xx with a context-looking phrase is NOT an overflow (only 400/413)", () = assert.equal(info.isOverflow, false); }); -test("5xx is NOT an overflow (server error, not context)", () => { - const info = inspectContextOverflow(500, "context length exceeded"); - assert.equal(info.isOverflow, false); +test("a 5xx carrying an overflow marker IS an overflow (gateway-relayed rejection, #2484)", () => { + // Some gateways relay the model provider's overflow rejection under + // 502/503 instead of 400 — the body marker is the real gate, so these count. + assert.equal(inspectContextOverflow(502, '{"error":{"message":"exceeds the context window","type":"upstream_error"}}').isOverflow, true); + assert.equal(inspectContextOverflow(500, "context length exceeded").isOverflow, true); +}); + +test("a bare 5xx without an overflow marker is NOT an overflow", () => { + assert.equal(inspectContextOverflow(500, "Internal Server Error").isOverflow, false); + assert.equal(inspectContextOverflow(503, '{"error":"upstream unavailable"}').isOverflow, false); }); test("empty body is NOT an overflow", () => { diff --git a/tests/external-summary-settings.test.ts b/tests/external-summary-settings.test.ts index 1320fa333d..3812fdf58c 100644 --- a/tests/external-summary-settings.test.ts +++ b/tests/external-summary-settings.test.ts @@ -86,7 +86,7 @@ for (const invalid of [ { enabled: true, targets: [{}] }, { enabled: true, targets: ["glm"] }, { enabled: true, targets: ["glm/"] }, { enabled: true, targets: ["/flash"] }, { enabled: true, targets: ["glm/glm-4.9-flash\n"] }, - { enabled: true, budget: { totalTimeoutMs: 60_000 } }, + { enabled: true, budget: { totalTimeoutMs: 700_000 } }, { enabled: true, budget: { totalTimeoutMs: 100, targetTimeoutMs: 101 } }, { enabled: true, budget: { concurrency: 1000 } }, { enabled: true, targets: Array.from({ length: 17 }, () => "glm/glm-4.9-flash") }, @@ -97,6 +97,13 @@ for (const invalid of [ }); } +test("totalTimeoutMs accepts the widened cap and rejects above it (#2484)", () => { + // A big-session fold runs a dozen or more chunks against one shared + // deadline, so the cap was raised from 50s to 600s; the default stays 50s. + assert.doesNotThrow(() => parseExternalSummaryChain({ enabled: true, targets: ["glm/glm-4.9-flash"], budget: { totalTimeoutMs: 600_000 } })); + assert.throws(() => parseExternalSummaryChain({ enabled: true, targets: ["glm/glm-4.9-flash"], budget: { totalTimeoutMs: 600_001 } })); +}); + for (const invalid of [ "unknown/glm-4.9-flash", "glm/unknown-model", ]) { diff --git a/tests/issue2484-overflow-and-summary.test.ts b/tests/issue2484-overflow-and-summary.test.ts new file mode 100644 index 0000000000..b6545b7a04 --- /dev/null +++ b/tests/issue2484-overflow-and-summary.test.ts @@ -0,0 +1,167 @@ +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +// #2484: a session far over its window dead-looped because a gateway relayed +// the model provider's overflow rejection under HTTP 502 (body: "exceeds the +// context window") instead of 400. Three interlocking mechanisms: +// D2. inspectContextOverflow refused every 5xx, so the overflow arm never +// fired — and when it did fire the estimate-grade failure-shrink demoted +// it back to "estimate", dropping baselineFloorRaw below the probe +// threshold and re-firing the forward-probe loop every turn. +// D4. a misconfigured external-summary chain collapsed to one opaque +// "candidate unavailable" placeholder with no log — silent degradation. +// D5. the unusable-summary note dropped the batch status + per-attempt +// outcomes, so timeout vs error vs cancelled was indistinguishable. +// (D1 = the inspectContextOverflow 5xx gate itself, pinned in +// context-overflow.test.ts; D3 = the widened totalTimeoutMs cap, pinned in +// external-summary-settings.test.ts.) + +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { NamedProviderRecipe, ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { listSessions, _resetSessionsForTest, type Session } from "../src/session.ts"; +import { setLogCapture } from "../src/logger.ts"; +import { ConfiguredSummaryPlan } from "../src/external-summary-runtime.js"; +import { SummaryCredentialStore } from "../src/external-summary-credentials.js"; +import { expandExternalSummaryChain, parseExternalSummaryChain } from "../src/external-summary-settings.js"; +import { describeExternalSummaryFailure } from "../src/preflight.js"; + +const WINDOW = 120_000; +const OVERFLOW_BODY = '{"error":{"message":"Your input exceeds the context window","type":"upstream_error"}}'; + +// ── D2: the overflow arm must survive the concurrent failure-shrink ────────── + +/** Relay that answers every request with a fixed status + body (the gateway + * relaying the provider's overflow rejection under 502). */ +function makeRelay(status: number, body: string) { + const server = http.createServer((req, res) => { + req.resume(); + req.on("end", () => { + res.writeHead(status, { "content-type": "application/json" }); + res.end(body); + }); + }); + return server; +} + +async function startHarness(status: number, body: string) { + const logs: string[] = []; + setLogCapture((level, msg) => { logs.push(`${level} ${msg}`); }); + _resetSessionsForTest(); + const relay = makeRelay(status, body); + relay.listen(0, "127.0.0.1"); + await once(relay, "listening"); + const upstreamPort = (relay.address() as { port: number }).port; + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "gpt-test": { context: WINDOW } } } }, + modelContextLimit: WINDOW, + kernelConfig: defaultConfig(WINDOW), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: true, + debug: false, + passthrough: false, + compat: { roles: {} }, streamErrorShape: "protocol", passthroughSource: null, autoRestartOnUpdate: false, updateTag: "latest", advisoryCheck: false, releaseNotesCheck: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + const url = `http://127.0.0.1:${(proxy.address() as { port: number }).port}/bili/http://127.0.0.1:${upstreamPort}/v1/chat/completions`; + const post = (messages: Array<{ role: string; content: unknown }>) => fetch(url, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "gpt-test", max_tokens: 1024, stream: true, messages }), + }); + const anonSession = (): Session => { + const s = listSessions().find((x) => x.metadata.anonymousPrefixAffinity); + assert.ok(s, "an anonymous prefix-affinity session exists"); + return s!; + }; + const close = async () => { + await new Promise((r) => proxy.close(() => r())); + await new Promise((r) => relay.close(() => r())); + }; + return { logs, post, anonSession, close }; +} + +test("#2484 D2: a 5xx carrying an overflow marker keeps the overflow-arm (not demoted to estimate)", async () => { + const h = await startHarness(502, OVERFLOW_BODY); + try { + const r1 = await h.post([ + { role: "user", content: "hello, please help me with task A" }, + { role: "assistant", content: "sure, here is step one." }, + { role: "user", content: "continue with step two" }, + ]); + assert.equal(r1.status, 502, "the gateway 502 passes through verbatim"); + await r1.text(); + const s = h.anonSession(); + // Pre-fix: armFailureShrink ran right after armOverflowShrink in the + // !ok branch and overwrote lastInputTokensSource back to "estimate", + // dropping baselineFloorRaw and re-arming the forward-probe loop on + // every turn. Post-fix the upstream-proven ceiling survives. + assert.equal(s.stats.lastInputTokensSource, "overflow-arm", "the overflow arm is not demoted by the failure-shrink estimate"); + } finally { + await h.close(); + } +}); + +// ── D4: a misconfigured chain is logged, not silently degraded ─────────────── + +test("#2484 D4: an unresolvable summary credential warns once with the reference named", async () => { + const logs: string[] = []; + setLogCapture((level, msg) => { logs.push(`${level} ${msg}`); }); + const rootPath = mkdtempSync(join(tmpdir(), "bili-issue2484-")); + const store = new SummaryCredentialStore(join(rootPath, "keys.json")); + const recipes: Record = { + glm: { baseUrl: "https://open.bigmodel.cn/api/paas/v4", api: "openai", apiKeyEnv: "BILI_TEST_MISSING_KEY", models: { "glm-x": {} } }, + }; + const planSettings = expandExternalSummaryChain(parseExternalSummaryChain({ enabled: true, targets: ["glm/glm-x"] }), recipes); + try { + // An empty env guarantees the `env:BILI_TEST_MISSING_KEY` reference + // resolves to nothing → the candidate becomes a placeholder. + new ConfiguredSummaryPlan(planSettings, store, {}); + const warns = logs.filter((l) => l.includes("unavailable") && l.includes("BILI_TEST_MISSING_KEY")); + assert.equal(warns.length, 1, "exactly one diagnostic naming the unresolved reference"); + // Reconstructing the same broken chain must not spam a second warn. + new ConfiguredSummaryPlan(planSettings, store, {}); + assert.equal(logs.filter((l) => l.includes("unavailable") && l.includes("BILI_TEST_MISSING_KEY")).length, 1, "warn-once across reconstructions"); + } finally { + setLogCapture(null); + } +}); + +// ── D5: the unusable-summary diagnostic carries the real batch detail ──────── + +test("#2484 D5: describeExternalSummaryFailure surfaces the batch stop reason + per-attempt outcomes", () => { + assert.equal( + describeExternalSummaryFailure({ status: "cancelled", results: [{ status: "cancelled", attempts: [{ targetIndex: 0, outcome: "cancelled" }] }] }), + "batch=cancelled result=cancelled attempts=[t0:cancelled]", + ); + assert.equal( + describeExternalSummaryFailure({ status: "deadline", results: [] }), + "batch=deadline (no result)", + ); + assert.equal( + describeExternalSummaryFailure({ status: "finished", results: [{ status: "failed", reason: "exhausted", attempts: [{ targetIndex: 0, outcome: "timeout" }, { targetIndex: 1, outcome: "error" }] }] }), + "batch=finished result=failed reason=exhausted attempts=[t0:timeout,t1:error]", + ); + assert.equal( + describeExternalSummaryFailure({ status: "failed", reason: "invalid_plan", results: [] }), + "batch=failed reason=invalid_plan", + ); +});