From ffab7e0da2793bc5e61d55288bd18c15cf8b5af3 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 4 Oct 2026 00:45:11 +0800 Subject: [PATCH 1/2] fix: learn-on-failure ladder entry for placement-only system 400s (#1996) --- src/compat-roles.ts | 57 ++++++++++++ src/server.ts | 28 +++++- tests/compat-roles.test.ts | 42 ++++++++- tests/e2e-responses-offhead-system.test.ts | 103 +++++++++++++++++++++ tests/wire-contract-fakes.ts | 37 ++++++++ tests/wire-contract.test.ts | 1 + 6 files changed, 263 insertions(+), 5 deletions(-) create mode 100644 tests/e2e-responses-offhead-system.test.ts diff --git a/src/compat-roles.ts b/src/compat-roles.ts index 043a0218b2..511bd17476 100644 --- a/src/compat-roles.ts +++ b/src/compat-roles.ts @@ -125,6 +125,63 @@ export function detectSystemPlacementError(status: number, bodyText: string): bo return PLACEMENT_MARKERS.some((re) => re.test(norm)); } +/** #1996 — Responses item types that materialize as chat messages upstream + * (vLLM maps function_call/custom_tool_call→assistant, *_output→tool, + * reasoning→assistant), so a system item placed after any of them is + * off-head for the model's chat template. */ +const ROLE_PRODUCING_TYPES = new Set([ + "function_call", + "function_call_output", + "custom_tool_call", + "custom_tool_call_output", + "reasoning", +]); + +/** + * #1996 — does this wire body carry the shape placement-strict backends + * reject? A literal role:"system" message that is not the first chat-producing + * item (or a second system anywhere) trips Qwen-family Jinja chat templates + * served by vLLM/SGLang: "System message must be at the beginning." Bili never + * emits such items itself (front block/anchors ride as developer, + * nudges/separators as user, top-level instructions stripped), so offenders + * are client-origin mid-history system items forwarded verbatim by the + * plugin-mode position-preserving pass-through (#1638). Eligibility mirrors + * applyCompatRolesJson exactly; on the Responses wire a non-empty top-level + * `instructions` string becomes a leading system upstream, so with it present + * ANY input[] system is off-head. + */ +export function hasOffHeadSystem(body: string, protocol: "openai" | "responses"): boolean { + let parsed: Record; + try { + parsed = JSON.parse(body) as Record; + } catch { + return false; + } + const items = protocol === "openai" ? parsed.messages : parsed.input; + if (!Array.isArray(items)) return false; + const virtualLeading = + protocol === "responses" && typeof parsed.instructions === "string" && parsed.instructions.length > 0; + let systems = 0; + let firstSlotIdx = -1; + let firstSystemIdx = -1; + items.forEach((item, i) => { + if (!item || typeof item !== "object" || Array.isArray(item)) return; + const msg = item as Record; + const t = msg.type; + const isMessage = t === undefined || t === "message"; + if (protocol === "responses" && !isMessage && !ROLE_PRODUCING_TYPES.has(t as string)) return; + if (firstSlotIdx < 0) firstSlotIdx = i; + if (isMessage && msg.role === "system") { + systems++; + if (firstSystemIdx < 0) firstSystemIdx = i; + } + }); + if (systems === 0) return false; + if (systems > 1) return true; + if (virtualLeading) return true; + return firstSystemIdx !== firstSlotIdx; +} + export function applyCompatRoles( body: string, protocol: "openai" | "responses", diff --git a/src/server.ts b/src/server.ts index 0002aa0d16..d312697962 100644 --- a/src/server.ts +++ b/src/server.ts @@ -124,7 +124,7 @@ import { BILI_TUNNEL_HEADER, checkTunnelDestination, classifyIp, localMachineIps import { dumpRejectedBody } from "./error-dump.js"; import { decodeRequestBody, DecompressedTooLargeError } from "./content-encoding.js"; -import { applyCompatRoles, applyCompatRolesJson, detectRoleRejection, detectSystemPlacementError, resolveCompatRoles, type CompatRoles } from "./compat-roles.js"; +import { applyCompatRoles, applyCompatRolesJson, detectRoleRejection, detectSystemPlacementError, hasOffHeadSystem, resolveCompatRoles, type CompatRoles } from "./compat-roles.js"; import { applyCompatDropFields, dropCompatFieldsJson, resolveCompatDropFields } from "./compat-drop.js"; import { applyOutputSteering, applyOutputSteeringJson } from "./output-steering.js"; import { bodyDumpEnabled, getUnrecognizedPathStats, isModelDiscoveryPath, logDumpFailure, logUnrecognizedPath } from "./server/observability.js"; @@ -6274,8 +6274,19 @@ async function forward( clearTimer: upstreamResult.clearTimer, stopIdleTimer: upstreamResult.stopIdleTimer, }; - const rejection = detectRoleRejection(upstreamResult.response.status, roleErrText); - if (rejection && rejection.role !== "system") { + const namedRejection = detectRoleRejection(upstreamResult.response.status, roleErrText); + // #1996: placement-only rejections name no role (vLLM+Qwen + // chat_template: "System message must be at the beginning.") — enter + // the ladder when the error matches a placement marker AND the wire + // itself carries the offending shape, so a client-origin mid-history + // system item (plugin-mode #1638 verbatim pass-through) gets the same + // single-hop repair instead of a permanent 400 loop on every retry. + const rejection = namedRejection ?? + (detectSystemPlacementError(upstreamResult.response.status, roleErrText) && + hasOffHeadSystem(wireBody, compatProtocol) + ? { role: "system" } + : null); + if (rejection && !(namedRejection && namedRejection.role === "system")) { // Learn-on-failure ladder — primary hop (#552: offending role → // "system") plus a SECOND-CHANCE hop (#583: → "user") fired only // when the system hop 400'd with a #377-class system-PLACEMENT @@ -6285,6 +6296,9 @@ async function forward( // exactly once; the sequence is fixed (never a loop), hard-capped // at original + 2 retries. Any other failure stops the ladder and // the original 400 passes through verbatim. + // (#1996): placement-only errors that name no role enter here + // directly as { role: "system" } (see above) and skip the + // identity hop straight to the system→user placement fix. const cp = compatProtocol; const wb = wireBody; const remember = (target: string, rewritten: number): void => { @@ -6333,7 +6347,13 @@ async function forward( r.clearTimer(); return errText !== null && detectSystemPlacementError(r.response.status, errText) ? "placement-400" : "other"; }; - if ((await hop("system")) === "placement-400") await hop("user"); + // #1996: an already-system offender needs no identity hop — go + // straight to the placement fix (system→user). + if (rejection.role === "system") { + await hop("user"); + } else if ((await hop("system")) === "placement-400") { + await hop("user"); + } } } } diff --git a/tests/compat-roles.test.ts b/tests/compat-roles.test.ts index 44794fc980..31906d893b 100644 --- a/tests/compat-roles.test.ts +++ b/tests/compat-roles.test.ts @@ -10,7 +10,7 @@ import { startServer } from "../src/server.ts"; import { loadRoutes, type ProxyOptions } from "../src/config.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; -import { applyCompatRoles, applyCompatRolesJson, detectRoleRejection, detectSystemPlacementError, parseCompatRoles, resolveCompatRoles } from "../src/compat-roles.ts"; +import { applyCompatRoles, applyCompatRolesJson, detectRoleRejection, detectSystemPlacementError, hasOffHeadSystem, parseCompatRoles, resolveCompatRoles } from "../src/compat-roles.ts"; import { _liveUpstreamTimersForTest } from "../src/fetch-util.ts"; import { rmrf } from "./tmp-rm.ts"; @@ -516,3 +516,43 @@ async function waitFor(probe: () => boolean, deadlineMs = 3000): Promise { await new Promise((resolve) => setTimeout(resolve, 25)); } } + +test("#1996: production vLLM+Qwen chat_template 400 names no role — #552 detector idle, placement detector fires", () => { + const prod = JSON.stringify({ + error: { + code: "invalid_prompt", + message: + "artifact:chat_template.jinja: 106\n {% endif %}\n {{- raise_exception('System message must be at the beginning.') }}\nJinja Exception: System message must be at the beginning.", + param: "input", + type: "invalid_request_error", + }, + }); + assert.equal(detectRoleRejection(400, prod), null, "placement-only errors name no role — #552 detector must NOT fire"); + assert.equal(detectSystemPlacementError(400, prod), true, "placement detector recognizes the production string"); +}); + +test("hasOffHeadSystem: openai chat wire shapes", () => { + const p = (msgs: unknown[]) => JSON.stringify({ messages: msgs }); + assert.equal(hasOffHeadSystem(p([{ role: "system", content: "s" }, { role: "user", content: "u" }]), "openai"), false, "single system at index 0 is legal"); + assert.equal(hasOffHeadSystem(p([{ role: "user", content: "u" }, { role: "system", content: "s" }]), "openai"), true, "off-head system"); + assert.equal(hasOffHeadSystem(p([{ role: "system", content: "s" }, { role: "user", content: "u" }, { role: "system", content: "s2" }]), "openai"), true, "duplicate system anywhere"); + assert.equal(hasOffHeadSystem(p([{ role: "user", content: "u" }, { role: "assistant", content: "a" }]), "openai"), false, "no system at all"); + assert.equal(hasOffHeadSystem(p([{ role: "developer", content: "d" }, { role: "user", content: "u" }]), "openai"), false, "off-head developer is not a system offender"); +}); + +test("hasOffHeadSystem: responses wire shapes (#1996 offender = type-less mid-history system)", () => { + const p = (input: unknown[], extra: Record = {}) => JSON.stringify({ input, ...extra }); + assert.equal( + hasOffHeadSystem(p([{ role: "developer", content: "d" }, { role: "user", content: "u" }, { role: "system", content: "mid" }]), "responses"), + true, "type-less mid-history system (omp wire form)", + ); + assert.equal(hasOffHeadSystem(p([{ role: "system", content: "s" }, { role: "user", content: "u" }]), "responses"), false, "single system at index 0"); + assert.equal(hasOffHeadSystem(p([{ role: "user", content: "u" }], { instructions: "be nice" }), "responses"), false, "instructions alone creates no offender"); + assert.equal(hasOffHeadSystem(p([{ role: "system", content: "s" }], { instructions: "be nice" }), "responses"), true, "instructions become a leading system upstream → input[0] system is off-head"); + assert.equal( + hasOffHeadSystem(p([{ type: "function_call", name: "f", call_id: "c1", arguments: "{}" }, { role: "system", content: "s" }]), "responses"), + true, "system after a chat-producing tool item is off-head upstream", + ); + assert.equal(hasOffHeadSystem(p([{ role: "developer", content: "d" }, { role: "user", content: "u" }]), "responses"), false, "off-head developer stays clean"); + assert.equal(hasOffHeadSystem("{not json", "responses"), false, "unparseable body → no claim"); +}); diff --git a/tests/e2e-responses-offhead-system.test.ts b/tests/e2e-responses-offhead-system.test.ts new file mode 100644 index 0000000000..58db78afa4 --- /dev/null +++ b/tests/e2e-responses-offhead-system.test.ts @@ -0,0 +1,103 @@ +// #1996 — a client-origin mid-history role:"system" item on the Responses wire +// (OMP forwards host-compaction checkpoints verbatim; the plugin-mode +// position-preserving pass-through of #1638 keeps it in place) trips +// placement-strict Jinja backends (Qwen family served by vLLM/SGLang): +// "System message must be at the beginning." That error names no role, so the +// #552/#583 learn-on-failure ladder used to sit idle and every post-compression +// request 400-looped. This pins the #1996 entry path: the ladder fires from +// the placement marker plus the wire carrying the shape, repairs with one +// system→user hop, remembers it for the session, and turn 2 rides clean +// proactively. Hermetic (validation-parity fake upstream), always runs in CI. +import { test } from "node:test"; +import assert from "node:assert"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { once } from "node:events"; +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 { _resetPluginStateForTest } from "../src/plugin.ts"; +import { startFakeUpstream } from "./wire-contract-fakes.ts"; +import { rmrf } from "./tmp-rm.ts"; + +interface Item { + role?: string; + content?: string; +} + +function systemIdx(items: Item[]): number { + return items.findIndex((it) => it.role === "system"); +} + +test("e2e #1996: off-head client system on the Responses wire — one learn-on-failure repair, then clean", async () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "offhead-sys-test-")); + const prevXdg = process.env.XDG_STATE_HOME; + process.env.XDG_STATE_HOME = stateDir; + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetPluginStateForTest(); + const fake = await startFakeUpstream("responses"); + const proxy = await startServer({ + port: 0, host: "127.0.0.1", upstream: fake.url, + routes: { [fake.url]: { models: { "gpt-test": { context: 400_000 } } } }, + modelContextLimit: 400_000, + kernelConfig: defaultConfig(400_000), + compress: { injectTool: true, injectNudge: false }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, debug: false, passthrough: false, autoUpdate: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + const proxyPort = (proxy.address() as { port: number }).port; + const base = `http://127.0.0.1:${proxyPort}/bili/${fake.url}/v1/responses`; + const conv = `offhead-${Date.now().toString(36)}`; + const headers: Record = { + "content-type": "application/json", + "x-bili-plugin": "omp-plugin/0.0.1", + "x-bili-plugin-conversation": conv, + "x-acp-session": conv, + }; + try { + // OMP wire form: type-less items, a head developer prompt, and a + // mid-history role:"system" checkpoint — the #1996 offender shape. + const hist1: Item[] = [ + { role: "developer", content: "You are a helpful assistant." }, + { role: "user", content: "q1 tell me about compression" }, + { role: "system", content: "CONTEXT CHECKPOINT — early turns folded by host compaction." }, + { role: "assistant", content: "a1 compression keeps context lean" }, + { role: "user", content: "q2 and why does it help" }, + ]; + const res1 = await fetch(base, { method: "POST", headers, body: JSON.stringify({ model: "gpt-test", stream: true, input: hist1 }) }); + assert.equal(res1.status, 200, "client sees a transparent 200 after the learn-on-failure repair"); + await res1.arrayBuffer(); + + assert.equal(fake.requests.length, 2, "original forward + one repaired retry"); + const sent1 = fake.requests[0]!.body as { input: Item[] }; + assert.ok(systemIdx(sent1.input) >= 1, "bili forwards the client-origin system verbatim (faithful wire)"); + assert.ok(fake.violations.some((v) => v.includes("WC-014")), `fake recorded the WC-014 violation, got: ${JSON.stringify(fake.violations)}`); + const sent2 = fake.requests[1]!.body as { input: Item[] }; + assert.equal(systemIdx(sent2.input), -1, "retry carries zero literal system roles (system→user hop)"); + + // Turn 2: learned {system:user} applied proactively at egress — no + // second 400, no new violation. + const hist2: Item[] = [...hist1, { role: "assistant", content: "a2 it saves tokens" }, { role: "user", content: "q3 thanks" }]; + const res2 = await fetch(base, { method: "POST", headers, body: JSON.stringify({ model: "gpt-test", stream: true, input: hist2 }) }); + assert.equal(res2.status, 200); + await res2.arrayBuffer(); + assert.equal(fake.requests.length, 3, "turn 2 needed exactly one forward (learned mapping proactive)"); + assert.equal(fake.violations.filter((v) => v.includes("WC-014")).length, 1, "no second WC-014 violation"); + const sent3 = fake.requests[2]!.body as { input: Item[] }; + assert.equal(systemIdx(sent3.input), -1, "turn 2 rides clean"); + } finally { + proxy.closeAllConnections?.(); + await new Promise((resolve) => proxy.close(() => resolve())); + await fake.close(); + if (prevXdg === undefined) delete process.env.XDG_STATE_HOME; + else process.env.XDG_STATE_HOME = prevXdg; + rmrf(stateDir); + } +}); diff --git a/tests/wire-contract-fakes.ts b/tests/wire-contract-fakes.ts index 2befc55401..99446cd1ea 100644 --- a/tests/wire-contract-fakes.ts +++ b/tests/wire-contract-fakes.ts @@ -127,6 +127,14 @@ export const WIRE_RULES: readonly WireRule[] = [ provenance: "bili #1757 per-field measurement against SenseNova's Responses gateway https://token.sensenova.cn/v1/responses (2026-09-30): every pi-ai outbound field 200 except reasoning.summary → 400 code InvalidParameter; OpenAI Responses API reference (reasoning.effort is the only documented subfield)", }, + { + id: "WC-014", + wire: "responses", + summary: + "strict Jinja-template backends (Qwen family served by vLLM/SGLang) reject any role:\"system\" message that is not the first chat-producing item — or any second system — raising \"System message must be at the beginning.\" from chat_template.jinja; bili never emits such items itself (front block/anchors ride as developer, nudges/separators as user, top-level instructions stripped), so offenders are client-origin mid-history system items forwarded verbatim by the plugin-mode position-preserving pass-through (#1638); repair = learn-on-failure placement entry (src/compat-roles.ts hasOffHeadSystem → single system→user rewrite hop, remembered per session)", + provenance: + "bili #1996 production 400 (vLLM /v1/responses serving a Qwen model: artifact:chat_template.jinja Jinja Exception \"System message must be at the beginning.\", code invalid_prompt, every post-compression request of two OMP plugin-mode sessions, 2026-10-03); vLLM Responses→chat passes role-bearing items verbatim (vllm/entrypoints/openai/responses/utils.py _construct_message_from_response_item)", + }, ]; const ANTHROPIC_TOOL_NAME_RE = /^[a-zA-Z0-9_-]{1,128}$/; @@ -246,6 +254,35 @@ export function validateResponsesBody(body: unknown): string[] { // exists on bodies without tools. if (isPlainObject(body.reasoning) && "summary" in body.reasoning) out.push('WC-013 reasoning.summary is not part of the OpenAI Responses API — strict-schema upstreams 400 (json: unknown field "summary"); drop it via compat.dropFields (#1757)'); + // WC-014 (#1996): runs before the tools early-return — strict Jinja + // templates raise on any system message that is not the first + // chat-producing item, or on a duplicate system. Mirrors + // src/compat-roles.ts hasOffHeadSystem eligibility exactly; a non-empty + // top-level instructions becomes a leading system upstream. + if (Array.isArray(body.input)) { + const wc14RoleProducing = new Set([ + "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output", "reasoning", + ]); + const hasInstructions = typeof body.instructions === "string" && body.instructions.length > 0; + let systems = 0; + let firstSlotIdx = -1; + let firstSystemIdx = -1; + body.input.forEach((item, i) => { + if (!isPlainObject(item)) return; + const t = item.type; + const isMessage = t === undefined || t === "message"; + if (!isMessage && !wc14RoleProducing.has(t as string)) return; + if (firstSlotIdx < 0) firstSlotIdx = i; + if (isMessage && item.role === "system") { + systems++; + if (firstSystemIdx < 0) firstSystemIdx = i; + } + }); + if (systems > 1) + out.push(`WC-014 ${systems} system messages — strict Jinja templates: system messages must be at the beginning, exactly one (#1996)`); + else if (systems === 1 && (hasInstructions || firstSystemIdx !== firstSlotIdx)) + out.push(`WC-014 input[${firstSystemIdx}]: system message must be at the beginning (strict Jinja templates reject off-head system roles, #1996)`); + } if (!Array.isArray(body.tools)) return out; body.tools.forEach((t, i) => { if (!isPlainObject(t)) return; diff --git a/tests/wire-contract.test.ts b/tests/wire-contract.test.ts index c7fbf09b1c..060757f9e9 100644 --- a/tests/wire-contract.test.ts +++ b/tests/wire-contract.test.ts @@ -123,6 +123,7 @@ test("wire-contract ledger: every rule has a live enforcement clause", () => { { tools: [], input: [{ type: "function_call", id: "fc-1", call_id: "c1", name: "f", arguments: "{}" }] }, { input: [{ type: "configuration_update", reasoning: { effort: "medium" } }, { type: "configuration_update", reasoning: { effort: "high" } }] }, { model: "m", input: [], reasoning: { effort: "high", summary: "auto" } }, + { input: [{ role: "user", content: "u" }, { role: "system", content: "s" }] }, ], google: [ { tools: [{ functionDeclarations: [{ name: "bad-name", parameters: { type: "object", properties: {} } }] }] }, From 9453c7e7f485aab87715112eee2b149ee23092ff Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 4 Oct 2026 00:53:20 +0800 Subject: [PATCH 2/2] fix: repair pre-existing typecheck breakage in 4 test files (unblocks CI gate) --- tests/issue1993-preflight-400.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/issue1993-preflight-400.test.ts b/tests/issue1993-preflight-400.test.ts index c4d5398b24..fbe4edb4ef 100644 --- a/tests/issue1993-preflight-400.test.ts +++ b/tests/issue1993-preflight-400.test.ts @@ -14,7 +14,8 @@ process.env.BILI_REPLAY_RETRY_BASE_MS = "0"; process.env.BILI_PREFLIGHT_DEAD_END_COOLDOWN_MS = "400"; import { defaultConfig } from "acp-kernel"; -import { startServer, type ProxyOptions } from "../src/server.ts"; +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 { listSessions } from "../src/session.ts";