Skip to content
Open
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
2 changes: 1 addition & 1 deletion docs/configuration.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>`)は名前でスキルを選択する(#1947)。 |
| `compress.protectedLatestTools` | string[] | none | — | 最新の結果が古いものを上書きする累積スナップショット型ツールの最新インスタンスのみを保護する(例:todo リスト)。パスパターンはスキルごとに最新インスタンスを保持する(`skill/*`, #1947)。 |
Expand Down
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>) 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). |
Expand Down
2 changes: 1 addition & 1 deletion docs/configuration.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>)可按名指定 skill(#1947)。 |
| `compress.protectedLatestTools` | string[] | none | — | 只保护累积快照类工具「最新一次」实例(新结果覆盖旧结果的工具,如 todo 列表)。路径模式按 skill 分组各保最新(skill/*,#1947)。 |
Expand Down
4 changes: 2 additions & 2 deletions src/external-summary-compress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 27 additions & 11 deletions src/persist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down
59 changes: 47 additions & 12 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, number>();
// #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<string, number>();
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);
}
}

Expand Down Expand Up @@ -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;
}
Expand All @@ -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,
};
Expand Down Expand Up @@ -2167,6 +2201,7 @@ export function _resetSessionsForTest(max?: number, maxBytes?: number): void {
}
sessions.clear();
evictedWeights.clear();
evictedWeightAt.clear();
}

export function _sessionsSizeForTest(): number {
Expand Down
Loading
Loading