diff --git a/src/incremental-lane.ts b/src/incremental-lane.ts index e770bc4996..1a4505f3df 100644 --- a/src/incremental-lane.ts +++ b/src/incremental-lane.ts @@ -165,9 +165,6 @@ function warnDroppedRequestParams(conversationId: string, request: Record = { - "content-type": "application/json", - "content-length": String(bodyBuf.length), - host: headerValue(req, "host") ?? "127.0.0.1", - // Session identity rides the CLIENT's own conversation header (the - // strongest signal in the pipeline) — see laneSessionId(). - "x-bili-plugin": agent, - "x-bili-plugin-conversation": conversationId, - accept: headerValue(req, "accept") ?? "application/json", - }; + // Re-enter the pipeline (forward → handleRequest → buildForwardHeaders) with a + // synthetic indistinguishable from the ORIGINAL client request, so egress + // normalization is the SAME code that serves full-resend traffic (#5658). This + // mirrors the marker-divert replay (handle.ts): copy the client's own headers + // and drop only the lane-intent marker — do NOT hand-roll a strip list, which + // diverges from the proven non-incremental surface and risks upstream rejection. + // The only extra corrections are forced by the REBUILT body: its length, and the + // encoding marker (an assembled turn body is always plain JSON, so any inbound + // content-encoding is stale). Lane identity is stamped below. + const headers: Record = {}; + for (const [k, v] of Object.entries(req.headers)) { + if (v === undefined) continue; + const lower = k.toLowerCase(); + if (lower === INCREMENTAL_TURN_MARKER_HEADER.toLowerCase()) continue; + if (lower === "content-encoding") continue; + headers[k] = Array.isArray(v) ? v.join(", ") : v; + } + // Lane-owned values win, set explicitly (framing matches the assembled body; + // session identity rides the client's own conversation value — laneSessionId()). + headers["content-type"] = "application/json"; + headers["content-length"] = String(bodyBuf.length); + headers["host"] = headerValue(req, "host") ?? "127.0.0.1"; + headers["x-bili-plugin"] = agent; + headers["x-bili-plugin-conversation"] = conversationId; + headers["accept"] = headerValue(req, "accept") ?? "application/json"; // Plugin capability headers the client may contribute on the turn // POST (context window / max output reports for the [window] clamp). for (const h of ["x-bili-plugin-context-window", "x-bili-plugin-max-output"] as const) { const v = headerValue(req, h); if (v !== undefined) headers[h] = v; } - for (const h of PASSTHROUGH_HEADERS) { - const v = headerValue(req, h); - if (v !== undefined) headers[h] = v; - } if (model !== undefined) headers["x-bili-plugin-model"] = model; const synthetic = Readable.from([bodyBuf]) as unknown as http.IncomingMessage; diff --git a/src/server/headers.ts b/src/server/headers.ts index 217b660bbd..dd6bd69e78 100644 --- a/src/server/headers.ts +++ b/src/server/headers.ts @@ -33,6 +33,11 @@ export const UPSTREAM_HOP_HEADERS = new Set([ "x-bili-pf-count", "x-bili-pf-seq", "x-bili-pf-tail-ids", + // #5658: incremental-lane turn correlation id — the native plugin stamps it + // on a diverted model request alongside x-bili-plugin-turn to correlate the + // applied-seq ack. Pure host↔bili bookkeeping; like the pf-* handshake + // headers above it must never reach a model endpoint, so strip at egress. + "x-bili-turn-id", "te", "trailer", "upgrade", diff --git a/tests/e2e/e2e-native-pi.test.ts b/tests/e2e/e2e-native-pi.test.ts index e71682096d..7f0ee66eb3 100644 --- a/tests/e2e/e2e-native-pi.test.ts +++ b/tests/e2e/e2e-native-pi.test.ts @@ -458,6 +458,17 @@ function piRun( cwd: ctx.piCwd, env: { ...cleanEnv(), + // This suite documents the SPAWN-posture package-native contract: + // instance record + proxy origin, per-request wire stamps, the + // shared-proxy delegate-child ACP channel (#2268), /__bili/plugin/status + // over HTTP. #5428 flipped the pi lane DEFAULT to inline (in-process + // engine, no instance record) and this suite was not updated with it: + // primary-lane tests then pass for the wrong reason while the + // instance-record and delegate-child stamp assertions fail structurally + // (CI sentinel incident, #4599). Pin the legacy posture so this + // coverage stays deterministic; inline posture is covered by + // tests/pi-inline-ws.test.ts and tests/pi-native.test.ts. + BILI_PI_INLINE: "0", PI_CODING_AGENT_DIR: ctx.piAgentDir, XDG_CONFIG_HOME: ctx.xdg.config, XDG_CACHE_HOME: ctx.xdg.cache, diff --git a/tests/e2e/e2e-pi-codex-ws.test.ts b/tests/e2e/e2e-pi-codex-ws.test.ts index e73027ad06..a8df48ae7c 100644 --- a/tests/e2e/e2e-pi-codex-ws.test.ts +++ b/tests/e2e/e2e-pi-codex-ws.test.ts @@ -722,7 +722,14 @@ test("E: two subagent-style sessions share one proxy — distinct state, identic assert.ok(r.stdout.includes("WS_E2E_OK")); }; - ok("X warmup", await piRun(ctxX, "alpha marker ALPHA_X_SEED")); + // #5428 flipped the pi lane's DEFAULT posture to inline (in-process proxy): + // left unpinned, X's proxy would die with its pi process and unregister its + // instance record — nothing left to discover, nothing for Y to attach to. + // This scenario pins the legacy spawn/attach posture it was built on; + // scenarios A–D intentionally ride the new inline default. + const legacyPosture: NodeJS.ProcessEnv = { BILI_PI_INLINE: "0" }; + + ok("X warmup", await piRun(ctxX, "alpha marker ALPHA_X_SEED", { extraEnv: legacyPosture })); const origin = proxyOriginOf(ctxX); assert.ok(origin, "X's proxy origin discovered from its instance record"); // Y attaches to X's proxy (real subagent posture: inherited @@ -733,7 +740,7 @@ test("E: two subagent-style sessions share one proxy — distinct state, identic // Same tool args ({}) from both sessions, interleaved. const [xStatus, yStatus] = await Promise.all([ - piRun(ctxX, "WS_STATUS alpha status", { resume: true }), + piRun(ctxX, "WS_STATUS alpha status", { resume: true, extraEnv: legacyPosture }), piRun(ctxY, "WS_STATUS beta status", { resume: true, extraEnv: yEnv }), ]); ok("X status", xStatus); @@ -763,7 +770,7 @@ test("E: two subagent-style sessions share one proxy — distinct state, identic // Concurrent plain turns, same proxy, no cross-talk afterwards. const [xFin, yFin] = await Promise.all([ - piRun(ctxX, "concurrent X tail", { resume: true }), + piRun(ctxX, "concurrent X tail", { resume: true, extraEnv: legacyPosture }), piRun(ctxY, "concurrent Y tail", { resume: true, extraEnv: yEnv }), ]); ok("X concurrent", xFin); diff --git a/tests/event-loop-watchdog.test.ts b/tests/event-loop-watchdog.test.ts index e78045694d..1143518f8b 100644 --- a/tests/event-loop-watchdog.test.ts +++ b/tests/event-loop-watchdog.test.ts @@ -55,7 +55,15 @@ test("wedged main loop trips the watchdog: warn + fatal forensic lines land in t assert.ok(handle, "handle expected"); await sleep(50); // beats flowing — worker initialized blockMainLoop(400); // synchronous spin: zero heartbeats reach the worker - await sleep(80); // deliver the queued trip message + // Deliver the queued trip message. Poll to a bounded deadline instead + // of one fixed grace sleep: under runner load, worker init or the + // postMessage hop can land past any small fixed window without the + // mechanism breaking (#4762; same load-flake family as #4161 — the + // 2026-11-04 windows-latest/node-24 shard-4 red fired exactly this + // line on green code). A genuinely dead trip path still fails — after + // the full budget. + const tripDeadline = Date.now() + 3_000; + while (typeof trippedWith !== "number" && Date.now() < tripDeadline) await sleep(20); if (typeof trippedWith !== "number") throw new Error(`onTrip must fire after a continuous block past hardTimeoutMs (got ${String(trippedWith)})`); assert.ok(trippedWith >= 150, `gap ${trippedWith} must reach the hard threshold`); const content = fs.readFileSync(logFile, "utf8"); diff --git a/tests/issue5658-incremental-credential-headers.test.ts b/tests/issue5658-incremental-credential-headers.test.ts new file mode 100644 index 0000000000..06c3e2260b --- /dev/null +++ b/tests/issue5658-incremental-credential-headers.test.ts @@ -0,0 +1,151 @@ +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +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 { _resetPluginStateForTest } from "../src/plugin.ts"; +import { _resetSessionsForTest } from "../src/session.ts"; +import { _setForTest } from "../src/registry.ts"; +import { resetToolRingForTest } from "../src/tool-ring.ts"; +import { __resetIncrementalLaneForTests } from "../src/incremental-lane.ts"; + +// #5658: the delta lane rebuilt the outbound request with a positive header +// allowlist (authorization / anthropic-version / anthropic-beta), so any +// credential outside it — x-api-key above all — was silently dropped and the +// upstream answered 401 ("governor"), which DSH maps to an account sign-out. +// The fix forwards the client's own end-to-end headers (minus hop-by-hop and +// x-bili-* markers); these tests pin that credentials reach the upstream and +// lane markers do not. +process.env.NODE_ENV = "test"; +const testRoot = mkdtempSync(join(tmpdir(), "bili-incr-cred-")); +test.after(() => rmSync(testRoot, { recursive: true, force: true })); + +interface UpstreamHit { + headers: Record; + body: unknown; +} + +async function harness(): Promise<{ + proxyUrl: string; + turn: (extraHeaders: Record) => Promise; + markerTurn: (extraHeaders: Record) => Promise; + hits: UpstreamHit[]; + close: () => Promise; +}> { + const dir = mkdtempSync(join(testRoot, "run-")); + const savedRollout = process.env.BILI_ROLLOUT_PLUGIN_INCREMENTAL_TURNS; + for (const key of ["XDG_STATE_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME"]) process.env[key] = dir; + process.env.BILI_STORAGE_UNIFIED = "full"; + // The marker-divert entry gates on the pluginIncrementalTurns rollout feature. + process.env.BILI_ROLLOUT_PLUGIN_INCREMENTAL_TURNS = "1"; + _resetSessionsForTest(); + _resetPluginStateForTest(); + resetToolRingForTest(); + __resetIncrementalLaneForTests(); + const store = new SessionStore({ dir: dir + "/sessions", enabled: true, debounceMs: 60000 }); + _setStoreForTest(store); + _setForTest({}); + const hits: UpstreamHit[] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk: Buffer) => chunks.push(chunk)); + req.on("end", () => { + hits.push({ headers: req.headers, body: JSON.parse(Buffer.concat(chunks).toString("utf8")) }); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ id: "msg_test", role: "assistant", content: [{ type: "text", text: "answer" }], usage: { input_tokens: 10000, output_tokens: 10 } })); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const addr = upstream.address(); + assert(addr && typeof addr === "object"); + const upstreamUrl = `http://127.0.0.1:${addr.port}`; + const proxy = await startServer({ port: 0, host: "127.0.0.1", upstream: upstreamUrl, routes: { [upstreamUrl]: { models: { "claude-test": { context: 400000 } } } }, modelContextLimit: 400000, kernelConfig: defaultConfig(400000), 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); + if (!(proxy as unknown as { listening?: boolean }).listening) await once(proxy, "listening"); + const proxyUrl = `http://127.0.0.1:${(proxy.address() as { port: number }).port}`; + const path = "/v1/messages"; + const seedBody = { conversationId: "conv-cred", sinceSeq: 0, path, request: { model: "claude-test", max_tokens: 1024 }, messages: [{ role: "user", content: "hello" }] }; + // Direct /__bili/plugin/turn entry: the client carries its credentials on the + // turn POST exactly as it would on a full-resend request. + const turn = async (extraHeaders: Record): Promise => { + const response = await fetch(`${proxyUrl}/__bili/plugin/turn`, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": "conv-cred", ...extraHeaders }, + body: JSON.stringify(seedBody), + }); + return response.status; + }; + // Marker-divert entry: shaped turn posted on the ORDINARY model path with the + // x-bili-plugin-turn marker — the marker must NOT reach the upstream. + const markerTurn = async (extraHeaders: Record): Promise => { + const response = await fetch(`${proxyUrl}${path}`, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": "conv-cred-marker", "x-acp-session": "conv-cred-marker", "x-bili-plugin-turn": "1", ...extraHeaders }, + body: JSON.stringify({ conversationId: "conv-cred-marker", sinceSeq: 0, request: { model: "claude-test", max_tokens: 1024 }, messages: [{ role: "user", content: "hello" }] }), + }); + return response.status; + }; + const close = async (): Promise => { + if (savedRollout === undefined) delete process.env.BILI_ROLLOUT_PLUGIN_INCREMENTAL_TURNS; + else process.env.BILI_ROLLOUT_PLUGIN_INCREMENTAL_TURNS = savedRollout; + await new Promise((resolve) => proxy.close(() => resolve())); + store.closeQuietly(); + await new Promise((resolve) => upstream.close(() => resolve())); + }; + return { proxyUrl, turn, markerTurn, hits, close }; +} + +const CREDENTIALS: [string, string][] = [ + ["authorization", "Bearer TEST-AUTH"], + ["x-api-key", "sk-TEST-XAPIKEY"], + ["x-goog-api-key", "goog-TEST"], + ["api-key", "vendor-TEST"], +]; + +function hitHasCredential(h: UpstreamHit, name: string, value: string): boolean { + const v = h.headers[name.toLowerCase()]; + return v === value || (Array.isArray(v) && v.includes(value)); +} + +test("#5658 direct turn: every credential header reaches the upstream, no x-bili marker leaks", async () => { + const h = await harness(); + try { + const status = await h.turn({ ...Object.fromEntries(CREDENTIALS), "x-custom-gateway": "gw-TEST", "x-bili-turn-id": "turn-direct-TEST" }); + assert.equal(status, 200); + assert.equal(h.hits.length, 1); + const hit = h.hits[0]; + for (const [name, value] of CREDENTIALS) { + assert.ok(hitHasCredential(hit, name, value), `credential header ${name} must reach the upstream`); + } + // Full-resend parity (#5658): the lane forwards the client's OWN end-to-end + // headers verbatim (buildForwardHeaders downstream), never an allowlist — an + // arbitrary non-credential client header must ride through as well. + assert.ok(hitHasCredential(hit, "x-custom-gateway", "gw-TEST"), "an arbitrary client end-to-end header must reach the upstream"); + assert.equal(hit.headers["x-bili-turn-id"] ?? null, null, "lane turn-id bookkeeping must not be forwarded verbatim"); + } finally { + await h.close(); + } +}); + +test("#5658 marker divert: credentials reach the upstream, x-bili-plugin-turn marker is stripped", async () => { + const h = await harness(); + try { + const status = await h.markerTurn({ ...Object.fromEntries(CREDENTIALS), "x-bili-turn-id": "turn-divert-TEST" }); + assert.equal(status, 200); + assert.equal(h.hits.length, 1); + const hit = h.hits[0]; + for (const [name, value] of CREDENTIALS) { + assert.ok(hitHasCredential(hit, name, value), `credential header ${name} must reach the upstream`); + } + assert.equal(hit.headers["x-bili-plugin-turn"] ?? null, null, "the divert marker must never ride onto the upstream request"); + assert.equal(hit.headers["x-bili-turn-id"] ?? null, null, "lane turn-id bookkeeping must not be forwarded verbatim"); + } finally { + await h.close(); + } +}); diff --git a/tests/wire-exit-matrix.test.ts b/tests/wire-exit-matrix.test.ts index 6611f3156b..71d66dc2d4 100644 --- a/tests/wire-exit-matrix.test.ts +++ b/tests/wire-exit-matrix.test.ts @@ -35,14 +35,53 @@ const SLOW_MS = 1500; // Raised to 10s after 6s still flaked three consecutive runs on windows-latest // node22 shard 2 (master c78ecb4b + ci-fixes c49bf8b1/12b988ff, all closed=0, // same cell, sibling shards green — load latency, not a teardown regression; -// recorded under #4599). If it flakes again at 10s, investigate a real teardown -// hang instead of raising further. -const ABORT_TEARDOWN_BUDGET_MS = 10000; +// recorded under #4599). Flaked once more at 10s (master 9dc4c945, run +// 41686972484, 2026-11-03: openai-sse + anthropic-sse closed=0 after the full +// poll, ~11s each; same code green on the ubuntu22/24 and windows24 shard-2 +// siblings, pass durations 23–352ms). The mandated "investigate a real +// teardown hang" audit found none: relay.ts arms res.on("close") -> +// clientAbort.abort() synchronously with no linger/backstop on this path, and +// no commit since d244ffff touched destroy/abort wiring — the residual latency +// is runner-side event-loop starvation on loaded Windows runners. Hence a +// platform-scoped budget instead of another flat raise: win32 doubles to 20s +// (every recorded starvation instance was windows-latest — node22+24, multiple +// shards, #3665/#4347 era — ubuntu never showed the signature), keeping the +// tight 10s gate everywhere else so a genuine teardown hang still fails fast. +// Flaked once more at 20s (ci-fixes c37293b6, run 41776902208, 2026-11-04: +// openai-sse closed=0 after the full poll, duration 20518ms; anthropic/ +// responses/json siblings 131–410ms in the same run; master main CI green +// 40min earlier at 23a826d3 — same load-starvation draw, not a regression). +// That closes out the flat-raise ladder: the poller and the upstream mock +// share ONE event loop with whatever is starving the runner, so a close event +// cannot be delivered faster than the loop itself — an absolute wall-clock +// budget measures the runner, not the teardown. The budget is therefore +// extended by the poll's OWN measured event-loop lag (each tick that lands +// late adds its lateness), capped at 2×base so a genuine hang still fails: on +// a healthy loop the gate stays byte-for-byte the flat budget (zero +// extension); under starvation the window grows with the measured lag up to +// 2×base (win32: 20s base ⇒ ≤40s — the same ceiling a flat 40s raise would +// give unconditionally, applied only when lag is actually observed). Same +// relative-invariant discipline as the #3228/#3152-C error-delivery cells. +const ABORT_TEARDOWN_BUDGET_MS = process.platform === "win32" ? 20000 : 10000; +const TEARDOWN_POLL_MS = 100; + +/** May the teardown poll keep going? base + measured event-loop lag, capped + * at 2×base — see the budget comment above for the starvation mechanics. */ +function teardownPollContinues(elapsedMs: number, baseMs: number, lagMs: number): boolean { + return elapsedMs < baseMs + Math.min(lagMs, baseMs); +} async function awaitUpstreamTeardown(socketsClosed: () => number): Promise { - const deadline = Date.now() + ABORT_TEARDOWN_BUDGET_MS; - while (socketsClosed() < 1 && Date.now() < deadline) { - await new Promise((r) => setTimeout(r, 100)); + const base = ABORT_TEARDOWN_BUDGET_MS; + const t0 = Date.now(); + let lagMs = 0; + let last = t0; + while (socketsClosed() < 1 && teardownPollContinues(Date.now() - t0, base, lagMs)) { + await new Promise((r) => setTimeout(r, TEARDOWN_POLL_MS)); + const now = Date.now(); + const lateBy = now - last - TEARDOWN_POLL_MS; + if (lateBy > 0) lagMs += lateBy; + last = now; } } @@ -393,3 +432,13 @@ test("error-delivery x proxy-openai-sse: preflight failure after the early commi await once(up.server, "close"); } }); + +test("abort x teardown-budget arithmetic: measured lag extends the window, capped at 2×base", () => { + const base = 10_000; + assert.equal(teardownPollContinues(9_999, base, 0), true, "healthy loop: inside the flat budget"); + assert.equal(teardownPollContinues(10_000, base, 0), false, "healthy loop: boundary unchanged (zero lag ⇒ old flat gate byte-for-byte)"); + assert.equal(teardownPollContinues(12_000, base, 5_000), true, "measured event-loop lag extends the window"); + assert.equal(teardownPollContinues(15_000, base, 5_000), false, "extension equals the measured lag, no more"); + assert.equal(teardownPollContinues(19_999, base, 999_999), true, "runaway lag cannot push the window past 2×base"); + assert.equal(teardownPollContinues(20_000, base, 999_999), false, "hard ceiling at 2×base guarantees termination"); +});