Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions src/external-summary-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>();

export class ConfiguredSummaryPlan {
private readonly candidates: readonly SummaryCandidate[];
private readonly settings: ExternalSummarySettings;
Expand All @@ -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<string, string> = 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<string> { throw new Error("External summary candidate unavailable"); } };
}
});
Expand Down
6 changes: 5 additions & 1 deletion src/external-summary-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down
17 changes: 16 additions & 1 deletion src/preflight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -869,6 +870,20 @@ function emptyCompletionDetail(json: Record<string, unknown>): 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<SummaryOutcome> {
// #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
Expand All @@ -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
Expand Down
16 changes: 11 additions & 5 deletions src/server/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
}
Expand Down
10 changes: 7 additions & 3 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down
13 changes: 10 additions & 3 deletions tests/context-overflow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
9 changes: 8 additions & 1 deletion tests/external-summary-settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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") },
Expand All @@ -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",
]) {
Expand Down
Loading
Loading