diff --git a/docs/configuration.ja.md b/docs/configuration.ja.md index 80a4e18ec4..254dcd1cf8 100644 --- a/docs/configuration.ja.md +++ b/docs/configuration.ja.md @@ -296,7 +296,7 @@ | `compress.maxSummaryLength` | number | kernel 20000 | — | 1つの生成サマリーに対する文字数のハード上限。これを超える返信は全体として拒否される(切り詰めもリトライもされない)。外部サマライザーにはこの正確な上限が事前に通知される(#3635)。0 = 無制限。 | | `compress.minSummaryLength` | number | kernel 50 | — | 生成サマリーの文字数下限:単一範囲はこれに単独で達する必要がある。複数範囲のバッチは、その結合サマリーがこれに達した場合に合格する(#5894)。0 = 無効。外部サマライザーはサマリーごとの下限に引き続き従う(#3635)。 | | `compress.reconcile` | "off" \| "warn" \| "repair" | "repair" | BILI_FOLD_RECONCILE | クライアントがターン間で履歴を巻き戻しまたは書き換えた場合、フォールド状態を調整する。 | -| `compress.promptPack` | string (builtin: "default", "lean") | builtin "default" | — | 圧縮プロンプトパック。解決順序はプロジェクトパック → ユーザーパック → ビルトイン。`acknowledgePromptsRisk` によるゲートはされない。 | +| `compress.promptPack` | string (builtin: "default", "lean", "chat") | builtin "default" | — | 圧縮プロンプトパック。解決順序はプロジェクトパック → ユーザーパック → 同梱(chat)→ ビルトイン。`acknowledgePromptsRisk` によるゲートはされない。 | | `compress.tiers` | boolean | true | — | T1→T3 の階層型蒸留により、フォールドコストを世代間で分散する。 | | `compress.protectedTools` | string[] | none | — | 全履歴に対するハード除外:リストされたツールの結果は決してフォールドされない。パスパターン(`skill/`)は名前でスキルを選択する(#1947)。 | | `compress.protectedLatestTools` | string[] | none | — | 最新の結果が古いものを上書きする累積スナップショット型ツールの最新インスタンスのみを保護する(例:todo リスト)。パスパターンはスキルごとに最新インスタンスを保持する(`skill/*`, #1947)。 | diff --git a/docs/configuration.md b/docs/configuration.md index bae6ef4768..4f1468b1d2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -297,7 +297,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `compress.maxSummaryLength` | number | kernel 20000 | — | Hard character cap on ONE generated summary; longer replies are rejected whole (no truncation, no retry). External summarizers are told this exact cap up front (#3635). 0 = unbounded. | | `compress.minSummaryLength` | number | kernel 50 | — | Character floor for generated summaries: a single range must meet it alone; a multi-range batch passes when its combined summaries reach it (#5894). 0 = disabled. External summarizers remain held to the per-summary floor (#3635). | | `compress.reconcile` | "off" \| "warn" \| "repair" | "repair" | BILI_FOLD_RECONCILE | Reconcile folded state when the client rewinds or rewrites history between turns. | -| `compress.promptPack` | string (builtin: "default", "lean") | builtin "default" | — | Compression prompt pack, resolved project pack → user pack → builtin; not gated by acknowledgePromptsRisk. | +| `compress.promptPack` | string (builtin: "default", "lean", "chat") | builtin "default" | — | Compression prompt pack, resolved project pack → user pack → shipped pack → builtin; not gated by acknowledgePromptsRisk. | | `compress.tiers` | boolean | true | — | Tiered T1→T3 distillation spreads folding cost across generations. | | `compress.protectedTools` | string[] | none | — | Hard exclusion across all history: results of listed tools never fold. Path patterns (skill/) select skills by name (#1947). | | `compress.protectedLatestTools` | string[] | none | — | Protects only the LATEST instance of cumulative-snapshot tools whose newest result supersedes older ones (e.g. todo lists). Path patterns keep the latest instance per skill (skill/*, #1947). | diff --git a/docs/configuration.zh-CN.md b/docs/configuration.zh-CN.md index 45861d8461..3ac9155d64 100644 --- a/docs/configuration.zh-CN.md +++ b/docs/configuration.zh-CN.md @@ -297,7 +297,7 @@ | `compress.maxSummaryLength` | number | kernel 20000 | — | 单条生成摘要的硬字符上限;超长的回复被整段拒绝(不截断、不重试)。外部摘要模型会被提前告知这个确切上限(#3635)。0 = 不限制。 | | `compress.minSummaryLength` | number | kernel 50 | — | 生成摘要的字符下限:单段压缩按自身判定;批量压缩按合计判定——一段偷懒不再拖垮整批(#5894)。0 = 禁用。外部摘要模型仍受逐段下限约束(#3635)。 | | `compress.reconcile` | "off" \| "warn" \| "repair" | "repair" | BILI_FOLD_RECONCILE | 客户端在轮次之间回退或改写历史时校准已折叠状态。 | -| `compress.promptPack` | string (builtin: "default", "lean") | builtin "default" | — | 压缩提示词包,按 项目包 → 用户包 → 内置 解析;不受 acknowledgePromptsRisk 门控。 | +| `compress.promptPack` | string (builtin: "default", "lean", "chat") | builtin "default" | — | 压缩提示词包,按 项目包 → 用户包 → 随包附带(chat)→ 内置 解析;不受 acknowledgePromptsRisk 门控。 | | `compress.tiers` | boolean | true | — | T1→T3 分级蒸馏把折叠成本摊到多代。 | | `compress.protectedTools` | string[] | none | — | 全历史硬排除:列出工具的结果永不折叠。路径模式(skill/)可按名指定 skill(#1947)。 | | `compress.protectedLatestTools` | string[] | none | — | 只保护累积快照类工具「最新一次」实例(新结果覆盖旧结果的工具,如 todo 列表)。路径模式按 skill 分组各保最新(skill/*,#1947)。 | diff --git a/src/external-summary-compress.ts b/src/external-summary-compress.ts index 1b0fe34898..6bfdf1886e 100644 --- a/src/external-summary-compress.ts +++ b/src/external-summary-compress.ts @@ -45,8 +45,8 @@ export async function applyConfiguredCompression(input: unknown, ctx: RewriteCtx const parsed = parseCompressInput(withOptionalSummaries(input), callId); if (parsed.ranges.length === 0) return applyRanges(parsed, ctx); normalizeRangeOrder(parsed.ranges); - recoverEvictedView(ctx); - const noView = noVisibleContextRefusal(ctx, parsed.ranges); + const tailViewReason = recoverEvictedView(ctx); + const noView = noVisibleContextRefusal(ctx, parsed.ranges, { tailViewReason }); if (noView) return noView; // #5558: resolve superseded refs BEFORE the probe preview — the preview // judges foldability while applyRanges re-resolves refs on every entry, so diff --git a/src/persist.ts b/src/persist.ts index ace6808cd4..d25ce870f7 100644 --- a/src/persist.ts +++ b/src/persist.ts @@ -2469,6 +2469,19 @@ export class SessionStore { } } + /** #5111: same read as unifiedTailViewRows, but WHY it came back empty is + * part of the answer — the no-visible-context refusal quotes this reason so + * a reporter can distinguish "store never had a copy" from "store degraded". */ + unifiedTailViewDiagnostic(sessionId: string): { rows: import("./storage/store.js").MessageRow[] | null; reason: string } { + if (!this.shadow) return { rows: null, reason: "unified-store-off" }; + if (this.shadow.stats.disabled) return { rows: null, reason: "sidecar-degraded" }; + try { + return { rows: this.shadow.tailViewRows(sessionId), reason: "ok" }; + } catch { + return { rows: null, reason: "read-error" }; + } + } + /** #4738: per-ref message bodies from the unified store — the web fallback * for hosts whose native compaction pruned the resident window. Null when * the unified store is unavailable — callers keep their legacy "missing" @@ -4449,26 +4462,29 @@ function peekStoreForStamp(): SessionStore | null { * session from the unified transcript. Read-only and peek-only — the module * singleton must already exist (never construct a store on a compress path); * a disabled/unavailable sidecar, zero rows, or ANY unparsable row returns - * null so callers keep their honest refusal instead of folding against a - * half-readable view. Rows are the raw client view caliber (#2627 — what a - * live model request would have re-sent), persisted on every save via the - * raw-tail ingest. */ -export function peekStoredTailView(sessionId: string): BiliMessage[] | null { + * unreadable (view: null + named reason) so callers keep their honest + * refusal instead of folding against a half-readable view. Rows are the raw + * client view caliber (#2627 — what a live model request would have + * re-sent), persisted on every save via the raw-tail ingest. #5111: the + * failure reason is named, so the refusal receipt can say WHY no fallback + * copy was readable instead of only that none was. */ +export function storedTailViewStatus(sessionId: string): { view: BiliMessage[] | null; reason: string } { const store = peekStoreForStamp(); - if (!store) return null; - const rows = store.unifiedTailViewRows(sessionId); - if (!rows || rows.length === 0) return null; + if (!store) return { view: null, reason: "store-inactive" }; + const { rows, reason } = store.unifiedTailViewDiagnostic(sessionId); + if (!rows) return { view: null, reason }; + if (rows.length === 0) return { view: null, reason: "no-persisted-rows" }; const messages: BiliMessage[] = []; for (const row of rows) { try { const parsed = JSON.parse(row.content) as BiliMessage; - if (typeof parsed?.id !== "string" || typeof parsed?.role !== "string") return null; + if (typeof parsed?.id !== "string" || typeof parsed?.role !== "string") return { view: null, reason: "unparsable-row" }; messages.push(parsed); } catch { - return null; + return { view: null, reason: "unparsable-row" }; } } - return messages; + return { view: messages, reason: "recovered" }; } export function getStore(): SessionStore { diff --git a/src/session.ts b/src/session.ts index 33c9833c52..69400ac214 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1207,15 +1207,21 @@ function isColdLoadGraced(session: Session): boolean { // is advisory (it only shapes refusal wording), never load-bearing; bounded so // a long-lived process cannot accumulate unbounded entries. const evictedWeights = new Map(); +// #5111: when each eviction-time measurement was taken — the refusal receipt +// quotes the stamped weight as "last measured", and reporters comparing it +// against /__bili/memory minutes later need to know how stale that number is. +const evictedWeightAt = new Map(); const EVICTED_WEIGHT_CAP = 256; function stampEvictedWeight(id: string, bytes: number): void { if (evictedWeights.has(id)) evictedWeights.delete(id); evictedWeights.set(id, bytes); + evictedWeightAt.set(id, Date.now()); while (evictedWeights.size > EVICTED_WEIGHT_CAP) { const oldest = evictedWeights.keys().next().value; if (oldest === undefined) break; evictedWeights.delete(oldest); + evictedWeightAt.delete(oldest); } } @@ -1324,25 +1330,42 @@ function residentBytes(): number { return bytes; } -/** #3918: can this session's message view survive BETWEEN model requests? The - * empty-view compress refusal (#3126) self-heals on the next model request ONLY - * when the reloaded session stays resident afterwards. When the session's - * last-known live weight plus the other residents exceeds the byte budget, - * every request cycle ends with it evicted again (releaseInFlight discharge) - * and the refusal repeats identically forever — the incident's 444 MiB image - * session ping-ponged against an 87.5 MiB peer under the 512 MiB default. - * Returns the measured pressure so the refusal receipt says so plainly instead - * of promising a heal that will not come. #5782: a RESIDENT session inside its - * cold-load grace window is protected from that discharge, so the same shape is - * transient again while graced — the claim must say so or the receipt lies. */ +// #5111: peers with traffic within this window are "active" for permanence +// accounting — only they can evict a reloaded session back out between requests. +// Idle peers yield their slot to admission (evictOldest walks by lastSeen), so +// counting them made the #3918 refusal verdict falsely permanent. +const PEER_ACTIVE_WINDOW_MS = 5 * 60 * 1000; + +/** #3918/#5111: can this session's message view survive BETWEEN model requests? + * The empty-view compress refusal (#3126) self-heals on the next model request ONLY + * when the reloaded session stays resident afterwards. Admission (makeResidentRoom) + * seats any incoming session whose own weight fits the budget by evicting the + * OLDEST idle residents first — idle peers do not block recovery. The refusal is + * permanent only when (a) the session's last-known live weight alone exceeds the + * whole budget (closing others cannot help), or (b) that weight cannot fit alongside + * the ACTIVE peers (traffic within PEER_ACTIVE_WINDOW_MS): every request cycle then + * ends with it evicted again (releaseInFlight discharge) and the refusal repeats + * identically forever — the incident's 444 MiB image session ping-ponged against an + * 87.5 MiB peer under the 512 MiB default. Returns the measured pressure so the + * refusal receipt says so plainly instead of promising a heal that will not come. + * #5782: a RESIDENT session inside its cold-load grace window is protected from + * that discharge, so the same shape is transient again while graced — the claim + * must say so or the receipt lies. */ interface ResidentPressure { /** True when retrying cannot restore a usable view under the CURRENT pool state. */ permanent: boolean; /** Last-known LIVE weight of this session (eviction-time measurement; falls * back to its resident weight when it is resident now). Undefined = unknown. */ weightBytes?: number; + /** Age in ms of the eviction-time measurement behind weightBytes (the pool + * drains over time — /__bili/memory minutes later can be far lower); + * undefined when the quoted weight is a live resident measurement or unknown. */ + weightAgeMs?: number; /** Resident bytes held by all OTHER sessions (this one excluded). */ otherBytes: number; + /** Resident bytes held by OTHER sessions with traffic within + * PEER_ACTIVE_WINDOW_MS — the peers that actually compete for the slot. */ + activeOtherBytes: number; residentBytes: number; budgetBytes: number; } @@ -1353,11 +1376,22 @@ export function residentPressure(id: string): ResidentPressure { const total = residentBytes(); const known = evictedWeights.get(id); const weightBytes = known !== undefined ? Math.max(known, self) : resident ? self : undefined; + const now = Date.now(); + let activeOtherBytes = 0; + for (const s of sessions.values()) { + if (s.id !== id && now - s.lastSeen <= PEER_ACTIVE_WINDOW_MS) activeOtherBytes += sessionWeight(s); + } const graced = resident !== undefined && isColdLoadGraced(resident); + const stampedAt = evictedWeightAt.get(id); return { - permanent: weightBytes !== undefined && !graced && weightBytes + (total - self) > MAX_RESIDENT_BYTES, + permanent: !graced && weightBytes !== undefined && + (weightBytes > MAX_RESIDENT_BYTES || weightBytes + activeOtherBytes > MAX_RESIDENT_BYTES), weightBytes, + // The quoted figure is only "last measured" when the eviction-time stamp + // dominates a live resident weight — then its age is what makes it stale. + weightAgeMs: known !== undefined && known >= self && stampedAt !== undefined ? now - stampedAt : undefined, otherBytes: total - self, + activeOtherBytes, residentBytes: total, budgetBytes: MAX_RESIDENT_BYTES, }; @@ -2167,6 +2201,7 @@ export function _resetSessionsForTest(max?: number, maxBytes?: number): void { } sessions.clear(); evictedWeights.clear(); + evictedWeightAt.clear(); } export function _sessionsSizeForTest(): number { diff --git a/src/stream.ts b/src/stream.ts index ec673240df..951e94563f 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -11,7 +11,7 @@ import { executeSearchContextTarget, resolveDecompress } from "./decompress-shar import { ONE_CALL_HINT } from "acp-kernel"; import { adoptContentStore, contentStoreOf, ccrEnabled, drainPendingRetrievals, executeRetrieve, retrieveToolName } from "./store.js"; import { recordThreadTail } from "./server/thread-tracking.js"; -import { peekStoredTailView } from "./persist.js"; +import { storedTailViewStatus } from "./persist.js"; import { imagePlaceholdersForSummary } from "./image-note.js"; import { containsBiliInternalText, containsMarkerLineText, containsRenderTagText, containsToolCallEmissionText, stripAcpTags } from "./loop/tag-echo-filter.js"; import { maxShrinkPerCompress } from "./fetch-util.js"; @@ -763,7 +763,7 @@ const DEGENERATE_FOLD_COVERAGE = 0.8; export function noVisibleContextRefusal( ctx: RewriteCtx, ranges: ParsedRange[], - opts?: { loopTracking?: boolean }, + opts?: { loopTracking?: boolean; /** #5111: why the persisted-view fallback (#3982) came up empty — named so the receipt stops asserting a cause the diagnostics endpoint contradicts. */ tailViewReason?: string }, ): ProxyToolResult | null { const view = ctx.compressMessages ?? ctx.messages; const mappedRefs = Object.keys(ctx.session.state.messageRefs?.byRef ?? {}).length; @@ -790,24 +790,45 @@ export function noVisibleContextRefusal( const detail = ranges.map((r) => `${r.startRef}–${r.endRef}`).join(", "); // #3918: the "self-heals on the next model request" promise holds ONLY when // the reloaded session survives between requests. When this session's - // last-known live weight cannot fit alongside the current residents within + // last-known live weight cannot fit alongside the ACTIVE residents within // the byte budget, every request cycle ends with it evicted again and this // exact refusal repeats forever — say so plainly instead of advising an // impossible retry (the incident: a ~444 MiB image session ping-ponging - // against an ~87.5 MiB peer under the 512 MiB default budget). + // against an ~87.5 MiB peer under the 512 MiB default budget). #5111: idle + // peers do not break the promise — admission evicts them to seat the + // reloaded session — so permanence is judged against active peers only, and + // a session too heavy for the WHOLE budget gets its own exit advice (closing + // others cannot help there). const pressure = residentPressure(ctx.session.id); + const selfExceedsBudget = (pressure.weightBytes ?? 0) > pressure.budgetBytes; + // #5111: the stamped weight is a snapshot of eviction time — name its age so + // a later /__bili/memory reading (the pool DRAINS between requests) is not + // misread as contradicting this refusal. + const ageSec = pressure.weightAgeMs !== undefined ? Math.max(1, Math.round(pressure.weightAgeMs / 1000)) : undefined; + const weightNote = ageSec !== undefined ? `, measured ${ageSec}s ago` : ""; + const recoveryReason = opts?.tailViewReason && opts.tailViewReason !== "recovered" && opts.tailViewReason !== "live-view" ? opts.tailViewReason : undefined; + const tailLogNote = recoveryReason ? `; persisted-view recovery unavailable (${recoveryReason})` : ""; ctx.log(pressure.permanent - ? `[acp-proxy: compress REFUSED ${detail} — no visible context (view=0 message(s), ${mappedRefs} ref(s) mapped); refs left untouched and nothing recorded as dead — PERMANENT: last-known weight ${formatMiB(pressure.weightBytes)} + other residents ${formatMiB(pressure.otherBytes)} > budget ${formatMiB(pressure.budgetBytes)}; the session cannot stay resident between model requests (#3918)]` - : `[acp-proxy: compress REFUSED ${detail} — no visible context (view=0 message(s), ${mappedRefs} ref(s) mapped); refs left untouched and nothing recorded as dead — the view self-heals on the next model request (#3126)]`); + ? `[acp-proxy: compress REFUSED ${detail} — no visible context (view=0 message(s), ${mappedRefs} ref(s) mapped); refs left untouched and nothing recorded as dead — PERMANENT: last-known weight ${formatMiB(pressure.weightBytes)}${weightNote}${selfExceedsBudget ? " alone exceeds the whole budget" : ` + active other residents ${formatMiB(pressure.activeOtherBytes)} (idle peers excluded)`} > budget ${formatMiB(pressure.budgetBytes)}; the session cannot stay resident between model requests (#3918/#5111)${tailLogNote}]` + : `[acp-proxy: compress REFUSED ${detail} — no visible context (view=0 message(s), ${mappedRefs} ref(s) mapped); refs left untouched and nothing recorded as dead — the view self-heals on the next model request (#3126)${tailLogNote}]`); const specKey = normalizedSpecKey(ranges); const repeatGuard = recordCompressFailure(ctx.session, specKey, pressure.permanent - ? "This failure repeats until the resident pool can hold this session alongside the others — closing another open session or raising sessions.residentMaxBytes clears it; waiting for the next turn does NOT." + ? (selfExceedsBudget + ? "This failure repeats until the pool budget can hold this session ALONE — closing other sessions will NOT free room for it; raise sessions.residentMaxBytes above ~the session's footprint and restart bili." + : "This failure repeats until the resident pool can hold this session alongside the others — closing another open session or raising sessions.residentMaxBytes clears it; waiting for the next turn does NOT.") : "This failure is the proxy's missing in-memory message view, not your refs — it clears on the next model request. Wait for that turn instead of re-issuing."); const loopGuard = opts?.loopTracking === false ? "" : noteCompressLoopFailure(ctx, specKey, undefined, "no-visible-context"); const healClause = pressure.permanent - ? ` THIS REFUSAL IS NOT TRANSIENT: your session's last measured memory footprint (~${formatMiB(pressure.weightBytes)}) plus the other resident sessions (~${formatMiB(pressure.otherBytes)}) exceed the resident pool budget (${formatMiB(pressure.budgetBytes)}), so every reload of this session is evicted again and no usable view survives between model requests — retrying now or after the next turn fails identically. To recover: finish or close the other open session(s), or raise sessions.residentMaxBytes in ~/.config/billion-context/billion-context.json (env twin BILI_SESSION_RESIDENT_MAX_BYTES) above ~${formatMiB((pressure.weightBytes ?? 0) + pressure.otherBytes)} and restart bili.` + ? (selfExceedsBudget + ? ` THIS REFUSAL IS NOT TRANSIENT: your session's last measured memory footprint (~${formatMiB(pressure.weightBytes)}${weightNote}) alone exceeds the resident pool budget (${formatMiB(pressure.budgetBytes)}) — closing other sessions will NOT free room for it, so retrying now or after the next turn fails identically. To recover: raise sessions.residentMaxBytes in ~/.config/billion-context/billion-context.json (env twin BILI_SESSION_RESIDENT_MAX_BYTES) above ~${formatMiB(pressure.weightBytes)} and restart bili.` + : ` THIS REFUSAL IS NOT TRANSIENT: your session's last measured memory footprint (~${formatMiB(pressure.weightBytes)}${weightNote}) plus the other ACTIVE resident sessions (~${formatMiB(pressure.activeOtherBytes)}) exceed the resident pool budget (${formatMiB(pressure.budgetBytes)}), so every reload of this session is evicted again and no usable view survives between model requests — retrying now or after the next turn fails identically. To recover: finish or close the other open session(s), or raise sessions.residentMaxBytes in ~/.config/billion-context/billion-context.json (env twin BILI_SESSION_RESIDENT_MAX_BYTES) above ~${formatMiB((pressure.weightBytes ?? 0) + pressure.activeOtherBytes)} and restart bili.`) : "Do NOT retry now — every retry fails identically until the next model request re-sends the conversation and restores the view. Continue your task; after the next turn you can compress the same ranges again."; - const receipt = `[Compression FAILED: no visible context — the proxy holds no live message view of this conversation right now (its in-memory copy was dropped between model requests, e.g. by memory eviction or a restart). Your refs are intact and NOTHING was marked dead: ${mappedRefs} ref(s) remain mapped, and this is NOT a ref problem.${healClause} [cause: no-visible-context]${repeatGuard}${loopGuard}]`; + // #5111: name why the persisted-view fallback (#3982) could not serve this + // call — "no readable fallback copy" has several distinct causes, and the + // old receipt asserted over-budget eviction as THE cause even when the pool + // had since drained below budget. Additive line; existing wording untouched. + const tailReceiptNote = recoveryReason ? ` Persisted-view recovery was attempted and found nothing readable (${recoveryReason}).` : ""; + const receipt = `[Compression FAILED: no visible context — the proxy holds no live message view of this conversation right now (its in-memory copy was dropped between model requests, e.g. by memory eviction or a restart). Your refs are intact and NOTHING was marked dead: ${mappedRefs} ref(s) remain mapped, and this is NOT a ref problem.${healClause}${tailReceiptNote} [cause: no-visible-context]${repeatGuard}${loopGuard}]`; return compressResult(receipt, "refused", 0, "gate:no-visible-context"); } @@ -818,13 +839,18 @@ export function noVisibleContextRefusal( * A non-empty live view stays authoritative — the store is never consulted * for it. Shared by the plain-compress lane (applyRanges) and the external- * summary lane (applyConfiguredCompression). */ -export function recoverEvictedView(ctx: RewriteCtx): void { - if ((ctx.compressMessages ?? ctx.messages).length > 0) return; - const recovered = peekStoredTailView(ctx.session.id); - if (recovered && recovered.length > 0) { - ctx.compressMessages = recovered; - ctx.log(`[acp-proxy: view recovered from the unified store — ${recovered.length} message(s); folding against the persisted raw view (#3982)]`); +export function recoverEvictedView(ctx: RewriteCtx): string { + if ((ctx.compressMessages ?? ctx.messages).length > 0) return "live-view"; + const { view, reason } = storedTailViewStatus(ctx.session.id); + if (view && view.length > 0) { + ctx.compressMessages = view; + ctx.log(`[acp-proxy: view recovered from the unified store — ${view.length} message(s); folding against the persisted raw view (#3982)]`); + return "recovered"; } + // #5111: the reason is now part of the answer — the refusal receipt quotes + // it so "no fallback copy" stops being an unexplained assertion. + ctx.log(`[acp-proxy: persisted-view recovery unavailable (${reason}) — keeping the honest empty-view path (#5111)]`); + return reason; } function formatMiB(bytes: number | undefined): string { @@ -1227,8 +1253,8 @@ export function applyRanges(parsed: ReturnType, ctx: 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}]`); } - recoverEvictedView(ctx); - const noView = noVisibleContextRefusal(ctx, ranges, { loopTracking: trackLoop }); + const tailViewReason = recoverEvictedView(ctx); + const noView = noVisibleContextRefusal(ctx, ranges, { loopTracking: trackLoop, tailViewReason }); if (noView) return noView; // #2749: reject summaries that are byte-identical to a display stub the // model can currently see (the fragments it can "recall" after the diff --git a/tests/issue5111-resident-pressure-idle-peers.test.ts b/tests/issue5111-resident-pressure-idle-peers.test.ts new file mode 100644 index 0000000000..b2a6decd22 --- /dev/null +++ b/tests/issue5111-resident-pressure-idle-peers.test.ts @@ -0,0 +1,177 @@ +// #5111: the #3918 permanence verdict counted ALL other residents, but +// admission (makeResidentRoom) seats any session whose own weight fits the +// budget by evicting IDLE peers first — so an evicted session whose peers are +// just leftover idle sessions was told "NOT TRANSIENT ... close sessions or +// raise the limit and restart" when its next model request would have healed +// it. These tests pin the refined verdict: idle peers do not make the refusal +// permanent (self-heal wording stands), active peers still do, and a session +// too heavy for the whole budget alone keeps the permanent claim WITH ITS OWN +// exit advice (closing others cannot help). The gate itself stays pinned in +// tests/issue3126-no-visible-context.test.ts; the fresh-peer direction stays +// pinned in tests/issue3918-resident-eviction-refusal.test.ts. +// +// The "exact reason code" test below asserts the receipt names the persisted-view +// fallback failure as (no-persisted-rows) — that code only exists when the unified +// sidecar is OPEN (a closed sidecar yields unified-store-off instead). The ambient +// storage mode is environment-dependent: a developer's config may set storage.unified, +// but CI's hermetic preload (tests/preload-test-env.mjs) points XDG_CONFIG_HOME at a +// fresh temp dir with none, so the sidecar is closed there and the receipt reads +// (unified-store-off) — the #5118 CI red. Pin the sidecar open to keep the receipt +// deterministic (same ambient-env note as tests/issue4241-judge-render-baseline.test.ts). +process.env.BILI_STORAGE_UNIFIED = "shadow"; +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import type { CoreMessage } from "acp-kernel"; +import { createCore, defaultConfig, assignRefs, emptyRefMap } from "acp-kernel"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { getSession, acquireInFlight, releaseInFlight, markDirty, peekSession, residentPressure, _resetSessionsForTest } from "../src/session.ts"; +import { parseCompressInput } from "../src/compress-tool.ts"; +import { applyRanges, type RewriteCtx } from "../src/stream.ts"; + +const BUDGET = 300_000; + +const MESSAGES = Array.from({ length: 80 }, (_, i) => ({ + id: `raw${i}`, + role: (i % 2 ? "assistant" : "user") as "assistant" | "user", + text: "lorem ipsum dolor sit amet conseq ".repeat(8) + i, +})) as unknown as CoreMessage[]; + +function makeCtx(session: RewriteCtx["session"], logs: string[]): RewriteCtx { + return { + core: createCore(), + config: defaultConfig(200000, { preserveRecentMessages: 5, preserveRecentTokens: 0 }), + messages: [], + session, + log: (m: string) => { logs.push(m); }, + }; +} + +const SPEC = () => parseCompressInput({ content: [{ startId: "m00010", endId: "m00040", summary: "y".repeat(100) }] }); + +async function fixture(run: () => Promise): Promise { + const root = mkdtempSync(path.join(os.tmpdir(), "bili-5111-")); + const store = new SessionStore({ dir: path.join(root, "sessions"), enabled: true, debounceMs: 0 }); + _resetSessionsForTest(256, BUDGET); + _setStoreForTest(store); + try { await run(); } finally { + store.closeQuietly(); + _resetSessionsForTest(256, 512 * 1024 * 1024); + _setStoreForTest(new SessionStore({ enabled: false })); + rmSync(root, { recursive: true, force: true }); + } +} + +/** Same recipe as growAndEvictBig in the #3918 suite: big-sess is evicted by + * releaseInFlight's discharge with its live weight stamped, peer-sess stays + * resident. Returns the evicted object (alive in JS, refs intact). */ +function growAndEvictBig(): RewriteCtx["session"] { + const big = getSession("big-sess"); + const peer = getSession("peer-sess"); + big.state.messageRefs = assignRefs(MESSAGES, { existing: emptyRefMap(), nextIndex: 0 }).map; + big.metadata.blob = "x".repeat(80_000); + peer.metadata.blob = "y".repeat(60_000); + markDirty(big); + markDirty(peer); + acquireInFlight(big); + releaseInFlight(big); + return big; +} + +test("#5111: an IDLE peer does not make the refusal permanent — admission evicts it to seat the reloaded session", async () => fixture(async () => { + const big = growAndEvictBig(); + // Backdate the peer past PEER_ACTIVE_WINDOW_MS (5 min): a leftover session + // with no recent traffic is exactly what the #5111 report hit. + const peer = peekSession("peer-sess"); + assert.ok(peer, "peer still resident after big's discharge"); + peer!.lastSeen = Date.now() - 10 * 60 * 1000; + const p = residentPressure(big.id); + assert.ok(p.weightBytes !== undefined && p.weightBytes < BUDGET, `self fits the budget alone: ${p.weightBytes} < ${BUDGET}`); + assert.ok(p.otherBytes > 50_000, `idle peer still occupies budget space (diagnostics unchanged): ${p.otherBytes}`); + assert.equal(p.activeOtherBytes, 0, `idle peer excluded from permanence accounting: ${p.activeOtherBytes}`); + assert.equal(p.permanent, false, "self fits + no active peers → transient again"); + const logs: string[] = []; + const res = applyRanges(SPEC(), makeCtx(big, logs)); + assert.equal(res.outcome, "refused"); + assert.equal(res.reason, "gate:no-visible-context"); + assert.ok(res.text.includes("Do NOT retry now"), `self-heal wording restored: ${res.text}`); + assert.ok(!res.text.includes("NOT TRANSIENT"), `no false permanent claim with idle peers: ${res.text}`); + assert.ok(!logs.some((l) => l.includes("PERMANENT")), "log stays on the #3126 self-heal line"); +})); + +test("#5111: an ACTIVE peer still makes the refusal permanent (negative direction of the refined verdict)", async () => fixture(async () => { + const big = growAndEvictBig(); + const p = residentPressure(big.id); + assert.ok(p.activeOtherBytes > 50_000, `freshly-touched peer counts as active: ${p.activeOtherBytes}`); + assert.ok(p.permanent, `weight ${p.weightBytes} + active ${p.activeOtherBytes} > budget ${BUDGET} → still permanent`); + const logs: string[] = []; + const res = applyRanges(SPEC(), makeCtx(big, logs)); + assert.equal(res.outcome, "refused"); + assert.ok(res.text.includes("NOT TRANSIENT"), `permanent case named: ${res.text}`); + assert.ok(res.text.includes("ACTIVE resident sessions"), `receipt quotes the active-peer bytes: ${res.text}`); + assert.ok(logs.some((l) => l.includes("PERMANENT") && l.includes("active other residents")), `log carries the active-peer marker: ${JSON.stringify(logs)}`); +})); + +test("#5111: a session heavier than the WHOLE budget alone is permanent — and closing others is NOT offered as an exit", async () => fixture(async () => { + const big = getSession("big-sess"); + big.state.messageRefs = assignRefs(MESSAGES, { existing: emptyRefMap(), nextIndex: 0 }).map; + big.metadata.blob = "x".repeat(350_000); + markDirty(big); + acquireInFlight(big); + releaseInFlight(big); + const p = residentPressure(big.id); + assert.ok(p.weightBytes !== undefined && p.weightBytes > BUDGET, `self alone exceeds the budget: ${p.weightBytes} > ${BUDGET}`); + assert.equal(p.otherBytes, 0, "no peers at all"); + assert.equal(p.activeOtherBytes, 0, "nothing to count as active"); + assert.ok(p.permanent, "heavier-than-budget-alone → permanent even with an empty pool"); + const logs: string[] = []; + const res = applyRanges(SPEC(), makeCtx(big, logs)); + assert.equal(res.outcome, "refused"); + assert.equal(res.reason, "gate:no-visible-context"); + assert.ok(res.text.includes("NOT TRANSIENT"), `permanent case named: ${res.text}`); + assert.ok(res.text.includes("will NOT free room"), `closing-others advice withdrawn for this shape: ${res.text}`); + assert.ok(res.text.includes("sessions.residentMaxBytes"), `raise-limit exit still given: ${res.text}`); + assert.ok(logs.some((l) => l.includes("PERMANENT") && l.includes("alone exceeds the whole budget")), `log names the self-exceeds shape: ${JSON.stringify(logs)}`); +})); + +test("#5111: unknown session keeps no permanent claim and zeroed active accounting", async () => fixture(async () => { + growAndEvictBig(); + const p = residentPressure("never-seen"); + assert.equal(p.permanent, false, "unknown session: no permanent claim without a known weight"); + assert.equal(p.weightBytes, undefined, "unknown session: no weight to quote"); +})); + +// #5111 follow-up (repro on a live box): the refusal asserted over-budget +// eviction as THE cause while the persisted-view fallback (#3982) failed for +// its own unexplained reason, and the quoted footprint carried no timestamp +// even though the pool drains between requests. Pin both fixes: the receipt +// names WHY no fallback copy was readable (stable reason codes from +// storedTailViewStatus) and quotes how stale the stamped weight is. +test("#5111: the refusal names why the persisted-view fallback came up empty (exact reason code)", async () => fixture(async () => { + const big = growAndEvictBig(); + const peer = peekSession("peer-sess"); + assert.ok(peer); + peer!.lastSeen = Date.now() - 10 * 60 * 1000; + const logs: string[] = []; + const res = applyRanges(SPEC(), makeCtx(big, logs)); + assert.equal(res.outcome, "refused"); + // Fixture shape: unified-FULL store exists but never persisted a raw-tail + // row for this session (transient views are not saved) → no-persisted-rows. + assert.ok(res.text.includes("Persisted-view recovery was attempted and found nothing readable (no-persisted-rows)."), + `receipt names the fallback failure cause: ${res.text}`); + assert.ok(logs.some((l) => l.includes("persisted-view recovery unavailable (no-persisted-rows)")), + `log carries the same code: ${JSON.stringify(logs)}`); +})); + +test("#5111: the quoted footprint carries its measurement age (stale-snapshot guard)", async () => fixture(async () => { + const big = growAndEvictBig(); + const p = residentPressure(big.id); + assert.ok(p.weightAgeMs !== undefined && p.weightAgeMs >= 0 && p.weightAgeMs < 60_000, + `freshly evicted stamp has a small age: ${p.weightAgeMs}`); + const logs: string[] = []; + const res = applyRanges(SPEC(), makeCtx(big, logs)); + assert.match(res.text, /measured \d+s ago/, `receipt timestamps the quoted footprint: ${res.text}`); + assert.ok(logs.some((l) => l.includes("PERMANENT") && /measured \d+s ago/.test(l)), `log timestamps it too: ${JSON.stringify(logs)}`); +})); diff --git a/website/config-reference/compress.yaml b/website/config-reference/compress.yaml index 700ac82737..d427cb0868 100644 --- a/website/config-reference/compress.yaml +++ b/website/config-reference/compress.yaml @@ -226,14 +226,14 @@ entries: site_en: "\"off\" | \"warn\" | \"repair\" (default repair): reconcile folded state when the client rewinds or rewrites history between turns." site_zh: "\"off\" | \"warn\" | \"repair\"(默认 repair):客户端在轮次之间回退或改写历史时校准已折叠状态。" - key: compress.promptPack - type: "string (builtin: \"default\", \"lean\")" + type: "string (builtin: \"default\", \"lean\", \"chat\")" default: "builtin \"default\"" group: compress id: cw.ppk render: compress-row - desc_en: "Compression prompt pack, resolved project pack → user pack → builtin; not gated by acknowledgePromptsRisk." - desc_zh: "压缩提示词包,按 项目包 → 用户包 → 内置 解析;不受 acknowledgePromptsRisk 门控。" - desc_ja: "圧縮プロンプトパック。解決順序はプロジェクトパック → ユーザーパック → ビルトイン。`acknowledgePromptsRisk` によるゲートはされない。" + desc_en: "Compression prompt pack, resolved project pack → user pack → shipped pack → builtin; not gated by acknowledgePromptsRisk." + desc_zh: "压缩提示词包,按 项目包 → 用户包 → 随包附带(chat)→ 内置 解析;不受 acknowledgePromptsRisk 门控。" + desc_ja: "圧縮プロンプトパック。解決順序はプロジェクトパック → ユーザーパック → 同梱(chat)→ ビルトイン。`acknowledgePromptsRisk` によるゲートはされない。" site_en: "Compression prompt pack, resolved project pack → user pack → builtin. Builtins: \"default\" and \"lean\" (one-line tool descriptions). Not gated by acknowledgePromptsRisk." site_zh: "压缩提示词包,按 项目包 → 用户包 → 内置 解析。内置:\"default\" 与 \"lean\"(单行工具描述)。不受 acknowledgePromptsRisk 门控。" - key: compress.tiers diff --git a/website/docs/index.html b/website/docs/index.html index 4b1172324e..9cb6b813df 100644 --- a/website/docs/index.html +++ b/website/docs/index.html @@ -201,7 +201,7 @@

compress — every knob

maxSummaryLengthnumberHard cap, in characters, on one generated summary (kernel default 20000): longer replies are rejected whole by the kernel check or the external-summary executor. External summarizers receive this exact cap in their instructions (#3635); 0 disables the cap. minSummaryLengthnumberFloor, in characters, for generated summaries (kernel default 50): a single range must meet it on its own; a multi-range batch passes when its COMBINED summaries reach it — one lazy paragraph no longer sinks the whole batch (#5894). 0 disables the floor. External summarizers remain held to the per-summary floor (#3635). reconcile"off" | "warn" | "repair""off" | "warn" | "repair" (default repair): reconcile folded state when the client rewinds or rewrites history between turns. - promptPackstring (builtin: "default", "lean")Compression prompt pack, resolved project pack → user pack → builtin. Builtins: "default" and "lean" (one-line tool descriptions). Not gated by acknowledgePromptsRisk. + promptPackstring (builtin: "default", "lean", "chat")Compression prompt pack, resolved project pack → user pack → builtin. Builtins: "default" and "lean" (one-line tool descriptions). Not gated by acknowledgePromptsRisk. tiersbooleanOn by default: tiered T1→T3 distillation spreads folding cost across generations. protectedToolsstring[]Hard exclusion across all history: results of listed tools never fold (use with care). protectedLatestToolsstring[]Protects only the LATEST instance of cumulative-snapshot tools whose newest result supersedes older ones (e.g. todo lists).