Skip to content
Closed
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
7 changes: 5 additions & 2 deletions src/external-summary-compress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { ResolvedKernelConfig } from "./compress-settings.js";
import { applyRanges, noVisibleContextRefusal, normalizeRangeOrder, recoverEvictedView, supersededRefRejection, type RewriteCtx } from "./stream.js";
import { compressResult, type ProxyToolResult } from "./proxy-tool-result.js";
import { imagePlaceholders } from "./image-note.js";
import { describeExternalSummaryFailure, summaryLengthBudgetClause, type SummaryWork } from "./external-summary.js";
import { describeExternalSummaryFailure, externalSummaryFailureAdvice, summaryLengthBudgetClause, type SummaryWork } from "./external-summary.js";
import { newExternalCallId } from "./external-summary-marker.js";

// Re-exported for callers that historically imported it here; the canonical
Expand Down Expand Up @@ -125,7 +125,10 @@ export async function applyConfiguredCompression(input: unknown, ctx: RewriteCtx
ctx.log(`[external-summary] completed ${successful.length}/${parsed.ranges.length} range(s); ${describeExternalSummaryFailure(batch)}`);
// #4833: the bounded attempt diagnostics (source + budgets + outcomes) ride
// the tool result too — enums and numbers only, never payload bytes.
if (successful.length === 0) return compressResult(`[Compression FAILED: all configured external summary candidates failed or exceeded their budget. Nothing compressed; do not retry unchanged configuration — summaries longer than the configured cap are rejected whole, so raise compress.maxSummaryLength or request less via per-range summaryMaxChars.] [${describeExternalSummaryFailure(batch)}]`, "refused", 0);
// #6885: the advice follows the batch's own stop reason and attempt
// outcomes — the old text blamed maxSummaryLength for every failure,
// including budget and parse failures that knob cannot help.
if (successful.length === 0) return compressResult(`[Compression FAILED: all configured external summary candidates failed or exceeded their budget. Nothing compressed; do not retry unchanged configuration — ${externalSummaryFailureAdvice(batch)}] [${describeExternalSummaryFailure(batch)}]`, "refused", 0);
const applied = applyRanges({ ...parsed, ranges: successful }, ctx);
// Client call arguments carry only an optional hint, never the generated summary.
// In-place refolds retain their old call id in the kernel; keep their anchor too.
Expand Down
70 changes: 67 additions & 3 deletions src/external-summary.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { log } from "./logger.js";

export interface SummaryWork {
readonly content: string;
readonly instructions: string;
Expand Down Expand Up @@ -74,7 +76,7 @@ export type ExternalSummaryBatchResult =
| { status: "finished" | "cancelled" | "deadline"; results: ExternalSummaryResult[] }
| { status: "failed"; reason: "invalid_plan"; results: [] };

type AttemptResult = { kind: "value"; value: string } | { kind: "error" } | { kind: "aborted" };
type AttemptResult = { kind: "value"; value: string } | { kind: "error"; detail?: string; warnedByCandidate?: boolean } | { kind: "aborted" };
type Release = () => void;
interface Waiter {
signal: AbortSignal;
Expand All @@ -99,6 +101,55 @@ function invalidSummaryDetail(value: unknown, limits: SummaryBudget, request: Re
return `summary ${chars} chars exceeds cap ${request.maxSummaryChars}`;
}

/** #6885: a non-fetch rejection's SAFE cause, if it has one. The executor used
* to drop every rejection reason, so a sync guard (context budget) or a
* post-fetch parse failure left only a bare `tN:error` with no warn line and
* no way to tell it from a network death. Only our own fixed error strings
* are named — the message itself, which carries no payload, status aside —
* so an unknown provider error stays opaque in the result (the no-leak rule
* the executor tests pin). `warnedByCandidate` is true for the upstream
* rejection, which the HTTP candidate already warns once per attempt with
* status + truncated body; the executor must not warn it a second time. */
interface SummaryErrorDetail { readonly detail: string; readonly warnedByCandidate: boolean; }
function summaryErrorDetail(error: unknown): SummaryErrorDetail | undefined {
const message = error instanceof Error ? error.message : undefined;
if (message === undefined) return undefined;
if (message.startsWith("External summary upstream rejected the request with HTTP ")) return { detail: message, warnedByCandidate: true };
for (const prefix of [
"Summary attempt cancelled before dispatch",
"External summary input exceeds the target context budget",
"External summary response is empty",
"External summary response exceeds its byte budget",
"External summary response did not complete",
"External summary response contains an invalid frame",
"External summary response contains no summary",
]) {
if (message.startsWith(prefix)) return { detail: message, warnedByCandidate: false };
}
return undefined;
}

/** #6885: pick the advice a failed compress result carries, from the batch's
* own stop reason and attempt outcomes — a timeout/deadline means the budget
* ran out, an over-cap rejection means the summary cap, and a named
* non-fetch failure means the cause in the attempts, not the cap. The old
* text blamed maxSummaryLength for every failure, which sent the operator to
* a knob that cannot help a budget or parse failure. */
export function externalSummaryFailureAdvice(batch: ExternalSummaryBatchResult): string {
const result = batch.status === "failed" ? undefined : (batch.results.find((entry) => entry.status !== "success") ?? batch.results[0]);
if (result === undefined) return "see the attempt outcomes for the cause.";
if (result.status === "deadline" || result.attempts.some((attempt) => attempt.outcome === "timeout")) {
return "candidates ran out of budget before a summary completed, so raise the external-summary budget (budget.totalTimeoutMs / budget.targetTimeoutMs) or request less via per-range summaryMaxChars.";
}
if (result.attempts.some((attempt) => attempt.outcome === "invalid_summary")) {
return "summaries longer than the configured cap are rejected whole, so raise compress.maxSummaryLength or request less via per-range summaryMaxChars.";
}
if (result.attempts.some((attempt) => attempt.outcome === "error" && attempt.detail !== undefined)) {
return "the attempts below name the failing cause — address that cause; a rejected or unparseable reply is not fixed by raising the summary cap.";
}
return "see the attempt outcomes for the cause; raising the summary cap only helps replies rejected for length.";
}

/** #1775/#3635: the length-budget clause every external-summarizer prompt
* carries — rendered up front with the EXACT cap the validator enforces, so
* the first attempt fits instead of paying full latency for a wholesale-
Expand Down Expand Up @@ -275,7 +326,10 @@ export class ExternalSummaryExecutor {
if (performance.now() >= targetDeadline) expireTarget();
if (attempt.signal.aborted) throw new Error("Summary attempt cancelled before dispatch");
return target.summarize(request, attempt.signal);
}).then<AttemptResult, AttemptResult>((value) => ({ kind: "value", value }), () => ({ kind: "error" })).finally(release);
}).then<AttemptResult, AttemptResult>((value) => ({ kind: "value", value }), (error) => {
const known = summaryErrorDetail(error);
return known === undefined ? { kind: "error" } : { kind: "error", detail: known.detail, warnedByCandidate: known.warnedByCandidate };
}).finally(release);
let result: AttemptResult;
try {
result = await awaitAttempt(operation, attempt.signal);
Expand All @@ -293,7 +347,17 @@ export class ExternalSummaryExecutor {
if (result.kind === "aborted" || attempt.signal.aborted) {
attempts.push({ targetIndex, outcome: "timeout", detail: timeoutDetail(summaryAbortSource(attempt.signal) ?? "target-timeout", limits, performance.now() - startedAt) });
} else if (result.kind === "error") {
attempts.push({ targetIndex, outcome: "error" });
if (result.detail === undefined) {
attempts.push({ targetIndex, outcome: "error" });
} else {
attempts.push({ targetIndex, outcome: "error", detail: result.detail });
// #6885: a sync guard or a post-fetch parse failure used
// to vanish without any warn line — the candidate logs
// its fetch failures, but these never reached one. Log
// it once here, unless the candidate already warned
// (upstream rejection).
if (!result.warnedByCandidate) log("warn", `[external-summary] candidate <t${targetIndex}> failed: ${result.detail}`);
}
} else if (typeof result.value !== "string" || !result.value.trim()
|| Buffer.byteLength(result.value, "utf8") > limits.maxSummaryBytes
|| result.value.trim().length < (request.minSummaryChars ?? 1)
Expand Down
4 changes: 2 additions & 2 deletions tests/external-summary-http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ test("external summary HTTP: an exhausted transient chain logs every attempt and
await upstream((_req, res) => { res.writeHead(503); res.end("upstream unavailable"); }, async (url) => {
const result = await new ExternalSummaryExecutor(1).execute(work, [createSummaryHttpCandidate(target(url), 4096)], budget);
assert.equal(result.status, "failed");
assert.deepEqual(result.attempts, [{ targetIndex: 0, outcome: "error" }]);
assert.deepEqual(result.attempts, [{ targetIndex: 0, outcome: "error", detail: "External summary upstream rejected the request with HTTP 503" }]);
});
assert.equal(lines.filter((line) => line.includes("rejected: HTTP 503")).length, 3);
});
Expand All @@ -282,7 +282,7 @@ for (const protocol of ["responses", "anthropic", "openai", "google"] as const)
await upstream((_req, res) => res.end(JSON.stringify(body)), async (url) => {
const result = await new ExternalSummaryExecutor(1).execute(work, [createSummaryHttpCandidate(target(url, protocol), 4096)], budget);
assert.equal(result.status, "failed");
assert.deepEqual(result.attempts, [{ targetIndex: 0, outcome: "error" }]);
assert.deepEqual(result.attempts, [{ targetIndex: 0, outcome: "error", detail: "External summary response did not complete" }]);
});
});
}
Expand Down
33 changes: 32 additions & 1 deletion tests/external-summary.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { ExternalSummaryExecutor, type SummaryBudget, type SummaryCandidate, type SummaryWork } from "../src/external-summary.ts";
import { ExternalSummaryExecutor, externalSummaryFailureAdvice, type SummaryBudget, type SummaryCandidate, type SummaryWork } from "../src/external-summary.ts";
import { setLogCapture } from "../src/logger.ts";

const work: SummaryWork = { content: "Historical task evidence", instructions: "Preserve constraints and unfinished work", reference: "Read-only current task" };
const budget: SummaryBudget = { totalTimeoutMs: 2000, targetTimeoutMs: 500, maxSummaryBytes: 200 };
Expand Down Expand Up @@ -240,3 +241,33 @@ test("external summary: queued time does not spend the per-target dispatch budge
leave.resolve("holder");
assert.equal((await queued).status, "success");
});

test("external summary #6885: a non-fetch rejection keeps its safe cause in the attempt and logs once", async () => {
const lines: string[] = [];
setLogCapture((level, msg) => { if (level === "warn") lines.push(msg); });
try {
const result = await new ExternalSummaryExecutor(1).execute(work, [{ summarize: async () => { throw new Error("External summary input exceeds the target context budget"); } }], budget);
assert.deepEqual(result, { status: "failed", reason: "exhausted", attempts: [{ targetIndex: 0, outcome: "error", detail: "External summary input exceeds the target context budget" }] });
assert.equal(lines.filter((line) => line.includes("External summary input exceeds the target context budget")).length, 1);
} finally { setLogCapture(null); }
});

test("external summary #6885: a post-fetch parse rejection is named, not swallowed", async () => {
const result = await new ExternalSummaryExecutor(1).execute(work, [{ summarize: async () => { throw new Error("External summary response did not complete"); } }], budget);
assert.deepEqual(result.attempts, [{ targetIndex: 0, outcome: "error", detail: "External summary response did not complete" }]);
});

test("external summary #6885: an unknown candidate error stays opaque in the result", async () => {
const result = await new ExternalSummaryExecutor(1).execute(work, [{ summarize: async () => { throw new Error("private-key private-url source-content"); } }], budget);
assert.deepEqual(result.attempts, [{ targetIndex: 0, outcome: "error" }]);
assert.equal(JSON.stringify(result).includes("private"), false);
});

test("external summary #6885: failure advice names the budget on deadline, the cap on over-long replies", () => {
assert.match(externalSummaryFailureAdvice({ status: "deadline", results: [{ status: "deadline", attempts: [{ targetIndex: 0, outcome: "timeout", detail: "target-timeout 25000ms (elapsed 25002ms)" }] }] }), /budget\.totalTimeoutMs/);
assert.match(externalSummaryFailureAdvice({ status: "finished", results: [{ status: "failed", reason: "exhausted", attempts: [{ targetIndex: 0, outcome: "invalid_summary", detail: "summary 5 chars exceeds cap 4" }] }] }), /maxSummaryLength/);
const errorAdvice = externalSummaryFailureAdvice({ status: "finished", results: [{ status: "failed", reason: "exhausted", attempts: [{ targetIndex: 0, outcome: "error", detail: "External summary input exceeds the target context budget" }] }] });
assert.equal(errorAdvice.includes("maxSummaryLength"), false);
assert.match(errorAdvice, /failing cause/);
assert.match(externalSummaryFailureAdvice({ status: "finished", results: [{ status: "failed", reason: "exhausted", attempts: [{ targetIndex: 0, outcome: "error" }] }] }), /attempt outcomes/);
});
2 changes: 1 addition & 1 deletion tests/wire-contract-go-session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ test("WC-016 negative control: a Go candidate with no session id fails on the up
const result = await withFetchTransport(goFake(capture), () =>
new ExternalSummaryExecutor(1).execute(work, [createSummaryHttpCandidate(goTarget(), 4096)], budget));
assert.equal(result.status, "failed");
assert.deepEqual(result.attempts, [{ targetIndex: 0, outcome: "error" }]);
assert.deepEqual(result.attempts, [{ targetIndex: 0, outcome: "error", detail: "External summary upstream rejected the request with HTTP 400" }]);
assert.equal(capture[0].headers["x-opencode-session"], undefined, "no session id is fabricated — the failure stays honest");
});

Expand Down
Loading