From ddb2306adc3f7d736ac791f7887bf77e1016b1a1 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 27 Sep 2026 20:32:50 +0800 Subject: [PATCH 1/2] fix: surface partial compress drops in the model-facing receipt (#1495) --- src/compress-tool.ts | 7 +- src/stream.ts | 33 +++++- tests/issue1495-partial-compress-drop.test.ts | 110 ++++++++++++++++++ 3 files changed, 145 insertions(+), 5 deletions(-) create mode 100644 tests/issue1495-partial-compress-drop.test.ts diff --git a/src/compress-tool.ts b/src/compress-tool.ts index 64ffdf82e9..bff555d253 100644 --- a/src/compress-tool.ts +++ b/src/compress-tool.ts @@ -309,10 +309,13 @@ export function parseCompressInput(input: unknown, callId?: string) { } if (!parsed.diagnostics.ok && parsed.diagnostics.kind !== "ok") { loggerLog("warn", `[acp-compress-input] rejected: kind=${parsed.diagnostics.kind} invalidItems=${parsed.diagnostics.invalidItems}${parsed.diagnostics.keys ? ` keys=[${parsed.diagnostics.keys.join(",")}]` : ""}${parsed.diagnostics.length !== undefined ? ` len=${parsed.diagnostics.length}` : ""}${parsed.diagnostics.invalidReasons && parsed.diagnostics.invalidReasons.length > 0 ? ` reasons=[${parsed.diagnostics.invalidReasons.join(" | ")}]` : ""}`); - } else if (parsed.diagnostics.invalidItems > 0) { + } else if (parsed.diagnostics.invalidItems > 0 || parsed.diagnostics.kind === "truncated") { // #1494: partial drop — at least one range survived, so the old // condition above never fired and the rejection was invisible on both - // the server log and the model-facing receipt. + // the server log and the model-facing receipt. #1495: kind="truncated" + // (gateway-stringified + cut content array) salvages the complete + // leading entries and reports the same way — often with invalidItems=0, + // so it needs the explicit kind arm. loggerLog("warn", `[acp-compress-input] partial: ${parsed.ranges.length} range(s) applied, ${parsed.diagnostics.invalidItems} rejected (kind=${parsed.diagnostics.kind}) reasons=[${(parsed.diagnostics.invalidReasons ?? []).join(" | ")}]`); } return { ranges: parsed.ranges, diagnostics: parsed.diagnostics }; diff --git a/src/stream.ts b/src/stream.ts index 3cdc78b44a..84ebd65e76 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -203,6 +203,12 @@ export function summaryFingerprintLine(blockId: string, summary: string): string // success (the exact report in the issue; the kernel diagnostics carry the // per-entry reasons but nothing surfaced them when ≥1 range survived). function droppedEntriesNote(diagnostics: CompressParseDiagnostics): string { + // #1495: a gateway-stringified content array can arrive CUT — the lenient + // parser salvages only the complete leading entries (kind="truncated") and + // the unterminated tail is lost without counting as invalidItems. + if (diagnostics.kind === "truncated" && diagnostics.invalidItems <= 0) { + return `[The compress arguments arrived TRUNCATED — only the complete leading entries could be salvaged; any requested range not listed above was LOST, not compressed. Check acp_status for what is still compressible and re-issue the missing range(s).]`; + } if (diagnostics.invalidItems <= 0) return ""; const reasons = (diagnostics.invalidReasons ?? []).slice(0, 3).map((r) => (r.length > 160 ? r.slice(0, 160) + "..." : r)); const why = reasons.length > 0 ? reasons.join(" | ") : `${diagnostics.invalidItems} entr(ies) failed validation (parse kind=${diagnostics.kind})`; @@ -253,6 +259,23 @@ function postCompressTail(ctx: RewriteCtx, cleanSuccess: boolean): string { return `\n\n${NO_RANGES_REMAIN_TEXT}`; } +// #1495: the kernel's lenient parser salvages complete entries from damaged +// arguments (truncated gateway-stringified arrays, corrupted elements) and +// reports what it dropped via diagnostics — which this path only read on TOTAL +// failure. On partial success the receipt was a clean "[Compressed … → N +// block(s)]" for ranges that were requested but never folded. Every non-total +// receipt now names what was dropped so partial application stays visible and +// re-issuable. Apply-layer per-range errors (unknown refs, …) get the same +// treatment: previously also invisible when some other range in the batch +// succeeded. +// #1495: apply-layer per-range errors were invisible whenever some other +// range in the batch succeeded; surface them (capped) on the receipt. +function applyErrorNote(r: { errors: string[] }): string { + if (r.errors.length === 0) return ""; + const errs = r.errors.slice(0, 3).map((e) => e.length > 200 ? `${e.slice(0, 200)}…` : e).join(" | "); + return ` Errors: ${errs}`; +} + export function applyRanges(parsed: ReturnType, ctx: RewriteCtx): string { const { ranges, diagnostics } = parsed; if (ranges.length === 0) { @@ -392,7 +415,7 @@ export function applyRanges(parsed: ReturnType, ctx: ? ` This conversation holds only ${totalChars} char(s) — below the ${minChars}-char minimum, so NO range can succeed yet; do not retry compress or call acp_status/search_context about it — continue answering the user's task.` : ""; const dropped = droppedEntriesNote(diagnostics); - return `[Compression FAILED: ${errs}${revNote}${currentRefsSnapshot(ctx)}${recordCompressFailure(ctx.session, normalizedSpecKey(ranges))}${spanHint}${noViableAnywhere}${dropped ? " " + dropped : ""}]`; + return `[Compression FAILED: ${errs}${revNote}${currentRefsSnapshot(ctx)}${recordCompressFailure(ctx.session, normalizedSpecKey(ranges))}${spanHint}${noViableAnywhere}${dropped ? " " + dropped : ""}${applyErrorNote(r)}]`; } clearCompressFailures(ctx.session); @@ -423,13 +446,17 @@ export function applyRanges(parsed: ReturnType, ctx: ); const warn = r.warnings.length > 0 ? ` ${r.warnings.join("; ")}` : ""; - let msg = `[Compressed ${detail} → ${r.blocksCreated} block(s), ~${r.tokensCompressed} tokens saved.${warn}]`; + // #1495: apply-layer per-range errors (unknown refs, …) were invisible + // whenever some other range in the batch succeeded — surface them on + // the success line too, not only on total failure. + let msg = `[Compressed ${detail} → ${r.blocksCreated} block(s), ~${r.tokensCompressed} tokens saved.${warn}${applyErrorNote(r)}]`; // #1494: a partial fold must not read as a clean success — surface the // parse-dropped entries (and log them server-side) so the model // re-issues the rejected range instead of believing it folded. + // #1495: droppedEntriesNote also covers kind="truncated" salvage loss. const dropped = droppedEntriesNote(diagnostics); if (dropped !== "") { - ctx.log(`[acp-proxy: compress PARTIAL — ${diagnostics.invalidItems} entr(ies) rejected at parse: ${(diagnostics.invalidReasons ?? []).join(" | ")}]`); + ctx.log(`[acp-proxy: compress PARTIAL — kind=${diagnostics.kind} ${diagnostics.invalidItems} entr(ies) rejected at parse: ${(diagnostics.invalidReasons ?? []).join(" | ")}]`); msg += `\n${dropped}`; } // #1294 P1: append a fingerprint line per created/updated block — diff --git a/tests/issue1495-partial-compress-drop.test.ts b/tests/issue1495-partial-compress-drop.test.ts new file mode 100644 index 0000000000..fc61d2fb66 --- /dev/null +++ b/tests/issue1495-partial-compress-drop.test.ts @@ -0,0 +1,110 @@ +// #1495: 批量压缩静默丢条目 — kernel 的宽容解析器会从损坏的参数里抢救完整条目 +// (被网关 stringify+截断的数组、单条损坏), 但 applyRanges 在"部分成功"时把 +// invalidItems/invalidReasons/kind=truncated 全部丢掉: 模型收到干净的 +// "[Compressed X, Y → 2 block(s)]" 回执, 第 3 条从未折叠却无任何失败说明. +// 非全量回执必须显式说出丢了什么(解析层拒绝、truncated salvage 丢失、apply 层逐条错误); +// 让部分应用可见、可补发. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import type { CoreMessage } from "acp-kernel"; +import { createCore, createInitialState, assignRefs, emptyRefMap, defaultConfig } from "acp-kernel"; +import { parseCompressInput } from "../src/compress-tool.ts"; +import { applyRanges, type RewriteCtx } from "../src/stream.ts"; + +type Ctx = Omit & { log: (m: string) => void; logs: string[] }; + +function makeCtx(messages: CoreMessage[]): Ctx { + const logs: string[] = []; + return { + core: createCore(), + config: defaultConfig(200000), + messages, + session: { + id: "issue1495-partial-drop-test", + meta: {}, + stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 0, compressCreditTokens: 0, contextTokens: 0 }, + metadata: {}, + state: createInitialState(), + createdAt: Date.now(), + lastSeen: Date.now(), + blockContents: new Map(), + inFlight: 0, + persisted: false, + }, + log: (m: string) => { logs.push(m); }, + logs, + }; +} + +function withRefs(ctx: Ctx): Ctx { + const res = assignRefs(ctx.messages, { existing: emptyRefMap(), nextIndex: 0 }); + ctx.session.state.messageRefs = res.map; + return ctx; +} + +function textMsg(id: string, role: "user" | "assistant", text: string): CoreMessage { + return { id, role, contentType: "text", text }; +} + +const S = "PARTIAL-DROP-TEST-SUMMARY-PAYLOAD-LONG-ENOUGH-FOR-THE-KERNEL-MIN-LENGTH-CHECK"; + +function freshCtx(): Ctx { + // Default preserveRecentMessages: 5 → folding m00001–m00002 succeeds and + // drains every compressible range (m00003–m00007 stay protected). + const msgs = [ + textMsg("raw_1", "user", "x".repeat(20000)), + textMsg("raw_2", "assistant", "x".repeat(20000)), + textMsg("raw_3", "user", "x".repeat(5000)), + textMsg("raw_4", "assistant", "x".repeat(5000)), + textMsg("raw_5", "user", "x".repeat(5000)), + textMsg("raw_6", "assistant", "x".repeat(5000)), + textMsg("raw_7", "user", "x".repeat(5000)), + ]; + const ctx = withRefs(makeCtx(msgs)); + ctx.session.stats.lastInputTokens = 80000; + return ctx; +} + +test("#1495: valid + invalid entry mix — success receipt names the rejected entry and its reason", () => { + const out = applyRanges(parseCompressInput({ content: [ + { startId: "m00001", endId: "m00002", summary: S }, + { summary: "no bounds" }, + ]}), freshCtx()); + assert.ok(out.startsWith("[Compressed"), `partial success expected, got: ${out.slice(0, 160)}`); + assert.ok(out.includes("1 of the submitted entry was REJECTED and NOT compressed"), `dropped entry must be named:\n${out}`); + assert.ok(out.includes("entry 1: missing range bounds"), `rejection reason inline:\n${out}`); +}); + +test("#1495: truncated gateway-stringified array — salvage loss is named, lost range not listed as applied", () => { + const complete = JSON.stringify({ startId: "m00001", endId: "m00002", summary: S }); + const damaged = `{"content": [${complete},{"startId":"m00003","endId":"m00004","sum`; + const parsed = parseCompressInput(damaged); + assert.equal(parsed.ranges.length, 1, "one complete entry salvaged"); + assert.equal(parsed.diagnostics.kind, "truncated"); + const ctx = freshCtx(); + const out = applyRanges(parsed, ctx); + assert.ok(out.startsWith("[Compressed"), `salvage success expected, got: ${out.slice(0, 160)}`); + assert.ok(out.includes("arrived TRUNCATED"), `truncation loss must be named:\n${out}`); + assert.ok(out.includes("was LOST, not compressed"), `salvage loss guidance:\n${out}`); + assert.ok(!out.includes("m00003–m00004"), "lost range must not appear in the applied detail:\n" + out); + assert.ok(ctx.logs.some((l) => l.includes("compress PARTIAL") && l.includes("kind=truncated")), `server-side PARTIAL log for truncated salvage:\n${ctx.logs.join("\n")}`); +}); + +test("#1495: apply-layer per-range error surfaces on partial success (unknown refs)", () => { + const out = applyRanges(parseCompressInput({ content: [ + { startId: "m00001", endId: "m00002", summary: S }, + { startId: "m00099", endId: "m00100", summary: S }, + ]}), freshCtx()); + assert.ok(out.startsWith("[Compressed"), `partial success expected, got: ${out.slice(0, 160)}`); + assert.ok(out.includes("Errors:"), `apply-layer error must be surfaced:\n${out}`); +}); + +test("#1495: clean call — no drop/error annotation (existing output unchanged)", () => { + const out = applyRanges(parseCompressInput({ content: [ + { startId: "m00001", endId: "m00002", summary: S }, + ]}), freshCtx()); + assert.ok(out.startsWith("[Compressed"), `success expected, got: ${out.slice(0, 160)}`); + assert.ok(!out.includes("REJECTED"), `clean call must stay unannotated:\n${out}`); + assert.ok(!out.includes("TRUNCATED"), `clean call must stay unannotated:\n${out}`); + assert.ok(!out.includes("Errors:"), `clean call must stay unannotated:\n${out}`); +}); From dd1e4d65436f5259e6ce6357df6d45ae0c9c81b1 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 27 Sep 2026 22:39:36 +0800 Subject: [PATCH 2/2] chore(#1495): drop duplicated comment lines left by the rebase conflict resolution --- src/stream.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/stream.ts b/src/stream.ts index 84ebd65e76..1e85d5c98d 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -268,8 +268,6 @@ function postCompressTail(ctx: RewriteCtx, cleanSuccess: boolean): string { // re-issuable. Apply-layer per-range errors (unknown refs, …) get the same // treatment: previously also invisible when some other range in the batch // succeeded. -// #1495: apply-layer per-range errors were invisible whenever some other -// range in the batch succeeded; surface them (capped) on the receipt. function applyErrorNote(r: { errors: string[] }): string { if (r.errors.length === 0) return ""; const errs = r.errors.slice(0, 3).map((e) => e.length > 200 ? `${e.slice(0, 200)}…` : e).join(" | ");