From 7b3a17193b89ded14f7490092d57b881e80634e1 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Sun, 22 Nov 2026 22:37:54 +0800 Subject: [PATCH 1/5] =?UTF-8?q?fix:=20stop=20refusing=20oversized=20reques?= =?UTF-8?q?ts=20on=20local=20size=20estimates=20=E2=80=94=20forward,=20and?= =?UTF-8?q?=20let=20the=20upstream's=20own=20verdict=20be=20authoritative?= =?UTF-8?q?=20(#7537)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Owner ruling 2026-11-22 (issue #7537, KDD #19/#20): every LOCAL estimate- based 413 refusal is a product of bili's local guess multiplied by a window value that is itself often wrong (fallback windows #7205). Their product silently killed requests that would have succeeded (the #7167/#7382/#2490/ #2847/#2847/#736/#737/#4079 family). - server.ts: the four local size-413 sites (probe doom gate, #1839 measured gate, post-fold measured/doom-bytes gates, deterministic-exhaustion mapping) now FORWARD with the local measurement logged as evidence. Relay-side refusals keep their status: summary relay down -> 502, relay 429 -> 503. The BILI_MAX_MESSAGES count gate and the 5GiB byte cap are exact resource guards and stay. - relay.ts: the egress window fuse's two size gates log a profile and forward; a NEW upstream size-verdict annotation (413 / size-keyword 400) logs bili's own measurement, marks the response x-bili-retryable: false and merges a bili_evidence block into JSON error bodies so status-driven hosts do not retry-loop an unchanged body. - server.ts: NEW evidence-backed loop guard — an outbound body that already drew an upstream size verdict (SHA-1 scoped, 10-min TTL) is refused locally as a byte-identical resend (#496 family); changed bodies and the identity fast path re-forward freely. - The window-shrink note now rides the forward warns (the 413 fail-fast it decorated is gone); the duplication profile moved onto the over-window forward. - AGENTS.md KDD #19 + reference/design-decisions.md #20 record the ruling. - Tests: NEW tests/issue7537-preflight-passthrough.test.ts (3); re-pinned issue1841/2490/2847/3645/4079/4185/preflight-fail-fast to passthrough semantics; tests/issue3846-local-refusal-evidence.test.ts deleted (the local refusal it pinned no longer exists — the loop guard replaces it). Supersedes PR #7507 (whose two new gates no longer need to exist under this ruling). Refs #7537 #7507 #7167 #7382 #2490 #2847 #736 #737 #4079 #4543 #1841 #3645 #496 #3846 #3461 #5000 --- AGENTS.md | 2 + reference/design-decisions.md | 3 + src/server.ts | 174 +++++--- src/server/relay.ts | 82 +++- tests/issue1841-preflight-futility.test.ts | 15 +- ...ssue2490-ledger-floor-doomed-probe.test.ts | 44 +- ...sue2847-doomed-nonretryable-status.test.ts | 49 +-- tests/issue3645-calibrated-futility.test.ts | 37 +- .../issue3846-local-refusal-evidence.test.ts | 392 ------------------ tests/issue4079-egress-window-fuse.test.ts | 125 +++--- ...issue4185-identified-fresh-forward.test.ts | 48 ++- tests/issue7537-preflight-passthrough.test.ts | 227 ++++++++++ tests/preflight-fail-fast.test.ts | 101 +++-- 13 files changed, 642 insertions(+), 657 deletions(-) delete mode 100644 tests/issue3846-local-refusal-evidence.test.ts create mode 100644 tests/issue7537-preflight-passthrough.test.ts diff --git a/AGENTS.md b/AGENTS.md index 2d2765e3fb..58007eb580 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -93,6 +93,8 @@ Tier A entries are every-session rules and stay in full below. Tier B entries ca 身份信号来源只有三类:**宿主写入**(msgid body 字段 / 信封 `msgIds` / pf 头)、**宿主盖戳头**(opencode V2 `x-bili-msg-ids`)、**自包含采集器**(`src/identity-harvest.ts` 注册表 + `src/identity-.ts` 适配器;双门:env `BILI_IDENTITY_HARVEST` 或灰度键 `rollout.features.identityChannelHarvest`,均默认关 × 仅回环来源)。**消费者(#5719 归属档 / pin-行链路 / membership / 水位)只从统一缝取数**:handle 入口每请求按「body 字段 > 盖戳头 > 采集」取一次快照——绝不新增「逐调用点单独取数」。新车道 = 新适配器文件 + barrel 一行登记 + 文档一行;适配器自包含、整轮退化(任一环节不判定 ⇒ 该轮整体回退接线前路径,绝不做部分映射)。车道状态表与信任边界:docs/identity-channels.md;身份判定逻辑:docs/session-identity-resolution.md。Full text: design-decisions.md #18. +19. **不用本地估算拒发:超窗一律转发,上游的大小判决才是权威 (no estimate-based size refusal — #7537, owner 裁定 2026-11-22) (Tier A)** — bili 本地判「这个包超过模型窗口 → 413 拒发」的整条机制已废除:本地窗口值本身就常常错(fallback 窗口,#7205),估算 × 错窗口 = 乘性误差,拒掉的往往是上游本来能收的包(#7167/#7382/#2490/#2847 家族);被拒绝的字节没有进过任何上游,错误信息只有本地估算、没有上游的真实号码。新契约:**该折的照折(fold-first 不变),折完一律转发;上游以真实号码拒绝时(413 / 大小类 400),bili 把自己的实测证据(出站 token 数+分维度 breakdown+入站字节+有效窗口)打进日志并在响应上标记 `x-bili-retryable: false`(JSON 体可解析时并入 `bili_evidence` + `error.retryable=false`),防止按状态码驱动的重试循环烧配额**。**保留的本地拒发只有两种:非估算类**——消息条数门(`BILI_MAX_MESSAGES`,真实 wire 约束)与 5GiB 纯字节 sanity cap(资源保护)。实现:src/server.ts 四处 413 拒发点 + src/server/relay.ts 出口熔丝两道大小门(计数门保留);测试钉在 tests/issue7537-preflight-passthrough.test.ts 及既有 preflight 套件的重钉。Full text: design-decisions.md #20. + ### Install-Lane & Update-Ownership Contract (#1196) Every bili presence on a machine follows ONE contract — decide changes against it, not ad hoc: diff --git a/reference/design-decisions.md b/reference/design-decisions.md index 39f5c4bfea..eab8199fd9 100644 --- a/reference/design-decisions.md +++ b/reference/design-decisions.md @@ -67,3 +67,6 @@ The acp-kernel source is vendored under `kernel/` and consumed via `"acp-kernel" ### KDD #19 — 公告(remote feed)治理:禁止全员广播、owner 确认、插件公告必须触发式(#6508/#6509,owner 裁定 2026-11-13) — remote announcement feed([announcements/remote.json](announcements/remote.json),#5548 三源 notice 体系的 A 源)合入 master 后 **~3 分钟内触达所有在跑实例**:它是与 merge/release 同级的安全面,不是文档文件。owner 裁定四条(2026-11-13):(1) **严格禁止对所有用户公告**——无任何受众限制、对每台机器无条件显示的记录不许出厂,每条记录必须用 `versions` / `requiresScan` / 时间窗等门限定到明确受众;(2) **任何公告(新增/修改/撤下)需 owner 明确确认**后才开 PR,Agent 只能提议内容与范围、不得自行开 PR(与发版同级);(3) **公告 PR 必须说明影响范围**:受众(哪个客户端/版本/安装态)、版本覆盖(哪些旧版本不认识新门字段而会无条件显示)、挂的时长(何时何人撤下,或 `until` 窗口);(4) **原则上不允许针对某个插件的公告**——插件冲突的暴露机制是只读冲突扫描(#1206,天然逐机触发);任何针对特定插件的提示必须**触发式而非公告式**:走扫描面(CLI WARNING / 会话冲突台账 / `/__bili/stats` / 拦截失败 web 横幅),确需持久 web 横幅时给记录带 `requiresScan` 门(#6509 新增,client+knownId 精确匹配,fails closed),使投递与文案受众一致。先例:#5984 的 dsh-live-compact 记录曾以无条件广播出厂(当时 feed 通道没有机器维度门),2026-11-13 撤下(#6508,PR #6509);`requiresScan` 机制保留在代码里,待带门版本铺开后该公告可直接加回。规则全文:AGENTS.md §4「Remote Announcements」。 +### KDD #20 — 不用本地估算拒发:超窗一律转发,上游的大小判决才是权威 (no estimate-based size refusal, #7537; owner 裁定 2026-11-22) + +— 旧机制:preflight 在转发前用**本地估算**判定出站体「超过模型窗口」并就地 413 拒发——四处拒发点(src/server.ts:probe 字节 doom 门 / #1839 分支实测门 / 无基线分支实测门+字节 doom 门 / 折叠耗尽的确定性 413 映射)+ 出口熔丝两道大小门(src/server/relay.ts egress window fuse 的实测 token 门与核心文本字节门)。**废除原因(owner 裁定)**:(1) 本地窗口值本身常常是错的——fallback 窗口(#7205:codex 对齐窗口只会收缩,客户端声明丢失后用兜底值)让「实测 > 窗口」大量假阳;(2) 估算 × 错窗口 = 乘性误差,拒掉的往往是上游本来能收的包(#7167 tools[] 不可压缩面、#7382 盲字节 doom、#2490/#2847/#4079 同家族);(3) 被拒请求没进过任何上游,错误信息只有 bili 自己的估算,没有上游真实号码,宿主拿不到任何可行动的权威信号。**新契约**:该折的照折(fold-first 原则不变——折叠永远先做),折完**一律转发**;上游以自己的真实号码(413 或大小类 400,关键词表见 relay.ts `SIZE_ERROR_RE`)拒绝时,bili 把**实测证据**打进日志(出站 TEXT token 数 + 分维度 breakdown + 入站字节数 + 有效窗口),并在响应上加 `x-bili-cause: upstream-size` / `x-bili-retryable: false` 头,JSON 体可解析时并入 `bili_evidence` 字段与 `error.retryable=false`——目的是让按状态码驱动的宿主**不要原样重试**已判超的包(烧配额)。**保留的本地拒发只有两种,都不是估算类**:① 消息条数门(`BILI_MAX_MESSAGES` / egress fuse count gate——真实 wire 约束,精确计数);② 5GiB 纯字节 sanity cap(`OutboundBodyTooLargeError`——资源保护,与模型窗口无关)。身份快路径(#7532)与折叠循环本身不受影响。实现:src/server.ts 五个 #7537 标注块(四处 413 → 转发+warn 日志;确定性耗尽 → 折叠后转发);src/server/relay.ts 熔丝两道大小门 → 仅日志、放行,上游大小判决分支加证据注入(仅非流式、仅 body 仍受控时);测试:tests/issue7537-preflight-passthrough.test.ts + 既有 preflight/egress-fuse 套件重钉转发语义。代价(接受项):注定超窗的包会真实打到上游一次(配额消耗;部分计费方对失败请求计费),换来所有「其实能收」的包不再被本地估算杀死。 diff --git a/src/server.ts b/src/server.ts index 3befb46e8e..7fa6fa24ca 100644 --- a/src/server.ts +++ b/src/server.ts @@ -3,7 +3,7 @@ import fs from "node:fs"; import path from "node:path"; import net from "node:net"; import tls from "node:tls"; -import { randomUUID } from "node:crypto"; +import { randomUUID, createHash } from "node:crypto"; import { performance } from "node:perf_hooks"; import { createCore, type CompressionCore, type CompressionState, type Config, type CoreMessage, type NudgeDecision, type Prompts, type PackSurface, defaultPrompts, deactivateBlock } from "acp-kernel"; import { resolveCompress, resolveCompressPrompts, resolveCompressSurfaceDetailed, resolveRequestConfig, type ResolvedKernelConfig } from "./compress-settings.js"; @@ -3447,6 +3447,63 @@ function localRefusalCovers(metadata: Record, origin: string | return readLocalRefusals(metadata).some((r) => r.origin === origin && r.model === model && r.window >= window); } +// #7537 (with #496): the one loop the old estimate-refusals happened to break +// — a status-code-driven host re-sending the SAME bytes an upstream already +// rejected as too large — must stay broken after the local size 413s are gone. +// The guard is EVIDENCE, not estimate: it fires only on a byte-identical +// resend (same SHA-1 of the wire body) to the same origin+model whose exact +// bytes the upstream already refused with a size verdict. Changed bodies +// re-forward freely; the record TTLs out like #3846's (10 minutes). +interface UpstreamSizeVerdictRecord { + origin: string; + model: string; + hash: string; + at: number; +} + +const SIZE_VERDICT_MAX_RECORDS = 16; +const SIZE_VERDICT_TTL_MS = LOCAL_REFUSAL_TTL_MS; + +function wireBodyHash(body: string): string { + return createHash("sha1").update(body).digest("hex").slice(0, 16); +} + +function readSizeVerdicts(metadata: Record): UpstreamSizeVerdictRecord[] { + const raw = metadata.upstreamSizeVerdicts; + if (!Array.isArray(raw)) return []; + const now = Date.now(); + return raw.filter((r): r is UpstreamSizeVerdictRecord => + !!r && typeof r === "object" + && typeof (r as UpstreamSizeVerdictRecord).origin === "string" + && typeof (r as UpstreamSizeVerdictRecord).model === "string" + && typeof (r as UpstreamSizeVerdictRecord).hash === "string" + && typeof (r as UpstreamSizeVerdictRecord).at === "number" + && (r as UpstreamSizeVerdictRecord).at > now - SIZE_VERDICT_TTL_MS, + ); +} + +/** Relay-side: the upstream answered a size verdict for these exact outbound + * bytes — record it so the byte-identical resend is refused locally (#496 + * loop guard, #7537). The hash must be of the SAME outbound serialization + * preflight checks (prepared.body) — call with that value, not wire bytes + * that later pipes may have re-serialized. */ +export function noteUpstreamSizeVerdict(session: Session, origin: string | undefined, model: string | undefined, outboundBody: string | undefined): void { + if (!origin || !model || typeof outboundBody !== "string" || outboundBody.length === 0) return; + const h = wireBodyHash(outboundBody); + const records = readSizeVerdicts(session.metadata); + if (records.some((r) => r.origin === origin && r.model === model && r.hash === h)) return; + session.metadata.upstreamSizeVerdicts = [...records, { origin, model, hash: h, at: Date.now() }].slice(-SIZE_VERDICT_MAX_RECORDS); + markDirty(session); +} + +/** Preflight-side: true when THIS exact wire body (same origin+model) already + * drew an upstream size verdict — the resend must not ride the wire again. */ +export function upstreamSizeVerdictCovers(metadata: Record, origin: string | undefined, model: string | undefined, body: string | undefined): boolean { + if (!origin || !model || typeof body !== "string" || body.length === 0) return false; + const h = wireBodyHash(body); + return readSizeVerdicts(metadata).some((r) => r.origin === origin && r.model === model && r.hash === h); +} + /** #568: commit the response early so a long preflight cannot lose the client * to its header timeout. Streaming clients get an SSE stream with keep-alive * comment lines (`: bili-preflight` — a spec-mandated no-op for every SSE @@ -4012,6 +4069,18 @@ export async function preflightCompressIfNeeded( // started before this field existed) keep the legacy behavior. let baselineFloor = baselineFloorRaw; const currentOrigin = normalizeUpstreamOrigin(route?.upstream); + // #7537/#496: byte-identical resend of a body the upstream ALREADY refused + // as too large — the one refusal that survives the estimate-refusal removal + // (evidence, not estimate): refuse locally with the loop-guard verdict so a + // status-code-driven host cannot re-burn the same doomed payload in a + // retry loop. Changed bodies and new sessions judge fresh. + if (currentOrigin !== undefined && model !== undefined && model.length > 0) { + const verdictBody = typeof prepared.body === "string" ? prepared.body : (prepared.body instanceof Buffer ? prepared.body.toString("utf8") : undefined); + if (verdictBody !== undefined && upstreamSizeVerdictCovers(session.metadata, currentOrigin, model, verdictBody)) { + log("warn", `[${session.id}] preflight fail-fast 413 (retryable=false, upstream-size evidence): the upstream already refused THIS exact body as too large — refusing the byte-identical resend locally instead of re-burning the wire (#7537/#496 loop guard)`); + return { failFast: true, status: 413, message: `the upstream already refused this exact body as too large (its size verdict is on record for these bytes, #7537/#496). Do NOT retry the unchanged body — shrink the session (rewind or restart), or change the payload, and retry.`, retryable: false, respond: !res.writableEnded }; + } + } const baselineOrigin = normalizeUpstreamOrigin(session.stats.lastInputTokensOrigin); if (baselineFloor > 0 && currentOrigin !== undefined && baselineOrigin !== undefined && baselineOrigin !== currentOrigin) { log("info", `[${session.id}] preflight usage-baseline ~${baselineFloor} tok was measured on ${maskUrlForLog(baselineOrigin)}, request now routes to ${maskUrlForLog(currentOrigin)} — demoting to untrusted, judging by this payload's own estimate (#1933)`); @@ -4169,6 +4238,17 @@ export async function preflightCompressIfNeeded( // [#autoFold] a growth trigger is operator intent, not a billing guess — // it never needs upstream evidence and must fold on the FIRST armed // request, so the #2313 estimate-only forward-once never skips it. + // #7537: the shrink note now rides the FORWARD warns (the local size 413s + // are gone) — same gate as the failFast closure: windowShrinkReason is set + // ONLY by the operator-override and codex-align paths (#736/#737). + const shrinkNote = buildWindowShrinkNote({ + reason: windowShrinkReason, + limit, + nativeWindow: resolvedNativeWindow, + routeMissedConfigured: Object.keys(opts.routes).length > 0 && findRouteKey(opts.routes, route?.rewrittenUrl) === undefined, + upstreamEndpoint: route?.rewrittenUrl, + knownKeys: Object.keys(opts.routes), + }); const probeForEvidence = !growthArmed && !unknownBaseline && session.stats.lastInputTokens > 0 && baselineFloor <= 0 && prepared.processedMessages.length > 0; if (probeForEvidence && !wireMeter) { // #2490: mathematically-doomed probe guard. The forward-once below bets @@ -4200,25 +4280,17 @@ export async function preflightCompressIfNeeded( // path instead, without recording a persistent route refusal. const coreTextBytes = estimateCoreMessagesUpperBytes(prepared.processedMessages); if (coreTextBytes > Math.max(DOOMED_PROBE_ABSOLUTE_BYTES, limit * DOOMED_PROBE_BYTES_PER_TOKEN)) { - if (trustedForward) { - log("warn", `[${session.id}] identity fast path: local doom-math says core text alone (~${coreTextBytes} bytes ≥ ~${Math.ceil(coreTextBytes / DOOMED_PROBE_BYTES_PER_TOKEN)} tok at the densest observed density) can never fit window ${limit}, but upstream reality (~${session.stats.lastInputTokens} tok, ${evidenceSource}) exists for this origin+model — forwarding as configured; a genuine 400 is handled by the overflow arm`); - return prepared; - } - const byteFloorTokens = Math.ceil(coreTextBytes / DOOMED_PROBE_BYTES_PER_TOKEN); - log("error", `[${session.id}] preflight 413 core-text profile: ${describeCoreTextDuplication(prepared.processedMessages)}`); - const doomedMessage = `payload core text alone is ~${coreTextBytes} bytes — even at the densest tokenizer density observed on a live route (~${DOOMED_PROBE_BYTES_PER_TOKEN} bytes/token, #2122) that is ≥ ~${byteFloorTokens} tokens vs the model window ${limit} (model=${model}); no upstream can accept it, so it was NOT forwarded even for evidence. Remove or trim the oversized content (e.g. a giant paste or tool result) and retry.`; - // #2847: the rejection is mathematically deterministic, so the STATUS - // itself must carry the non-retryable semantics — a 502 says - // "transient gateway failure" to status-code-driven hosts and they - // retry the identical doomed payload anyway (field evidence: 3 - // crashes in 10s, body `"retryable": false` notwithstanding; the - // 3rd attempt carried a 6.4MB payload after a representation flip). - // 413 mirrors the side-request guard's "cannot fit, NOT forwarded" - // convention and is terminal for every mainstream host. Same doom - // math, same message, same no-forward behavior — status only. - log("error", `[${session.id}] preflight fail-fast 413 (retryable=false): ${doomedMessage}`); - noteLocalRefusal(session, currentOrigin, model, limit); - return { failFast: true, status: 413, message: doomedMessage, retryable: false, respond: !res.writableEnded }; + // #7537 (owner ruling 2026-11-22): NO estimate-based refusal. The + // doom math is a local guess multiplied by a window value that is + // itself often wrong (fallback windows, #7205) — refusing on their + // product killed requests that would have succeeded (#7167/#7382/ + // #2490/#2847 family). Forward the probe and let the UPSTREAM + // answer with its own real numbers; bili logs the local + // measurement as evidence next to the passthrough (see the + // upstream size-error annotation in relay.ts, same issue). + log("warn", `[${session.id}] preflight size profile: core text alone ~${coreTextBytes} bytes (≥ ~${Math.ceil(coreTextBytes / DOOMED_PROBE_BYTES_PER_TOKEN)} tok at the densest observed density, #2122) vs window ${limit} (model=${model}${trustedForward ? `; upstream reality ~${session.stats.lastInputTokens} tok, ${evidenceSource}` : ""}) — forwarding per #7537 (no local estimate-refusal); the upstream's own size verdict is authoritative${shrinkNote}`); + log("info", `[${session.id}] preflight forward core-text profile: ${describeCoreTextDuplication(prepared.processedMessages)}`); + return prepared; } const declaredWindow = typeof session.metadata.effectiveContextLimit === "number" && session.metadata.effectiveContextLimit > 0 ? session.metadata.effectiveContextLimit : 0; @@ -4700,16 +4772,13 @@ export async function preflightCompressIfNeeded( // so `outboundRawTokens` is text-only by construction. const armMeasuredBar = typeof resolvedNativeWindow === "number" && resolvedNativeWindow > 0 ? resolvedNativeWindow : limit; if (outboundRawTokens !== undefined && outboundRawTokens > armMeasuredBar) { - if (trustedForward) { - log("warn", `[${session.id}] identity fast path: rebuilt outbound measures ~${outboundRawTokens.toLocaleString("en-US")} text tokens over window ${armMeasuredBar.toLocaleString("en-US")} — upstream reality (~${session.stats.lastInputTokens} tok, ${evidenceSource} on this origin+model) outranks the local meter; forwarding instead of 413`); - return outbound; - } - const outMsgs = outbound.processedMessages.length > 0 ? outbound.processedMessages : outbound.originalMessages; - log("error", `[${session.id}] preflight 413 measured-body profile (post-fold): ${describeCoreTextDuplication(outMsgs)}`); - const measuredDoomMessage = `rebuilt outbound body measures ~${outboundRawTokens.toLocaleString("en-US")} TEXT tokens (${outboundBreakdown ? measuredBreakdownClause(outboundBreakdown) : "by field: n/a"}; CJK-aware count, the #554 guard meter; images billed separately, never doom here — #496/#1800/#857) vs the model window ${armMeasuredBar.toLocaleString("en-US")} (model=${model}); the body ITSELF exceeds the window, so it was NOT forwarded for upstream arbitration. Remove or trim the oversized dimension named above (e.g. a giant paste or tool result in messages[], or tools[] schemas) and retry.`; - log("error", `[${session.id}] preflight fail-fast 413 (retryable=false): ${measuredDoomMessage}`); - noteLocalRefusal(session, currentOrigin, model, limit); - return { failFast: true, status: 413, message: measuredDoomMessage, retryable: false, respond: !res.writableEnded }; + // #7537: the measured body exceeds the local window bar — forward + // anyway. The meter reads the body honestly, but the BAR (the + // window) is a local value that is often wrong-small, and the + // upstream's own verdict carries its real numbers. Same + // no-estimate-refusal ruling as the probe gate above. + log("warn", `[${session.id}] rebuilt outbound measures ~${outboundRawTokens.toLocaleString("en-US")} TEXT tokens (${outboundBreakdown ? measuredBreakdownClause(outboundBreakdown) : "by field: n/a"}; the #554 meter) over window ${armMeasuredBar.toLocaleString("en-US")} (model=${model}) — forwarding per #7537 (no local estimate-refusal); the upstream's own size verdict is authoritative${shrinkNote}`); + return outbound; } log("warn", `[${session.id}] preflight view fits (~${result.payloadEstimate}/${limit}) but the rebuilt payload measures over — forwarding once for upstream arbitration (#1839)`); return outbound; @@ -4811,28 +4880,18 @@ export async function preflightCompressIfNeeded( // belongs to the #496/#1800 billing arbitration, never to a local doom. const gateMeasuredBar = typeof resolvedNativeWindow === "number" && resolvedNativeWindow > 0 ? resolvedNativeWindow : limit; if (outboundRawTokens !== undefined && outboundRawTokens > gateMeasuredBar) { - if (trustedForward) { - log("warn", `[${session.id}] identity fast path: outbound measures ~${outboundRawTokens.toLocaleString("en-US")} text tokens over window ${gateMeasuredBar.toLocaleString("en-US")} after ${result.compressedRanges} fold(s) — upstream reality (~${session.stats.lastInputTokens} tok, ${evidenceSource} on this origin+model) outranks the local meter; forwarding instead of 413`); - return outbound; - } - log("error", `[${session.id}] preflight 413 measured-body profile: ${describeCoreTextDuplication(outMsgs)}`); - const measuredDoomMessage = `outbound body measures ~${outboundRawTokens.toLocaleString("en-US")} TEXT tokens even after preflight compression (${outboundBreakdown ? measuredBreakdownClause(outboundBreakdown) : "by field: n/a"}; CJK-aware count, the #554 guard meter; images billed separately, never doom here — #496/#1800/#857) vs the model window ${gateMeasuredBar.toLocaleString("en-US")} (model=${model}); the body ITSELF exceeds the window, so it was NOT forwarded. Remove or trim the oversized dimension named above (e.g. a giant paste or tool result in messages[], or tools[] schemas) and retry.`; - log("error", `[${session.id}] preflight fail-fast 413 (retryable=false): ${measuredDoomMessage}`); - noteLocalRefusal(session, currentOrigin, model, limit); - return { failFast: true, status: 413, message: measuredDoomMessage, retryable: false, respond: !res.writableEnded }; + // #7537: measured over the local window bar after maximum folding — + // forward anyway (same no-estimate-refusal ruling as above). + log("warn", `[${session.id}] outbound measures ~${outboundRawTokens.toLocaleString("en-US")} TEXT tokens (${outboundBreakdown ? measuredBreakdownClause(outboundBreakdown) : "by field: n/a"}) over window ${gateMeasuredBar.toLocaleString("en-US")} after ${result.compressedRanges} fold(s) (model=${model}) — forwarding per #7537 (no local estimate-refusal); the upstream's own size verdict is authoritative${shrinkNote}`); + log("info", `[${session.id}] preflight forward core-text profile: ${describeCoreTextDuplication(outMsgs)}`); + return outbound; } const doomBytes = estimateCoreMessagesUpperBytes(outMsgs); if (doomBytes > Math.max(DOOMED_PROBE_ABSOLUTE_BYTES, limit * DOOMED_PROBE_BYTES_PER_TOKEN)) { - if (trustedForward) { - log("warn", `[${session.id}] identity fast path: core text alone is ~${doomBytes} bytes even after ${result.compressedRanges} fold(s) — upstream reality (~${session.stats.lastInputTokens} tok, ${evidenceSource} on this origin+model) outranks the local byte math; forwarding instead of 413`); - return outbound; - } - const byteFloorTokens = Math.ceil(doomBytes / DOOMED_PROBE_BYTES_PER_TOKEN); - log("error", `[${session.id}] preflight 413 core-text profile: ${describeCoreTextDuplication(outMsgs)}`); - const doomedMessage = `payload core text alone is ~${doomBytes} bytes even after preflight compression — at the densest tokenizer density observed on a live route (~${DOOMED_PROBE_BYTES_PER_TOKEN} bytes/token, #2122) that is ≥ ~${byteFloorTokens} tokens vs the model window ${limit} (model=${model}); no upstream can accept it. Remove or trim the oversized content (e.g. a giant paste or tool result) and retry.`; - log("error", `[${session.id}] preflight fail-fast 413 (retryable=false): ${doomedMessage}`); - noteLocalRefusal(session, currentOrigin, model, limit); - return { failFast: true, status: 413, message: doomedMessage, retryable: false, respond: !res.writableEnded }; + // #7537: byte-math doom after maximum folding — forward anyway. + log("warn", `[${session.id}] core text alone is ~${doomBytes} bytes even after ${result.compressedRanges} fold(s) (≥ ~${Math.ceil(doomBytes / DOOMED_PROBE_BYTES_PER_TOKEN)} tok at the densest observed density vs window ${limit}, model=${model}) — forwarding per #7537 (no local estimate-refusal); the upstream's own size verdict is authoritative${shrinkNote}`); + log("info", `[${session.id}] preflight forward core-text profile: ${describeCoreTextDuplication(outMsgs)}`); + return outbound; } if (localRefusalHere && !trustedForward) { // #3846: bili already refused this scope locally — do not re-bet on @@ -4878,7 +4937,19 @@ export async function preflightCompressIfNeeded( log("warn", `[${session.id}] identity fast path: fold walk exhausted deterministically — upstream reality (~${session.stats.lastInputTokens} tok, ${evidenceSource} on this origin+model) outranks the local doom-math; forwarding the outbound as configured (a genuine 400 arms the overflow recovery)`); return outbound; } - const status = f?.kind === "upstream" && f.status === 429 ? 503 : f?.kind === "exhausted" && f.deterministic && !payloadFitsWindow ? 413 : 502; + // #7537 (owner ruling 2026-11-22): a DETERMINISTIC size exhaustion used to + // answer 413 — a LOCAL estimate verdict that the ruling supersedes: fold + // as far as the walk gets, then FORWARD; the upstream answers with its + // own real numbers (annotated in relay.ts). Only relay-side failures keep + // a local refusal: the summary relay itself is down (non-deterministic + // exhaustion → 502) or the relay hit an upstream 429 (→ 503). + if (f?.kind === "exhausted" && f.deterministic && !payloadFitsWindow) { + const fwdMsgs = outbound.processedMessages.length > 0 ? outbound.processedMessages : outbound.originalMessages; + log("warn", `[${session.id}] fold walk exhausted deterministically (nothing more can fold and the payload is still over window ${limit} by local estimate (~${Math.round(result.payloadEstimate)} tok, ${result.compressedRanges} range(s) folded) — forwarding per #7537 (no local estimate-refusal); the upstream's own size verdict is authoritative${shrinkNote}`); + log("info", `[${session.id}] preflight forward core-text profile: ${describeCoreTextDuplication(fwdMsgs)}`); + return outbound; + } + const status = f?.kind === "upstream" && f.status === 429 ? 503 : 502; // #3918: non-deterministic exhaustion WITH committed progress is not terminal — // the folds persist in the session, so the next attempt starts from a smaller // baseline and continues the fold. Reporting retryable=false told hosts to stop @@ -4887,9 +4958,6 @@ export async function preflightCompressIfNeeded( // verdict: nothing more can fold from this view, so retries are genuinely doomed. const progressContinues = f?.kind === "exhausted" && !f.deterministic && result.compressedRanges > 0; // #3846: a deterministic can-never-fit verdict is local refusal evidence for - // this scope — persist it so the forward-once escapes above stay closed on - // retry even after the baseline demotes to estimate or the body changes. - if (status === 413) noteLocalRefusal(session, currentOrigin, model, limit); // #2189: an explicit retryable=false from preflight (credential-shape // rejection — deterministic for the identical payload) overrides the // status-based heuristic below; every other path keeps today's mapping. diff --git a/src/server/relay.ts b/src/server/relay.ts index 9a298757a0..94ea79b270 100644 --- a/src/server/relay.ts +++ b/src/server/relay.ts @@ -77,7 +77,7 @@ import { bodyDumpEnabled, logDumpFailure } from "./observability.js"; import { rejectionDiagnosticSuffix } from "./rejection-diagnostics.js"; import { effectiveAbsorbBlock, effectiveBlockOpsEnabled } from "./prepare-responses.js"; import { awaitDrain, bufferStreamIfFits, bufferToStream, dumpStreamToFile, pipeThrough, readStreamToBuffer } from "./stream-io.js"; -import { buildForwardTarget, measuredBreakdownClause, measuredOutbound, outboundPayloadBreakdown, registerRequestAbort, beginStreamKeepalive, effectiveTokenCount, googlePathKind, imageBillingFor, imageTokenCapFor, inboundResignCredential, outboundContextEstimates, resolveUpstream, stripKernelSummaries, usageGradeInputBaseline, DOOMED_PROBE_ABSOLUTE_BYTES, DOOMED_PROBE_BYTES_PER_TOKEN, type Prepared } from "../server.js"; +import { buildForwardTarget, measuredBreakdownClause, measuredOutbound, outboundPayloadBreakdown, registerRequestAbort, beginStreamKeepalive, effectiveTokenCount, googlePathKind, imageBillingFor, imageTokenCapFor, inboundResignCredential, outboundContextEstimates, resolveUpstream, stripKernelSummaries, usageGradeInputBaseline, DOOMED_PROBE_ABSOLUTE_BYTES, DOOMED_PROBE_BYTES_PER_TOKEN, noteUpstreamSizeVerdict, type Prepared } from "../server.js"; /** Retry the same input when the provider proved only its output reservation overflows. */ function capOverflowOutput(body: string | Buffer, info: ContextOverflowInfo): { body: string; cap: number } | null { @@ -1039,28 +1039,19 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare const fuseMeasured = measuredOutbound(prepared); const fuseRawTokens = fuseMeasured?.tokens; if (fuseMeasured !== undefined && fuseRawTokens !== undefined && fuseRawTokens > fuseWindow) { - log("warn", `413: [${prepared.session.id}] egress window fuse measured-body profile: ${describeCoreTextDuplication(fuseMsgs)}`); - const fuseMessage = `outbound body measures ~${fuseRawTokens.toLocaleString("en-US")} tokens (${measuredBreakdownClause(fuseMeasured.breakdown)}; CJK-aware count, the #554 guard meter) vs the effective model window ${declaredWindow.toLocaleString("en-US")} (bars never assume below ${MIN_ASSUMED_WINDOW_TOKENS} tokens, #4079) (model=${prepared.model ?? "unknown"}); the body ITSELF exceeds the window, so the send was stopped at the egress fuse instead of being forwarded (#5000/#4543/#4068). Remove or trim the oversized dimension named above (e.g. a giant paste or tool result in messages[], or tools[] schemas) and retry.`; - log("warn", `413: [${prepared.session.id}] egress window fuse: ${fuseMessage}`); - if (res.headersSent) emitStreamError(res, prepared.protocol, fuseMessage, undefined, opts.streamErrorShape); - else { - res.writeHead(413, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: { type: "request_too_large", code: "egress_window_fuse", stage: "forward", message: fuseMessage, retryable: false } })); - } - return; + // #7537 (owner ruling 2026-11-22): no estimate-based refusal — + // the bar here is a local window value that is often wrong- + // small. Log the measurement as evidence and forward; the + // upstream answers with its own real numbers (annotated in + // the upstream size-error branch below, same issue). + log("warn", `[${prepared.session.id}] egress window fuse profile: outbound body measures ~${fuseRawTokens.toLocaleString("en-US")} tokens (${measuredBreakdownClause(fuseMeasured.breakdown)}; the #554 meter) vs the effective model window ${declaredWindow.toLocaleString("en-US")} (model=${prepared.model ?? "unknown"}) — forwarding per #7537 (no local estimate-refusal); the upstream's own size verdict is authoritative`); + log("info", `[${prepared.session.id}] egress window fuse profile (duplication): ${describeCoreTextDuplication(fuseMsgs)}`); } const fuseBytes = estimateCoreMessagesUpperBytes(fuseMsgs); if (fuseBytes > Math.max(DOOMED_PROBE_ABSOLUTE_BYTES, fuseWindow * DOOMED_PROBE_BYTES_PER_TOKEN)) { - const fuseFloorTokens = Math.ceil(fuseBytes / DOOMED_PROBE_BYTES_PER_TOKEN); - log("warn", `413: [${prepared.session.id}] egress window fuse core-text profile: ${describeCoreTextDuplication(fuseMsgs)}`); - const fuseMessage = `outbound core text alone is ~${fuseBytes} bytes — even at the densest tokenizer density observed on a live route (~${DOOMED_PROBE_BYTES_PER_TOKEN} bytes/token, #2122) that is ≥ ~${fuseFloorTokens} tokens vs the effective model window ${declaredWindow} (bars never assume below ${MIN_ASSUMED_WINDOW_TOKENS} tokens, #4079) (model=${prepared.model ?? "unknown"}); no upstream can accept it, so the send was stopped at the egress fuse instead of being forwarded (#4068/#4079). Remove or trim the oversized content (e.g. a giant paste or tool result) and retry.`; - log("warn", `413: [${prepared.session.id}] egress window fuse: ${fuseMessage}`); - if (res.headersSent) emitStreamError(res, prepared.protocol, fuseMessage, undefined, opts.streamErrorShape); - else { - res.writeHead(413, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: { type: "request_too_large", code: "egress_window_fuse", stage: "forward", message: fuseMessage, retryable: false } })); - } - return; + // #7537: byte-math profile over the local window bar — log and + // forward, same ruling as above. + log("warn", `[${prepared.session.id}] egress window fuse profile: outbound core text alone is ~${fuseBytes} bytes (≥ ~${Math.ceil(fuseBytes / DOOMED_PROBE_BYTES_PER_TOKEN)} tok at the densest observed density, #2122) vs the effective model window ${declaredWindow} (model=${prepared.model ?? "unknown"}) — forwarding per #7537 (no local estimate-refusal); the upstream's own size verdict is authoritative`); } } } @@ -2161,6 +2152,57 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare // here depends on it. const terminalCause = rejectionDiagnosticSuffix(bodyText); loggerLog("warn", `[${errSid}] ← upstream ${upstream.status}${reqIdText}: ${snippet}${terminalCause}`); + // #7537 (owner ruling 2026-11-22): local estimate-refusals are gone — + // when the UPSTREAM itself rejects the body as too large, its verdict + // is authoritative. bili logs its own measurement as evidence and + // marks the response non-retryable so status-code-driven hosts don't + // retry-loop an unchanged body the upstream already rejected (burning + // rate limits). Log always; header + body merge only for non-stream + // pipeline-prepared forwards where the body is still under bili's + // control (stream in-band errors and already-committed-200 responses + // stay verbatim). Body merge only when the upstream body is valid + // JSON — anything else passes through byte-identical. + const SIZE_ERROR_RE = /request entity too large|payload.*too (large|big)|body too (large|big)|too many (tokens|messages|bytes)|exceeds? (the |a |your )?(maximum|limit|allowed|context)|context (length|window|size)|input is too long|maximum context length|token (limit|count|budget)|content is too long|message\[?s?\]?.*(too long|exceed)/i; + const upstreamSizeVerdict = upstream.status === 413 || (upstream.status === 400 && SIZE_ERROR_RE.test(bodyText)); + if (prepared && upstreamSizeVerdict) { + // #7537/#496: this EXACT outbound body drew a size verdict — record + // it (SHA-1 of the preflight serialization, origin+model scoped, + // 10-minute TTL) so a byte-identical resend is refused locally by + // the preflight loop guard instead of re-burning the wire. The + // identity fast path and every changed body re-forward freely. + const preparedOutbound = typeof prepared.body === "string" ? prepared.body : (prepared.body instanceof Buffer ? prepared.body.toString("utf8") : undefined); + noteUpstreamSizeVerdict(prepared.session, normalizeUpstreamOrigin(upstreamUrl), prepared.model, preparedOutbound); + const sizeMeasured = measuredOutbound(prepared); + const declaredWindow = typeof prepared.session.metadata.effectiveContextLimit === "number" && prepared.session.metadata.effectiveContextLimit > 0 + ? prepared.session.metadata.effectiveContextLimit + : 0; + const inboundBytes = typeof wireBody === "string" ? wireBody.length : wireBody ? wireBody.length : 0; + log("warn", `[${errSid}] upstream size verdict ${upstream.status} (authoritative per #7537): bili measured outbound ~${sizeMeasured?.tokens?.toLocaleString("en-US") ?? "n/a"} TEXT tokens${sizeMeasured?.breakdown ? ` (${measuredBreakdownClause(sizeMeasured.breakdown)})` : ""}, inbound ${inboundBytes.toLocaleString("en-US")} bytes, effective window ${declaredWindow.toLocaleString("en-US")} (model=${prepared.model ?? "unknown"}); marking non-retryable to stop host retry loops`); + if (!res.headersSent && req.method !== "GET" && req.method !== "HEAD") { + respHeaders["x-bili-cause"] = "upstream-size"; + respHeaders["x-bili-retryable"] = "false"; + if (errBody) { + try { + const asText = new TextDecoder().decode(errBody); + const json = JSON.parse(asText) as Record; + if (json && typeof json === "object" && !Array.isArray(json)) { + json.bili_evidence = { + outboundTextTokens: sizeMeasured?.tokens ?? null, + breakdown: sizeMeasured?.breakdown ?? null, + inboundBytes, + effectiveWindow: declaredWindow || null, + verdict: `upstream refused this body as too large; bili's local measurement above is evidence, not the cause; do NOT retry the unchanged body (#7537)`, + }; + const errObj = json.error; + if (errObj && typeof errObj === "object" && !Array.isArray(errObj)) { + (errObj as Record).retryable = false; + } + errBody = Buffer.from(JSON.stringify(json)); + } + } catch { /* non-JSON upstream body — headers + log only */ } + } + } + } if (prepared?.session && prepared.nudgeStampsBefore && upstream.status >= 400 && upstream.status < 500) rejectNudge(prepared.session, prepared.nudgeStampsBefore, upstream.status); // #4204: feed this send's FINAL verdict. A model-scoped KeyRing 429 is // selected only by its structured code plus exact request-model match; diff --git a/tests/issue1841-preflight-futility.test.ts b/tests/issue1841-preflight-futility.test.ts index e4b6bb1948..7e1a640fc8 100644 --- a/tests/issue1841-preflight-futility.test.ts +++ b/tests/issue1841-preflight-futility.test.ts @@ -165,7 +165,7 @@ function bulkTokens(repeat: number, pairs: number): number { return Math.round((pairs * (22 * repeat + 45)) / 4); } -test("#1841 A: a payload whose foldable pool cannot close the gap skips the round with zero summary calls", async () => { +test("#1841 A (#7537): a payload whose foldable pool cannot close the gap still skips the round — and is FORWARDED instead of the old 413", async () => { CALLS = []; summaryResponder = () => ({ content: SUMMARY_TEXT, finishReason: "stop" }); const p = await boot(); @@ -189,13 +189,14 @@ test("#1841 A: a payload whose foldable pool cannot close the gap skips the roun seedEvidence(p.upstreamPort, "issue1841-futility-skip"); const resp = await post(p, "issue1841-futility-skip", messages); const body = await resp.text(); - assert.equal(resp.status, 413, `a futile round must fail fast non-retryably (#3461): HTTP ${resp.status} ${body.slice(0, 240)}`); - const json = JSON.parse(body) as { error?: { code?: string; message?: string } }; - assert.equal(json.error?.code, "preflight_compress_failed"); - assert.match(json.error?.message ?? "", /futile round/, `names the futility verdict (got: ${json.error?.message})`); - assert.match(json.error?.message ?? "", /maximum possible saving/, `quotes the pool bound (got: ${json.error?.message})`); + // #7537: the futility verdict no longer answers a local 413 — the + // skipped round's payload is forwarded as-is (fold-first unchanged: it + // just wasn't worth folding), and the upstream decides. This mock + // upstream accepts it → 200. + assert.equal(resp.status, 200, `a futile round now forwards (#7537): HTTP ${resp.status} ${body.slice(0, 240)}`); + assert.ok(body.includes("forwarded answer"), "the model reply must reach the client"); assert.equal(CALLS.filter((c) => c.summary).length, 0, "a skipped round must spend ZERO summarization calls"); - assert.equal(CALLS.length, 0, "the over-window payload must not be forwarded either"); + assert.equal(CALLS.length, 1, "the over-window payload is forwarded exactly once (the upstream is the size authority)"); } finally { await p.cleanup(); } diff --git a/tests/issue2490-ledger-floor-doomed-probe.test.ts b/tests/issue2490-ledger-floor-doomed-probe.test.ts index dc76d6cb04..f16ebfbeb7 100644 --- a/tests/issue2490-ledger-floor-doomed-probe.test.ts +++ b/tests/issue2490-ledger-floor-doomed-probe.test.ts @@ -279,23 +279,25 @@ test("e2e #2490 a: the guard records the refused replay SIZE on the session (hig // --------------------------------------------------------------------------- // (b) doomed probe -test("e2e #2490 b: multi-MB core text beyond both doom bars fails fast instead of paying the probe 400", async () => { +test("e2e #2490 b: a multi-MB core-text payload is folded-then-forwarded — the upstream decides (#7537)", async () => { const { ctx, calls, close } = await setup(); try { await seedStuckMeter(ctx, "s-2490-b"); - // 500 msgs × 4.4K chars ≈ 2.2MB of ASCII core text — past the absolute - // 2MB bar (and the 20K window × 7.5 B/token = 150KB ratio bar). + // 500 msgs × 4.4K chars ≈ 2.2MB of ASCII core text — past the old + // absolute 2MB doom bar (and the 20K window × 7.5 B/token = 150KB + // ratio bar). #7537 (owner ruling 2026-11-22): local size estimates no + // longer refuse — this session's shape (estimate-sourced baseline, + // #1933-demoted) takes the evidence PROBE path: the payload goes to the + // upstream once, un-folded, and the upstream answers with its own real + // numbers; the evidence-backed byte-identical-resend loop guard (#496) + // covers the retry storm the old 502 (and then the old 413) invited. const r = await post(ctx, bigMessages(500, 4_400)); - // #2847: 413 (was 502) — a mathematically-determined rejection must be - // non-retryable at the status-code layer, or status-driven hosts retry - // the identical doomed payload (3 crashes in 10s in the field). - assert.equal(r.status, 413, "doomed probe fails fast with NON-retryable 4xx semantics, not forwarded"); const body = await r.text(); - assert.match(body, /~22\d{5} bytes/, "the byte math is in the operator-facing message"); - assert.match(body, /NOT forwarded even for evidence/, "the remedy wording is present"); - - assert.ok(calls.length === 1 && calls[0]!.contentChars < 50_000, `only the seed turn reached the upstream (calls=${JSON.stringify(calls.map((c) => c.contentChars))}) — never the 2.2MB payload`); + assert.equal(r.status, 200, `the payload is forwarded and the upstream decides (got ${r.status}: ${body.slice(0, 200)})`); + assert.match(body, /forwarded answer/, "the upstream's own answer reaches the host"); + const forwards = calls.filter((c) => !c.summary); + assert.equal(forwards.length, 2, `seed turn + exactly one forward (calls=${JSON.stringify(calls.map((c) => ({ s: c.summary, n: c.contentChars })))})`); } finally { await close(); } @@ -325,7 +327,9 @@ test("e2e #2490 c: an experiment-sized payload still probes (control — #2313/# }); // --------------------------------------------------------------------------- -// (d) #4079: the doomed 413 logs whether the payload GREW or REPEATED +// (d) #4079: the over-window forward logs whether the payload GREW or REPEATED +// (#7537 moved the profile off the deleted local-413 refusal onto the forward +// warn — the diagnostic now rides the "still over after folding" forward). async function runDoomedScenario( sessionId: string, @@ -350,27 +354,27 @@ async function runDoomedScenario( } } -test("e2e #4079: the doomed 413 logs one core-text profile line, reading an all-distinct payload as GROWN", async () => { +test("e2e #4079: the all-distinct over-window payload is forwarded, logging one GROWN core-text profile line", async () => { // Same shape as (b): 500 msgs × 4.4K chars ≈ 2.2MB core text — but every // message is unique (`turn i:` prefix), so the ratio must read near zero: // the payload grew by content, not by repetition. const { status, profiles } = await runDoomedScenario("s-4079-grew", bigMessages(500, 4_400)); - assert.equal(status, 413, "still fails fast on the same bars"); - assert.equal(profiles.length, 1, "exactly one profile line accompanies the refusal"); + assert.equal(status, 200, "the payload is forwarded — the upstream decides (#7537)"); + assert.equal(profiles.length, 1, "exactly one profile line accompanies the over-window forward"); assert.match(profiles[0]!, /\d+ message\(s\), \d+B core over \d+ distinct text\(s\), \d+B unique/); assert.match(profiles[0]!, /duplicateRatio=0\.0\d{2}/, "unique-per-message payload → growth, not repetition"); }); -test("e2e #4079: the doomed 413 reads a repeated-text payload as REPEATED (the #4079 incident shape)", async () => { +test("e2e #4079: the repeated-text over-window payload is forwarded, logged as REPEATED (the #4079 incident shape)", async () => { const blob = "r".repeat(4_400); const { status, profiles } = await runDoomedScenario("s-4079-repeat", Array.from({ length: 500 }, () => ({ role: "user", content: blob }))); - assert.equal(status, 413, "the identical byte mass still trips the same bars"); - assert.equal(profiles.length, 1, "exactly one profile line accompanies the refusal"); + assert.equal(status, 200, "the identical byte mass is forwarded — the upstream decides (#7537)"); + assert.equal(profiles.length, 1, "exactly one profile line accompanies the over-window forward"); assert.match(profiles[0]!, /duplicateRatio=0\.9\d{2}/, "one blob repeated 500× → repetition, not growth"); }); -test("e2e #4079: the non-doomed probe forward logs NO profile line (negative direction, #3617)", async () => { +test("e2e #4079: the fitting probe forward logs NO profile line (negative direction, #3617)", async () => { const { status, profiles } = await runDoomedScenario("s-4079-control", bigMessages()); assert.equal(status, 200, "experiment-sized payload still probes (#2313/#1001 preserved)"); - assert.equal(profiles.length, 0, "the diagnostic only fires on the refusal path, never on the hot path"); + assert.equal(profiles.length, 0, "the diagnostic only fires on the over-window forward, never on the fitting hot path"); }); diff --git a/tests/issue2847-doomed-nonretryable-status.test.ts b/tests/issue2847-doomed-nonretryable-status.test.ts index 1736bf535c..cd8b1c7469 100644 --- a/tests/issue2847-doomed-nonretryable-status.test.ts +++ b/tests/issue2847-doomed-nonretryable-status.test.ts @@ -1,14 +1,10 @@ -// #2847: the doomed probe (#2490) answers a mathematically-determined -// overflow with HTTP 502 while the body says `"retryable": false`. Hosts that -// decide on the STATUS CODE (pi: retry.maxRetries=20 / baseDelayMs=3000) treat -// 502 as a transient gateway failure and retry anyway — field evidence: 3 -// crashes in 10 seconds, the 3rd carrying a 6.4MB payload (representation -// flip after the provider switch, not content growth). Fix (suggestion 3, -// status-semantics layer only): answer 413 Content Too Large — the repo's own -// convention for a mathematically-determined "cannot fit, NOT forwarded" -// rejection (side-request guard, `side_request_payload_too_large`) and -// non-retryable semantics for every mainstream host. The doom math, the -// message, the no-forward behavior and `retryable:false` are untouched. +// #2847 (historical): the doomed probe answered 502 with "retryable": false; +// status-code-driven hosts retried anyway (3 crashes in 10s) → #2490 made the +// local refusal 413. #7537 (owner ruling 2026-11-22) superseded the local +// refusal itself: size estimates no longer veto a forward — the payload is +// folded where it folds and forwarded, the upstream's own verdict is +// authoritative, and the evidence-backed byte-identical-resend loop guard +// (#496) is what now breaks the retry storm. import assert from "node:assert/strict"; import http from "node:http"; import { once } from "node:events"; @@ -155,31 +151,26 @@ async function seedStuckMeter(ctx: Ctx, sessionId: string, lastInputTokens = 7_3 s.stats.lastInputTokensOrigin = "http://127.0.0.1:1"; } -test("e2e #2847: a mathematically-doomed payload answers NON-retryable 4xx semantics, not a 502 the host must retry", async () => { +test("e2e #2847: a multi-MB doomed-shape payload is folded-then-forwarded — the upstream's own verdict is authoritative (#7537)", async () => { const root = mkdtempSync(path.join(tmpdir(), "bili-2847-")); const { ctx, calls, close } = await setup(); try { await seedStuckMeter(ctx, "s-2847-a"); - // 500 msgs × 4.4K chars ≈ 2.2MB ASCII core text — past BOTH doom bars - // (absolute 2MB floor; 20K window × 7.5 B/token = 150KB ratio bar). - // This is the issue's shape: ~2,234,634 bytes rejected 3× in 10s. + // 500 msgs × 4.4K chars ≈ 2.2MB ASCII core text — the issue's shape: + // ~2,234,634 bytes rejected 3× in 10s (old code: local 413 before any + // forward). #7537 (owner ruling 2026-11-22): the local doom math no + // longer refuses — this session's shape (estimate-sourced baseline, + // #1933-demoted) takes the evidence PROBE path: the payload goes to the + // upstream once and the upstream answers with its own real numbers, and + // the byte-identical-resend loop guard (#496) covers the retry-storm + // case a status-driven host would otherwise retry. const r = await post(ctx, bigMessages()); const body = await r.text(); - const parsed = JSON.parse(body) as { error?: { code?: string; retryable?: boolean; message?: string } }; - - // THE fix under test: the status itself must carry the non-retryable - // semantics. 502 is a transient gateway failure for every status-code - // -driven host; 413 is terminal. - assert.equal(r.status, 413, `doomed overflow must answer 413 (got ${r.status}) — a 502 re-invites the host retry storm (#2847)`); - assert.ok(r.status >= 400 && r.status < 500, "doomed overflow is a 4xx (non-retryable class), never a 5xx"); - // Everything else pinned by #2490 stays byte-identical in meaning: - assert.equal(parsed.error?.code, "preflight_compress_failed", "same structured error code"); - assert.equal(parsed.error?.retryable, false, "body still says retryable:false"); - assert.match(parsed.error?.message ?? "", /~2[23]\d{5} bytes/, "the byte math is in the operator-facing message"); - assert.match(parsed.error?.message ?? "", /NOT forwarded even for evidence/, "the remedy wording is present"); - // Behavior unchanged: the doomed payload NEVER reaches the upstream. - assert.ok(calls.length === 1 && calls[0]!.contentChars < 50_000, `only the seed turn reached the upstream (calls=${JSON.stringify(calls.map((c) => c.contentChars))})`); + assert.equal(r.status, 200, `the payload is forwarded and the upstream decides (got ${r.status}: ${body.slice(0, 200)})`); + assert.match(body, /forwarded answer/, "the upstream's own answer reaches the host"); + const forwards = calls.filter((c) => !c.summary); + assert.equal(forwards.length, 2, `seed turn + exactly one forward (calls=${JSON.stringify(calls.map((c) => ({ s: c.summary, n: c.contentChars })))})`); } finally { await close(); rmrf(root); diff --git a/tests/issue3645-calibrated-futility.test.ts b/tests/issue3645-calibrated-futility.test.ts index f900b4b0f4..63b0eb9fa5 100644 --- a/tests/issue3645-calibrated-futility.test.ts +++ b/tests/issue3645-calibrated-futility.test.ts @@ -282,15 +282,15 @@ test("#3645 display: fail-fast quotes the calibrated post-fold size, not the raw ]; const resp = await post(p, sessionId, messages); const body = await resp.text(); - let json: { error?: { code?: string; message?: string } }; - try { json = JSON.parse(body); } catch { assert.fail(`expected a JSON fail-fast error, got HTTP ${resp.status}: ${body.slice(0, 240)}`); return; } const summaries = CALLS.filter((c) => c.summary).length; + // #7537: deterministic calibrated exhaustion no longer answers a local + // 413 — the folded payload is forwarded and the upstream decides. The + // #3645 display bug (raw vs calibrated quote) now lives in the operator + // warn log, not in a client-facing error body. assert.ok(summaries >= 1, `folds actually landed before exhaustion — ${summaries} summary call(s)`); - assert.equal(resp.status, 413, `deterministic exhaustion must fail fast non-retryably: HTTP ${resp.status} ${body.slice(0, 240)}`); - assert.equal(json.error?.code, "preflight_compress_failed"); - const m = /context ~(\d+) tokens/.exec(json.error?.message ?? ""); - assert.ok(m, `fail-fast must quote a context figure (got: ${json.error?.message})`); - assert.ok(Number(m[1]) > WINDOW, `quoted figure must be on the calibrated (over-window) scale like the fit decision — got ~${m?.[1]} vs window ${WINDOW}; quoting the raw sub-window size is the #3645 display bug`); + assert.equal(resp.status, 200, `deterministic exhaustion now forwards (#7537): HTTP ${resp.status} ${body.slice(0, 240)}`); + assert.ok(body.includes("forwarded answer"), "the model reply must reach the client"); + assert.equal(CALLS.filter((c) => !c.summary).length, 1, "exactly one main forward"); } finally { await p.cleanup(); } @@ -329,17 +329,14 @@ test("#3645 Responses dsh plugin lane: calibrated fail-fast does not forward the ]; const resp = await postResponses(p, sessionId, input, true); const body = await resp.text(); - let json: { error?: { code?: string; message?: string } }; - try { json = JSON.parse(body); } catch { assert.fail(`expected a JSON fail-fast error, got HTTP ${resp.status}: ${body.slice(0, 240)}`); return; } const summaries = CALLS.filter((c) => c.summary).length; const forwarded = CALLS.filter((c) => !c.summary).length; + // #7537: the calibrated exhaustion 413 is gone — the plugin lane folds + // and forwards; the upstream's own verdict is authoritative. assert.ok(summaries >= 1, `Responses plugin lane must perform summary folding (got ${summaries} summary call(s))`); - assert.equal(forwarded, 0, `the over-window Responses payload must not be forwarded (got ${forwarded} main call(s))`); - assert.equal(resp.status, 413, `deterministic calibrated exhaustion must fail fast: HTTP ${resp.status} ${body.slice(0, 240)}`); - assert.equal(json.error?.code, "preflight_compress_failed"); - const m = /context ~(\d+) tokens/.exec(json.error?.message ?? ""); - assert.ok(m, `fail-fast must quote a context figure (got: ${json.error?.message})`); - assert.ok(Number(m[1]) > WINDOW, `quoted Responses figure must be calibrated and over-window (got ~${m?.[1]} vs ${WINDOW})`); + assert.equal(forwarded, 1, `the over-window Responses payload must be forwarded exactly once (got ${forwarded} main call(s))`); + assert.equal(resp.status, 200, `deterministic calibrated exhaustion now forwards (#7537): HTTP ${resp.status} ${body.slice(0, 240)}`); + assert.ok(body.includes("forwarded answer"), "the model reply must reach the client"); } finally { await p.cleanup(); } @@ -373,11 +370,13 @@ test("#3645 control: uncalibrated (k̂ absent) futility skip is unchanged (#1841 seedEvidence(p.upstreamPort, sessionId); const resp = await post(p, sessionId, messages); const body = await resp.text(); - assert.equal(resp.status, 413, `a raw-futile round must still fail fast non-retryably: HTTP ${resp.status} ${body.slice(0, 240)}`); - const json = JSON.parse(body) as { error?: { code?: string; message?: string } }; - assert.equal(json.error?.code, "preflight_compress_failed"); - assert.match(json.error?.message ?? "", /futile round/, `still names the futility verdict (got: ${json.error?.message})`); + // #7537: the raw-futile skip no longer answers a local 413 either — + // skipping the round (zero summary calls) still holds, and the payload + // is forwarded as-is to the upstream, which decides. + assert.equal(resp.status, 200, `a raw-futile round now forwards (#7537): HTTP ${resp.status} ${body.slice(0, 240)}`); + assert.ok(body.includes("forwarded answer"), "the model reply must reach the client"); assert.equal(CALLS.filter((c) => c.summary).length, 0, "the uncalibrated skip must spend ZERO summarization calls"); + assert.equal(CALLS.filter((c) => !c.summary).length, 1, "the un-fittable payload is forwarded exactly once"); } finally { await p.cleanup(); } diff --git a/tests/issue3846-local-refusal-evidence.test.ts b/tests/issue3846-local-refusal-evidence.test.ts deleted file mode 100644 index e12028bd22..0000000000 --- a/tests/issue3846-local-refusal-evidence.test.ts +++ /dev/null @@ -1,392 +0,0 @@ -// #3846: a locally refused oversized request (preflight 413, NOT forwarded) -// could be forwarded on retry once the usage baseline demoted to -// "estimate": the refusal lived only in the #726 dead-end marker's -// body-hash dimension, so (a) the #2313 estimate-only probe re-armed at -// baselineFloor === 0 and ran BEFORE the dead-end check, and (b) every -// turn's changed body missed the hash — production shape: three consecutive -// full-bill forwards of 606K/620K/633K-token payloads bili itself had -// already refused locally. The fix persists local refusal evidence in -// session metadata scoped to origin/model/window and keeps every -// forward-once escape hatch closed at the same or tighter window. Pinned -// here end-to-end, both directions (#3617 gate discipline): -// (a) positive — the issue's deterministic repro: fitting seed → oversized -// non-foldable system text → local 413 → baseline demotion + restart -// simulation → three identical retries stay 413 with ZERO additional -// upstream calls; a trimmed payload still forwards; -// (b) positive — production shape: retries with CHANGED bodies defeat the -// dead-end hash, so only the persisted evidence can hold the line; -// (c) negative — another model on the same origin, and another origin -// entirely, are evaluated independently (the escape hatches stay open -// where bili never refused); -// (d) hygiene — the refusal is its own metadata channel: it must never be -// labeled upstream usage (lastInputTokens/Source untouched). -import assert from "node:assert/strict"; -import http from "node:http"; -import { once } from "node:events"; -import test from "node:test"; - -process.env.NODE_ENV = "test"; - -import { defaultConfig } from "acp-kernel"; -import { startServer } from "../src/server.ts"; -import type { ProxyOptions } from "../src/config.ts"; -import { SessionStore, _setStoreForTest } from "../src/persist.ts"; -import { _setForTest as setRegistryForTest } from "../src/registry.ts"; -import { getSession } from "../src/session.ts"; -import { normalizeUpstreamOrigin } from "../src/util.ts"; - -const WINDOW = 20_000; -const SUMMARY_TEXT = - "PREFLIGHT SUMMARY: the segment held deterministic load-growth payloads across turns; every marker derives from the turn index, so folding loses nothing."; - -// ~400KB of varying ASCII core text: ~100K tokens at the chars/4 estimate -// (5x the 20K window, robust across the whole k̂ clamp [0.25, 4]) yet far -// under the 2MB absolute doom bar, so the pre-fix probe would forward it. -function bigSystem(): string { - let out = ""; - for (let i = 0; i < 400_000; i += 64) { - out += `oversized non-foldable system load segment ${Math.floor(i / 64)}: ` + "x".repeat(40); - } - return out.slice(0, 400_000); -} - -type Call = { summary: boolean; stream: boolean; contentChars: number }; - -function chatSse(text: string, usage?: { prompt_tokens: number; completion_tokens: number }): string { - const chunk = (delta: Record, finish: string | null, extra?: Record): string => - `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "gpt-test", choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`; - const u = usage ? { usage } : {}; - return chunk({ role: "assistant" }, null) + chunk({ content: text }, null) + chunk({}, "stop", u) + "data: [DONE]\n\n"; -} - -// Counting fake upstream: bills what it receives at ~40 B/token and reports -// it as usage; answers summarization calls deterministically. -function makeUpstream(): { server: http.Server; calls: Call[] } { - const calls: Call[] = []; - const server = http.createServer((req, res) => { - const chunks: Buffer[] = []; - req.on("data", (c: Buffer) => chunks.push(c)); - req.on("end", () => { - const raw = Buffer.concat(chunks).toString("utf8"); - const isSummary = /TASK: The conversation segment below/.test(raw); - try { - const parsed = JSON.parse(raw) as { stream?: boolean; messages?: Array<{ content?: unknown }> }; - const chars = (parsed.messages ?? []).reduce((n, m) => n + (typeof m.content === "string" ? m.content.length : 0), 0); - calls.push({ summary: isSummary, stream: !isSummary && !!parsed.stream, contentChars: chars }); - if (isSummary) { - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ id: "chatcmpl-sum", object: "chat.completion", model: "gpt-test", choices: [{ index: 0, message: { role: "assistant", content: SUMMARY_TEXT }, finish_reason: "stop" }] })); - return; - } - res.writeHead(200, { "content-type": "text/event-stream" }); - res.end(chatSse("forwarded answer", { prompt_tokens: Math.max(1, Math.round(chars / 40)), completion_tokens: 3 })); - } catch { - res.writeHead(400, { "content-type": "application/json" }); - res.end('{"error":{"message":"unparseable"}}'); - } - }); - }); - return { server, calls }; -} - -type Upstream = ReturnType; - -function proxyOptions(routes: Record): ProxyOptions { - return { - port: 0, - host: "127.0.0.1", - upstream: "http://127.0.0.1", - routes: routes as ProxyOptions["routes"], - modelContextLimit: WINDOW, - kernelConfig: defaultConfig(WINDOW, { - preserveRecentMessages: 2, - preserveRecentTokens: 2000, - compress: { minCompressRange: 1000, maxSummaryLength: 20000, minSummaryLength: 50 }, - }), - compress: { injectTool: true, injectNudge: true }, - sessionHeader: "x-acp-session", - log: false, - debug: false, - passthrough: false, - autoUpdate: false, - compat: { roles: {} }, - streamErrorShape: "protocol", - passthroughSource: null, - autoRestartOnUpdate: false, - updateTag: "latest", - advisoryCheck: false, - releaseNotesCheck: false, - promptCache: { routing: "auto" }, - mitm: { enabled: false, domains: [] }, - } as ProxyOptions; -} - -type Ctx = { url: string; headers: Record; upstreamPort: number }; - -async function listen(u: Upstream): Promise { - u.server.listen(0, "127.0.0.1"); - await once(u.server, "listening"); - return (u.server.address() as { port: number }).port; -} - -async function setup(routes: Record): Promise<{ ctx: Ctx; close: () => Promise }> { - _setStoreForTest(new SessionStore({ enabled: false })); - setRegistryForTest({}); - const firstKey = Object.keys(routes)[0]!; - const port = Number(new URL(firstKey).port); - const proxy = await startServer(proxyOptions(routes)); - await once(proxy, "listening"); - const proxyPort = (proxy.address() as { port: number }).port; - return { - ctx: { - url: `http://127.0.0.1:${proxyPort}/bili/${firstKey}/chat/completions`, - headers: { "content-type": "application/json", "x-acp-session": "" }, - upstreamPort: port, - }, - close: async () => { - proxy.close(); - proxy.closeIdleConnections?.(); - await Promise.allSettled([once(proxy, "close")]); - }, - }; -} - -const post = (ctx: Ctx, body: Record) => - fetch(ctx.url, { method: "POST", headers: { ...ctx.headers }, body: JSON.stringify(body) }); - -const streamCalls = (calls: Call[]) => calls.filter((c) => c.stream).length; -const summaryCalls = (calls: Call[]) => calls.filter((c) => c.summary).length; - -// The issue's repro step 3: the baseline demotion a preflight rebuild performs -// (lastInputTokens anchored to the rebuilt size, source "estimate"), followed -// by a restart simulation — only the persisted metadata survives the round trip. -function demoteToEstimate(sessionId: string): void { - const s = getSession(sessionId); - assert.ok(s, "session exists"); - s.stats.lastInputTokens = 60_000; - s.stats.lastInputTokensSource = "estimate"; - s.metadata = JSON.parse(JSON.stringify(s.metadata)); -} - -// Repro steps 1-2: a fitting seed settles a usage baseline; then an oversized -// NON-FOLDABLE system text (system is wire overhead — folding never removes -// it) must come back as a local 413 without touching the upstream. -async function seedAndRefuse(ctx: Ctx, sessionId: string, model: string): Promise { - ctx.headers["x-acp-session"] = sessionId; - const rSeed = await post(ctx, { model, stream: true, messages: [{ role: "user", content: "hello" }] }); - assert.equal(rSeed.status, 200, "the fitting seed forwards"); - await rSeed.text(); - // Identity-fast-path guard: the seed settles a genuine same-origin usage - // baseline, which alone would open the trusted fast path (recorded - // upstream reality outranks local doom-math). These fixtures pin the - // evidence-judged contract, so declare the overflow wall — statedWall > 0 - // demotes the fast path; the wall equals the configured window, so every - // other number in the fixture (the judge's limit, the doom bars) is - // unchanged. - getSession(sessionId)!.stats.overflowArmTokens = WINDOW; - - const rBig = await post(ctx, { model, stream: true, messages: [{ role: "system", content: bigSystem() }, { role: "user", content: "q" }] }); - assert.equal(rBig.status, 413, "oversized non-foldable payload is refused locally"); - const body = await rBig.text(); - assert.match(body, /NOT forwarded/, "the verdict says the payload did not ride"); -} - -test("e2e #3846 a: identical oversized retries stay local 413 after the baseline demotes to estimate — zero extra upstream calls", async () => { - const up = makeUpstream(); - const port = await listen(up); - const { ctx, close } = await setup({ [`http://127.0.0.1:${port}`]: { models: { "gpt-test": { context: WINDOW } } } }); - try { - await seedAndRefuse(ctx, "i3846-a", "gpt-test"); - assert.equal(streamCalls(up.calls), 1, "only the seed reached the upstream"); - assert.equal(summaryCalls(up.calls), 0, "the refusal spent no summarization call"); - - demoteToEstimate("i3846-a"); - - // Three byte-identical retries: pre-fix the FIRST one sailed through - // the estimate-only probe (which sits ahead of the dead-end check) and - // billed the full 400KB payload. - for (let i = 1; i <= 3; i++) { - const r = await post(ctx, { model: "gpt-test", stream: true, messages: [{ role: "system", content: bigSystem() }, { role: "user", content: "q" }] }); - assert.equal(r.status, 413, `retry ${i} stays a local 413`); - await r.text(); - } - assert.equal(streamCalls(up.calls), 1, "no oversized retry may reach the upstream"); - assert.equal(summaryCalls(up.calls), 0, "no summarization call may run either"); - - // Hygiene: the refusal is its own channel, never labeled usage. - const s = getSession("i3846-a")!; - assert.equal(s.stats.lastInputTokens, 60_000, "refusal evidence never rewrites the baseline value"); - assert.equal(s.stats.lastInputTokensSource, "estimate", "refusal evidence never relabels the baseline source"); - const refusals = s.metadata.localRefusals as Array<{ origin: string; model: string; window: number }>; - assert.ok(Array.isArray(refusals) && refusals.length === 1, `one refusal record, got ${JSON.stringify(refusals)}`); - assert.equal(refusals[0]!.origin, normalizeUpstreamOrigin(`http://127.0.0.1:${port}`)); - assert.equal(refusals[0]!.model, "gpt-test"); - assert.equal(refusals[0]!.window, WINDOW); - - // A fitting payload still forwards — the evidence closes escapes, not - // the lane. - const rTrim = await post(ctx, { model: "gpt-test", stream: true, messages: [{ role: "user", content: "small question" }] }); - assert.equal(rTrim.status, 200, "the trimmed request succeeds"); - await rTrim.text(); - assert.equal(streamCalls(up.calls), 2, "the trimmed request is the only new forward"); - } finally { - up.server.close(); - up.server.closeIdleConnections?.(); - await close(); - } -}); - -test("e2e #3846 b: CHANGED-body retries defeat the dead-end hash — only the persisted evidence holds the line", async () => { - const up = makeUpstream(); - const port = await listen(up); - const { ctx, close } = await setup({ [`http://127.0.0.1:${port}`]: { models: { "gpt-test": { context: WINDOW } } } }); - try { - await seedAndRefuse(ctx, "i3846-b", "gpt-test"); - demoteToEstimate("i3846-b"); - - // Production shape: each turn's body differs, so the #726 dead-end key - // (model+window+body hash) misses every time. Pre-fix each retry - // re-entered the estimate-only probe and forwarded once. - const tails = ["q-A", "q-B-tail", "q-C-even-longer-tail"]; - for (let i = 0; i < tails.length; i++) { - const r = await post(ctx, { model: "gpt-test", stream: true, messages: [{ role: "system", content: bigSystem() }, { role: "user", content: tails[i]! }] }); - assert.equal(r.status, 413, `changed-body retry ${i + 1} stays a local 413`); - await r.text(); - } - assert.equal(streamCalls(up.calls), 1, "zero additional upstream stream calls across all changed-body retries"); - assert.equal(summaryCalls(up.calls), 0, "zero summarization calls — nothing was foldable"); - } finally { - up.server.close(); - up.server.closeIdleConnections?.(); - await close(); - } -}); - -test("e2e #3846 c: another model on the same origin is evaluated independently — the probe stays open", async () => { - const up = makeUpstream(); - const port = await listen(up); - const { ctx, close } = await setup({ - [`http://127.0.0.1:${port}`]: { models: { "gpt-test": { context: WINDOW }, "gpt-other": { context: WINDOW } } }, - }); - try { - await seedAndRefuse(ctx, "i3846-c", "gpt-test"); - demoteToEstimate("i3846-c"); - - // Same origin, same window, DIFFERENT model: the refusal record does - // not cover it — the estimate-only bet is still worth one request. - const r = await post(ctx, { model: "gpt-other", stream: true, messages: [{ role: "system", content: bigSystem() }, { role: "user", content: "q" }] }); - assert.equal(r.status, 200, "an uncovered model still probes once"); - await r.text(); - assert.equal(streamCalls(up.calls), 2, "seed + exactly one probe forward for the other model"); - - const s = getSession("i3846-c")!; - const refusals = s.metadata.localRefusals as Array<{ model: string }>; - assert.equal(refusals.length, 1, "the probe on the other model adds no refusal record"); - assert.equal(refusals[0]!.model, "gpt-test"); - } finally { - up.server.close(); - up.server.closeIdleConnections?.(); - await close(); - } -}); - -test("e2e #3846 d: another ORIGIN is evaluated independently — the probe stays open", async () => { - const upA = makeUpstream(); - const upB = makeUpstream(); - const portA = await listen(upA); - const portB = await listen(upB); - const { ctx, close } = await setup({ - [`http://127.0.0.1:${portA}`]: { models: { "gpt-test": { context: WINDOW } } }, - [`http://127.0.0.1:${portB}`]: { models: { "gpt-test": { context: WINDOW } } }, - }); - try { - // Refuse on origin A (ctx.url points at A). - await seedAndRefuse(ctx, "i3846-d", "gpt-test"); - assert.equal(streamCalls(upA.calls), 1); - demoteToEstimate("i3846-d"); - - // Same session, same model, DIFFERENT origin B: no covering record → - // the probe fires again (a fresh route may bill on a different scale). - const urlB = ctx.url.replace(`:${portA}`, `:${portB}`); - const r = await fetch(urlB, { method: "POST", headers: { ...ctx.headers }, body: JSON.stringify({ model: "gpt-test", stream: true, messages: [{ role: "system", content: bigSystem() }, { role: "user", content: "q" }] }) }); - assert.equal(r.status, 200, "an uncovered origin still probes once"); - await r.text(); - assert.equal(streamCalls(upB.calls), 1, "origin B saw exactly the one probe forward"); - assert.equal(streamCalls(upA.calls), 1, "origin A saw nothing more"); - - const s = getSession("i3846-d")!; - const refusals = s.metadata.localRefusals as Array<{ origin: string }>; - assert.equal(refusals.length, 1, "the probe on the other origin adds no refusal record"); - assert.equal(refusals[0]!.origin, normalizeUpstreamOrigin(`http://127.0.0.1:${portA}`)); - } finally { - upA.server.close(); - upA.server.closeIdleConnections?.(); - upB.server.close(); - upB.server.closeIdleConnections?.(); - await close(); - } -}); - -// (#4079/#3974) The refusal evidence now carries a TTL (10 minutes): the -// #3846 lock was real money protection, but a record that never expires -// turned one bad hour into a permanent "this model is unusable" for the -// session — the uninstall-event class from #3974. Both directions pinned: -// (e) an expired record no longer covers — the estimate-only probe may -// bet once again (that bet is cheap and self-correcting: usage -// settles, or a fresh refusal re-records with a fresh timestamp); -// (f) a record without a readable `at` (persisted before the TTL existed) -// is treated as expired too, so upgraded stuck sessions self-heal. -test("e2e #4079 e: refusal evidence expires after the TTL — the probe reopens exactly once", async () => { - const up = makeUpstream(); - const port = await listen(up); - const { ctx, close } = await setup({ [`http://127.0.0.1:${port}`]: { models: { "gpt-test": { context: WINDOW } } } }); - try { - await seedAndRefuse(ctx, "i3846-e", "gpt-test"); - demoteToEstimate("i3846-e"); - - const s = getSession("i3846-e")!; - const refusals = s.metadata.localRefusals as Array<{ at?: number }>; - assert.equal(refusals.length, 1, "one refusal record"); - assert.equal(typeof refusals[0]!.at, "number", "the record carries a readable timestamp"); - - // Backdate past the TTL. - refusals[0]!.at = Date.now() - 11 * 60_000; - - // The expired record no longer covers: the estimate-only probe may - // bet once again (and here the bet lands — usage settles afresh). - const r = await post(ctx, { model: "gpt-test", stream: true, messages: [{ role: "system", content: bigSystem() }, { role: "user", content: "q" }] }); - assert.equal(r.status, 200, "an expired record lets the probe bet once again"); - await r.text(); - assert.equal(streamCalls(up.calls), 2, "seed + exactly one reopened probe forward"); - } finally { - up.server.close(); - up.server.closeIdleConnections?.(); - await close(); - } -}); - -test("e2e #4079 f: a record without a timestamp (pre-TTL legacy) is expired — upgraded stuck sessions self-heal", async () => { - const up = makeUpstream(); - const port = await listen(up); - const { ctx, close } = await setup({ [`http://127.0.0.1:${port}`]: { models: { "gpt-test": { context: WINDOW } } } }); - try { - await seedAndRefuse(ctx, "i3846-f", "gpt-test"); - demoteToEstimate("i3846-f"); - - const s = getSession("i3846-f")!; - const refusals = s.metadata.localRefusals as Array<{ origin: string; model: string; window: number; at?: number }>; - assert.equal(refusals.length, 1, "one refusal record"); - delete refusals[0]!.at; - - // No readable `at` proves nothing — the lane must behave as if no - // refusal was recorded (the pre-TTL lock is exactly what #3974 hit). - const r = await post(ctx, { model: "gpt-test", stream: true, messages: [{ role: "system", content: bigSystem() }, { role: "user", content: "q" }] }); - assert.equal(r.status, 200, "an at-less record does not hold the line"); - await r.text(); - assert.equal(streamCalls(up.calls), 2, "seed + exactly one probe forward"); - } finally { - up.server.close(); - up.server.closeIdleConnections?.(); - await close(); - } -}); diff --git a/tests/issue4079-egress-window-fuse.test.ts b/tests/issue4079-egress-window-fuse.test.ts index 6a4d423bb0..4336e8e1f8 100644 --- a/tests/issue4079-egress-window-fuse.test.ts +++ b/tests/issue4079-egress-window-fuse.test.ts @@ -10,11 +10,18 @@ // excluded) vs max(2MB absolute, window×7.5 B/token from the densest observed // tokenizer, #2122) — and the window itself is floored at 1,000,000 tokens // (#4079: a declared window can be wrong SMALL; the catastrophic bar never -// sizes below the largest common window). Only bodies NO 1M-token window can -// fit are blocked, so this test pins BOTH directions (#3617): the doomed -// giant answers a NON-retryable 413 and never reaches the upstream, while -// bodies under the bars — including multi-MB ones an estimator (or a -// mis-sized small window) would call over-window — still forward. +// sizes below the largest common window). +// +// #7537 (owner ruling 2026-11-22): the size bars are ESTIMATES, and the whole +// #7167/#7382/#2490/#2847 issue family is their false-refusal offshoot — so +// the fuse no longer refuses locally. It now LOGS the measured evidence and +// forwards; the upstream's own verdict is authoritative, and a size error +// comes back annotated (x-bili-cause: upstream-size, x-bili-retryable: false, +// error.bili_evidence) so the host doesn't retry the same doomed body. This +// test pins the new both-ways semantics: an over-bar body is FORWARDED and the +// upstream's 413 passes through annotated; under-bar bodies forward silently. +// The count gate (BILI_MAX_MESSAGES) remains the only local 413 (exact wire +// constraint, not an estimate). import assert from "node:assert/strict"; import http from "node:http"; import { once } from "node:events"; @@ -59,6 +66,14 @@ function makeUpstream(): { server: http.Server; calls: Call[] } { req.on("end", () => { const bytes = Buffer.concat(chunks).length; calls.push({ bytes }); + // #7537: the upstream is the size authority — bodies it cannot fit + // answer 413 with its own message; the proxy must pass it through + // annotated instead of judging locally. + if (bytes > 2_000_000) { + res.writeHead(413, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: { message: "upstream says: request entity too large", type: "invalid_request_error", code: "entity_too_large" } })); + return; + } res.writeHead(200, { "content-type": "text/event-stream" }); res.end(chatSse("forwarded answer")); }); @@ -142,49 +157,47 @@ const post = (ctx: Ctx, messages: Array<{ role: string; content: string }>, with body: JSON.stringify({ ...(withModel ? { model: "gpt-test" } : {}), stream: true, messages }), }); -test("e2e #4079: a body that provably cannot fit any window is stopped at the egress fuse, not forwarded", async () => { +test("e2e #4079 (#7537): a body that no window can fit is FORWARDED — the fuse logs, the upstream's 413 passes through annotated", async () => { const root = mkdtempSync(path.join(tmpdir(), "bili-4079a-")); const { ctx, calls, close } = await setup(); try { // No `model` in the body → preflight's `!model` early return skips its // doom math and folding entirely; forward() is the last line (#4079). - // The measured tier (the #554 meter on the ACTUAL body, #5000/#4543) - // fires first for this parseable body: ~2.17M measured tokens > the - // floored 1M bar. The byte floor below it stays as the fallback for - // unparseable bodies and is still covered by the both-ways test's - // 8.68MB-class arithmetic. - // 2000 msgs × 4.4K chars ≈ 8.68MB core text — past the floored ratio bar - // (max(20K declared, 1M assumed) × 7.5 B/token = 7.5MB; the 2MB absolute - // bar is dominated). + // The measured tier still measures and LOGS the evidence, but per + // #7537 it no longer refuses: the payload reaches the upstream, which + // answers its own 413 — passed through with the bili annotation so the + // host learns "don't retry this unchanged body" from ONE round trip. + // 2000 msgs × 4.4K chars ≈ 8.68MB core text — over every old bar; the + // fake upstream 413s above 2MB. const r = await post(ctx, bigMessages(2000, 4_400), false); const body = await r.text(); - const parsed = JSON.parse(body) as { error?: { type?: string; code?: string; retryable?: boolean; message?: string } }; + const parsed = JSON.parse(body) as { error?: { type?: string; code?: string; retryable?: boolean; message?: string }; bili_evidence?: { inboundBytes?: number; verdict?: string } }; - assert.equal(r.status, 413, `doomed egress must answer 413 (got ${r.status}) — the send must not reach an upstream that can only reject it (#4068)`); - assert.equal(parsed.error?.type, "request_too_large", "same structured too-large family as the byte budget"); - assert.equal(parsed.error?.code, "egress_window_fuse", "the fuse names itself for log greppability"); - assert.equal(parsed.error?.retryable, false, "4xx non-retryable class — retrying re-sends the same oversized history (#2847 semantics)"); - assert.match(parsed.error?.message ?? "", /outbound body measures ~[\d,]+ tokens/, "the measured token math is in the operator-facing message"); - assert.match(parsed.error?.message ?? "", /bars never assume below 1000000 tokens/, "the assumed-window floor is stated for the operator (#4079)"); - assert.match(parsed.error?.message ?? "", /stopped at the egress fuse instead of being forwarded/, "the remedy wording is present"); - // THE behavior under test: the doomed payload NEVER reaches the upstream. - assert.equal(calls.length, 0, `upstream must see zero calls (got ${JSON.stringify(calls)})`); + assert.equal(r.status, 413, `the upstream's size verdict must pass through (got ${r.status}): ${body.slice(0, 300)}`); + assert.match(parsed.error?.message ?? "", /upstream says: request entity too large/, "the 413 is the UPSTREAM's message, not a local refusal"); + assert.equal(r.headers.get("x-bili-cause"), "upstream-size", "the annotation names the size verdict"); + assert.equal(r.headers.get("x-bili-retryable"), "false", "non-retryable — retrying re-sends the same oversized history (#2847 semantics)"); + assert.equal(parsed.error?.retryable, false, "the host must not retry the unchanged body"); + assert.ok((parsed.bili_evidence?.inboundBytes ?? 0) > 1_000_000, "bili's local measurement rides along as evidence (not cause)"); + assert.match(parsed.bili_evidence?.verdict ?? "", /do NOT retry/i, "the evidence tells the host what to do"); + // THE behavior under test: the payload WAS forwarded — the fuse logs, + // it does not judge (#7537). + assert.equal(calls.length, 1, `upstream must see exactly one call (got ${JSON.stringify(calls)})`); } finally { await close(); rmrf(root); } }); -test("e2e #5000: a body whose mass rides tools[] — core text clearing the byte floor — is still stopped by the measured tier, not forwarded", async () => { +test("e2e #5000 (#7537): a body whose mass rides tools[] is FORWARDED — the measured tier logs evidence, the upstream decides", async () => { const root = mkdtempSync(path.join(tmpdir(), "bili-4079t-")); const { ctx, calls, close } = await setup(); try { - // Incident #5000's shape: the wire body's mass sits in tool definitions, - // which the core-text byte floor never sees (it prices m.text only). + // Incident #5000's shape: the wire body's mass sits in tool definitions. // 120 tools × 40KB descriptions ≈ 4.8MB of tool text ≈ ~1.2M measured - // tokens — over the floored 1M bar — while the core text is ~1.5KB, - // ~5000× under the 7.5MB byte floor. With `model` present the preflight - // measured gate fires before the relay fuse; same verdict either way. + // tokens — over every old bar. Pre-#7537 the measured tier answered a + // local 413 first; now it measures, logs the breakdown (tools are the + // mass), forwards, and the upstream's 413 passes through annotated. const tools = Array.from({ length: 120 }, (_, i) => ({ type: "function", function: { name: `tool_${i}`, description: "d".repeat(40_000) }, @@ -196,48 +209,48 @@ test("e2e #5000: a body whose mass rides tools[] — core text clearing the byte body: JSON.stringify({ model: "gpt-test", stream: true, tools, messages }), }); const body = await r.text(); - const parsed = JSON.parse(body) as { error?: { type?: string; code?: string; retryable?: boolean; message?: string } }; + const parsed = JSON.parse(body) as { error?: { message?: string; retryable?: boolean }; bili_evidence?: { inboundBytes?: number; verdict?: string } }; - assert.equal(r.status, 413, `tools-mass body must fail fast (got ${r.status}): ${body.slice(0, 300)}`); - assert.equal(parsed.error?.code, "preflight_compress_failed", "the preflight fail-fast house shape (the measured gate answers before the relay)"); - assert.equal(parsed.error?.retryable, false, "4xx non-retryable class — retrying re-sends the same oversized history (#2847 semantics)"); - assert.match(parsed.error?.message ?? "", /outbound body measures ~[\d,]+ TEXT tokens/, "the measured tier names itself (text-only; image payloads are #496 arbitration, never doom)"); - assert.match(parsed.error?.message ?? "", /NOT forwarded/, "the remedy wording is present"); - // THE behavior under test: the doomed payload NEVER reaches the upstream - // (before the measured tier it cleared the byte floor and rode forward - // to a guaranteed 400 — incident #5000's 55.2 MiB send). - assert.equal(calls.length, 0, `upstream must see zero calls (got ${JSON.stringify(calls)})`); + assert.equal(r.status, 413, `the upstream's size verdict must pass through (got ${r.status}): ${body.slice(0, 300)}`); + assert.match(parsed.error?.message ?? "", /upstream says: request entity too large/, "the 413 is the UPSTREAM's message"); + assert.equal(r.headers.get("x-bili-retryable"), "false", "non-retryable — the tools[] mass won't change on retry"); + assert.equal(parsed.error?.retryable, false, "the host must not retry the unchanged body"); + assert.ok((parsed.bili_evidence?.inboundBytes ?? 0) > 1_000_000, "bili's local measurement rides along as evidence (not cause)"); + assert.match(parsed.bili_evidence?.verdict ?? "", /do NOT retry/i, "the evidence tells the host what to do"); + // THE behavior under test: the payload WAS forwarded — the measured + // tier is now an evidence logger, not a judge (#7537). + assert.equal(calls.length, 1, `upstream must see exactly one call (got ${JSON.stringify(calls)})`); } finally { await close(); rmrf(root); } }); -test("e2e #4543: a CJK body whose CORE TEXT alone measures over the floored fuse bar — while its BYTES clear the byte floor — is stopped at the fuse (the incident's 4.1 MiB sailed to a guaranteed 400)", async () => { +test("e2e #4543 (#7537): a dense CJK body over every old bar is FORWARDED — the fuse logs, the upstream decides", async () => { const root = mkdtempSync(path.join(tmpdir(), "bili-4079c-")); const { ctx, calls, close } = await setup(); try { // Incident #4543's shape: dense CJK history. 1.12M CJK chars ≈ 3.36MB — - // ~55% under the 7.5MB floored byte floor (which the meter-based floor - // at ~7.5 B/token cannot see at CJK's 3.4 B/tok) — but CJK bills ~1 - // token per character, so the #554 meter prices ~1.12M tokens: over the - // 1M floored bar. No `model` in the body → preflight skipped → the - // relay fuse is the last line. On master this body forwarded to a - // guaranteed upstream 400 (incident logs: 4.1 MiB, 1,121,674 tokens, - // grep "egress window fuse" = 0). + // ~1.1M measured tokens: over the 1M floored bar. No `model` in the + // body → preflight skipped → the relay fuse is the last line. + // Pre-#7537 this body answered a local 413; on master (pre-fuse) it + // sailed to a guaranteed upstream 400. Now: forwarded, and the + // upstream's own verdict passes through annotated (#7537). const cjk = "数".repeat(1_120_000); const messages = [{ role: "user", content: cjk + "\n" + "x".repeat(3_072) }] as Array<{ role: string; content: string }>; const r = await post(ctx, messages, false); const body = await r.text(); - const parsed = JSON.parse(body) as { error?: { type?: string; code?: string; retryable?: boolean; message?: string } }; + const parsed = JSON.parse(body) as { error?: { message?: string; retryable?: boolean }; bili_evidence?: { inboundBytes?: number; verdict?: string } }; - assert.equal(r.status, 413, `the CJK-measured body must stop at the fuse (got ${r.status}): ${body.slice(0, 300)}`); - assert.equal(parsed.error?.code, "egress_window_fuse", "the fuse names itself"); - assert.equal(parsed.error?.retryable, false, "non-retryable — retrying re-sends the same oversized history (#2847 semantics)"); - assert.match(parsed.error?.message ?? "", /outbound body measures ~[\d,]+ tokens/, "the measured token math is in the operator-facing message"); - assert.match(parsed.error?.message ?? "", /stopped at the egress fuse instead of being forwarded/, "the remedy wording is present"); - // THE behavior under test: the doomed payload NEVER reaches the upstream. - assert.equal(calls.length, 0, `upstream must see zero calls (got ${JSON.stringify(calls)})`); + assert.equal(r.status, 413, `the upstream's size verdict must pass through (got ${r.status}): ${body.slice(0, 300)}`); + assert.match(parsed.error?.message ?? "", /upstream says: request entity too large/, "the 413 is the UPSTREAM's message"); + assert.equal(r.headers.get("x-bili-cause"), "upstream-size", "the annotation names the size verdict"); + assert.equal(parsed.error?.retryable, false, "non-retryable — the CJK mass won't change on retry"); + assert.ok((parsed.bili_evidence?.inboundBytes ?? 0) > 1_000_000, "bili's local measurement rides along as evidence (not cause)"); + assert.match(parsed.bili_evidence?.verdict ?? "", /do NOT retry/i, "the evidence tells the host what to do"); + // THE behavior under test: the payload WAS forwarded — the fuse logs, + // it does not judge (#7537). + assert.equal(calls.length, 1, `upstream must see exactly one call (got ${JSON.stringify(calls)})`); } finally { await close(); rmrf(root); diff --git a/tests/issue4185-identified-fresh-forward.test.ts b/tests/issue4185-identified-fresh-forward.test.ts index f8527ce93b..045e3ac287 100644 --- a/tests/issue4185-identified-fresh-forward.test.ts +++ b/tests/issue4185-identified-fresh-forward.test.ts @@ -212,31 +212,38 @@ test("usage-backed session: over the headroom limit, zero compressible → forwa }); }); -test("identified fresh session whose MEASURED body exceeds the native window but clears the 2MB byte floor → still fail-fast 413, nothing forwarded (#5000/#4185 measured tier)", async () => { +test("identified fresh session whose MEASURED body exceeds the native window but clears the 2MB byte floor → forwarded, the upstream's 400 passes through annotated (#7537)", async () => { await withFixture(async (proxyPort, upstreamPort, calls) => { // 300K chars of tool-result text ≈ ~75K measured tokens: over the 40K - // native window, but only ~300KB — ~7× under the 2MB core-text byte - // floor, which the old path alone let ride to a guaranteed 400. + // native window. Pre-#7537 the measured tier answered a local 413; now + // it measures, logs, forwards — the upstream's own 400 is the verdict, + // passed through with the bili evidence annotation. const r = await post(proxyPort, upstreamPort, "s-4185-measured", incidentConversation(300_000)); const body = await r.text(); - assert.equal(r.status, 413, `measured-over body must fail fast: ${body.slice(0, 300)}`); - assert.match(body, /outbound body measures ~[\d,]+ TEXT tokens even after preflight compression/, `measured diagnostic present: ${body.slice(0, 300)}`); - assert.ok(body.includes("the body ITSELF exceeds the window"), `doom wording present: ${body.slice(0, 300)}`); - assert.equal(calls.filter((c) => c.body.includes("TOOLMARKER_4185_")).length, 0, "the giant payload was never forwarded"); + assert.equal(r.status, 400, `measured-over body is now forwarded and the upstream decides: ${body.slice(0, 300)}`); + assert.match(body, /context_length_exceeded/, `the upstream's own size verdict rides through: ${body.slice(0, 300)}`); + assert.equal(r.headers.get("x-bili-cause"), "upstream-size", "the annotation names the size verdict"); + assert.equal(r.headers.get("x-bili-retryable"), "false", "non-retryable — the mass won't change on retry"); + const json = JSON.parse(body) as { bili_evidence?: { inboundBytes?: number; verdict?: string } }; + assert.ok((json.bili_evidence?.inboundBytes ?? 0) > 100_000, "bili's local measurement rides along as evidence (not cause)"); + assert.match(json.bili_evidence?.verdict ?? "", /do NOT retry/i, "the evidence tells the host what to do"); + assert.equal(calls.filter((c) => c.body.includes("TOOLMARKER_4185_")).length, 1, "the giant payload WAS forwarded (the upstream is the size authority, #7537)"); }); }); -test("identified fresh session with mathematically doomed bytes (>2MB core) → still fail-fast 413, nothing forwarded (#4185 negative)", async () => { +test("identified fresh session with mathematically doomed bytes (>2MB core) → forwarded, the upstream decides (#7537)", async () => { await withFixture(async (proxyPort, upstreamPort, calls) => { const r = await post(proxyPort, upstreamPort, "s-4185-doomed", incidentConversation(2_100_000)); const body = await r.text(); - assert.equal(r.status, 413, "doomed bytes must still fail fast"); - assert.ok(body.includes("the body ITSELF exceeds the window"), `doom diagnostic present: ${body.slice(0, 300)}`); - assert.equal(calls.length, 0, "nothing forwarded and no summarization spent"); + const json = JSON.parse(body) as { error?: { message?: string }; bili_evidence?: { inboundBytes?: number } }; + assert.ok(r.status === 400 || r.status === 413, `doomed bytes are forwarded; the upstream's size verdict answers (${r.status}): ${body.slice(0, 300)}`); + assert.match(json.error?.message ?? "", /context_length_exceeded|too large/i, `the verdict is the upstream's, not a local refusal: ${body.slice(0, 300)}`); + assert.ok((json.bili_evidence?.inboundBytes ?? 0) > 1_000_000, "the multi-MB payload really was forwarded (evidence shows the inbound mass)"); + assert.equal(calls.length, 1, "one forward, no summarization"); }); }); -test("usage-backed session whose payload exceeds the NATIVE window → forwarded once, the 400 stamps the wall, the resend fails fast 413 locally (#4185 negative)", async () => { +test("usage-backed session whose payload exceeds the NATIVE window → forwarded, the 400 passes through annotated; the byte-identical RESEND is refused by the loop guard (#7537/#496)", async () => { await withFixture(async (proxyPort, upstreamPort, calls) => { const small = await post(proxyPort, upstreamPort, "s-4185-native-over", [ { role: "user", content: "hello" }, @@ -248,19 +255,24 @@ test("usage-backed session whose payload exceeds the NATIVE window → forwarded // ~45k realistic tokens: over the 40000 NATIVE window itself — no // clamp can make input+output fit. Identity fast path: the session's // recorded same-origin reality outranks the local doom-math, so this - // payload is forwarded once and the upstream's 400 is the verdict. + // payload is forwarded and the upstream's 400 is the verdict. const giant = incidentConversation(180_000); const r = await post(proxyPort, upstreamPort, "s-4185-native-over", giant); const body = await r.text(); - assert.ok(r.status === 400 || r.status === 413, `over-native payload is rejected after the experiment, got ${r.status}: ${body.slice(0, 200)}`); + assert.equal(r.status, 400, `over-native payload is rejected BY THE UPSTREAM after the experiment, got ${r.status}: ${body.slice(0, 200)}`); assert.equal(calls.filter((c) => c.body.includes("TOOLMARKER_4185_")).length, 1, "the giant payload was forwarded exactly once"); - // The 400 stamped the session wall (overflowArmTokens) — the identical - // resend now fails fast locally: 413, nothing new reaches upstream. + // #7537: the stamped wall no longer turns the resend into a LOCAL 413 + // on estimate — but the EVIDENCE-backed loop guard does: this exact + // body drew a size verdict from the upstream, so the byte-identical + // resend is refused locally instead of re-burning the wire (#496). + // Changed bodies still forward freely; the host learns "shrink or + // change" from the 413 message, not from an estimate. const before = calls.length; const r2 = await post(proxyPort, upstreamPort, "s-4185-native-over", giant); const body2 = await r2.text(); - assert.equal(r2.status, 413, `the resend must fail fast 413 after the wall is stamped, got ${r2.status}: ${body2.slice(0, 200)}`); - assert.equal(calls.length, before, "the resented payload was never forwarded again"); + assert.equal(r2.status, 413, `the byte-identical resend is refused by the loop guard (#7537/#496), got ${r2.status}: ${body2.slice(0, 200)}`); + assert.match(body2, /already refused this exact body as too large/, "the 413 message names the recorded upstream size verdict"); + assert.equal(calls.length, before, "the resend was NEVER forwarded (the #496 loop stays broken)"); }); }); diff --git a/tests/issue7537-preflight-passthrough.test.ts b/tests/issue7537-preflight-passthrough.test.ts new file mode 100644 index 0000000000..7fe4ae3d47 --- /dev/null +++ b/tests/issue7537-preflight-passthrough.test.ts @@ -0,0 +1,227 @@ +// #7537 (owner ruling 2026-11-22): bili must NOT refuse oversized requests on +// its own estimate. Every estimate-based 413 site (probe byte-doom, the +// #1839 measured gate, the no-baseline measured + byte-doom gates, the +// deterministic-exhaustion 413 mapping, and the egress fuse's two size gates) +// was forwarding-decided: fold what can fold, then ALWAYS forward; the +// upstream's own verdict (with its real numbers) is authoritative. When the +// upstream answers with a size error (413 / size-keyword 400), bili marks the +// response non-retryable (headers + JSON body merge) so status-code-driven +// hosts don't retry-loop the already-refused body, and logs its local +// measurement as evidence. The ONLY local refusals that remain are the +// non-estimate ones: the message-COUNT gate (BILI_MAX_MESSAGES, an exact wire +// constraint) and the 5GiB pure-byte sanity cap. +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { SessionStore, _resetStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { rmrf } from "./tmp-rm.ts"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const WINDOW = 20_000; +// Above this many message chars the fake upstream declares ITS OWN 413 — +// the authoritative size verdict bili must pass through (annotated). +const UPSTREAM_SIZE_LIMIT_CHARS = 1_000_000; + +type Call = { summary: boolean; contentChars: number }; +type UpstreamMode = "size-limited" | "always-413"; + +function chatSse(text: string, usage?: { prompt_tokens: number; completion_tokens: number }): string { + const chunk = (delta: Record, finish: string | null, extra?: Record): string => + `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "gpt-test", choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`; + const u = usage ? { usage } : {}; + return chunk({ role: "assistant" }, null) + chunk({ content: text }, null) + chunk({}, "stop", u) + "data: [DONE]\n\n"; +} + +function bigMessages(count: number, charsPerMsg: number): Array<{ role: string; content: string }> { + const messages: Array<{ role: string; content: string }> = []; + const pad = Math.max(1, charsPerMsg - 12); + for (let i = 0; i < count; i++) { + messages.push({ role: i % 2 === 0 ? "user" : "assistant", content: `turn ${i}: ` + "f".repeat(pad) }); + } + return messages; +} + +function makeUpstream(mode: UpstreamMode): { server: http.Server; calls: Call[] } { + const calls: Call[] = []; + const server = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + const isSummary = /TASK: The conversation segment below/.test(raw); + try { + const parsed = JSON.parse(raw) as { messages?: Array<{ content?: unknown }> }; + const chars = (parsed.messages ?? []).reduce((n, m) => n + (typeof m.content === "string" ? m.content.length : 0), 0); + calls.push({ summary: isSummary, contentChars: chars }); + if (isSummary) { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ id: "chatcmpl-sum", object: "chat.completion", model: "gpt-test", choices: [{ index: 0, message: { role: "assistant", content: "PREFLIGHT SUMMARY: " + "f".repeat(120) }, finish_reason: "stop" }] })); + return; + } + if (mode === "always-413" || chars > UPSTREAM_SIZE_LIMIT_CHARS) { + // The upstream's OWN authoritative size verdict. + res.writeHead(413, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: { message: "maximum context length exceeded for this model", type: "invalid_request_error" } })); + return; + } + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(chatSse("forwarded answer", { prompt_tokens: Math.max(1, Math.round(chars / 40)), completion_tokens: 3 })); + } catch { + res.writeHead(400, { "content-type": "application/json" }); + res.end('{"error":{"message":"unparseable"}}'); + } + }); + }); + return { server, calls }; +} + +function proxyOptions(routes: Record): ProxyOptions { + return { + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: routes as ProxyOptions["routes"], + modelContextLimit: WINDOW, + kernelConfig: defaultConfig(WINDOW, { + preserveRecentMessages: 2, + preserveRecentTokens: 2000, + compress: { minCompressRange: 1000, maxSummaryLength: 20000, minSummaryLength: 50 }, + }), + compress: { injectTool: true, injectNudge: true }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + promptCache: { routing: "auto" }, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions; +} + +type Ctx = { url: string; headers: Record }; + +async function setup(mode: UpstreamMode = "size-limited"): Promise<{ ctx: Ctx; calls: Call[]; close: () => Promise }> { + _resetStoreForTest(); + setRegistryForTest({}); + const { server: upstream, calls } = makeUpstream(mode); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + const proxy = await startServer(proxyOptions({ [`http://127.0.0.1:${upstreamPort}`]: { models: { "gpt-test": { context: WINDOW } } } })); + await once(proxy, "listening"); + const proxyPort = (proxy.address() as { port: number }).port; + return { + ctx: { + url: `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/chat/completions`, + headers: { "content-type": "application/json", "x-acp-session": `s-7537-${Math.random().toString(36).slice(2)}` }, + }, + calls, + close: async () => { + proxy.close(); + proxy.closeIdleConnections?.(); + upstream.close(); + upstream.closeIdleConnections?.(); + await Promise.allSettled([once(proxy, "close"), once(upstream, "close")]); + }, + }; +} + +const post = (ctx: Ctx, messages: Array<{ role: string; content: string }>) => + fetch(ctx.url, { + method: "POST", + headers: { ...ctx.headers }, + body: JSON.stringify({ model: "gpt-test", stream: true, messages }), + }); + +test("#7537 A: the mathematically-doomed payload is FORWARDED, and the upstream's own 413 passes through annotated (non-retryable)", async () => { + const root = mkdtempSync(path.join(tmpdir(), "bili-7537-")); + const { ctx, calls, close } = await setup("always-413"); + try { + // 500 msgs × 4.4K chars ≈ 2.2MB ASCII core text — past BOTH of the old + // local doom bars (2MB absolute floor; 20K × 7.5 B/token ratio bar). + // Pre-#7537 this answered a LOCAL 413 and never reached the upstream. + // The fake upstream here always answers 413: it models an upstream + // whose REAL window is smaller than anything bili would send — the + // upstream's verdict is the authoritative one bili must relay. + const r = await post(ctx, bigMessages(500, 4_400)); + const body = await r.text(); + const parsed = JSON.parse(body) as { error?: { message?: string; retryable?: boolean }; bili_evidence?: { outboundTextTokens?: number | null; inboundBytes?: number; verdict?: string } }; + + // THE fix: no local estimate-refusal — the payload reached the + // upstream, which made the authoritative call (413). + assert.ok(calls.some((c) => !c.summary), + `the forward must reach the upstream (calls=${JSON.stringify(calls.map((c) => ({ s: c.summary, n: c.contentChars })))})`); + assert.equal(r.status, 413, "the status is the UPSTREAM's 413"); + assert.match(parsed.error?.message ?? "", /maximum context length exceeded/, "the UPSTREAM's own error text (not bili's local estimate) is what the host sees"); + // Annotation: non-retryable marking so status-code-driven hosts stop + // retry-looping the already-refused body. + assert.equal(r.headers.get("x-bili-retryable"), "false", "x-bili-retryable header present"); + assert.equal(r.headers.get("x-bili-cause"), "upstream-size", "x-bili-cause header present"); + assert.equal(parsed.error?.retryable, false, "error.retryable=false merged into the JSON body"); + assert.ok(parsed.bili_evidence, "bili_evidence merged into the JSON body"); + assert.ok(typeof parsed.bili_evidence?.inboundBytes === "number" && (parsed.bili_evidence?.inboundBytes ?? 0) > 100_000, + `evidence carries the measured inbound size (got ${JSON.stringify(parsed.bili_evidence)})`); + assert.match(parsed.bili_evidence?.verdict ?? "", /do NOT retry/i, "the evidence names the anti-retry verdict"); + } finally { + await close(); + rmrf(root); + } +}); + +test("#7537 B: a measured-over-window payload the UPSTREAM accepts now arrives (old: killed by the local measured 413)", async () => { + const root = mkdtempSync(path.join(tmpdir(), "bili-7537-")); + const { ctx, close } = await setup(); + try { + // 60 msgs × 1.7K chars ≈ 102KB core text ≈ ~26K measured tokens + // (dense repetitive metering): over the old measured bar (20K + // window) — pre-#7537 the rebuilt body's measured size killed it + // with a local 413 before any forward — yet a handful of folds + // converges it and the fake upstream (1M-char acceptance limit) + // accepts the folded forward. Now: folded where it folds, + // forwarded, upstream 200 reaches the host. + const r = await post(ctx, bigMessages(60, 1_700)); + const text = await r.text(); + assert.equal(r.status, 200, `the upstream accepted it — bili must have forwarded, not refused locally (got ${r.status}: ${text.slice(0, 200)})`); + assert.match(text, /forwarded answer/, "the upstream's answer reaches the host"); + } finally { + await close(); + rmrf(root); + } +}); + +test("#7537 C: the message-COUNT gate remains a local refusal (it is an exact wire constraint, not an estimate)", async () => { + const root = mkdtempSync(path.join(tmpdir(), "bili-7537-")); + const { ctx, calls, close } = await setup(); + const prev = process.env.BILI_MAX_MESSAGES; + process.env.BILI_MAX_MESSAGES = "10"; + try { + // 30 small messages — no size bar is near, only the count gate trips. + const r = await post(ctx, bigMessages(30, 200)); + const body = await r.text(); + assert.equal(r.status, 413, "the count gate still refuses locally"); + assert.match(body, /message count 30 exceeds the upstream wire limit 10/, "the count-gate message names the exact constraint"); + assert.ok(calls.length === 0, "the count-gate refusal is NOT forwarded"); + } finally { + if (prev === undefined) delete process.env.BILI_MAX_MESSAGES; + else process.env.BILI_MAX_MESSAGES = prev; + await close(); + rmrf(root); + } +}); diff --git a/tests/preflight-fail-fast.test.ts b/tests/preflight-fail-fast.test.ts index b2714dd509..e0fc13e9b2 100644 --- a/tests/preflight-fail-fast.test.ts +++ b/tests/preflight-fail-fast.test.ts @@ -15,6 +15,7 @@ import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { METADATA_FOLD_COVERAGE } from "../src/fold-reconcile.ts"; import { getSession } from "../src/session.ts"; import { normalizeUpstreamOrigin } from "../src/util.ts"; +import { setLogCapture } from "../src/logger.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; // #301: when preflight (overflow) compression cannot proceed — the summary @@ -36,6 +37,19 @@ function okSse(inputTokens: number): string { ); } +// OpenAI-chat wire form of the same answer — the /v1/chat/completions lane +// completes on a finish_reason chunk + `data: [DONE]`, NOT on Anthropic event +// names (the relay otherwise declares the stream truncated and re-forwards +// once, doubling the upstream call count these tests pin). +function okSseOpenAI(inputTokens: number): string { + return ( + `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "gpt-small", choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }] })}\n\n` + + `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "gpt-small", choices: [{ index: 0, delta: { content: "ok" }, finish_reason: null }] })}\n\n` + + `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "gpt-small", choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: inputTokens, completion_tokens: 3, total_tokens: inputTokens + 3 } })}\n\n` + + `data: [DONE]\n\n` + ); +} + function bigConversation(): Array<{ role: string; content: string }> { const msgs: Array<{ role: string; content: string }> = []; for (let i = 0; i < 12; i++) { @@ -59,7 +73,7 @@ function makeUpstream429(calls?: Call[]): http.Server { calls?.push({ stream: !!parsed.stream, body: raw }); if (parsed.stream) { res.writeHead(200, { "content-type": "text/event-stream" }); - res.end(okSse(1000)); + res.end(req.url?.includes("/chat/completions") ? okSseOpenAI(1000) : okSse(1000)); } else { res.writeHead(429, { "content-type": "application/json" }); res.end(JSON.stringify({ error: { message: "rate limited", type: "rate_limit_error" } })); @@ -104,7 +118,7 @@ function seedEvidence(sessionId: string, upstreamPort: number): void { s.stats.lastInputTokensOrigin = normalizeUpstreamOrigin(`http://127.0.0.1:${upstreamPort}`); } -function startProxy(upstreamPort: number, models: Record, kernelOverrides?: Partial, compressOverrides?: Partial): Promise { +function startProxy(upstreamPort: number, models: Record, kernelOverrides?: Partial, compressOverrides?: Partial, extra?: Partial): Promise { _setStoreForTest(new SessionStore({ enabled: false })); setRegistryForTest({}); return startServer({ @@ -129,6 +143,7 @@ function startProxy(upstreamPort: number, models: Record { +test("e2e #301: over-window payload with nothing compressible → forwarded once, the upstream decides (#7537)", async () => { const calls: Call[] = []; const upstream = makeUpstream429(calls); upstream.listen(0, "127.0.0.1"); @@ -326,14 +341,10 @@ test("e2e #301: over-window payload with nothing compressible → structured 413 ], }), }); - assert.equal(r.status, 413, "fail-fast 413 when nothing is compressible (#3461: deterministic exhaustion is non-retryable)"); - const json = JSON.parse(await r.text()) as { error?: { code?: string; message?: string; retryable?: boolean } }; - assert.equal(json.error?.code, "preflight_compress_failed"); - assert.equal(json.error?.retryable, false); - assert.ok(json.error?.message?.includes("NOT forwarded"), `message states the payload was withheld (got: ${json.error?.message})`); - assert.ok(json.error?.message?.includes("Raise the model context window"), `actionable error names the operator remedy (got: ${json.error?.message})`); + assert.equal(r.status, 200, "nothing is compressible → the payload is forwarded and the upstream's own verdict is authoritative (#7537: no local estimate-refusal)"); + await r.text(); assert.equal(calls.filter((c) => !c.stream).length, 0, "no summarization call was spent on an incompressible payload"); - assert.equal(calls.filter((c) => c.stream).length, 0, "the over-window payload was NOT forwarded upstream"); + assert.equal(calls.filter((c) => c.stream).length, 1, "the over-window payload was forwarded exactly once"); } finally { proxy.close(); proxy.closeIdleConnections?.(); @@ -444,7 +455,7 @@ test("e2e #470: system + tools overhead counts in the preflight trigger — text } }); -test("e2e #736: operator-shrunk window (compress.modelContextLimit below the model's declared window) → fail-fast names the setting", async () => { +test("e2e #736: operator-shrunk window (compress.modelContextLimit below the model's declared window) → the forward warn names the setting", async () => { const calls: Call[] = []; const upstream = makeUpstream429(calls); upstream.listen(0, "127.0.0.1"); @@ -452,13 +463,16 @@ test("e2e #736: operator-shrunk window (compress.modelContextLimit below the mod const upstreamPort = (upstream.address() as { port: number }).port; // Same incompressible-payload shape as the #301 exhausted test, but the - // 4k window is an OPERATOR override of the model's declared 10k — the - // fail-fast must point at compress.modelContextLimit, not just say + // 4k window is an OPERATOR override of the model's declared 10k. #7537 + // removed the local 413, so the shrink note now rides the FORWARD warn — + // it must still point at compress.modelContextLimit, not just say // "raise the model context window" (which sends operators to the upstream). - const proxy = await startProxy(upstreamPort, { "claude-small": { context: 10_000 } }, { protectedTools: ["bash"] }, { modelContextLimit: 4_000 }); + const proxy = await startProxy(upstreamPort, { "claude-small": { context: 10_000 } }, { protectedTools: ["bash"] }, { modelContextLimit: 4_000 }, { log: true, logFile: "/tmp/429/bc-pr9/tmp-bili-736.log" }); await once(proxy, "listening"); const proxyPort = (proxy.address() as { port: number }).port; + const lines: string[] = []; + setLogCapture((_level, msg) => lines.push(msg)); try { const filler = "FILLER_".repeat(7000); seedEvidence("preflight-shrink-sess", upstreamPort); @@ -475,22 +489,20 @@ test("e2e #736: operator-shrunk window (compress.modelContextLimit below the mod ], }), }); - assert.equal(r.status, 413, "fail-fast 413 when nothing is compressible under the shrunken window (#3461)"); - const json = JSON.parse(await r.text()) as { error?: { code?: string; message?: string } }; - assert.equal(json.error?.code, "preflight_compress_failed"); - const msg = json.error?.message ?? ""; - assert.ok(msg.includes("NOT forwarded"), `payload withheld (got: ${msg})`); - assert.ok(msg.includes("effective window 4000"), `names the shrunken effective window (got: ${msg})`); - assert.ok(msg.includes("full window 10000"), `names the model's full window (got: ${msg})`); - assert.ok(msg.includes("compress.modelContextLimit"), `points at the operator setting (got: ${msg})`); - assert.ok(!/\.\./.test(msg), `no doubled period (got: ${msg})`); - assert.equal(calls.length, 0, "no upstream call was spent on an incompressible payload"); + assert.equal(r.status, 200, "the incompressible payload is forwarded — the upstream decides (#7537)"); + await r.text(); + assert.equal(calls.filter((c) => c.stream).length, 1, "exactly one forward"); + const note = lines.find((l) => l.includes("compress.modelContextLimit")); + assert.ok(note, `the forward warn names the operator setting (log: ${lines.filter((l) => l.includes("#7537")).join(" | ")})`); + assert.ok(note!.includes("effective window 4000"), `names the shrunken effective window (got: ${note})`); + assert.ok(note!.includes("full window 10000"), `names the model's full window (got: ${note})`); // Negative control: the same payload with NO operator override must not // carry the shrink note (effective === full window). - const proxyPlain = await startProxy(upstreamPort, { "claude-small": { context: 10_000 } }, { protectedTools: ["bash"] }); + const proxyPlain = await startProxy(upstreamPort, { "claude-small": { context: 10_000 } }, { protectedTools: ["bash"] }, undefined, { log: true, logFile: "/tmp/429/bc-pr9/tmp-bili-736b.log" }); await once(proxyPlain, "listening"); const plainPort = (proxyPlain.address() as { port: number }).port; + lines.length = 0; seedEvidence("preflight-shrink-plain-sess", upstreamPort); const r2 = await fetch(`http://127.0.0.1:${plainPort}/bili/http://127.0.0.1:${upstreamPort}/v1/messages`, { method: "POST", @@ -505,13 +517,14 @@ test("e2e #736: operator-shrunk window (compress.modelContextLimit below the mod ], }), }); - assert.equal(r2.status, 413); - const msg2 = (JSON.parse(await r2.text()) as { error?: { message?: string } }).error?.message ?? ""; - assert.ok(!msg2.includes("full window"), `no shrink note when the window was not operator-shrunk (got: ${msg2})`); + assert.equal(r2.status, 200); + await r2.text(); + assert.ok(!lines.some((l) => l.includes("full window")), `no shrink note when the window was not operator-shrunk (log: ${lines.join(" | ")})`); proxyPlain.close(); proxyPlain.closeIdleConnections?.(); await once(proxyPlain, "close"); } finally { + setLogCapture(null); proxy.close(); proxy.closeIdleConnections?.(); await once(proxy, "close"); @@ -529,7 +542,7 @@ test("e2e #736: operator-shrunk window (compress.modelContextLimit below the mod // (the pre-fix logic) therefore blamed compress.modelContextLimit for a reduction // the operator never made. This guards that path: an OpenAI-chat incompressible // payload under a headroom-shrunk window must NOT carry the shrink note. -test("e2e #737: output-headroom-shrunk window (non-Anthropic, no operator override) → fail-fast does NOT name compress.modelContextLimit", async () => { +test("e2e #737: output-headroom-shrunk window (non-Anthropic, no operator override) → the forward warn does NOT name compress.modelContextLimit", async () => { const calls: Call[] = []; const upstream = makeUpstream429(calls); upstream.listen(0, "127.0.0.1"); @@ -540,10 +553,12 @@ test("e2e #737: output-headroom-shrunk window (non-Anthropic, no operator overri // OpenAI-chat endpoint reserves output headroom: max_tokens 4000 shrinks the // effective window 10000 -> 6000. A ~12k incompressible (hard-protected bash) // tool result overflows 6000 → fail-fast. - const proxy = await startProxy(upstreamPort, { "gpt-small": { context: 10_000 } }, { protectedTools: ["bash"] }); + const proxy = await startProxy(upstreamPort, { "gpt-small": { context: 10_000 } }, { protectedTools: ["bash"] }, undefined, { log: true, logFile: "/tmp/429/bc-pr9/tmp-bili-737.log" }); await once(proxy, "listening"); const proxyPort = (proxy.address() as { port: number }).port; + const lines: string[] = []; + setLogCapture((_level, msg) => lines.push(msg)); try { const filler = "FILLER_".repeat(7000); seedEvidence("preflight-headroom-sess", upstreamPort); @@ -560,22 +575,22 @@ test("e2e #737: output-headroom-shrunk window (non-Anthropic, no operator overri ], }), }); - assert.equal(r.status, 413, "fail-fast 413 when nothing is compressible under the headroom-shrunk window (#3461)"); - const json = JSON.parse(await r.text()) as { error?: { code?: string; message?: string } }; - assert.equal(json.error?.code, "preflight_compress_failed"); - const msg = json.error?.message ?? ""; - assert.ok(msg.includes("NOT forwarded"), `payload withheld (got: ${msg})`); - // Proves the headroom path was exercised: the reported window is the - // 7500 after the #896-capped headroom reservation (min(max_tokens, - // outputHeadroomMaxPct·window) = min(4000, 2500) = 2500 off 10000), not - // the declared 10000. - assert.ok(msg.includes("model window 7500"), `effective window reflects headroom reservation (got: ${msg})`); + assert.equal(r.status, 200, "the incompressible payload is forwarded — the upstream decides (#7537)"); + await r.text(); + assert.equal(calls.filter((c) => c.stream).length, 1, "exactly one forward"); + // Proves the headroom path was exercised: the forwarded warn reports the + // 7500 effective window after the #896-capped headroom reservation + // (min(max_tokens, outputHeadroomMaxPct·window) = min(4000, 2500) = 2500 + // off 10000), not the declared 10000. + const fwd = lines.find((l) => l.includes("#7537")); + assert.ok(fwd, `the #7537 forward warn was logged (log: ${lines.join(" | ").slice(0, 400)})`); + assert.ok(fwd!.includes("window 7500"), `effective window reflects headroom reservation (got: ${fwd})`); // Regression guard: the reduction here came from output-headroom, NOT an // operator setting — the shrink note must stay silent. - assert.ok(!msg.includes("full window"), `no shrink note for a headroom-shrunk window (got: ${msg})`); - assert.ok(!msg.includes("compress.modelContextLimit"), `does not blame an untouched operator setting (got: ${msg})`); - assert.equal(calls.length, 0, "no upstream call was spent on an incompressible payload"); + assert.ok(!fwd!.includes("full window"), `no shrink note for a headroom-shrunk window (got: ${fwd})`); + assert.ok(!fwd!.includes("compress.modelContextLimit"), "does not blame an untouched operator setting"); } finally { + setLogCapture(null); proxy.close(); proxy.closeIdleConnections?.(); await once(proxy, "close"); From 6cf7d60a9da87e393460721c5df54c7c3038b885 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Mon, 23 Nov 2026 00:06:34 +0800 Subject: [PATCH 2/5] chore: drop the export from upstreamSizeVerdictCovers (unused-exports gate, #1440) --- src/server.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server.ts b/src/server.ts index 7fa6fa24ca..83669c4e6b 100644 --- a/src/server.ts +++ b/src/server.ts @@ -3498,7 +3498,7 @@ export function noteUpstreamSizeVerdict(session: Session, origin: string | undef /** Preflight-side: true when THIS exact wire body (same origin+model) already * drew an upstream size verdict — the resend must not ride the wire again. */ -export function upstreamSizeVerdictCovers(metadata: Record, origin: string | undefined, model: string | undefined, body: string | undefined): boolean { +function upstreamSizeVerdictCovers(metadata: Record, origin: string | undefined, model: string | undefined, body: string | undefined): boolean { if (!origin || !model || typeof body !== "string" || body.length === 0) return false; const h = wireBodyHash(body); return readSizeVerdicts(metadata).some((r) => r.origin === origin && r.model === model && r.hash === h); From 2d65b3cb25fa95f2ebc95295a2b8a84eee413e8e Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 23 Nov 2026 01:24:13 +0800 Subject: [PATCH 3/5] test: catch up fix-identity-fast-path-preflight to the #7537 no-estimate-refusal behavior MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The #7537 PR (owner ruling 2026-11-22: no local estimate-based size refusal) removed every estimate 413 and updated 7 preflight test files plus deleted issue3846, but missed tests/fix-identity-fast-path-preflight.test.ts — its 3 tests still pinned the old 413-veto, so the full suite went red. Apply the PR's own rewrite pattern (issue2847/issue4185): the 413-veto assertions become forward/upstream-decides assertions; the log-line assertion moves from 'identity fast path' to the #7537 no-estimate-refusal forward line. A2 (fresh evidence) keeps the 200-forward behavior; B (stale-origin) and B2 (stale-model) drop the 413 veto and assert the payload is forwarded, the upstream decides. Verified locally: file 5/5 green, typecheck clean. --- .../fix-identity-fast-path-preflight.test.ts | 61 ++++++++----------- 1 file changed, 27 insertions(+), 34 deletions(-) diff --git a/tests/fix-identity-fast-path-preflight.test.ts b/tests/fix-identity-fast-path-preflight.test.ts index 07419fc09f..4b929d79e9 100644 --- a/tests/fix-identity-fast-path-preflight.test.ts +++ b/tests/fix-identity-fast-path-preflight.test.ts @@ -250,7 +250,7 @@ test("e2e identity fast path: identified sid + same-origin upstream reality outr } }); -test("e2e identity fast path fires: a TEXT doom verdict (no images) is converted by the fast path itself, not the #496/#1800 hatch", async () => { +test("e2e #7537: a TEXT doom verdict (no images) is forwarded with no local estimate-refusal, not via the #496/#1800 hatch", async () => { const root = mkdtempSync(path.join(tmpdir(), "bili-identity-")); const { ctx, calls, close } = await setup(); const logs: string[] = []; @@ -261,10 +261,11 @@ test("e2e identity fast path fires: a TEXT doom verdict (no images) is converted // TEXT-dominated doomed shape (issue2847: 500 msgs × 4.4K chars ≈ 2.2MB // — past BOTH doom bars; NO images, so the #496/#1800 image-arbitration - // hatch cannot intercept). This is the shape that reaches the doom-math - // sites and is converted by the identity fast path itself (test A's - // image payload is caught earlier by the image hatch, so it does NOT - // pin this gate — #3617: the positive direction needs its own row). + // hatch cannot intercept). Under #7537 the payload is forwarded with no + // local estimate-refusal — the upstream's own size verdict is + // authoritative (test A's image payload is caught earlier by the image + // hatch, so it does NOT pin this gate — #3617: the positive direction + // needs its own row). const r = await post(ctx, bigMessages()); const body = await r.text(); @@ -273,9 +274,9 @@ test("e2e identity fast path fires: a TEXT doom verdict (no images) is converted const since = calls.slice(before); assert.equal(since.length, 1, `exactly one upstream call for the forward (got ${JSON.stringify(since)})`); assert.equal(since[0]!.summary, false); - // THE fast path line specifically — the #496/#1800 arbitration line is - // image-only and must NOT be the carrier for a text payload. - assert.ok(logs.some((m) => m.includes("identity fast path") && !m.includes("demoted")), "log carries the identity fast path conversion line"); + // The #7537 no-estimate-refusal forward line specifically — the #496/#1800 + // arbitration line is image-only and must NOT be the carrier for a text payload. + assert.ok(logs.some((m) => m.includes("forwarding per #7537")), "log carries the #7537 no-estimate-refusal forward line"); assert.ok(!logs.some((m) => m.includes("arbitrate billing (#496/#1800)")), "the text payload did not ride the image-arbitration hatch"); } finally { setLogCapture(null); @@ -284,16 +285,16 @@ test("e2e identity fast path fires: a TEXT doom verdict (no images) is converted } }); -test("e2e identity fast path demotion: usage-grade reality on ANOTHER origin stays demoted — the 413 veto holds (#1933, #2847)", async () => { +test("e2e #7537: usage-grade reality on ANOTHER origin no longer vetoes — the payload is forwarded, the upstream decides (#1933 superseded)", async () => { const root = mkdtempSync(path.join(tmpdir(), "bili-identity-")); const { ctx, calls, close } = await setup(); const logs: string[] = []; setLogCapture((_lvl, msg) => { logs.push(msg); }); try { - // usage-grade reality exists — but on a FOREIGN origin. The fast path - // must stay closed (a bill from another provider is not evidence for - // this lane, #1933 F2); with no current-route reality left, the local - // doom-math keeps its #2847 veto. + // usage-grade reality exists — but on a FOREIGN origin. The #2847 + // demotion (413 for stale-origin evidence) is SUPERSEDED by #7537: no + // local estimate-refusal. The payload is forwarded regardless of the + // evidence's origin — the upstream's own size verdict is authoritative. await seedTrusted(ctx, "s-id-stale-origin", { source: "usage", origin: "http://127.0.0.1:1" }); const before = calls.length; @@ -302,15 +303,12 @@ test("e2e identity fast path demotion: usage-grade reality on ANOTHER origin sta // cannot intercept). const r = await post(ctx, bigMessages()); const body = await r.text(); - const parsed = JSON.parse(body) as { error?: { code?: string; retryable?: boolean; message?: string } }; - assert.equal(r.status, 413, `stale-origin reality must NOT open the fast path (got ${r.status}); body=${body.slice(0, 300)}`); - assert.equal(parsed.error?.code, "preflight_compress_failed"); - assert.equal(parsed.error?.retryable, false); + assert.equal(r.status, 200, `stale-origin evidence no longer vetoes — forward (got ${r.status}); body=${body.slice(0, 300)}`); + assert.match(body, /forwarded answer/, "the payload actually reached the upstream"); const since = calls.slice(before); - assert.ok(since.every((c) => c.summary), "the doomed payload was not forwarded (only summary calls, if any)"); - assert.ok(logs.some((m) => m.includes("identity fast path demoted")), "log carries the demotion line"); - assert.ok(!logs.some((m) => /identity fast path(?! demoted)/.test(m)), "no fast-path conversion line for stale-origin evidence"); + assert.ok(since.length >= 1, "the payload was forwarded to the upstream"); + assert.ok(logs.some((m) => m.includes("forwarding per #7537")), "log carries the #7537 no-estimate-refusal forward line"); } finally { setLogCapture(null); await close(); @@ -318,19 +316,17 @@ test("e2e identity fast path demotion: usage-grade reality on ANOTHER origin sta } }); -test("e2e identity fast path demotion: a MODEL change since the last evidence keeps the 413 veto (#2117 model gate)", async () => { +test("e2e #7537: a MODEL change since the last evidence no longer vetoes — the payload is forwarded, the upstream decides (#2117 superseded)", async () => { const root = mkdtempSync(path.join(tmpdir(), "bili-identity-")); const { ctx, calls, close } = await setup(); const logs: string[] = []; setLogCapture((_lvl, msg) => { logs.push(msg); }); try { // Same origin, usage-grade reality ≥ window — but the session last ran - // on a DIFFERENT model. Acceptance evidence is per model (#2117: a bill - // on claude-big binds nothing for claude-small), so the fast path must - // stay closed and the local doom-math keeps its #2847 veto. This is the - // model-mismatch negative direction of the gate — #3617 requires it to - // be pinned (the PR body's "regression-covered by #2189" claim does not - // hold: #2189's cross-model turns never exercise this gate). + // on a DIFFERENT model. The #2117 model gate (413 for stale-model + // evidence) is SUPERSEDED by #7537: no local estimate-refusal. The + // payload is forwarded regardless of the model — the upstream's own + // size verdict is authoritative. await seedTrusted(ctx, "s-id-stale-model"); const s = getSession("s-id-stale-model"); assert.ok(s, "session exists after seed"); @@ -341,15 +337,12 @@ test("e2e identity fast path demotion: a MODEL change since the last evidence ke // arbitration cannot intercept — the model gate is what must judge). const r = await post(ctx, bigMessages()); const body = await r.text(); - const parsed = JSON.parse(body) as { error?: { code?: string; retryable?: boolean; message?: string } }; - assert.equal(r.status, 413, `stale-model reality must NOT open the fast path (got ${r.status}); body=${body.slice(0, 300)}`); - assert.equal(parsed.error?.code, "preflight_compress_failed"); - assert.equal(parsed.error?.retryable, false); + assert.equal(r.status, 200, `stale-model evidence no longer vetoes — forward (got ${r.status}); body=${body.slice(0, 300)}`); + assert.match(body, /forwarded answer/, "the payload actually reached the upstream"); const since = calls.slice(before); - assert.ok(since.every((c) => c.summary), "the doomed payload was not forwarded (only summary calls, if any)"); - assert.ok(logs.some((m) => m.includes("identity fast path demoted")), "log carries the demotion line"); - assert.ok(!logs.some((m) => /identity fast path(?! demoted)/.test(m)), "no fast-path conversion line for stale-model evidence"); + assert.ok(since.length >= 1, "the payload was forwarded to the upstream"); + assert.ok(logs.some((m) => m.includes("forwarding per #7537")), "log carries the #7537 no-estimate-refusal forward line"); } finally { setLogCapture(null); await close(); From 033c679db612747d3f6e70c7c7ae01e8743a9055 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Mon, 23 Nov 2026 02:09:24 +0800 Subject: [PATCH 4/5] =?UTF-8?q?fix:=20keep=20only=20EVIDENCE-based=20size?= =?UTF-8?q?=20refusals=20=E2=80=94=20drop=20the=20loop=20guard=20and=20the?= =?UTF-8?q?=20body=20merge=20(#7537)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The preflight loop guard (byte-hash of an upstream-refused body) fired before the fit check and the fold walk, so it 413'd two contracts: #3900's identical retry while the local estimate still fits (the learning loop needs a second forward) and #987 T3's resend that preflight can fold under the declared window. The guard is gone — the anti-loop protection for the truly-doomed payload is the EVIDENCE branch restored in the deterministic-exhaustion path: nothing more can fold AND the upstream has already proved the wall (stated/armed overflow) AND the calibrated meter agrees → local 413, retryable=false (#3461/#496/#767/#857). Estimation- only exhaustion keeps forwarding (#7537). The relay size-verdict annotation now marks x-bili-cause/x-bili-retryable via headers only; the upstream body passes through byte-identical (#1195 B and request-input-lifetime pin verbatim bodies). Test re-pins: #2391 eager/loaded tool overflow forwards (measured tier is an evidence logger, not a judge); #1841 A splits into wall-413 (evidence survives) + A2 no-wall forward; #4185 resend hits the evidence 413; #4079/#7537 assert the header-only annotation; ci-shard weights drop the deleted #3846 pin. --- scripts/ci-shard-weights.json | 1 - src/server.ts | 86 ++++--------------- src/server/relay.ts | 49 +++-------- tests/deferred-tool-budget.test.ts | 13 +-- tests/issue1841-preflight-futility.test.ts | 51 +++++++++-- tests/issue4079-egress-window-fuse.test.ts | 18 ++-- ...issue4185-identified-fresh-forward.test.ts | 25 +++--- tests/issue7537-preflight-passthrough.test.ts | 12 +-- 8 files changed, 101 insertions(+), 154 deletions(-) diff --git a/scripts/ci-shard-weights.json b/scripts/ci-shard-weights.json index 71a305ff15..1aead49d83 100644 --- a/scripts/ci-shard-weights.json +++ b/scripts/ci-shard-weights.json @@ -477,7 +477,6 @@ "tests/issue4147-dsh-overlay-structural.test.ts": 109, "tests/issue4159-client-mid-system-verbatim.test.ts": 3538, "tests/issue-393-registry-window.test.ts": 12678, - "tests/issue3846-local-refusal-evidence.test.ts": 18918, "tests/issue411-abort-usage.test.ts": 13408, "tests/issue4185-identified-fresh-forward.test.ts": 12740, "tests/issue496-forward-once-learn.test.ts": 3571, diff --git a/src/server.ts b/src/server.ts index 83669c4e6b..f21cbc24db 100644 --- a/src/server.ts +++ b/src/server.ts @@ -3,7 +3,7 @@ import fs from "node:fs"; import path from "node:path"; import net from "node:net"; import tls from "node:tls"; -import { randomUUID, createHash } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { performance } from "node:perf_hooks"; import { createCore, type CompressionCore, type CompressionState, type Config, type CoreMessage, type NudgeDecision, type Prompts, type PackSurface, defaultPrompts, deactivateBlock } from "acp-kernel"; import { resolveCompress, resolveCompressPrompts, resolveCompressSurfaceDetailed, resolveRequestConfig, type ResolvedKernelConfig } from "./compress-settings.js"; @@ -3447,63 +3447,6 @@ function localRefusalCovers(metadata: Record, origin: string | return readLocalRefusals(metadata).some((r) => r.origin === origin && r.model === model && r.window >= window); } -// #7537 (with #496): the one loop the old estimate-refusals happened to break -// — a status-code-driven host re-sending the SAME bytes an upstream already -// rejected as too large — must stay broken after the local size 413s are gone. -// The guard is EVIDENCE, not estimate: it fires only on a byte-identical -// resend (same SHA-1 of the wire body) to the same origin+model whose exact -// bytes the upstream already refused with a size verdict. Changed bodies -// re-forward freely; the record TTLs out like #3846's (10 minutes). -interface UpstreamSizeVerdictRecord { - origin: string; - model: string; - hash: string; - at: number; -} - -const SIZE_VERDICT_MAX_RECORDS = 16; -const SIZE_VERDICT_TTL_MS = LOCAL_REFUSAL_TTL_MS; - -function wireBodyHash(body: string): string { - return createHash("sha1").update(body).digest("hex").slice(0, 16); -} - -function readSizeVerdicts(metadata: Record): UpstreamSizeVerdictRecord[] { - const raw = metadata.upstreamSizeVerdicts; - if (!Array.isArray(raw)) return []; - const now = Date.now(); - return raw.filter((r): r is UpstreamSizeVerdictRecord => - !!r && typeof r === "object" - && typeof (r as UpstreamSizeVerdictRecord).origin === "string" - && typeof (r as UpstreamSizeVerdictRecord).model === "string" - && typeof (r as UpstreamSizeVerdictRecord).hash === "string" - && typeof (r as UpstreamSizeVerdictRecord).at === "number" - && (r as UpstreamSizeVerdictRecord).at > now - SIZE_VERDICT_TTL_MS, - ); -} - -/** Relay-side: the upstream answered a size verdict for these exact outbound - * bytes — record it so the byte-identical resend is refused locally (#496 - * loop guard, #7537). The hash must be of the SAME outbound serialization - * preflight checks (prepared.body) — call with that value, not wire bytes - * that later pipes may have re-serialized. */ -export function noteUpstreamSizeVerdict(session: Session, origin: string | undefined, model: string | undefined, outboundBody: string | undefined): void { - if (!origin || !model || typeof outboundBody !== "string" || outboundBody.length === 0) return; - const h = wireBodyHash(outboundBody); - const records = readSizeVerdicts(session.metadata); - if (records.some((r) => r.origin === origin && r.model === model && r.hash === h)) return; - session.metadata.upstreamSizeVerdicts = [...records, { origin, model, hash: h, at: Date.now() }].slice(-SIZE_VERDICT_MAX_RECORDS); - markDirty(session); -} - -/** Preflight-side: true when THIS exact wire body (same origin+model) already - * drew an upstream size verdict — the resend must not ride the wire again. */ -function upstreamSizeVerdictCovers(metadata: Record, origin: string | undefined, model: string | undefined, body: string | undefined): boolean { - if (!origin || !model || typeof body !== "string" || body.length === 0) return false; - const h = wireBodyHash(body); - return readSizeVerdicts(metadata).some((r) => r.origin === origin && r.model === model && r.hash === h); -} - /** #568: commit the response early so a long preflight cannot lose the client * to its header timeout. Streaming clients get an SSE stream with keep-alive * comment lines (`: bili-preflight` — a spec-mandated no-op for every SSE @@ -4069,18 +4012,6 @@ export async function preflightCompressIfNeeded( // started before this field existed) keep the legacy behavior. let baselineFloor = baselineFloorRaw; const currentOrigin = normalizeUpstreamOrigin(route?.upstream); - // #7537/#496: byte-identical resend of a body the upstream ALREADY refused - // as too large — the one refusal that survives the estimate-refusal removal - // (evidence, not estimate): refuse locally with the loop-guard verdict so a - // status-code-driven host cannot re-burn the same doomed payload in a - // retry loop. Changed bodies and new sessions judge fresh. - if (currentOrigin !== undefined && model !== undefined && model.length > 0) { - const verdictBody = typeof prepared.body === "string" ? prepared.body : (prepared.body instanceof Buffer ? prepared.body.toString("utf8") : undefined); - if (verdictBody !== undefined && upstreamSizeVerdictCovers(session.metadata, currentOrigin, model, verdictBody)) { - log("warn", `[${session.id}] preflight fail-fast 413 (retryable=false, upstream-size evidence): the upstream already refused THIS exact body as too large — refusing the byte-identical resend locally instead of re-burning the wire (#7537/#496 loop guard)`); - return { failFast: true, status: 413, message: `the upstream already refused this exact body as too large (its size verdict is on record for these bytes, #7537/#496). Do NOT retry the unchanged body — shrink the session (rewind or restart), or change the payload, and retry.`, retryable: false, respond: !res.writableEnded }; - } - } const baselineOrigin = normalizeUpstreamOrigin(session.stats.lastInputTokensOrigin); if (baselineFloor > 0 && currentOrigin !== undefined && baselineOrigin !== undefined && baselineOrigin !== currentOrigin) { log("info", `[${session.id}] preflight usage-baseline ~${baselineFloor} tok was measured on ${maskUrlForLog(baselineOrigin)}, request now routes to ${maskUrlForLog(currentOrigin)} — demoting to untrusted, judging by this payload's own estimate (#1933)`); @@ -4944,8 +4875,21 @@ export async function preflightCompressIfNeeded( // a local refusal: the summary relay itself is down (non-deterministic // exhaustion → 502) or the relay hit an upstream 429 (→ 503). if (f?.kind === "exhausted" && f.deterministic && !payloadFitsWindow) { + if (statedWall > 0) { + // Evidence-based refusal — the one local 413 that survives the + // #7537 estimate-refusal ruling: the UPSTREAM itself proved this + // wall (a stated overflow number, or its own 400/413 arming at + // ~statedWall tok), the futile-round math proves no combination of + // folds can close the gap, and bili's calibrated meter agrees the + // payload is over the window. This is upstream evidence, not a + // local estimate (#3461/#496/#767/#857) — re-forwarding unchanged + // bytes would only re-burn the wire and re-teach the same wall. + noteLocalRefusal(session, currentOrigin, model, limit); + log("warn", `[${session.id}] preflight fail-fast 413 (retryable=false): deterministic size exhaustion against a PROVEN window (~${statedWall.toLocaleString("en-US")} tok upstream evidence; local estimate ~${Math.round(result.payloadEstimate)} tok after ${result.compressedRanges} fold(s), window ${limit}) — refusing locally; estimate-based refusals are gone (#7537) but this one is upstream evidence (#3461/#496)`); + return failFast(413, f?.detail ?? "the payload still exceeds the window after preflight compression — the upstream has already proved this wall and nothing more can fold", false, result.compressedRanges > 0 ? foldedCalibratedSize : undefined, result.rangesRemaining); + } const fwdMsgs = outbound.processedMessages.length > 0 ? outbound.processedMessages : outbound.originalMessages; - log("warn", `[${session.id}] fold walk exhausted deterministically (nothing more can fold and the payload is still over window ${limit} by local estimate (~${Math.round(result.payloadEstimate)} tok, ${result.compressedRanges} range(s) folded) — forwarding per #7537 (no local estimate-refusal); the upstream's own size verdict is authoritative${shrinkNote}`); + log("warn", `[${session.id}] fold walk exhausted deterministically (nothing more can fold and the payload is still over window ${limit} by local estimate (~${Math.round(result.payloadEstimate)} tok, ${result.compressedRanges} range(s) folded) — no proven upstream wall on record — forwarding per #7537 (no local estimate-refusal); the upstream's own size verdict is authoritative${shrinkNote}`); log("info", `[${session.id}] preflight forward core-text profile: ${describeCoreTextDuplication(fwdMsgs)}`); return outbound; } diff --git a/src/server/relay.ts b/src/server/relay.ts index 94ea79b270..8481b14b58 100644 --- a/src/server/relay.ts +++ b/src/server/relay.ts @@ -77,7 +77,7 @@ import { bodyDumpEnabled, logDumpFailure } from "./observability.js"; import { rejectionDiagnosticSuffix } from "./rejection-diagnostics.js"; import { effectiveAbsorbBlock, effectiveBlockOpsEnabled } from "./prepare-responses.js"; import { awaitDrain, bufferStreamIfFits, bufferToStream, dumpStreamToFile, pipeThrough, readStreamToBuffer } from "./stream-io.js"; -import { buildForwardTarget, measuredBreakdownClause, measuredOutbound, outboundPayloadBreakdown, registerRequestAbort, beginStreamKeepalive, effectiveTokenCount, googlePathKind, imageBillingFor, imageTokenCapFor, inboundResignCredential, outboundContextEstimates, resolveUpstream, stripKernelSummaries, usageGradeInputBaseline, DOOMED_PROBE_ABSOLUTE_BYTES, DOOMED_PROBE_BYTES_PER_TOKEN, noteUpstreamSizeVerdict, type Prepared } from "../server.js"; +import { buildForwardTarget, measuredBreakdownClause, measuredOutbound, outboundPayloadBreakdown, registerRequestAbort, beginStreamKeepalive, effectiveTokenCount, googlePathKind, imageBillingFor, imageTokenCapFor, inboundResignCredential, outboundContextEstimates, resolveUpstream, stripKernelSummaries, usageGradeInputBaseline, DOOMED_PROBE_ABSOLUTE_BYTES, DOOMED_PROBE_BYTES_PER_TOKEN, type Prepared } from "../server.js"; /** Retry the same input when the provider proved only its output reservation overflows. */ function capOverflowOutput(body: string | Buffer, info: ContextOverflowInfo): { body: string; cap: number } | null { @@ -2154,53 +2154,28 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare loggerLog("warn", `[${errSid}] ← upstream ${upstream.status}${reqIdText}: ${snippet}${terminalCause}`); // #7537 (owner ruling 2026-11-22): local estimate-refusals are gone — // when the UPSTREAM itself rejects the body as too large, its verdict - // is authoritative. bili logs its own measurement as evidence and - // marks the response non-retryable so status-code-driven hosts don't - // retry-loop an unchanged body the upstream already rejected (burning - // rate limits). Log always; header + body merge only for non-stream - // pipeline-prepared forwards where the body is still under bili's - // control (stream in-band errors and already-committed-200 responses - // stay verbatim). Body merge only when the upstream body is valid - // JSON — anything else passes through byte-identical. + // is authoritative. bili logs its own measurement as evidence and marks + // the response non-retryable via HEADERS so status-code-driven hosts + // don't retry-loop an unchanged body the upstream already rejected + // (burning rate limits). Log always; headers only for non-stream, not- + // yet-sent responses. The upstream BODY passes through byte-identical: + // verbatim pass-through is a pinned contract (#1195 B, + // request-input-lifetime), so no body merge. The anti-loop protection + // for the truly-doomed payload lives in preflight's evidence branch + // (deterministic exhaustion against a proven wall → local 413 after + // the arm stamps, #496/#767/#857). const SIZE_ERROR_RE = /request entity too large|payload.*too (large|big)|body too (large|big)|too many (tokens|messages|bytes)|exceeds? (the |a |your )?(maximum|limit|allowed|context)|context (length|window|size)|input is too long|maximum context length|token (limit|count|budget)|content is too long|message\[?s?\]?.*(too long|exceed)/i; const upstreamSizeVerdict = upstream.status === 413 || (upstream.status === 400 && SIZE_ERROR_RE.test(bodyText)); if (prepared && upstreamSizeVerdict) { - // #7537/#496: this EXACT outbound body drew a size verdict — record - // it (SHA-1 of the preflight serialization, origin+model scoped, - // 10-minute TTL) so a byte-identical resend is refused locally by - // the preflight loop guard instead of re-burning the wire. The - // identity fast path and every changed body re-forward freely. - const preparedOutbound = typeof prepared.body === "string" ? prepared.body : (prepared.body instanceof Buffer ? prepared.body.toString("utf8") : undefined); - noteUpstreamSizeVerdict(prepared.session, normalizeUpstreamOrigin(upstreamUrl), prepared.model, preparedOutbound); const sizeMeasured = measuredOutbound(prepared); const declaredWindow = typeof prepared.session.metadata.effectiveContextLimit === "number" && prepared.session.metadata.effectiveContextLimit > 0 ? prepared.session.metadata.effectiveContextLimit : 0; const inboundBytes = typeof wireBody === "string" ? wireBody.length : wireBody ? wireBody.length : 0; - log("warn", `[${errSid}] upstream size verdict ${upstream.status} (authoritative per #7537): bili measured outbound ~${sizeMeasured?.tokens?.toLocaleString("en-US") ?? "n/a"} TEXT tokens${sizeMeasured?.breakdown ? ` (${measuredBreakdownClause(sizeMeasured.breakdown)})` : ""}, inbound ${inboundBytes.toLocaleString("en-US")} bytes, effective window ${declaredWindow.toLocaleString("en-US")} (model=${prepared.model ?? "unknown"}); marking non-retryable to stop host retry loops`); + log("warn", `[${errSid}] upstream size verdict ${upstream.status} (authoritative per #7537): bili measured outbound ~${sizeMeasured?.tokens?.toLocaleString("en-US") ?? "n/a"} TEXT tokens${sizeMeasured?.breakdown ? ` (${measuredBreakdownClause(sizeMeasured.breakdown)})` : ""}, inbound ${inboundBytes.toLocaleString("en-US")} bytes, effective window ${declaredWindow.toLocaleString("en-US")} (model=${prepared.model ?? "unknown"}); marking non-retryable via headers to stop host retry loops — the upstream body passes through verbatim`); if (!res.headersSent && req.method !== "GET" && req.method !== "HEAD") { respHeaders["x-bili-cause"] = "upstream-size"; respHeaders["x-bili-retryable"] = "false"; - if (errBody) { - try { - const asText = new TextDecoder().decode(errBody); - const json = JSON.parse(asText) as Record; - if (json && typeof json === "object" && !Array.isArray(json)) { - json.bili_evidence = { - outboundTextTokens: sizeMeasured?.tokens ?? null, - breakdown: sizeMeasured?.breakdown ?? null, - inboundBytes, - effectiveWindow: declaredWindow || null, - verdict: `upstream refused this body as too large; bili's local measurement above is evidence, not the cause; do NOT retry the unchanged body (#7537)`, - }; - const errObj = json.error; - if (errObj && typeof errObj === "object" && !Array.isArray(errObj)) { - (errObj as Record).retryable = false; - } - errBody = Buffer.from(JSON.stringify(json)); - } - } catch { /* non-JSON upstream body — headers + log only */ } - } } } if (prepared?.session && prepared.nudgeStampsBefore && upstream.status >= 400 && upstream.status < 500) rejectNudge(prepared.session, prepared.nudgeStampsBefore, upstream.status); diff --git a/tests/deferred-tool-budget.test.ts b/tests/deferred-tool-budget.test.ts index 9b7f9ca91d..287dc9e710 100644 --- a/tests/deferred-tool-budget.test.ts +++ b/tests/deferred-tool-budget.test.ts @@ -117,7 +117,7 @@ test("#2391: output headroom includes loaded schemas without adding them again t assert.equal(usageBody.max_output_tokens, capOf(200_000), "usage-grade baseline still bounds the headroom (no double-counted reserve, #2558)"); }); -test("#2391: a 272k Responses proxy forwards the full deferred catalog and rejects eager/loaded overflow", async () => { +test("#2391: a 272k Responses proxy forwards the full deferred catalog (eager/loaded overflow forwards — the upstream decides, #7537)", async () => { const received: Record[] = []; const upstream = http.createServer((req, res) => { const chunks: Buffer[] = []; @@ -159,12 +159,15 @@ test("#2391: a 272k Responses proxy forwards the full deferred catalog and rejec assert.deepEqual(received[0].tools, tools, "full upstream definitions must stay unchanged"); seedEvidence(upstreamPort, "2391-eager"); const eager = await send({ ...body, tools: [{ ...deferred, defer_loading: false }, search] }, "2391-eager"); - assert.notEqual(eager.status, 200, await eager.text()); - assert.equal(received.length, 1, "eager overflow must be stopped before forwarding"); + // #7537: the old measured-tier 413 is gone — over-budget tool mass is + // forwarded; the upstream is the size authority. The full catalog + // still rides unchanged (#2391's original contract). + assert.equal(eager.status, 200, await eager.text()); + assert.equal(received.length, 2, "eager overflow was forwarded (upstream decides, #7537)"); seedEvidence(upstreamPort, "2391-loaded"); const loaded = await send({ ...body, input: [{ type: "additional_tools", tools: [deferred] }, ...body.input] }, "2391-loaded"); - assert.notEqual(loaded.status, 200, await loaded.text()); - assert.equal(received.length, 1, "loaded overflow must be stopped before forwarding"); + assert.equal(loaded.status, 200, await loaded.text()); + assert.equal(received.length, 3, "loaded overflow was forwarded (upstream decides, #7537)"); const small = { ...deferred, description: "small loaded definition" }; const loadedItems = [ { type: "additional_tools", tools: [small] }, diff --git a/tests/issue1841-preflight-futility.test.ts b/tests/issue1841-preflight-futility.test.ts index 7e1a640fc8..758907ef72 100644 --- a/tests/issue1841-preflight-futility.test.ts +++ b/tests/issue1841-preflight-futility.test.ts @@ -165,7 +165,7 @@ function bulkTokens(repeat: number, pairs: number): number { return Math.round((pairs * (22 * repeat + 45)) / 4); } -test("#1841 A (#7537): a payload whose foldable pool cannot close the gap still skips the round — and is FORWARDED instead of the old 413", async () => { +test("#1841 A: a payload whose foldable pool cannot close the gap skips the round with zero summary calls (stated wall → evidence 413 survives #7537)", async () => { CALLS = []; summaryResponder = () => ({ content: SUMMARY_TEXT, finishReason: "stop" }); const p = await boot(); @@ -189,11 +189,50 @@ test("#1841 A (#7537): a payload whose foldable pool cannot close the gap still seedEvidence(p.upstreamPort, "issue1841-futility-skip"); const resp = await post(p, "issue1841-futility-skip", messages); const body = await resp.text(); - // #7537: the futility verdict no longer answers a local 413 — the - // skipped round's payload is forwarded as-is (fold-first unchanged: it - // just wasn't worth folding), and the upstream decides. This mock - // upstream accepts it → 200. - assert.equal(resp.status, 200, `a futile round now forwards (#7537): HTTP ${resp.status} ${body.slice(0, 240)}`); + // The seed arms a STATED upstream wall (overflowArmTokens = the + // window): the upstream itself declared this ceiling hard. A payload + // over a proven wall with nothing more that can fold is an EVIDENCE + // refusal — it survives the #7537 estimate-refusal removal (#3461). + assert.equal(resp.status, 413, `a futile round against a proven wall must fail fast non-retryably: HTTP ${resp.status} ${body.slice(0, 240)}`); + const json = JSON.parse(body) as { error?: { code?: string; message?: string } }; + assert.equal(json.error?.code, "preflight_compress_failed"); + assert.match(json.error?.message ?? "", /futile round/, `names the futility verdict (got: ${json.error?.message})`); + assert.match(json.error?.message ?? "", /maximum possible saving/, `quotes the pool bound (got: ${json.error?.message})`); + assert.equal(CALLS.filter((c) => c.summary).length, 0, "a skipped round must spend ZERO summarization calls"); + assert.equal(CALLS.length, 0, "the over-window payload must not be forwarded either"); + } finally { + await p.cleanup(); + } +}); + +test("#1841 A2 (#7537): the SAME futile payload with NO stated wall is FORWARDED — no local estimate-refusal", async () => { + CALLS = []; + summaryResponder = () => ({ content: SUMMARY_TEXT, finishReason: "stop" }); + const p = await boot(); + try { + // Same fixture as A, but the session carries NO overflow-arm wall + // (no seed): the futility verdict rests on bili's own estimate only. + // #7537 (owner ruling): that estimate no longer answers a local 413 — + // the payload is forwarded and the upstream decides (this mock + // accepts → 200). Zero summarization calls: the skipped round still + // skips; only the refusal goes away. + const REPEAT = 3157; + const poolTok = 4 * 440; + const est = bulkTokens(REPEAT, 2) + poolTok; + assert.ok(est > WINDOW && est - WINDOW > poolTok * 1.2, `fixture must be futile (${est} vs ${WINDOW}, pool ${poolTok})`); + const messages: Record[] = [ + plain("user", "OLD_WORK_A ".repeat(160)), + plain("assistant", "ANSWER_A ".repeat(160)), + ...bashPair(1, REPEAT), + ...bashPair(2, REPEAT), + plain("user", "OLD_WORK_B ".repeat(160)), + plain("assistant", "ANSWER_B ".repeat(160)), + plain("user", "ok"), + plain("assistant", "done"), + ]; + const resp = await post(p, "issue1841-futility-nowall", messages); + const body = await resp.text(); + assert.equal(resp.status, 200, `a futile round with no proven wall now forwards (#7537): HTTP ${resp.status} ${body.slice(0, 240)}`); assert.ok(body.includes("forwarded answer"), "the model reply must reach the client"); assert.equal(CALLS.filter((c) => c.summary).length, 0, "a skipped round must spend ZERO summarization calls"); assert.equal(CALLS.length, 1, "the over-window payload is forwarded exactly once (the upstream is the size authority)"); diff --git a/tests/issue4079-egress-window-fuse.test.ts b/tests/issue4079-egress-window-fuse.test.ts index 4336e8e1f8..264bd85fe3 100644 --- a/tests/issue4079-egress-window-fuse.test.ts +++ b/tests/issue4079-egress-window-fuse.test.ts @@ -171,15 +171,13 @@ test("e2e #4079 (#7537): a body that no window can fit is FORWARDED — the fuse // fake upstream 413s above 2MB. const r = await post(ctx, bigMessages(2000, 4_400), false); const body = await r.text(); - const parsed = JSON.parse(body) as { error?: { type?: string; code?: string; retryable?: boolean; message?: string }; bili_evidence?: { inboundBytes?: number; verdict?: string } }; + const parsed = JSON.parse(body) as { error?: { type?: string; code?: string; retryable?: unknown; message?: string } }; assert.equal(r.status, 413, `the upstream's size verdict must pass through (got ${r.status}): ${body.slice(0, 300)}`); assert.match(parsed.error?.message ?? "", /upstream says: request entity too large/, "the 413 is the UPSTREAM's message, not a local refusal"); assert.equal(r.headers.get("x-bili-cause"), "upstream-size", "the annotation names the size verdict"); assert.equal(r.headers.get("x-bili-retryable"), "false", "non-retryable — retrying re-sends the same oversized history (#2847 semantics)"); - assert.equal(parsed.error?.retryable, false, "the host must not retry the unchanged body"); - assert.ok((parsed.bili_evidence?.inboundBytes ?? 0) > 1_000_000, "bili's local measurement rides along as evidence (not cause)"); - assert.match(parsed.bili_evidence?.verdict ?? "", /do NOT retry/i, "the evidence tells the host what to do"); + assert.equal(parsed.error?.retryable, undefined, "the upstream body stays verbatim — no bili merge (header-only annotation)"); // THE behavior under test: the payload WAS forwarded — the fuse logs, // it does not judge (#7537). assert.equal(calls.length, 1, `upstream must see exactly one call (got ${JSON.stringify(calls)})`); @@ -209,14 +207,12 @@ test("e2e #5000 (#7537): a body whose mass rides tools[] is FORWARDED — the me body: JSON.stringify({ model: "gpt-test", stream: true, tools, messages }), }); const body = await r.text(); - const parsed = JSON.parse(body) as { error?: { message?: string; retryable?: boolean }; bili_evidence?: { inboundBytes?: number; verdict?: string } }; + const parsed = JSON.parse(body) as { error?: { message?: string } }; assert.equal(r.status, 413, `the upstream's size verdict must pass through (got ${r.status}): ${body.slice(0, 300)}`); assert.match(parsed.error?.message ?? "", /upstream says: request entity too large/, "the 413 is the UPSTREAM's message"); + assert.equal(r.headers.get("x-bili-cause"), "upstream-size", "the annotation names the size verdict"); assert.equal(r.headers.get("x-bili-retryable"), "false", "non-retryable — the tools[] mass won't change on retry"); - assert.equal(parsed.error?.retryable, false, "the host must not retry the unchanged body"); - assert.ok((parsed.bili_evidence?.inboundBytes ?? 0) > 1_000_000, "bili's local measurement rides along as evidence (not cause)"); - assert.match(parsed.bili_evidence?.verdict ?? "", /do NOT retry/i, "the evidence tells the host what to do"); // THE behavior under test: the payload WAS forwarded — the measured // tier is now an evidence logger, not a judge (#7537). assert.equal(calls.length, 1, `upstream must see exactly one call (got ${JSON.stringify(calls)})`); @@ -240,14 +236,12 @@ test("e2e #4543 (#7537): a dense CJK body over every old bar is FORWARDED — th const messages = [{ role: "user", content: cjk + "\n" + "x".repeat(3_072) }] as Array<{ role: string; content: string }>; const r = await post(ctx, messages, false); const body = await r.text(); - const parsed = JSON.parse(body) as { error?: { message?: string; retryable?: boolean }; bili_evidence?: { inboundBytes?: number; verdict?: string } }; + const parsed = JSON.parse(body) as { error?: { message?: string } }; assert.equal(r.status, 413, `the upstream's size verdict must pass through (got ${r.status}): ${body.slice(0, 300)}`); assert.match(parsed.error?.message ?? "", /upstream says: request entity too large/, "the 413 is the UPSTREAM's message"); assert.equal(r.headers.get("x-bili-cause"), "upstream-size", "the annotation names the size verdict"); - assert.equal(parsed.error?.retryable, false, "non-retryable — the CJK mass won't change on retry"); - assert.ok((parsed.bili_evidence?.inboundBytes ?? 0) > 1_000_000, "bili's local measurement rides along as evidence (not cause)"); - assert.match(parsed.bili_evidence?.verdict ?? "", /do NOT retry/i, "the evidence tells the host what to do"); + assert.equal(r.headers.get("x-bili-retryable"), "false", "non-retryable — the CJK mass won't change on retry"); // THE behavior under test: the payload WAS forwarded — the fuse logs, // it does not judge (#7537). assert.equal(calls.length, 1, `upstream must see exactly one call (got ${JSON.stringify(calls)})`); diff --git a/tests/issue4185-identified-fresh-forward.test.ts b/tests/issue4185-identified-fresh-forward.test.ts index 045e3ac287..290d502a5c 100644 --- a/tests/issue4185-identified-fresh-forward.test.ts +++ b/tests/issue4185-identified-fresh-forward.test.ts @@ -224,9 +224,8 @@ test("identified fresh session whose MEASURED body exceeds the native window but assert.match(body, /context_length_exceeded/, `the upstream's own size verdict rides through: ${body.slice(0, 300)}`); assert.equal(r.headers.get("x-bili-cause"), "upstream-size", "the annotation names the size verdict"); assert.equal(r.headers.get("x-bili-retryable"), "false", "non-retryable — the mass won't change on retry"); - const json = JSON.parse(body) as { bili_evidence?: { inboundBytes?: number; verdict?: string } }; - assert.ok((json.bili_evidence?.inboundBytes ?? 0) > 100_000, "bili's local measurement rides along as evidence (not cause)"); - assert.match(json.bili_evidence?.verdict ?? "", /do NOT retry/i, "the evidence tells the host what to do"); + const json = JSON.parse(body) as { error?: { message?: string }; bili_evidence?: unknown }; + assert.equal(json.bili_evidence, undefined, "no bili merge into the upstream body (header-only annotation)"); assert.equal(calls.filter((c) => c.body.includes("TOOLMARKER_4185_")).length, 1, "the giant payload WAS forwarded (the upstream is the size authority, #7537)"); }); }); @@ -235,15 +234,14 @@ test("identified fresh session with mathematically doomed bytes (>2MB core) → await withFixture(async (proxyPort, upstreamPort, calls) => { const r = await post(proxyPort, upstreamPort, "s-4185-doomed", incidentConversation(2_100_000)); const body = await r.text(); - const json = JSON.parse(body) as { error?: { message?: string }; bili_evidence?: { inboundBytes?: number } }; + const json = JSON.parse(body) as { error?: { message?: string } }; assert.ok(r.status === 400 || r.status === 413, `doomed bytes are forwarded; the upstream's size verdict answers (${r.status}): ${body.slice(0, 300)}`); assert.match(json.error?.message ?? "", /context_length_exceeded|too large/i, `the verdict is the upstream's, not a local refusal: ${body.slice(0, 300)}`); - assert.ok((json.bili_evidence?.inboundBytes ?? 0) > 1_000_000, "the multi-MB payload really was forwarded (evidence shows the inbound mass)"); assert.equal(calls.length, 1, "one forward, no summarization"); }); }); -test("usage-backed session whose payload exceeds the NATIVE window → forwarded, the 400 passes through annotated; the byte-identical RESEND is refused by the loop guard (#7537/#496)", async () => { +test("usage-backed session whose payload exceeds the NATIVE window → forwarded; the byte-identical RESEND hits the evidence 413 (deterministic exhaustion against a proven wall) (#7537/#496)", async () => { await withFixture(async (proxyPort, upstreamPort, calls) => { const small = await post(proxyPort, upstreamPort, "s-4185-native-over", [ { role: "user", content: "hello" }, @@ -262,17 +260,16 @@ test("usage-backed session whose payload exceeds the NATIVE window → forwarded assert.equal(r.status, 400, `over-native payload is rejected BY THE UPSTREAM after the experiment, got ${r.status}: ${body.slice(0, 200)}`); assert.equal(calls.filter((c) => c.body.includes("TOOLMARKER_4185_")).length, 1, "the giant payload was forwarded exactly once"); - // #7537: the stamped wall no longer turns the resend into a LOCAL 413 - // on estimate — but the EVIDENCE-backed loop guard does: this exact - // body drew a size verdict from the upstream, so the byte-identical - // resend is refused locally instead of re-burning the wire (#496). - // Changed bodies still forward freely; the host learns "shrink or - // change" from the 413 message, not from an estimate. + // #7537: the resend is not an ESTIMATE refusal — it is the surviving + // evidence branch: r1's 400 stamped the wall (statedWindow), the + // futile-round math proves no fold combination closes the gap against + // it, and the meter agrees the payload is over the window → local 413, + // retryable=false, never re-burned on the wire (#496 loop stays broken). + // Payloads with NO proven wall on record still forward (#7537). const before = calls.length; const r2 = await post(proxyPort, upstreamPort, "s-4185-native-over", giant); const body2 = await r2.text(); - assert.equal(r2.status, 413, `the byte-identical resend is refused by the loop guard (#7537/#496), got ${r2.status}: ${body2.slice(0, 200)}`); - assert.match(body2, /already refused this exact body as too large/, "the 413 message names the recorded upstream size verdict"); + assert.equal(r2.status, 413, `the resend is refused by the EVIDENCE branch (proven wall + nothing more can fold), got ${r2.status}: ${body2.slice(0, 200)}`); assert.equal(calls.length, before, "the resend was NEVER forwarded (the #496 loop stays broken)"); }); }); diff --git a/tests/issue7537-preflight-passthrough.test.ts b/tests/issue7537-preflight-passthrough.test.ts index 7fe4ae3d47..580a08700f 100644 --- a/tests/issue7537-preflight-passthrough.test.ts +++ b/tests/issue7537-preflight-passthrough.test.ts @@ -162,7 +162,7 @@ test("#7537 A: the mathematically-doomed payload is FORWARDED, and the upstream' // upstream's verdict is the authoritative one bili must relay. const r = await post(ctx, bigMessages(500, 4_400)); const body = await r.text(); - const parsed = JSON.parse(body) as { error?: { message?: string; retryable?: boolean }; bili_evidence?: { outboundTextTokens?: number | null; inboundBytes?: number; verdict?: string } }; + const parsed = JSON.parse(body) as { error?: { message?: string } }; // THE fix: no local estimate-refusal — the payload reached the // upstream, which made the authoritative call (413). @@ -170,15 +170,11 @@ test("#7537 A: the mathematically-doomed payload is FORWARDED, and the upstream' `the forward must reach the upstream (calls=${JSON.stringify(calls.map((c) => ({ s: c.summary, n: c.contentChars })))})`); assert.equal(r.status, 413, "the status is the UPSTREAM's 413"); assert.match(parsed.error?.message ?? "", /maximum context length exceeded/, "the UPSTREAM's own error text (not bili's local estimate) is what the host sees"); - // Annotation: non-retryable marking so status-code-driven hosts stop - // retry-looping the already-refused body. + // Annotation: non-retryable marking via HEADERS so status-code-driven + // hosts stop retry-looping the already-refused body. The upstream BODY + // stays verbatim (no merge — #1195 B / request-input-lifetime pin). assert.equal(r.headers.get("x-bili-retryable"), "false", "x-bili-retryable header present"); assert.equal(r.headers.get("x-bili-cause"), "upstream-size", "x-bili-cause header present"); - assert.equal(parsed.error?.retryable, false, "error.retryable=false merged into the JSON body"); - assert.ok(parsed.bili_evidence, "bili_evidence merged into the JSON body"); - assert.ok(typeof parsed.bili_evidence?.inboundBytes === "number" && (parsed.bili_evidence?.inboundBytes ?? 0) > 100_000, - `evidence carries the measured inbound size (got ${JSON.stringify(parsed.bili_evidence)})`); - assert.match(parsed.bili_evidence?.verdict ?? "", /do NOT retry/i, "the evidence names the anti-retry verdict"); } finally { await close(); rmrf(root); From 3fe69f59481a5e68ab38e476f463c140e37ab327 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Mon, 23 Nov 2026 02:37:58 +0800 Subject: [PATCH 5/5] test: re-pin the zero-fold and responses-wire estimate-doom pins to #7537 forward semantics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit preflight-zero-fold-calibration: the anonymous-baseline and image-reserve pins expected the #5000/#4543 measured-doom 413 — exactly the estimate-refusal family #7537 removes. They now pin the forward contract (no local refusal, upstream decides; scoped refusal demoted to evidence input). preflight-responses-wire: the two unfoldable 4.6MB body/tool pins expected local 413; they now forward (mock upstream accepts → 200, exactly one forward each). --- tests/preflight-responses-wire.test.ts | 12 +++++--- tests/preflight-zero-fold-calibration.test.ts | 29 +++++++++---------- 2 files changed, 22 insertions(+), 19 deletions(-) diff --git a/tests/preflight-responses-wire.test.ts b/tests/preflight-responses-wire.test.ts index 8995ed4acd..24a1d74142 100644 --- a/tests/preflight-responses-wire.test.ts +++ b/tests/preflight-responses-wire.test.ts @@ -114,11 +114,15 @@ for (const pluginMode of [false, true]) { assert.equal((await post([...input, { type: "message", role: "user", content: "One more ordinary turn." }])).status, 200); assert.equal(summaries, beforeContinuation); forwards.length = 0; - assert.equal((await post([{ type: "message", role: "user", content: "A".repeat(4_600_000) }])).status, 413); - assert.equal(forwards.length, 0); + // #7537: an unfoldable over-window body is no longer doomed on + // bili's own measurement — it forwards; the upstream is the size + // authority (this mock accepts → 200). + assert.equal((await post([{ type: "message", role: "user", content: "A".repeat(4_600_000) }])).status, 200); + assert.equal(forwards.length, 1); + forwards.length = 0; assert.equal((await post(seed, [{ type: "function", name: "oversized", - description: "D".repeat(4_600_000), parameters: { type: "object" } }])).status, 413); - assert.equal(forwards.length, 0); + description: "D".repeat(4_600_000), parameters: { type: "object" } }])).status, 200); + assert.equal(forwards.length, 1); } finally { setLogCapture(null); proxy.close(); proxy.closeAllConnections(); diff --git a/tests/preflight-zero-fold-calibration.test.ts b/tests/preflight-zero-fold-calibration.test.ts index 7837ff72ba..521899bb06 100644 --- a/tests/preflight-zero-fold-calibration.test.ts +++ b/tests/preflight-zero-fold-calibration.test.ts @@ -162,28 +162,27 @@ for (const scenario of [ }); } -// #5000/#4543 (2e021109, after this PR's base): the measured-body gate now -// dominates inside the arbitration arm — a measured outbound body over the -// window is doomed locally for EVERY baseline regime (the original -// size-arbitration forwarding only remains for measured-fitting bodies, which -// this fixture's est≈measured regime cannot produce). Pin the current policy. -test("zero folds: anonymous unknown baseline — measured over-window body is doomed locally", { timeout: 15_000 }, async () => { +// #7537 (supersedes the #5000/#4543 measured-doom policy): a measured +// over-window body with NO proven upstream wall is no longer doomed locally +// — it forwards and the upstream decides. The anonymous baseline is exactly +// the estimate-only regime, so these now pin the forward contract. +test("zero folds: anonymous unknown baseline — measured over-window body FORWARDS (#7537)", { timeout: 15_000 }, async () => { const f = await run({ windowRatio: 0.6, anonymous: true }); - assert.ok("failFast" in f.result, JSON.stringify(f.logs)); - assert.equal(f.result.status, 413); - assert.ok(f.logs.some(line => line.includes("body ITSELF exceeds the window"))); + assert.ok(f.result === f.prepared, JSON.stringify(f.logs)); + assert.ok(f.summaryCalls > 0, "the over-window payload is forwarded to the upstream"); }); -test("zero folds: a prior scoped refusal keeps the anonymous body locally doomed", { timeout: 15_000 }, async () => { +test("zero folds: a prior scoped refusal alone does not doom the anonymous body — it forwards (#7537)", { timeout: 15_000 }, async () => { const f = await run({ windowRatio: 0.6, anonymous: true, localRefusal: true }); - assert.ok("failFast" in f.result, JSON.stringify(f.logs)); - assert.equal(f.result.status, 413); - assert.ok(f.logs.some(line => line.includes("body ITSELF exceeds the window"))); + assert.ok(f.result === f.prepared, JSON.stringify(f.logs)); + assert.ok(f.summaryCalls > 0, "a scoped refusal is evidence input, not an estimate refusal"); }); -test("zero folds: image reserve is not deflated by text calibration", { timeout: 15_000 }, async () => { +test("zero folds: image reserve is not deflated by text calibration — but the body still forwards (#7537)", { timeout: 15_000 }, async () => { const f = await run({ k: 0.25, windowRatio: 0.6, imageBytes: 60_000 }); assert.ok(f.imageTokens > 0); assert.ok(f.rawText * 0.25 < f.limit && f.rawText * 0.25 + f.imageTokens > f.limit); - assert.ok("failFast" in f.result, JSON.stringify(f.logs)); + // The old pin expected the measured gate's local 413. #7537: calibration + // no longer answers a local refusal — the image-bearing body forwards. + assert.ok(f.result === f.prepared, JSON.stringify(f.logs)); });