From 64937a909be3d7e30102147cc9f23a0b1d980637 Mon Sep 17 00:00:00 2001 From: ci-check Date: Fri, 30 Oct 2026 14:16:33 +0800 Subject: [PATCH 1/5] fix: log compress applications onto reused ref numbers (#5199) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After a restart, the cold-load ledger restamp can hand a pre-restart ref to another message (a vacated number re-issued as someone else's seq+1 target in the same pass). The guard resolves endpoints live-first, so a replayed pre-restart compress call citing the old number applies to the new owner and returns success — silently folding the wrong message. Live-first stays the accepted resolution (rejecting dead-loops like #4797; translating to the old owner would mistranslate legitimate post-restamp cites). This change makes the application visible instead of silent: supersededRefRejection now reports every cited ref that is BOTH live and still another message's recorded pre-restamp label (dualIdentity), and applyRanges logs a prominent warning naming the refs with salted owner ids only (#1454 pattern). Acceptance behavior is unchanged — zero semantic change; direction decision pending #5204. --- src/stream.ts | 52 ++++++-- tests/issue5199-dual-identity-log.test.ts | 142 ++++++++++++++++++++++ 2 files changed, 186 insertions(+), 8 deletions(-) create mode 100644 tests/issue5199-dual-identity-log.test.ts diff --git a/src/stream.ts b/src/stream.ts index 2a18273036..0a56509eb4 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -860,16 +860,27 @@ export function findVisibleStubResubmissions(ctx: RewriteCtx, ranges: ParsedRang * Refusal only when an endpoint is a superseded key whose translation * dead-ends (the message lost its mapping entirely — an honest stale cite). * - * Transitional honesty: for sessions restamped by kernels WITHOUT the - * superseded-liveness prune, case 1 can in principle swallow a resent - * pre-restart call's intent (number now owned by someone else). The replay - * window is seconds; the deadlock it replaces is permanent — live-first is - * the right trade, and the kernel prune removes the ambiguity entirely for - * fresh restamps. */ + * Residual hazard (#5199): the kernel's superseded-liveness prune was drafted + * then REVERTED (storage-engine shadow-digest constraint — + * reference/ref-keyed-surfaces.md), so EVERY restamped session can carry + * numbers that are simultaneously live for one message and the recorded old + * label of another. For those, case 1 swallows a resent pre-restart call's + * intent: the call applies to the CURRENT owner while the model meant the + * old one — silently returning success. Live-first stays the accepted + * resolution (rejecting dead-loops like #4797; translating to the old owner + * would systematically mistranslate legitimate post-restamp cites), and the + * source-level fix (a restamp that never re-issues an issued number) is a + * kernel change pending decision #5204. Until then the application is no + * longer silent: dualIdentity below names every such ref so callers log it. */ interface SupersededResolution { rejection: string | null; translatedRanges: T[]; translated: number; + /** #5199: refs that are LIVE for one message while still the recorded old + * label of ANOTHER (the restamp re-issued an already-issued number). The + * live-first resolution applies to the current owner — callers log these + * so a replayed pre-restart citation is diagnosable instead of silent. */ + dualIdentity: string[]; } export function supersededRefRejection( @@ -877,7 +888,7 @@ export function supersededRefRejection { const superseded = session.restampSuperseded; - const out: SupersededResolution = { rejection: null, translatedRanges: [], translated: 0 }; + const out: SupersededResolution = { rejection: null, translatedRanges: [], translated: 0, dualIdentity: [] }; if (!superseded || superseded.size === 0) { out.translatedRanges = ranges.map((r) => ({ ...r })); return out; @@ -885,8 +896,17 @@ export function supersededRefRejection(); const resolveEndpoint = (ref: string): string => { - if (byRef[ref] !== undefined) return ref; + const liveOwner = byRef[ref]; + if (liveOwner !== undefined) { + // #5199: live AND still the recorded old label of another message — + // the restamp issued this number twice. Live-first wins (the + // accepted trade); record it so the caller can log the application. + const oldOwner = superseded.get(ref); + if (oldOwner !== undefined && oldOwner !== liveOwner) dualIdentity.add(ref); + return ref; + } const rawId = superseded.get(ref); if (rawId === undefined) return ref; const next = byRaw[rawId]; @@ -902,6 +922,7 @@ export function supersededRefRejection 5 ? ` (+${dead.length - 5} more)` : ""; @@ -1003,6 +1024,21 @@ export function applyRanges(parsed: ReturnType, ctx: } else { ranges = supersededRes.translatedRanges; } + if (supersededRes.dualIdentity.length > 0) { + // #5199: cited number(s) that are live for their CURRENT owner while + // still the recorded pre-restamp label of a DIFFERENT message. A + // replayed pre-restart call may have meant the old owner — the fold + // proceeds against the current one (the live-first trade), but the + // application must be visible. Salted ids only (#1454 pattern). + const detail = supersededRes.dualIdentity.map((ref) => { + const owners = [ctx.session.state.messageRefs?.byRef?.[ref], ctx.session.restampSuperseded?.get(ref)] + .filter((o): o is string => typeof o === "string") + .map((o) => saltedMsgIdForLog(o)) + .join("/"); + return `${ref}=${owners}`; + }).join(", "); + ctx.log(`[acp-proxy: ⚠️ compress applied onto reused ref number(s): ${detail} — each is live for its current owner yet was issued to a different message before the ledger alignment; a replayed pre-restart citation may have intended the old owner (#5199; direction decision #5204)]`); + } if (ctx.messages.length > 0) { const ids = ctx.messages.slice(0, 10).map((m) => `${saltedMsgIdForLog(m.id)}(${(m.text ?? "").length}c)`).join(", "); ctx.log(`[acp-proxy: first msg ids: ${ids}]`); diff --git a/tests/issue5199-dual-identity-log.test.ts b/tests/issue5199-dual-identity-log.test.ts new file mode 100644 index 0000000000..35649b7f99 --- /dev/null +++ b/tests/issue5199-dual-identity-log.test.ts @@ -0,0 +1,142 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +import { createCore, defaultConfig, createInitialState, restampRefsToLedger, emptyRefMap, type CoreMessage, type CompressionState } from "acp-kernel"; +import { applyRanges, supersededRefRejection, type RewriteCtx } from "../src/stream.ts"; + +// #5199: after a restart, the cold-load ledger restamp can hand a pre-restart +// ref to ANOTHER message (a vacated number re-issued as someone else's seq+1 +// target in the same pass). The host guard resolves endpoints live-first, so +// a replayed pre-restart compress call citing the OLD number applies to the +// NEW owner and returns success — silently folding the wrong message. The +// live-first resolution is the accepted trade (rejecting dead-loops like +// #4797; translating to the old owner would mistranslate legitimate +// post-restamp cites); what was missing was visibility. This file pins: +// T1 dual-identity application — citing m00006 (live for f, e's old label) +// folds f, NOT e, returns success, and the prominent warning fires; +// T2 negative control — an ordinary live cite produces NO warning; +// T3 resolution contract — dualIdentity dedupes singleton endpoints, clean +// ranges stay empty, the no-map fast path carries an empty list; +// T4 translation path intact — a genuinely-vacated cite still translates +// onto the same message with no dual-identity entry. + +// Same drifted shape as tests/issue4797-superseded-deadlock.test.ts: +// rows/seq a=0..f=5; old refs a=m1 b=m3 c=BLOCKED d=m4 e=m6 f=m7. +// Post-restamp (master, no kernel liveness prune): b→m2, e→m5, f takes e's +// vacated m6 → LIVE a=m1 b=m2 d=m4 e=m5 f=m6; superseded {m3→b, m6→e, m7→f}. +// m6 is therefore dual-identity: live for f AND still e's recorded label. +function restampedSession(): { session: RewriteCtx["session"]; messages: CoreMessage[] } { + const state: CompressionState = createInitialState(); + const map = emptyRefMap(); + map.byRaw.a = "m00001"; map.byRef.m00001 = "a"; + map.byRaw.b = "m00003"; map.byRef.m00003 = "b"; + map.byRaw.c = "BLOCKED"; + map.byRaw.d = "m00004"; map.byRef.m00004 = "d"; + map.byRaw.e = "m00006"; map.byRef.m00006 = "e"; + map.byRaw.f = "m00007"; map.byRef.m00007 = "f"; + state.messageRefs = map; + const seq = new Map([["a", 0], ["b", 1], ["c", 2], ["d", 3], ["e", 4], ["f", 5]]); + const outcome = restampRefsToLedger(state, seq); + const messages: CoreMessage[] = [ + { id: "a", role: "user", contentType: "text", text: "message a body " + "with enough substance to be worth folding someday. ".repeat(120) }, + { id: "b", role: "assistant", contentType: "text", text: "message b body " + "with enough substance to be worth folding someday. ".repeat(120) }, + { id: "d", role: "user", contentType: "text", text: "message d body " + "with enough substance to be worth folding someday. ".repeat(120) }, + { id: "e", role: "assistant", contentType: "text", text: "message e body " + "with enough substance to be worth folding someday. ".repeat(120) }, + { id: "f", role: "user", contentType: "text", text: "message f body " + "with enough substance to be worth folding someday. ".repeat(120) }, + ]; + const session = { + id: "issue5199", + meta: { protocol: "anthropic" }, + stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 0, compressCreditTokens: 0, contextTokens: 0, retrieveCalls: 0, retrieveHits: 0, retrieveMisses: 0, storedBytes: 0, storeBytesSaved: 0, rangeRestores: 0 }, + metadata: {}, + state, + restampSuperseded: outcome.superseded, + createdAt: Date.now(), + lastSeen: Date.now(), + blockContents: new Map(), + inFlight: 0, + persisted: false, + pendingRetrievals: [], + } as never as RewriteCtx["session"]; + return { session, messages }; +} + +function makeCtx(): { ctx: RewriteCtx; logs: string[] } { + const logs: string[] = []; + const { session, messages } = restampedSession(); + const ctx = { + core: createCore(), + config: defaultConfig(100_000, { preserveRecentMessages: 0, preserveRecentTokens: 0 }), + messages, + compressMessages: messages, + session, + log: (m: string) => { logs.push(m); }, + } as never as RewriteCtx; + return { ctx, logs }; +} + +const SUMMARY = "Folded span covering the debugging arc with decisions, files touched, and outcomes preserved for later recall.".slice(0, 500); + +function spec(startRef: string, endRef: string): { ranges: { startRef: string; endRef: string; summary: string }[]; diagnostics: unknown } { + return { ranges: [{ startRef, endRef, summary: SUMMARY.repeat(2) }], diagnostics: [] }; +} + +test("T1: citing a dual-identity ref (live for f, e's pre-restamp label) folds f, succeeds, and logs the reused-number warning", () => { + const { ctx, logs } = makeCtx(); + // Fixture precondition: m00006 is live for f while still recorded as e's + // old label — the exact shape #5199 reproduces in production. + const byRef = ctx.session.state.messageRefs?.byRef ?? {}; + assert.equal(byRef["m00006"], "f"); + assert.equal(ctx.session.restampSuperseded?.get("m00006"), "e"); + const res = applyRanges(spec("m00006", "m00006") as never, ctx); + const text = typeof (res as { text?: string }).text === "string" ? (res as { text?: string }).text! : ""; + assert.ok(!text.includes("REFUSED"), `dual-identity cite must not be refused (live-first trade); got: ${text.slice(0, 200)}`); + const covered = ctx.session.state.blocks.flatMap((b) => (b.active ? b.effectiveMessageIds : [])); + assert.ok(covered.includes("f"), "fold covers the CURRENT owner f"); + assert.ok(!covered.includes("e"), "the intended-but-old owner e is NOT folded"); + const warn = logs.find((l) => l.includes("reused ref number")); + assert.ok(warn !== undefined, `prominent warning must fire; logs: ${logs.join(" | ")}`); + assert.ok(warn!.includes("m00006"), "warning names the reused ref"); +}); + +test("T2: an ordinary live cite (no dual identity) folds cleanly with NO warning", () => { + const { ctx, logs } = makeCtx(); + const res = applyRanges(spec("m00004", "m00004") as never, ctx); + const text = typeof (res as { text?: string }).text === "string" ? (res as { text?: string }).text! : ""; + assert.ok(!text.includes("REFUSED"), `clean live cite must not be refused; got: ${text.slice(0, 200)}`); + const covered = ctx.session.state.blocks.flatMap((b) => (b.active ? b.effectiveMessageIds : [])); + assert.ok(covered.includes("d"), "fold covers d"); + assert.ok(!logs.some((l) => l.includes("reused ref number")), "no warning for non-dual identities"); +}); + +test("T3: resolution contract — singleton dedupe, clean ranges empty, no-map fast path empty", () => { + const { session } = restampedSession(); + // Singleton range: both endpoints hit the same dual-identity ref once. + const res = supersededRefRejection([{ startRef: "m00006", endRef: "m00006" }], session); + assert.equal(res.rejection, null); + assert.deepEqual(res.dualIdentity, ["m00006"]); + // Clean live range: nothing flagged. + const clean = supersededRefRejection([{ startRef: "m00004", endRef: "m00005" }], session); + assert.equal(clean.rejection, null); + assert.deepEqual(clean.dualIdentity, []); + // No-map fast path: field present and empty. + (session as { restampSuperseded?: Map }).restampSuperseded = undefined; + const bare = supersededRefRejection([{ startRef: "m00004", endRef: "m00005" }], session); + assert.deepEqual(bare.dualIdentity, []); +}); + +test("T4: genuinely-vacated cites still translate onto the same message, with no dual-identity entry", () => { + const { ctx, logs } = makeCtx(); + // m00003 is b's pre-restamp label; b now holds m00002. Translation must + // fold b — and flag nothing (the number is vacated, not re-issued). + const res = applyRanges(spec("m00003", "m00003") as never, ctx); + const text = typeof (res as { text?: string }).text === "string" ? (res as { text?: string }).text! : ""; + assert.ok(!text.includes("REFUSED"), `translatable old cite must not be refused; got: ${text.slice(0, 200)}`); + const covered = ctx.session.state.blocks.flatMap((b) => (b.active ? b.effectiveMessageIds : [])); + assert.ok(covered.includes("b"), "translated fold covers the cited message b"); + assert.ok(!covered.includes("a"), "neighbor a untouched"); + assert.ok(logs.some((l) => l.includes("translated") && l.includes("superseded")), "translation still logged"); + assert.ok(!logs.some((l) => l.includes("reused ref number")), "vacated (non-re-issued) numbers are not dual-identity"); +}); From af1f92abea029c2d633bd485ce27625d9fe06523 Mon Sep 17 00:00:00 2001 From: ci-check Date: Fri, 30 Oct 2026 14:16:33 +0800 Subject: [PATCH 2/5] docs: correct stale 'prune enforced / harm eliminated' claims (#5199) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Labeled follow-up fixes for comments that contradicted code facts after #4807's kernel liveness prune was reverted: - reference/ref-keyed-surfaces.md: the contract section listed the reverted prune as enforced, and the 暂缓 section claimed host live-first '已消除其全部用户可见危害' — disproven by #5199 (isolated fixture reproduced the silent wrong-target application). Both now say what is actually true and point at #5199/#5204. - tests/issue4797-superseded-deadlock.test.ts: header comment described the post-prune superseded shape ({m3→b, m7→f}); master produces {m3→b, m6→e, m7→f} where m6 is the dual-identity case now pinned in tests/issue5199-dual-identity-log.test.ts. --- reference/ref-keyed-surfaces.md | 8 ++++---- tests/issue4797-superseded-deadlock.test.ts | 6 ++++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/reference/ref-keyed-surfaces.md b/reference/ref-keyed-surfaces.md index f048fccf78..746c6f93ab 100644 --- a/reference/ref-keyed-surfaces.md +++ b/reference/ref-keyed-surfaces.md @@ -33,9 +33,9 @@ Losing it re-arms the restamp every turn; the re-stamp is a numbering no-op afte `restampRefsToLedger` vacates an old number and records it in `superseded` — but the SAME pass hands vacated numbers to other messages as `seq+1` targets. Post-pass, a number can be **simultaneously live (byRaw/byRef) and a superseded key**. Any consumer that consults `superseded` before the live map misclassifies live refs. -**Contract (enforced by kernel post-pass prune + host guard priority):** -1. Kernel: after the pass, drop `superseded` entries whose key resolves in the final live map. -2. Host guard (`supersededRefRejection`, src/stream.ts): a ref that resolves LIVE is never superseded — liveness first; only genuinely-dead numbers consult the map; translation `oldRef→rawId→live ref` is identity-preserving and mandatory for model-cited pre-restamp refs (the model may cite any number it has ever seen — kernel contract). +**Contract:** +1. Kernel: after the pass, drop `superseded` entries whose key resolves in the final live map. **DRAFTED in #4807, then REVERTED** (storage-engine shadow-digest constraint — see 暂缓 section): until it lands, dual-identity numbers exist on EVERY restamped session (#5199). +2. Host guard (`supersededRefRejection`, src/stream.ts): a ref that resolves LIVE is never superseded — liveness first; only genuinely-dead numbers consult the map; translation `oldRef→rawId→live ref` is identity-preserving and mandatory for model-cited pre-restamp refs (the model may cite any number it has ever seen — kernel contract). Cited numbers that are BOTH live and superseded resolve to the current owner and are logged prominently by callers (#5199). ## Inbound/outbound ref surfaces (verified all-live 2026-10-26, phase C audit) @@ -55,4 +55,4 @@ Outbound emitters all derive from live `state.messageRefs` via the kernel render ## 已评估、暂缓(需要 storage 影子层配合,单独立项) -- **kernel superseded 活键剪枝 + block startRef/endRef / deadRefs 迁移**:实现过并验证过单测,但 storage-engine 的重启不可见契约(wire-parity proofs + 影子摘要对比)依赖重排结果的确定性形状——迁移后影子层报 `DIGEST DRIFT [diverged: state]`,full 模式回退 legacy 信封,wire 漂移 4 项红。正确落地需要影子层把「对齐态」纳入摘要口径;在此之前 host 活表优先已消除其全部用户可见危害。剪枝与迁移的完整实现见 PR 历史(revert 前的 kernel/src/refs.ts)。 +- **kernel superseded 活键剪枝 + block startRef/endRef / deadRefs 迁移**:实现过并验证过单测,但 storage-engine 的重启不可见契约(wire-parity proofs + 影子摘要对比)依赖重排结果的确定性形状——迁移后影子层报 `DIGEST DRIFT [diverged: state]`,full 模式回退 legacy 信封,wire 漂移 4 项红。正确落地需要影子层把「对齐态」纳入摘要口径;⚠️ **2026-10-30 更正(#5199)**:此前「host 活表优先已消除其全部用户可见危害」不成立——隔离 fixture 复现了最坏形态:重启前引用被静默应用到新持有者(成功返回、块只覆盖错误消息)。活表优先只消除了 #4797 死循环;双身份应用现已有醒目日志(host 侧,tests/issue5199-dual-identity-log.test.ts),方向裁决(接受+文档化 vs kernel 不复用已发放号)见 decision request #5204。剪枝与迁移的完整实现见 PR 历史(revert 前的 kernel/src/refs.ts)。 diff --git a/tests/issue4797-superseded-deadlock.test.ts b/tests/issue4797-superseded-deadlock.test.ts index 5bcdd3ea98..27adbba3d5 100644 --- a/tests/issue4797-superseded-deadlock.test.ts +++ b/tests/issue4797-superseded-deadlock.test.ts @@ -23,8 +23,10 @@ import { applyRanges, supersededRefRejection, type RewriteCtx } from "../src/str // Same drifted shape as kernel/tests/ref-restamp-collision.test.ts: // rows/seq a=0..f=5; old refs a=m1 b=m3 c=BLOCKED d=m4 e=m6 f=m7. -// Post-restamp: b→m2, e→m5, f takes e's vacated m6. Superseded (post-prune): -// {m3→b, m7→f} — m6 is live for f and MUST NOT sit in the map. +// Post-restamp: b→m2, e→m5, f takes e's vacated m6. Superseded on master +// (the kernel liveness prune was reverted — reference/ref-keyed-surfaces.md): +// {m3→b, m6→e, m7→f} — m6 is LIVE for f AND still e's recorded old label: +// the #5199 dual-identity case, pinned in tests/issue5199-dual-identity-log.test.ts. function restampedSession(): { session: RewriteCtx["session"]; messages: CoreMessage[] } { const state: CompressionState = createInitialState(); const map = emptyRefMap(); From ea1119fc650bb79fb62b372c6b50f6981dcabff5 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Fri, 30 Oct 2026 14:10:25 +0800 Subject: [PATCH 3/5] docs(config): register sessions.hardMaxBytes + BILI_SESSION_RESIDENT_HARD_MAX_BYTES MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #4788 D2 added the per-session resident hard cap (config field sessions.hardMaxBytes / env BILI_SESSION_RESIDENT_HARD_MAX_BYTES) but never registered the surface: no YAML seed entry, no LIFECYCLE.md row, and a hand-edited EN-only CONFIGURATION.md row that diverged from the generator. That tripped config-surface-guard, docs-coverage, lifecycle-ledger-guard and docs-sync on master. Add the seed entry (restoring the author's original EN wording + the #4792 decision ref + honest dynamic default), the matching ZH rows, and the LIFECYCLE.md §2 ledger entry, then regenerate the config docs so the artifact matches the seed again. --- CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 2 ++ LIFECYCLE.md | 1 + website/config-reference/process.yaml | 7 +++++++ 4 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 6aefadce0b..0df8c5d4d5 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -1885,8 +1885,8 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_SESSION_GC_INTERVAL_MS` | `sessions.gc.intervalMs` | 3600000 | | `BILI_SESSION_GC_MAX_AGE_DAYS` | `sessions.gc.maxAgeDays` | 7 | | `BILI_SESSION_GC_MAX_TOKENS` | `sessions.gc.maxTokens` | 1000000 | +| `BILI_SESSION_RESIDENT_HARD_MAX_BYTES` | `sessions.hardMaxBytes` | (same as `sessions.residentMaxBytes`) | | `BILI_SESSION_RESIDENT_MAX_BYTES` | `sessions.residentMaxBytes` | 536870912 | -| `BILI_SESSION_RESIDENT_HARD_MAX_BYTES` | `sessions.hardMaxBytes` | (same as `BILI_SESSION_RESIDENT_MAX_BYTES`) | | `BILI_SESSION_WARM_MAX` | `sessions.warmMax` | 0 | | `BILI_SESSION_WARM_MAX_BYTES` | `sessions.warmMaxBytes` | 67108864 | | `BILI_SQLITE_AUTO_DOWNLOAD` | `storage.sqliteAutoDownload` | true | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index ac054a66e2..31c54c69d6 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -203,6 +203,7 @@ | `sessions.warmMax` | number | 0 | BILI_SESSION_WARM_MAX | 有界启动(#2803/#3050):启动监听前预热加载的最近保存会话数上限,更早的状态按需重新加载。默认 0(不预热——首次访问按需加载一次;设 8 恢复预热行为)。受 sessions.max 封顶。 | | `sessions.warmMaxBytes` | number | 67108864 | BILI_SESSION_WARM_MAX_BYTES | 启动预热集的解码字节预算(#2803)。按解码后大小计而非磁盘压缩字节,zstd 归档无法绕过内存上限;单文件超预算则永不预热。 | | `sessions.residentMaxBytes` | number | 536870912 | BILI_SESSION_RESIDENT_MAX_BYTES | 驻留会话估算字节的软目标(#2803)。活跃/在途状态始终固定保留;超过目标时,空闲状态随请求完成回写磁盘释放。 | +| `sessions.hardMaxBytes` | number | (same as `sessions.residentMaxBytes`) | BILI_SESSION_RESIDENT_HARD_MAX_BYTES | 单会话驻留字节的硬上限(#4788,决策 #4792 D1-A)。不同于池软上限——它只能逐出其他冷会话、从不触碰唯一活跃会话——它约束单个会话:在请求结束边界超过上限时,其可丢弃字段(已折叠块的原文、元数据账本、超出有界视图的原始尾巴)会被强制回写磁盘,即使该会话被池逐出豁免;下一轮通过窄盘读透明地重新读取所需内容。只要上一次保存已被证明落盘,安全丢弃就在每个请求边界运行;该上限额外加入单会话告警(warn,限流至 60 秒)。`0` 关闭该检查。 | | `sessions.gc.enabled` | boolean | false | BILI_SESSION_GC | 过期持久化会话的可选垃圾回收(未开启时用户数据绝不被悄悄清理)。 | | `sessions.gc.maxAgeDays` | number | 7 | BILI_SESSION_GC_MAX_AGE_DAYS | GC 年龄阈值(天)。 | | `sessions.gc.maxTokens` | number | 1000000 | BILI_SESSION_GC_MAX_TOKENS | GC 单会话记录的 token 大小阈值。 | @@ -1867,6 +1868,7 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 | `BILI_SESSION_GC_INTERVAL_MS` | `sessions.gc.intervalMs` | 3600000 | | `BILI_SESSION_GC_MAX_AGE_DAYS` | `sessions.gc.maxAgeDays` | 7 | | `BILI_SESSION_GC_MAX_TOKENS` | `sessions.gc.maxTokens` | 1000000 | +| `BILI_SESSION_RESIDENT_HARD_MAX_BYTES` | `sessions.hardMaxBytes` | (same as `sessions.residentMaxBytes`) | | `BILI_SESSION_RESIDENT_MAX_BYTES` | `sessions.residentMaxBytes` | 536870912 | | `BILI_SESSION_WARM_MAX` | `sessions.warmMax` | 0 | | `BILI_SESSION_WARM_MAX_BYTES` | `sessions.warmMaxBytes` | 67108864 | diff --git a/LIFECYCLE.md b/LIFECYCLE.md index 9564227eb1..9f6fdde0a8 100644 --- a/LIFECYCLE.md +++ b/LIFECYCLE.md @@ -121,6 +121,7 @@ | `BILI_SESSION_GC` | 会话 GC 总开关(`=1/true/on` 启用,默认 off;启用后下面三个参数生效) | | `BILI_SESSION_GC_INTERVAL_MS` / `BILI_SESSION_GC_MAX_AGE_DAYS` / `BILI_SESSION_GC_MAX_TOKENS` | 会话 GC 参数(默认 1h / 7d / 1M tokens) | | `BILI_SESSION_RESIDENT_MAX_BYTES` | sessions.residentMaxBytes,512 MiB 软上限(#2803) | +| `BILI_SESSION_RESIDENT_HARD_MAX_BYTES` | sessions.hardMaxBytes,单会话驻留字节硬上限(#4788 D1-A);默认同 residentMaxBytes(512 MiB),设 0 关闭——补软上限对唯一活跃会话的盲区 | | `BILI_SESSION_WARM_MAX_BYTES` | warm 解码字节上限,64 MiB(#2803) | | `BILI_PERSIST` | `=0` 关闭持久化(ephemeral/test) | | `BILI_PERSIST_DEBOUNCE_MS` | persist.debounceMs,500 | diff --git a/website/config-reference/process.yaml b/website/config-reference/process.yaml index 1d4aaebc3b..6aadc97e5a 100644 --- a/website/config-reference/process.yaml +++ b/website/config-reference/process.yaml @@ -367,6 +367,13 @@ entries: group: process desc_en: "Soft target for estimated resident session bytes (#2803). Active/in-flight state stays pinned above it; when over target, idle state discharges back to disk as requests complete." desc_zh: "驻留会话估算字节的软目标(#2803)。活跃/在途状态始终固定保留;超过目标时,空闲状态随请求完成回写磁盘释放。" + - key: sessions.hardMaxBytes + type: number + default: "(same as `sessions.residentMaxBytes`)" + env: BILI_SESSION_RESIDENT_HARD_MAX_BYTES + group: process + desc_en: "Per-SESSION hard cap on estimated resident bytes (#4788, decision #4792 D1-A). Unlike the pool soft cap — which can only evict OTHER cold sessions and never touches a sole-active session — this bounds ONE session: over the cap at a request-end boundary, its droppable fields (folded-block originals, metadata ledger, the raw tail beyond the bounded view) are forced back to disk even for a pool-exempt session, and the next turn transparently re-reads what it needs via narrow disk reads. Safe drops run at every request boundary as long as the last save has provably landed; the cap adds the per-session call-out (warn, throttled to 60 s). `0` disables the cap check." + desc_zh: "单会话驻留字节的硬上限(#4788,决策 #4792 D1-A)。不同于池软上限——它只能逐出其他冷会话、从不触碰唯一活跃会话——它约束单个会话:在请求结束边界超过上限时,其可丢弃字段(已折叠块的原文、元数据账本、超出有界视图的原始尾巴)会被强制回写磁盘,即使该会话被池逐出豁免;下一轮通过窄盘读透明地重新读取所需内容。只要上一次保存已被证明落盘,安全丢弃就在每个请求边界运行;该上限额外加入单会话告警(warn,限流至 60 秒)。`0` 关闭该检查。" - key: sessions.gc.enabled type: boolean default: "false" From 2fb797cf249bb61e76e1d9a72c56b4fa09505e07 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Fri, 30 Oct 2026 14:10:25 +0800 Subject: [PATCH 4/5] test(storage): expect v9 terminal stamp in #4666 concurrent-boots lock test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The #4666 suite's terminal-stamp asserts were moved to v9 when the schema advanced (commit 'expect the v9 stamp in the #4666 migration suite'), but the concurrent-boots lock test's final assert was missed and still expected v8. With MYSQL_SCHEMA_VERSION now 9 (#4796 zero-ref index — index-only, no row change), the migrator legitimately stamps 9 after the lock frees, so 'migration completed after the lock freed' asserted 9!=='8'. Bump to 9 to match the three sibling asserts; the lock-serialization discriminators (mid-flight stamp 7, rowCount 8, dedup collapse) are untouched. --- tests/issue4666-migration-dedup.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/issue4666-migration-dedup.test.ts b/tests/issue4666-migration-dedup.test.ts index bf7f9e62bf..ce41bfea59 100644 --- a/tests/issue4666-migration-dedup.test.ts +++ b/tests/issue4666-migration-dedup.test.ts @@ -537,7 +537,7 @@ test("#4666 mysql: concurrent boots serialize on the migration lock", assert.equal(Number(released[0].ok), 1, "lock released exactly once"); locker.release(); await migrating; - assert.equal(await H.stamp(), "8", "migration completed after the lock freed"); + assert.equal(await H.stamp(), "9", "migration completed after the lock freed"); const s1 = await H.q("SELECT seq FROM messages WHERE session_id = 's1' ORDER BY seq"); assert.deepEqual(s1.map((r) => Number(r.seq)), [1, 2, 3, 5], "fixture collapsed exactly once — no double-delete"); const sLock = await H.q("SELECT seq, identity FROM messages WHERE session_id = 's_lock' ORDER BY seq"); From 3de730d34349c761767a897521ebf47d9f2a8bde Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 12 Nov 2026 06:54:26 +0800 Subject: [PATCH 5/5] test(#5199): build dual-identity fixture by hand for the post-#5196 kernel The PR's original fixture drove its shape through restampRefsToLedger, but #5196's slot-retirement now parks a colliding fresh stamp on a brand-new number instead of reusing the vacated one, so byRef.m00006 no longer resolves to "f" and dualIdentity comes back empty. The host-side dualIdentity detection + warning log (#5199) still needs coverage for the sessions whose PERSISTED superseded map predates #5196, so hand-build that exact end-state (byRef.m00006="f", restampSuperseded={m3->b,m6->e,m7->f}) directly rather than regenerating it through the kernel. --- tests/issue5199-dual-identity-log.test.ts | 34 +++++++++++++++-------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/tests/issue5199-dual-identity-log.test.ts b/tests/issue5199-dual-identity-log.test.ts index 35649b7f99..8c434f6571 100644 --- a/tests/issue5199-dual-identity-log.test.ts +++ b/tests/issue5199-dual-identity-log.test.ts @@ -3,7 +3,7 @@ import test from "node:test"; process.env.NODE_ENV = "test"; -import { createCore, defaultConfig, createInitialState, restampRefsToLedger, emptyRefMap, type CoreMessage, type CompressionState } from "acp-kernel"; +import { createCore, defaultConfig, createInitialState, emptyRefMap, type CoreMessage, type CompressionState } from "acp-kernel"; import { applyRanges, supersededRefRejection, type RewriteCtx } from "../src/stream.ts"; // #5199: after a restart, the cold-load ledger restamp can hand a pre-restart @@ -22,23 +22,33 @@ import { applyRanges, supersededRefRejection, type RewriteCtx } from "../src/str // T4 translation path intact — a genuinely-vacated cite still translates // onto the same message with no dual-identity entry. -// Same drifted shape as tests/issue4797-superseded-deadlock.test.ts: -// rows/seq a=0..f=5; old refs a=m1 b=m3 c=BLOCKED d=m4 e=m6 f=m7. -// Post-restamp (master, no kernel liveness prune): b→m2, e→m5, f takes e's -// vacated m6 → LIVE a=m1 b=m2 d=m4 e=m5 f=m6; superseded {m3→b, m6→e, m7→f}. -// m6 is therefore dual-identity: live for f AND still e's recorded label. +// Pre-#5196 restamped-session shape, built DIRECTLY rather than via +// restampRefsToLedger: #5196 slot-retirement changed the kernel so a fresh +// restamp no longer re-issues a vacated number (in this shape f would park on +// m8 instead of taking e's vacated m6), so the restamp path can no longer +// reproduce the fixture. Sessions restamped BEFORE #5196 still carry exactly +// this persisted shape, which we build verbatim so the host-guard pin stays +// independent of the kernel's current restamp algorithm: +// LIVE: a=m1 b=m2 d=m4 e=m5 f=m6 ; superseded {m3→b, m6→e, m7→f}. +// m6 is therefore dual-identity: live for f AND still e's recorded old label. function restampedSession(): { session: RewriteCtx["session"]; messages: CoreMessage[] } { const state: CompressionState = createInitialState(); const map = emptyRefMap(); map.byRaw.a = "m00001"; map.byRef.m00001 = "a"; - map.byRaw.b = "m00003"; map.byRef.m00003 = "b"; + map.byRaw.b = "m00002"; map.byRef.m00002 = "b"; map.byRaw.c = "BLOCKED"; map.byRaw.d = "m00004"; map.byRef.m00004 = "d"; - map.byRaw.e = "m00006"; map.byRef.m00006 = "e"; - map.byRaw.f = "m00007"; map.byRef.m00007 = "f"; + map.byRaw.e = "m00005"; map.byRef.m00005 = "e"; + map.byRaw.f = "m00006"; map.byRef.m00006 = "f"; state.messageRefs = map; - const seq = new Map([["a", 0], ["b", 1], ["c", 2], ["d", 3], ["e", 4], ["f", 5]]); - const outcome = restampRefsToLedger(state, seq); + // The persisted superseded map such a legacy session carries: each vacated + // number mapped to its pre-restamp owner. m6→e is the dual-identity entry + // (m6 is live for f yet still recorded as e's old label). + const superseded = new Map([ + ["m00003", "b"], + ["m00006", "e"], + ["m00007", "f"], + ]); const messages: CoreMessage[] = [ { id: "a", role: "user", contentType: "text", text: "message a body " + "with enough substance to be worth folding someday. ".repeat(120) }, { id: "b", role: "assistant", contentType: "text", text: "message b body " + "with enough substance to be worth folding someday. ".repeat(120) }, @@ -52,7 +62,7 @@ function restampedSession(): { session: RewriteCtx["session"]; messages: CoreMes stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 0, compressCreditTokens: 0, contextTokens: 0, retrieveCalls: 0, retrieveHits: 0, retrieveMisses: 0, storedBytes: 0, storeBytesSaved: 0, rangeRestores: 0 }, metadata: {}, state, - restampSuperseded: outcome.superseded, + restampSuperseded: superseded, createdAt: Date.now(), lastSeen: Date.now(), blockContents: new Map(),