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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions src/compat-roles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>;
try {
parsed = JSON.parse(body) as Record<string, unknown>;
} 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<string, unknown>;
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",
Expand Down
28 changes: 24 additions & 4 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand All @@ -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 => {
Expand Down Expand Up @@ -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");
}
}
}
}
Expand Down
42 changes: 41 additions & 1 deletion tests/compat-roles.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -516,3 +516,43 @@ async function waitFor(probe: () => boolean, deadlineMs = 3000): Promise<void> {
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<string, unknown> = {}) => 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");
});
103 changes: 103 additions & 0 deletions tests/e2e-responses-offhead-system.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = {
"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<void>((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);
}
});
3 changes: 2 additions & 1 deletion tests/issue1993-preflight-400.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Loading
Loading