Skip to content
Closed
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
32 changes: 28 additions & 4 deletions src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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" });
Expand All @@ -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;
Expand Down Expand Up @@ -1592,6 +1603,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)` : "";
Expand Down
18 changes: 18 additions & 0 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -839,6 +839,24 @@ 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 (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;
}
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
Expand Down
10 changes: 10 additions & 0 deletions tests/issue2028-dsh-compaction-toggle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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: [
Expand Down
7 changes: 7 additions & 0 deletions tests/issue2490-ledger-floor-doomed-probe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
14 changes: 14 additions & 0 deletions tests/issue2709-passthrough-compaction-guard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.";
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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`, {
Expand Down Expand Up @@ -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`, {
Expand Down
Loading
Loading