From 4ed8b09862d1f889189acb87faf5859bd6bbdab5 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 13 Oct 2026 19:01:49 +0800 Subject: [PATCH 1/2] fix: gate dsh compaction refusal on live compression substrate (#3016) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A dsh native compaction call was refused unconditionally (422 dsh_compaction_refused) even when bili held no compression substrate (state.blocks=0) — there was nothing to protect. On the unattributed passthrough lane (x-bili-passthrough) this meant that when bili's own nudge/decision channel was dead (#3004), the last remaining shrink backstop was also disabled, pinning context at the wall until the hard limit. Gate the refusal on whether a substrate actually exists to protect: - pipeline path (target resolved): relay verbatim when session.state.blocks.length === 0. - passthrough lane (target unknowable — only x-bili-passthrough is stamped): refuse iff anyLiveSessionHasCompressionBlocks(); otherwise stand down and relay. No new config/env surface; the existing escape hatch allowDshCompaction / BILI_ALLOW_DSH_COMPACTION (#2028) still short-circuits first. Updates the pre-existing refusal fixtures (which used fresh sessions) to seed a substrate so they keep pinning the protective path. Closes #3016 --- src/server/handle.ts | 32 ++- src/session.ts | 15 ++ tests/issue2028-dsh-compaction-toggle.test.ts | 10 + ...ssue2490-ledger-floor-doomed-probe.test.ts | 7 + ...e2709-passthrough-compaction-guard.test.ts | 14 ++ ...ssue3016-compaction-substrate-gate.test.ts | 223 ++++++++++++++++++ 6 files changed, 297 insertions(+), 4 deletions(-) create mode 100644 tests/issue3016-compaction-substrate-gate.test.ts diff --git a/src/server/handle.ts b/src/server/handle.ts index 271299d1aa..b047f2c749 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -17,7 +17,7 @@ import { bodyMightCarryImages, buildIncomingImageIndex, pruneRetrieveImgExports, import { durableMessageToolPaths, withDurableProtection } from "../durable-message-guards.js"; import { biliToolsDeclaredOnWire, countBiliToolUses, evaluateSelfHealRound, nudgeSuppressed, pluginLaneDegraded, pluginLaneRestore } from "../session-self-heal.js"; import { compressBreakerArmed } from "../stream.js"; -import { acquireInFlight, getSession, hasProcessedState, markDirty, peekSession, releaseInFlight, storeEffectiveConfig, tickPostRebuildAnchor, withSessionLock, type Session } from "../session.js"; +import { acquireInFlight, anyLiveSessionHasCompressionBlocks, getSession, hasProcessedState, markDirty, peekSession, releaseInFlight, storeEffectiveConfig, tickPostRebuildAnchor, withSessionLock, type Session } from "../session.js"; import { buildCompressSystemPrompt } from "../compress-tool.js"; import { storeEffectiveImageCompression, type ImageCompressionSettings } from "../image-compress.js"; import { storeEffectiveSearchPlanAware } from "../decompress-shared.js"; @@ -255,10 +255,18 @@ async function handleRequest( // (#2028), fail-open on undecodable bodies (#1835 failure direction — // relay verbatim, today's behavior). The check decodes only a COPY: the // relay still forwards the original bytes with content-encoding intact. - if (protocol !== null && req.method === "POST" && bodyBuffer.length > 0 && opts.allowDshCompaction !== true - && await detectPassthroughDshCompactionCall(protocol, bodyBuffer, headerValue(req, "content-encoding"), async (enc, buf) => (await decodeRequestBody(enc, buf, MAX_DECODED_REQUEST_BYTES, { signal: decodingSignal, onBytes: (bytes) => admission.observe(bytes) })).body)) { + // #3016: the guard protects an EXISTING compression substrate from a + // landed checkpoint. This lane has no resolved session (only x-bili- + // passthrough is stamped, #1117/#2709), so the target's own blocks are + // unknowable here; gate the refusal on "is there ANY live substrate to + // protect". When every live session has zero blocks, a landed checkpoint + // destroys nothing, and refusing only kills the last backstop when bili's + // own nudge/decision channel is dead (#3004) — stand down and relay. + const passthroughCompactionCall = protocol !== null && req.method === "POST" && bodyBuffer.length > 0 && opts.allowDshCompaction !== true + && await detectPassthroughDshCompactionCall(protocol, bodyBuffer, headerValue(req, "content-encoding"), async (enc, buf) => (await decodeRequestBody(enc, buf, MAX_DECODED_REQUEST_BYTES, { signal: decodingSignal, onBytes: (bytes) => admission.observe(bytes) })).body); + if (passthroughCompactionCall && protocol !== null && anyLiveSessionHasCompressionBlocks()) { dshPassthroughGuardStats.refusals += 1; - log("warn", `[passthrough] dsh native compaction call identified on the unattributed passthrough lane (#1117/#2709) — REFUSED, not forwarded: bili owns compression on this lane; a landed dsh checkpoint would durably shadow the raw history (#1729, cf. #1772/#1206). No session exists on this lane, so this log line (not the #2490 ledger) is the record; passthrough refusals so far: ${dshPassthroughGuardStats.refusals}`); + log("warn", `[passthrough] dsh native compaction call identified on the unattributed passthrough lane (#1117/#2709) — REFUSED, not forwarded: a live compression substrate exists that a landed dsh checkpoint would durably shadow (#1729, cf. #1772/#1206), so the guard holds. No session exists on this lane, so this log line (not the #2490 ledger) is the record; passthrough refusals so far: ${dshPassthroughGuardStats.refusals}`); const refusal = dshCompactionRefusal(protocol); if (!res.headersSent && !res.writableEnded && !res.destroyed) { res.writeHead(refusal.status, { "content-type": "application/json" }); @@ -267,6 +275,9 @@ async function handleRequest( logRequestCost(log, "passthrough", null, inboundBytes, reqT0); return; } + if (passthroughCompactionCall) { + log("info", `[passthrough] dsh native compaction call identified on the unattributed passthrough lane (#1117/#2709) — RELAYED verbatim, guard stood down: no live compression substrate exists to protect (every live session has zero blocks), so refusing would only kill the last backstop when bili's own nudge/decision channel is dead (#3016, cf. #3004)`); + } log("debug", `passthrough: ${req.method ?? "?"} ${maskUrlForLog(req.url ?? "")} — unattributed in-process caller (#1117), relaying verbatim`); await forward(req, res, opts, scrubCompatDrop(scrubAnthropicPck(protocol, bodyBuffer, log), compatDropPaths, log), null, core, config, log, route, instanceId, undefined); return; @@ -1584,6 +1595,19 @@ async function handleRequest( // side-request lane: the compaction call is a full-budget request, so // only this guard can catch it. if (protocol !== null && opts.allowDshCompaction !== true && isDshCompactionCall(protocol, parsed)) { + // #3016: same substrate gate as the passthrough lane, but precise here — + // the target IS the resolved session, so read its own blocks. When it + // has none (state.blocks=0 — e.g. bili's nudge/decision channel died and + // never built substrate, #3004), a landed checkpoint destroys nothing and + // refusing only kills the last backstop: stand down and relay verbatim so + // dsh's own compaction can land. No metadata is recorded — no refusal + // happened, and a LANDED checkpoint shrinks dsh's ledger, so the #2490 + // raw-scale high-water mark does not apply. + if (session.state.blocks.length === 0) { + log("info", `[${session.id}] dsh native compaction call identified but the session has no compression substrate (state.blocks=0) — RELAYED verbatim so dsh's own compaction can land (#3016, cf. #3004); the guard protects an existing substrate, and there is none here`); + await forward(req, res, opts, scrubCompatDrop(scrubAnthropicPck(protocol, bodyBuffer, log), compatDropPaths, log), null, core, reqConfig, log, route, instanceId, undefined); + return; + } if (session.metadata.dshCompactionRefused !== true) { session.metadata.dshCompactionRefused = true; const shapeDrift = inboundMsgs !== null && inboundMsgs > DSH_COMPACTION_SHAPE_MSGS ? `, shape drifted from the ≤${DSH_COMPACTION_SHAPE_MSGS}-msg rc.1 envelope — rc.2 replays the full shadowed region (#2193)` : ""; diff --git a/src/session.ts b/src/session.ts index dca64219fb..6f3fd1ea5a 100644 --- a/src/session.ts +++ b/src/session.ts @@ -786,6 +786,21 @@ export function listSessions(): Session[] { return [...sessions.values()].sort((a, b) => b.lastSeen - a.lastSeen); } +/** #3016: whether ANY live (in-memory) session currently holds a compression + * substrate (state.blocks.length > 0). The unattributed passthrough lane has no + * resolved session to inspect, so the dsh compaction guard there cannot read the + * target's own blocks; it gates its refusal on this instead. When every live + * session has zero blocks, a landed dsh checkpoint would destroy nothing, and + * refusing only kills the last backstop when bili's own nudge/decision channel + * is dead (#3004). Reads the in-memory map only — never walks disk (this is a + * fast per-request gate; disk-only sessions are not actively being compacted). */ +export function anyLiveSessionHasCompressionBlocks(): boolean { + for (const s of sessions.values()) { + if (s.state.blocks.length > 0) return true; + } + return false; +} + // #2170 measure 4 (runtime canary): the #2165 failure shape — one dsh // conversation's traffic split across BOTH the raw id and a `|sub:` fork, // both live at once (the raw session steals the compressions / anchor while diff --git a/tests/issue2028-dsh-compaction-toggle.test.ts b/tests/issue2028-dsh-compaction-toggle.test.ts index 222a86721d..4a9864162f 100644 --- a/tests/issue2028-dsh-compaction-toggle.test.ts +++ b/tests/issue2028-dsh-compaction-toggle.test.ts @@ -17,6 +17,7 @@ import { allowDshCompactionState, loadOptions, type ProxyOptions } from "../src/ import { DSH_COMPACTION_INSTRUCTION_PREFIX, dshCompactionRefusal } from "../src/server/dsh-compaction-guard.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { getSession } from "../src/session.ts"; import { rmrf } from "./tmp-rm.ts"; /** Point BILI_CONFIG_FILE at a temp file (or a missing path when body is @@ -175,6 +176,15 @@ test("#2028: the web toggle flips the #1729 wire guard live (refuse -> forward - await once(bili, "listening"); const port = (bili.address() as { port: number }).port; + // #3016: the #1729 guard now refuses only while the target session holds a + // compression substrate; seed one so the default/clear refusal assertions + // below keep pinning the protective path (the toggle flip itself is unchanged). + getSession("s-2028").state.blocks.push({ + blockId: "b0", runId: "r0", tier: 1, topic: "t", summary: "s", + directMessageIds: ["m1"], effectiveMessageIds: ["m1"], directBlockIds: [], + compressedTokens: 100, createdAt: Date.now(), survivedCount: 1, generation: "young", active: true, + }); + const compactionPost = (): Promise<{ status: number; body: string }> => post(port, "/v1/chat/completions", { model: "mock", messages: [ diff --git a/tests/issue2490-ledger-floor-doomed-probe.test.ts b/tests/issue2490-ledger-floor-doomed-probe.test.ts index 90ad560e88..e432af7d6f 100644 --- a/tests/issue2490-ledger-floor-doomed-probe.test.ts +++ b/tests/issue2490-ledger-floor-doomed-probe.test.ts @@ -239,6 +239,13 @@ test("e2e #2490 a: the guard records the refused replay SIZE on the session (hig const { ctx, calls, close } = await setup(); try { ctx.headers["x-acp-session"] = "s-2490-a"; + // #3016: the guard now refuses only while the session holds substrate; seed + // one so the #2490 refused-bytes high-water assertions below still hold. + getSession("s-2490-a").state.blocks.push({ + blockId: "b0", runId: "r0", tier: 1, topic: "t", summary: "s", + directMessageIds: ["m1"], effectiveMessageIds: ["m1"], directBlockIds: [], + compressedTokens: 100, createdAt: Date.now(), survivedCount: 1, generation: "young", active: true, + }); const envelope = (prefixChars: number) => JSON.stringify({ model: "gpt-test", stream: true, diff --git a/tests/issue2709-passthrough-compaction-guard.test.ts b/tests/issue2709-passthrough-compaction-guard.test.ts index fcdd13df20..cfb215e055 100644 --- a/tests/issue2709-passthrough-compaction-guard.test.ts +++ b/tests/issue2709-passthrough-compaction-guard.test.ts @@ -31,6 +31,7 @@ import { DSH_COMPACTION_INSTRUCTION_PREFIX, dshPassthroughGuardStats } from "../ import type { ProxyOptions } from "../src/config.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { getSession, _resetSessionsForTest } from "../src/session.ts"; const INSTRUCTION = DSH_COMPACTION_INSTRUCTION_PREFIX + " Summarize the conversation so far, retaining key decisions and open tasks."; @@ -64,6 +65,7 @@ async function startHarness(allowDshCompaction = false): Promise<{ proxyPort: nu const upstreamPort = (upstream.address() as AddressInfo).port; _setStoreForTest(new SessionStore({ enabled: false })); setRegistryForTest({}); + _resetSessionsForTest(); const proxy = await startServer({ port: 0, host: "127.0.0.1", @@ -109,9 +111,20 @@ function compactionBody(): string { return JSON.stringify({ model: "gpt-test", messages: [...filler, { role: "user", content: INSTRUCTION }] }); } +// #3016: the lane guard now refuses only while a compression substrate exists to +// protect; these refusal tests seed one so they keep pinning the protective path. +function seedSubstrate(): void { + getSession("t-2709-substrate").state.blocks.push({ + blockId: "b0", runId: "r0", tier: 1, topic: "t", summary: "s", + directMessageIds: ["m1"], effectiveMessageIds: ["m1"], directBlockIds: [], + compressedTokens: 100, createdAt: Date.now(), survivedCount: 1, generation: "young", active: true, + }); +} + test("#2709: passthrough compaction call is refused 422, never forwarded", async () => { const before = dshPassthroughGuardStats.refusals; const h = await startHarness(); + seedSubstrate(); // #3016: guard refuses only while a substrate exists to protect try { const body = compactionBody(); const resp = await fetch(`http://127.0.0.1:${h.proxyPort}/bili/http://127.0.0.1:${h.upstreamPort}/v1/chat/completions`, { @@ -155,6 +168,7 @@ test("#2709: ordinary passthrough traffic relays byte-identical (no false positi test("#2709: gzip-encoded compaction body is still refused (decode path)", async () => { const h = await startHarness(); + seedSubstrate(); // #3016: guard refuses only while a substrate exists to protect try { const gz = gzipSync(Buffer.from(compactionBody(), "utf8")); const resp = await fetch(`http://127.0.0.1:${h.proxyPort}/bili/http://127.0.0.1:${h.upstreamPort}/v1/chat/completions`, { diff --git a/tests/issue3016-compaction-substrate-gate.test.ts b/tests/issue3016-compaction-substrate-gate.test.ts new file mode 100644 index 0000000000..87a1fcd9fb --- /dev/null +++ b/tests/issue3016-compaction-substrate-gate.test.ts @@ -0,0 +1,223 @@ +// #3016: the dsh native-compaction guard (#1729/#2722/#2843) refused EVERY dsh +// compaction envelope — on both the unattributed passthrough lane +// (x-bili-passthrough, #1117/#2709) and the attributed pipeline lane — WITHOUT +// ever checking whether bili had a compression substrate to protect. When bili's +// own nudge/decision channel dies and never builds substrate (state.blocks=0 — +// the #3004 deadlock), refusing destroys nothing: it only kills the LAST +// backstop (dsh's own compaction) exactly when it is the only shrink left, +// pinning context at the wall until the hard limit. Incident: session df251671, +// 765K/984K, blocks=0 → 422 dsh_compaction_refused on the unattributed lane. +// +// Fix: gate the refusal on substrate presence. +// - pipeline lane: the target IS the resolved session → read its OWN blocks; +// blocks==0 → relay verbatim so dsh's checkpoint lands. +// - passthrough lane: NO resolved session exists there (the client stamps only +// x-bili-passthrough, #1117/#2709), so the target's own blocks are unknowable +// → conservative-sound gate: refuse only while ANY live session holds +// substrate; when none does, stand down and relay. Never allows when the +// target could have substrate. +// +// These tests pin BOTH gates in BOTH substrate states. allowDshCompaction +// (#2028) short-circuits before either gate (covered by issue2028 / issue2709). +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import type { AddressInfo } from "node:net"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import { DSH_COMPACTION_INSTRUCTION_PREFIX } from "../src/server/dsh-compaction-guard.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, _resetSessionsForTest } from "../src/session.ts"; + +const INSTRUCTION = DSH_COMPACTION_INSTRUCTION_PREFIX + + " Summarize the conversation so far, retaining key decisions and open tasks."; + +/** rc.2 shape: full-region replay with the instruction as the FINAL user message. */ +function compactionBody(): string { + const filler = Array.from({ length: 6 }, (_, i) => ({ role: i % 2 ? "assistant" : "user", content: `earlier turn ${i} of the shadowed region` })); + return JSON.stringify({ model: "gpt-test", messages: [...filler, { role: "user", content: INSTRUCTION }] }); +} + +function seedSubstrate(id: string): void { + getSession(id).state.blocks.push({ + blockId: "b0", runId: "r0", tier: 1, topic: "t", summary: "s", + directMessageIds: ["m1"], effectiveMessageIds: ["m1"], directBlockIds: [], + compressedTokens: 100, createdAt: Date.now(), survivedCount: 1, generation: "young", active: true, + }); +} + +async function startMock(): Promise<{ port: number; captured: string[]; close(): Promise }> { + return new Promise((resolve, reject) => { + const captured: string[] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + captured.push(Buffer.concat(chunks).toString("utf8")); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ + id: "chatcmpl_3016", object: "chat.completion", created: 1, model: "gpt-test", + choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }], + usage: { prompt_tokens: 5, completion_tokens: 1, total_tokens: 6 }, + })); + }); + }); + upstream.once("error", reject); + upstream.listen(0, "127.0.0.1"); + once(upstream, "listening").then(() => resolve({ + port: (upstream.address() as AddressInfo).port, + captured, + async close() { upstream.close(); await once(upstream, "close"); }, + })).catch(reject); + }); +} + +async function startProxy(opts: ProxyOptions): Promise<{ port: number; close(): Promise }> { + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetSessionsForTest(); + const proxy = await startServer(opts); + await once(proxy, "listening"); + return { + port: (proxy.address() as AddressInfo).port, + async close() { proxy.close(); await once(proxy, "close"); }, + }; +} + +/** Unattributed-lane routing (#1117): explicit /bili//... target. */ +function passthroughOpts(mockPort: number): ProxyOptions { + return { + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${mockPort}`]: { models: { "gpt-test": { context: 400_000 } } } }, + modelContextLimit: 400_000, + kernelConfig: defaultConfig(400_000), + promptCache: { routing: "auto" }, + compress: { injectTool: false, injectNudge: false }, + 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, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions; +} + +/** Attributed-lane routing: default upstream + x-acp-session resolution. */ +function pipelineOpts(mockPort: number): ProxyOptions { + return { + port: 0, + host: "127.0.0.1", + upstream: `http://127.0.0.1:${mockPort}`, + routes: {}, + proxy: "", + proxyMode: "direct", + proxySource: "direct", + modelContextLimit: 400_000, + kernelConfig: defaultConfig(400_000), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions; +} + +test("#3016: passthrough compaction RELAYS verbatim when no live session has substrate (core fix)", async () => { + const mock = await startMock(); + const h = await startProxy(passthroughOpts(mock.port)); + try { + // Clean map (harness reset) — no compression substrate anywhere. The + // unattributed lane must let dsh's checkpoint land instead of refusing. + const body = compactionBody(); + const resp = await fetch(`http://127.0.0.1:${h.port}/bili/http://127.0.0.1:${mock.port}/v1/chat/completions`, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-passthrough": "1" }, + body, + }); + assert.equal(resp.status, 200, `expected relay (got ${resp.status}: ${await resp.clone().text()})`); + assert.equal(mock.captured.length, 1, "relayed to upstream — dsh's checkpoint can land"); + assert.equal(mock.captured[0], body, "byte-exact verbatim relay"); + } finally { + await h.close(); + await mock.close(); + }; +}); + +test("#3016: passthrough compaction REFUSES while any live session holds substrate (guard holds)", async () => { + const mock = await startMock(); + const h = await startProxy(passthroughOpts(mock.port)); + try { + // A DIFFERENT live session holds substrate → the conservative-sound gate + // cannot prove the (unknown) target is empty, so it still refuses. + seedSubstrate("some-other-live-session"); + const resp = await fetch(`http://127.0.0.1:${h.port}/bili/http://127.0.0.1:${mock.port}/v1/chat/completions`, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-passthrough": "1" }, + body: compactionBody(), + }); + assert.equal(resp.status, 422); + assert.match(await resp.text(), /dsh_compaction_refused/); + assert.equal(mock.captured.length, 0, "refused — nothing lands"); + } finally { + await h.close(); + await mock.close(); + }; +}); + +test("#3016: pipeline compaction RELAYS when the resolved session has no substrate", async () => { + const mock = await startMock(); + const h = await startProxy(pipelineOpts(mock.port)); + try { + // Do NOT pre-seed s-3016-p → the handler creates it fresh (blocks=0), + // the exact #3004-deadlock shape: huge context, zero substrate. + const body = compactionBody(); + const resp = await fetch(`http://127.0.0.1:${h.port}/v1/chat/completions`, { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": "s-3016-p" }, + body, + }); + assert.equal(resp.status, 200, `expected relay (got ${resp.status}: ${await resp.clone().text()})`); + assert.equal(mock.captured.length, 1, "relayed — dsh's checkpoint lands"); + } finally { + await h.close(); + await mock.close(); + }; +}); + +test("#3016: pipeline compaction REFUSES when the resolved session has substrate (+#2490 bytes recorded)", async () => { + const mock = await startMock(); + const h = await startProxy(pipelineOpts(mock.port)); + try { + seedSubstrate("s-3016-q"); + const resp = await fetch(`http://127.0.0.1:${h.port}/v1/chat/completions`, { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": "s-3016-q" }, + body: compactionBody(), + }); + assert.equal(resp.status, 422); + assert.match(await resp.text(), /dsh_compaction_refused/); + assert.equal(mock.captured.length, 0, "refused — nothing lands"); + const s = getSession("s-3016-q"); + assert.ok(s, "session exists"); + assert.equal(s.metadata.dshCompactionRefused, true, "#1835 flag still set"); + assert.ok(typeof s.metadata["dshCompactionRefusedBytes"] === "number" && (s.metadata["dshCompactionRefusedBytes"] as number) > 0, "#2490 refused-bytes high-water mark recorded"); + } finally { + await h.close(); + await mock.close(); + }; +}); From bed60a1a31c1dea21bc299e13da2695b5a592cd3 Mon Sep 17 00:00:00 2001 From: ework-daemon Date: Tue, 13 Oct 2026 19:48:23 +0800 Subject: [PATCH 2/2] docs: correct substrate-gate comments for post-#2803 eviction reality (#3016 review) The passthrough gate scans only the in-memory live-session map. Since #2803 (LRU session eviction) landed on master after this PR's base, a substrate-holding session can be flushed out of memory and become invisible to the scan. The previous wording ('disk-only sessions are not actively being compacted' / 'Never allows when the target could have substrate') documented a guarantee the merged code does not provide. Comments only; no behavior change. --- src/session.ts | 7 +++++-- tests/issue3016-compaction-substrate-gate.test.ts | 6 ++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/session.ts b/src/session.ts index 6f3fd1ea5a..1f4a48f3d8 100644 --- a/src/session.ts +++ b/src/session.ts @@ -792,8 +792,11 @@ export function listSessions(): Session[] { * target's own blocks; it gates its refusal on this instead. When every live * session has zero blocks, a landed dsh checkpoint would destroy nothing, and * refusing only kills the last backstop when bili's own nudge/decision channel - * is dead (#3004). Reads the in-memory map only — never walks disk (this is a - * fast per-request gate; disk-only sessions are not actively being compacted). */ + * is dead (#3004). Reads the in-memory map only — never walks disk (fast + * per-request gate). Residual under #2803 eviction: a substrate-holding + * session flushed out of memory is invisible to this scan, so a dsh checkpoint + * aimed exactly at it could be relayed while no other live session holds + * substrate (narrow window; tracked in #3016). */ export function anyLiveSessionHasCompressionBlocks(): boolean { for (const s of sessions.values()) { if (s.state.blocks.length > 0) return true; diff --git a/tests/issue3016-compaction-substrate-gate.test.ts b/tests/issue3016-compaction-substrate-gate.test.ts index 87a1fcd9fb..4c183bbba7 100644 --- a/tests/issue3016-compaction-substrate-gate.test.ts +++ b/tests/issue3016-compaction-substrate-gate.test.ts @@ -14,8 +14,10 @@ // - passthrough lane: NO resolved session exists there (the client stamps only // x-bili-passthrough, #1117/#2709), so the target's own blocks are unknowable // → conservative-sound gate: refuse only while ANY live session holds -// substrate; when none does, stand down and relay. Never allows when the -// target could have substrate. +// substrate; when none does, stand down and relay. Sound while the target's +// substrate stays resident; under #2803 eviction an evicted substrate holder +// is invisible to the scan (residual noted on anyLiveSessionHasCompressionBlocks +// in src/session.ts; tracked in #3016). // // These tests pin BOTH gates in BOTH substrate states. allowDshCompaction // (#2028) short-circuits before either gate (covered by issue2028 / issue2709).