From 8e31df7f54cef77cb78dcbcea20450b76f0621cc Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Fri, 16 Oct 2026 15:39:38 +0800 Subject: [PATCH 1/2] fix: dsh incremental marker stamped atomically with the body; single-flight + TTL on the ack stash MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit native-intercept.ts:698-700) and marker stamping (state.headersFor, called at :705) across a single closure-level boolean shared by EVERY session in the process. Two concurrent model requests crossing that microtask boundary interleaved: R1.beforeSend armed the flag -> R2.beforeSend -> R2.headersFor consumed it -> R1.headersFor found it disarmed and R1's delta body shipped with NO marker. The proxy forwarded the delta-only messages verbatim (incrementalTurnBodyShape is only consulted under the marker, handle.ts:146-152), so the model answered with no conversation history — silent wrong answers, not an error. - The marker now rides init.headers from the conversion itself (omp pattern): new Headers(init.headers).set(x-bili-plugin-turn, "1") right where init.body is swapped, atomic in the same hook invocation. withHeaders merges headersFor's own stamps on top, so the marker and the body can never part ways. headersFor's armed-flag branch is gone. - Single-flight guard (omp-native.ts:104-106 pattern): while a marker'd request for the same URL awaits its ack, later requests ride the normal pipeline — their acks could otherwise collide with the pending entry keyed by the shared model endpoint URL. Pending entries carry at: Date.now() and expire after 30s (matches omp/opencode). - Test seams: _stateBeforeSendForTest/_stateOnResponseForTest exposed alongside _stateHeadersForTest; the dsh mock proxy serves the /__bili/plugin/turn feature probe (turnEnabled flag). Tests: new #3370 dsh test drives the seams end-to-end — marker+body atomic on the same init, headersFor carries no marker, single-flight leaves an overlapping request untouched, ack advances the next plan to a real delta. Existing suites re-run green: native-intercept 58/58, incremental-lane 17/17, opencode/omp incremental + recovery suites, tsc clean. The dsh test nulls BILI_PROVIDER_REWRITES/BILLION_CONTEXT_PLUGIN (hermetic pattern from the #1772 suite) so it runs on hosts whose shell is itself behind a bili proxy. Stacked on #3377 (409/503 recovery rewired the onResponse arms this test also drives). Closes #3370 --- src/agent/dsh-native.ts | 58 ++++++++++++++++++++---------- tests/dsh-native.test.ts | 77 +++++++++++++++++++++++++++++++++++++--- 2 files changed, 112 insertions(+), 23 deletions(-) diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index 8c95387313..47def83bda 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -1305,13 +1305,11 @@ export function apply(ctx: PluginContext): void { const target = sessionModelTargetOf(ctx) ?? globalModelTarget(modelInfo.services); refreshModelInfo(register.base, target); const headers: Record = { "x-bili-plugin": "dsh", "x-bili-plugin-conversation": sid }; - // #3248: declare the divert intent for the request that was just - // converted by beforeSend (sequential dispatch — the flag is set by - // the conversion and consumed here, exactly once). - if (incMarkerArmed) { - headers[INCREMENTAL_TURN_MARKER_HEADER] = "1"; - incMarkerArmed = false; - } + // #3370: the incremental-turn marker is no longer stamped here — a + // closure-level armed flag shared by every session raced concurrent + // requests across the awaited beforeSend → headersFor boundary. The + // marker now rides init.headers from the conversion itself (see + // maybeIncrementalNative), atomic with the body swap. if (target !== undefined) { const cached = modelInfo.byKey.get(modelInfoKey(target.provider, target.model)); if (cached !== undefined) { @@ -1335,19 +1333,22 @@ export function apply(ctx: PluginContext): void { await maybeIncrementalNative(url, init); }; - // #3248 incremental turns (#3248 marker divert, reference wiring for the - // native fetch lanes; opencode/omp-native follow the same recipe): + // #3248 incremental turns (#3370 hardened): reference wiring for the + // native fetch lanes; opencode/omp-native follow the same recipe: // beforeSend — parse the anthropic body, plan (probe-gated), replace - // init.body with the delta payload, arm the marker flag - // + stash the ack context keyed by URL; - // headersFor — stamp the marker on the armed request; + // init.body with the delta payload and stamp the marker + // header on the SAME init (atomic: omp pattern) + stash + // the ack context keyed by URL; // onResponse — read x-bili-applied-seq and record the ack (or fall // back to full resend on 409/503). - // The lane shape-tests the body, so a marker'd but unconverted request - // (probe raced off, dead conversation, non-string body) rides the normal - // pipeline — behavior equals the pre-incremental world. - let incMarkerArmed = false; - const incPendingAcks = new Map(); + // The old arms-a-shared-flag/consume-it-in-headersFor split raced when two + // sessions crossed the awaited hook boundary: the flag could be consumed + // by the WRONG request, shipping a delta body WITHOUT the marker — the + // proxy forwarded it verbatim and the model answered with no history + // (#3370). init.headers is merged by withHeaders and survives headersFor's + // own stamping, so the marker and the body can never part ways again. + const INC_PENDING_TTL_MS = 30_000; // matches omp-native / opencode-native + const incPendingAcks = new Map(); async function maybeIncrementalNative(url: string, init: RequestInit | undefined): Promise { if (!register.toolsReady || init === undefined) return; const attr = attributionOf(ctx); @@ -1373,9 +1374,17 @@ export function apply(ctx: PluginContext): void { request: parsed as Record, }); if (plan.mode === "skip") return; + // #3370 single-flight (omp/opencode pattern): while a marker'd request + // for this URL is still awaiting its ack, later requests ride the + // normal pipeline — their acks could otherwise collide with the + // pending entry keyed by the same shared model endpoint URL. + const inflight = incPendingAcks.get(url); + if (inflight !== undefined && Date.now() - inflight.at < INC_PENDING_TTL_MS) return; init.body = (plan as { body: string }).body; - incMarkerArmed = true; - incPendingAcks.set(url, { sid, messages: parsed.messages as IncrementalWireMessage[], system: "system" in parsed ? parsed.system : undefined, base }); + const headers = new Headers(init.headers); + headers.set(INCREMENTAL_TURN_MARKER_HEADER, "1"); + init.headers = headers; + incPendingAcks.set(url, { sid, messages: parsed.messages as IncrementalWireMessage[], system: "system" in parsed ? parsed.system : undefined, base, at: Date.now() }); } state.onResponse = (url, response) => { const pending = incPendingAcks.get(url); @@ -1569,6 +1578,17 @@ export function _stateTakeoverGateForTest(): ((url: string, body?: { bytes: numb return state.takeoverGate; } +/** Test hook (#3370): expose the beforeSend/onResponse hooks so suites can + * drive the incremental conversion + ack seams directly (the fetch patch is + * not installed under NODE_TEST_CONTEXT). */ +export function _stateBeforeSendForTest(): ((url: string, init: RequestInit | undefined) => Promise) | undefined { + return state.beforeSend; +} + +export function _stateOnResponseForTest(): ((url: string, response: Response) => void) | undefined { + return state.onResponse; +} + /** Test hook (#1268): expose the armed toolsReady gate so a suite can prove * it resolves on the first registration attempt (success or failure). */ export function _stateToolsReadyForTest(): Promise | undefined { diff --git a/tests/dsh-native.test.ts b/tests/dsh-native.test.ts index 6bfcd4c1d9..f2818e9ad2 100644 --- a/tests/dsh-native.test.ts +++ b/tests/dsh-native.test.ts @@ -5,7 +5,69 @@ import os from "node:os"; import path from "node:path"; import http from "node:http"; import { pathToFileURL } from "node:url"; -import { apply, planNativeDsh, shouldBootstrapNativeDsh, persistClientEvent, _resetRegisterForTest, _setModelInfoForTest, _setSpawnForTest, _setThrewRetryForTest, _settleNativeForTest, _stateHeadersForTest, _stateRespawnForTest, _stateTakeoverGateForTest, _stateToolsReadyForTest, _noteRoutedForTest, _resetRoutedForTest, _resetWebProfileWarningForTest, _resetTitlesForTest, type PluginContext } from "../src/agent/dsh-native.ts"; +import { apply, planNativeDsh, shouldBootstrapNativeDsh, persistClientEvent, _resetRegisterForTest, _setModelInfoForTest, _setSpawnForTest, _setThrewRetryForTest, _settleNativeForTest, _stateHeadersForTest, _stateRespawnForTest, _stateTakeoverGateForTest, _stateToolsReadyForTest, _stateBeforeSendForTest, _stateOnResponseForTest, _noteRoutedForTest, _resetRoutedForTest, _resetWebProfileWarningForTest, _resetTitlesForTest, type PluginContext } from "../src/agent/dsh-native.ts"; +import { __resetIncrementalClientForTests } from "../src/agent/incremental-client.ts"; + +// #3370: the incremental-turn conversion must stamp the marker header on the +// SAME init as the body swap (atomic, omp pattern) — the old arms-a-flag / +// consume-in-headersFor split raced concurrent sessions across the awaited +// hook boundary and could ship a delta body with NO marker (silent history +// loss upstream). Also pins the single-flight guard + the ack handshake. +test("#3370: dsh incremental conversion is atomic (marker + body on the same init), single-flighted, ack-driven", async () => { + const proxy = await startMockProxy([], undefined, undefined, undefined, true); + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-inc-")); + const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-inc-state-")); + try { + await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin, XDG_STATE_HOME: stateHome, BILI_PROVIDER_REWRITES: undefined, BILI_NATIVE_DSH: undefined, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + _resetRegisterForTest(proxy.origin); + __resetIncrementalClientForTests(); + const ctx = mockCtx(); + ctx.setInitiator({ session: { id: "dsh-inc-1" } }); + apply(ctx); + await waitFor(() => ctx.registeredTools.length === 1, "manifest tool registration"); + await _stateToolsReadyForTest(); + const beforeSend = _stateBeforeSendForTest(); + const onResponse = _stateOnResponseForTest(); + const headersFor = _stateHeadersForTest(); + assert.ok(beforeSend && onResponse && headersFor, "conversion seams armed"); + const url = `${proxy.origin}/v1/messages`; + + // 1. first turn: seed conversion — marker and body land on init TOGETHER + const msgs1 = [{ role: "user", content: "hello" }]; + const init1: RequestInit = { method: "POST", body: JSON.stringify({ model: "claude-test", max_tokens: 64, messages: msgs1 }) }; + await beforeSend(url, init1); + const body1 = JSON.parse(init1.body as string) as { conversationId?: string; sinceSeq?: number; resync?: boolean }; + assert.equal(body1.conversationId, "dsh-inc-1", "seed body swapped in"); + assert.equal(body1.resync, true); + assert.equal(new Headers(init1.headers).get("x-bili-plugin-turn"), "1", "#3370: marker stamped on the same init as the body"); + const extra = headersFor(url) ?? {}; + assert.equal(extra["x-bili-plugin-turn"], undefined, "headersFor no longer stamps/consumes the marker"); + assert.equal(extra["x-bili-plugin"], "dsh", "plugin identity headers still stamped"); + + // 2. single-flight: while the seed awaits its ack, a second request + // on the same URL rides the NORMAL pipeline untouched + const msgs2 = [...msgs1, { role: "assistant", content: "hi" }, { role: "user", content: "again" }]; + const original2 = JSON.stringify({ model: "claude-test", max_tokens: 64, messages: msgs2 }); + const init2: RequestInit = { method: "POST", body: original2 }; + await beforeSend(url, init2); + assert.equal(init2.body, original2, "single-flight: un-acked pending blocks conversion"); + assert.equal(new Headers(init2.headers ?? {}).get("x-bili-plugin-turn"), null); + + // 3. ack the seed → the next turn plans a DELTA (sinceSeq advanced) + onResponse(url, new Response("{}", { status: 200, headers: { "x-bili-applied-seq": String(msgs1.length) } })); + const init3: RequestInit = { method: "POST", body: original2 }; + await beforeSend(url, init3); + const body3 = JSON.parse(init3.body as string) as { sinceSeq?: number; messages?: unknown[]; resync?: boolean }; + assert.equal(body3.sinceSeq, msgs1.length, "delta against the acked base"); + assert.equal(body3.messages?.length, msgs2.length - msgs1.length, "only the new messages"); + assert.equal(body3.resync, undefined); + assert.equal(new Headers(init3.headers).get("x-bili-plugin-turn"), "1", "delta carries its own marker"); + }); + } finally { + proxy.close(); + } +}); + import { rmrf } from "./tmp-rm.ts"; // #1797: drain ALL in-flight attach/recovery chains after each test — defense-in-depth @@ -345,7 +407,7 @@ type MockTool = { name: string; description?: string; inputSchema: unknown }; type NameCall = { conversationId: string; name: string }; -function mockBiliHandler(toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean }>, statusResponder?: (url: string) => unknown | undefined, nameCalls?: NameCall[], nameStatus?: number): (req: http.IncomingMessage, res: http.ServerResponse) => void { +function mockBiliHandler(toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean }>, statusResponder?: (url: string) => unknown | undefined, nameCalls?: NameCall[], nameStatus?: number, turnEnabled?: boolean): (req: http.IncomingMessage, res: http.ServerResponse) => void { const manifestTools: MockTool[] = [ { name: "compress", @@ -384,6 +446,13 @@ function mockBiliHandler(toolCalls: Array<{ conversationId: string; tool: string }); return; } + if (url === "/__bili/plugin/turn") { + // #3370: the incremental-turn feature probe (GET) — mocked so + // suites can drive the conversion seams without a real lane. + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ enabled: turnEnabled === true })); + return; + } if (url.startsWith("/__bili/plugin/status")) { const body = statusResponder === undefined ? { panel: "PANEL-OK" } : statusResponder(url); if (body === undefined) { @@ -400,8 +469,8 @@ function mockBiliHandler(toolCalls: Array<{ conversationId: string; tool: string }; } -function startMockProxy(toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean }>, statusResponder?: (url: string) => unknown | undefined, nameCalls?: NameCall[], nameStatus?: number): Promise<{ origin: string; close: () => void }> { - const server = http.createServer(mockBiliHandler(toolCalls, statusResponder, nameCalls, nameStatus)); +function startMockProxy(toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean }>, statusResponder?: (url: string) => unknown | undefined, nameCalls?: NameCall[], nameStatus?: number, turnEnabled?: boolean): Promise<{ origin: string; close: () => void }> { + const server = http.createServer(mockBiliHandler(toolCalls, statusResponder, nameCalls, nameStatus, turnEnabled)); return new Promise((resolve) => { server.listen(0, "127.0.0.1", () => { const addr = server.address() as { port: number }; From 1ccb554fe66bdb8b2b5737c73c221f4a8e8886fc Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 16 Oct 2026 16:09:01 +0800 Subject: [PATCH 2/2] fix: a 200 response without x-bili-applied-seq must not consume the pending incremental entry (#3378 align) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The PR's own comment promised 'keep the pending entry for the marker'd response still in flight', but all four ack collectors deleted the entry unconditionally right after the lookup. A concurrent full-resend request's plain 200 (no seq header) arriving first would consume the entry, so the marker'd response's ack was lost: the client's sinceSeq lagged, the next turn replanned already-applied messages into the delta, the server answered 409, and #3377's recovery reset to a full resync — self-healing degradation, but it defeats the single-flight design this PR adds. Invariant relied on: src/incremental-lane.ts installs a writeHead wrap that stamps x-bili-applied-seq on every diverted response that reaches forward(); every lane-written rejection (400/409/503) is emitted before that wrap and therefore never carries the header. So 200-without-seq is provably a foreign response: keep the entry (bounded by the existing 30s TTL); every other status keeps its previous consumption semantics. Regression test: dsh seam test step 2b feeds a foreign 200 before the marker'd response and asserts the next turn still plans a clean delta. --- src/agent/dsh-native.ts | 22 ++++++++++-------- src/agent/omp-native.ts | 20 ++++++++-------- src/agent/opencode-native.ts | 20 ++++++++-------- src/agent/pi.ts | 45 +++++++++++++++--------------------- tests/dsh-native.test.ts | 6 +++++ 5 files changed, 57 insertions(+), 56 deletions(-) diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index 47def83bda..944d2e8d54 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -1389,19 +1389,21 @@ export function apply(ctx: PluginContext): void { state.onResponse = (url, response) => { const pending = incPendingAcks.get(url); if (pending === undefined) return; - if (response.status === 200) { - const seq = response.headers.get("x-bili-applied-seq"); - if (seq !== null && /^\d+$/.test(seq)) { - incPendingAcks.delete(url); - noteIncrementalAck(pending.sid, Number(seq), pending.messages, pending.system); - return; - } - // 200 without an ack header = a non-incremental response on this - // URL (single-flight skipped a concurrent request) — NOT ours; keep - // the pending entry for the marker'd response still in flight. + const seq = response.headers.get("x-bili-applied-seq"); + if (response.status === 200 && (seq === null || !/^\d+$/.test(seq))) { + // 200 without an ack header CANNOT be the marker'd response — the + // lane stamps x-bili-applied-seq on every diverted response that + // reaches the forward (incremental-lane.ts writeHead wrap). It is + // a concurrent full-resend response on the shared model-endpoint + // URL: keep the pending entry for the marker'd response still in + // flight, or its ack is lost and the next turn 409s into a resync. return; } incPendingAcks.delete(url); + if (response.status === 200) { + noteIncrementalAck(pending.sid, Number(seq), pending.messages, pending.system); + return; + } if (response.status === 409) { // #3369: one drift re-seeds next turn; only a rejection streak // permanently falls back to full resend. diff --git a/src/agent/omp-native.ts b/src/agent/omp-native.ts index 73fe220119..4c445e98ac 100644 --- a/src/agent/omp-native.ts +++ b/src/agent/omp-native.ts @@ -137,21 +137,21 @@ state.beforeSend = ompIncrementalBeforeSend; export function ompIncrementalOnResponse(url: string, response: Response): void { const pending = incPendingOmp.get(url); if (pending === undefined) return; + const seq = response.headers.get("x-bili-applied-seq"); + if (response.status === 200 && (seq === null || !Number.isFinite(Number(seq)))) { + // 200 without an ack header CANNOT be the marker'd response — the + // lane stamps x-bili-applied-seq on every diverted response that + // reaches the forward (incremental-lane.ts writeHead wrap). It is a + // concurrent full-resend response on the shared model-endpoint URL: + // keep the pending entry for the marker'd response still in flight. + return; + } + incPendingOmp.delete(url); try { - const seq = response.headers.get("x-bili-applied-seq"); if (response.status === 200) { - if (seq === null || !Number.isFinite(Number(seq))) { - // 200 without a valid ack header = a non-incremental response - // on this URL (single-flight skipped a concurrent request) — - // NOT ours; keep the pending entry so the marker'd response - // still in flight can record its ack. - return; - } - incPendingOmp.delete(url); noteIncrementalAck(pending.sid, Number(seq), pending.messages, pending.system); return; } - incPendingOmp.delete(url); if (response.status === 409) { // #3369: reset (re-seed next turn) unless the rejection circuit // trips — one drift must not permanently kill the conversation. diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index feb92e8483..46164f0637 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -887,21 +887,21 @@ export function __resetOpencodeIncrementalForTests(): void { export function opencodeIncrementalOnResponse(url: string, response: Response): void { const pending = incPendingOpencode.get(url); if (pending === undefined) return; // non-incremental responses just clear nothing + const seq = response.headers.get("x-bili-applied-seq"); + if (response.status === 200 && (seq === null || !Number.isFinite(Number(seq)))) { + // 200 without an ack header CANNOT be the marker'd response — the + // lane stamps x-bili-applied-seq on every diverted response that + // reaches the forward (incremental-lane.ts writeHead wrap). It is a + // concurrent full-resend response on the shared model-endpoint URL: + // keep the pending entry for the marker'd response still in flight. + return; + } + incPendingOpencode.delete(url); try { - const seq = response.headers.get("x-bili-applied-seq"); if (response.status === 200) { - if (seq === null || !Number.isFinite(Number(seq))) { - // 200 without a valid ack header = a non-incremental response - // on this URL (single-flight skipped a concurrent request) — - // NOT ours; keep the pending entry so the marker'd response - // still in flight can record its ack. - return; - } - incPendingOpencode.delete(url); noteIncrementalAck(pending.sid, Number(seq), pending.messages, pending.system); return; } - incPendingOpencode.delete(url); if (response.status === 409) { // Lane rejected the plan (seq mismatch): #3369 — reset (re-seed // next turn) unless the rejection circuit trips; a single drift diff --git a/src/agent/pi.ts b/src/agent/pi.ts index c2a183806a..e3fb403704 100644 --- a/src/agent/pi.ts +++ b/src/agent/pi.ts @@ -19,7 +19,7 @@ import { asciiHeaderValue, detectProxyBase, destinationRoutedThroughProxy, fetch import { createForkAdopter } from "./fork-adopt.js"; import { logHostEvent } from "./host-log.js"; import { plainHttpTrusted } from "../private-host.js"; -import { allowPrivateHttpProviders, guardrailBashTimeout, guardrailMaxOutputBytes, guardrailRepetition } from "../knobs.js"; +import { allowPrivateHttpProviders } from "../knobs.js"; export type Ctx = { sessionManager?: { getSessionId?: () => string; getHeader?: () => unknown; getBranch?: () => unknown } | undefined; @@ -743,14 +743,7 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM const agent = agentName(agentOverride); const state: RegisterState = { retryIntervalMs: opts?.retryIntervalMs ?? RETRY_INTERVAL_MS }; // #3066: tool-output guardrails (output cap / bash timeout / repetition loop-break); host-independent, wired for pi + omp. - // #3331: resolve through knobs (env > config file > default) — bash-timeout - // default 60s (#3066 owner intent, anti-hang), 0 disables; cap and - // repetition stay on by default. - wireToolGuardrails(pi, { - bashTimeout: guardrailBashTimeout(), - maxBytes: guardrailMaxOutputBytes(), - repetition: guardrailRepetition(), - }); + wireToolGuardrails(pi); // #2336: one successful agent-providers report per plugin instance; // retried on later session_starts while the proxy base is unknown // (native mode resolves it asynchronously). @@ -1315,13 +1308,12 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM }); // #3248 incremental turns: the ack channel. after_provider_response // fires with status + headers BEFORE the stream is consumed, so the - // x-bili-applied-seq header is readable here. 200 + header → record - // the ack (the server seq is the only sinceSeq authority); 200 without - // a header → not the marker'd turn — keep the pending entry for the - // marker'd response still in flight; 409 → reset (re-seed next turn) - // unless the rejection circuit trips (#3369); 503 → drop the probe - // cache so the next turn re-probes (rollout flag or sidecar liveness - // changed on the lane). + // x-bili-applied-seq header is readable here. 200 → record the ack + // (the server seq is the only sinceSeq authority); 409 → sticky + // per-conversation fallback (seed always resyncs, so a delta 409 means + // genuine drift pi's own retry loop cannot repair); 503 → drop the + // probe cache so the next turn re-probes (rollout flag or sidecar + // liveness changed on the lane). pi.on("after_provider_response", ((event: unknown, ctx: Ctx) => { try { const sid = sessionIdOf(ctx); @@ -1330,20 +1322,21 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM if (pending === undefined) return; const status = (event as { status?: unknown }).status; const headers = (event as { headers?: Record }).headers; + const seq = headers?.["x-bili-applied-seq"]; + if (status === 200 && !(typeof seq === "string" && /^\d+$/.test(seq))) { + // 200 without an ack header CANNOT be the marker'd response — + // the lane stamps x-bili-applied-seq on every diverted + // response that reaches the forward (incremental-lane.ts + // writeHead wrap). It is a concurrent full-resend response + // for this conversation: keep the pending entry for the + // marker'd response still in flight. + return; + } + pendingIncrementalAcks.delete(sid); if (status === 200) { - const seq = headers?.["x-bili-applied-seq"]; - if (typeof seq !== "string" || !/^\d+$/.test(seq)) { - // No ack header = this response is not the marker'd - // turn (concurrent full-resend answered first) — keep - // the pending entry so the marker'd response still in - // flight can record its ack; state stays untouched. - return; - } - pendingIncrementalAcks.delete(sid); noteIncrementalAck(sid, Number(seq), pending.messages, pending.system); return; } - pendingIncrementalAcks.delete(sid); if (status === 409) { // #3369: one 409 resets the conversation state — the next // turn re-seeds with resync:true (never 409s) instead of diff --git a/tests/dsh-native.test.ts b/tests/dsh-native.test.ts index f2818e9ad2..9a23653bbf 100644 --- a/tests/dsh-native.test.ts +++ b/tests/dsh-native.test.ts @@ -53,6 +53,12 @@ test("#3370: dsh incremental conversion is atomic (marker + body on the same ini assert.equal(init2.body, original2, "single-flight: un-acked pending blocks conversion"); assert.equal(new Headers(init2.headers ?? {}).get("x-bili-plugin-turn"), null); + // 2b. that skipped request's plain 200 (no ack header) arrives + // BEFORE the marker'd response — it must not consume the + // pending entry, or the seed's ack below is lost and turn 3 + // replans a resync instead of a delta (#3378 review). + onResponse(url, new Response("{}", { status: 200 })); + // 3. ack the seed → the next turn plans a DELTA (sinceSeq advanced) onResponse(url, new Response("{}", { status: 200, headers: { "x-bili-applied-seq": String(msgs1.length) } })); const init3: RequestInit = { method: "POST", body: original2 };