From 3953671a61d527f110454bb86ec3e3eb9be7b2ce Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 23 Sep 2026 22:24:28 +0800 Subject: [PATCH 1/4] fix: GC the CCR content-store companions (#1180) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Session-file GC (#1082) ignored the per-session CCR content stores added by #1097: walkSessionFiles picked up .content-store.json but viewFromParsed rejected it (no savedAt field), so it was counted unreadable and kept forever — and when a session file WAS deleted its sibling store was never unlinked, orphaning potentially large lossless payload files with no code path to clean them. - co-delete the companion when its session file is deleted - sweep orphaned companions (session file already gone) once past the age gate; the reference check matches the shared hash stem across namespaces (meta fill-once can migrate _unknown/ -> namespaced without cleaning the old path), so a live store is never false-orphaned across that move - fold the store footprint (unique-content chars / 4) into the maxTokens gate: a tiny session carrying a huge store no longer slips under the size ceiling - unreadable/foreign companion next to an otherwise-eligible session keeps both files (never guess at unreadable data) - per-file audit lines for companion deletions (path + size), plus a companionsRemoved counter in GcResult (removed stays session files) - docs: companion lifecycle noted in README + CONFIGURATION, en/zh --- CONFIGURATION.md | 4 +- CONFIGURATION.zh-CN.md | 4 +- README.md | 8 ++- README.zh-CN.md | 2 +- src/session-gc.ts | 144 ++++++++++++++++++++++++++++++++++++--- tests/session-gc.test.ts | 120 +++++++++++++++++++++++++++++++- 6 files changed, 265 insertions(+), 17 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 6d1ab86ddd..73f6d89f18 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -577,9 +577,9 @@ Environment variables take precedence over the config file. They are useful for | `BILI_TUNNEL_ALLOWED_HOSTS` | `/bili/` tunnel admission for **remote clients** (#409): comma-separated `host` or `host:port` entries that unlock loopback/private destinations (e.g. a LAN relay or the machine's own sglang) for non-loopback clients. The proxy itself and link-local/metadata addresses are always denied; local (loopback) clients always pass. | | `BILI_MAX_SESSIONS` | Max sessions held in memory (default `256`; LRU eviction — disk is the source of truth). | | `BILI_SESSIONS_DIR` | Directory for persisted session state (default XDG data dir). | -| `BILI_SESSION_GC` | Cleanup of stale session files (#1082) is **opt-in**: set to `1`/`true`/`on` to enable — off by default, because session files are user data (exportable, resumable) and there is no silent deletion policy. When enabled, the sweep (boot + hourly) deletes a file only when BOTH conditions hold: older than `BILI_SESSION_GC_MAX_AGE_DAYS`, AND small in the lossless sense — the session was **never compressed** (zero folded blocks) and its newest request body ≤ the token ceiling below, so resuming it costs one cold rebuild from the client's own history and nothing else. Safety rails: compressed sessions are NEVER deleted (their summaries cannot be rebuilt losslessly); a session still held in memory is skipped unless idle since its last disk write; unreadable/corrupt files are left in place; every deletion is audit-logged individually (path, size, age) plus one summary line per non-empty sweep; only the sessions dir is ever touched; emptied protocol subdirectories are removed. Note the resident guard is per-process: another proxy instance sharing `BILI_SESSIONS_DIR` that does not persist (e.g. `BILI_PERSIST=0`) never refreshes file mtimes, so its still-live session files can age out and be swept — the cost is the same bounded cold rebuild, backstopped by the age gate. | +| `BILI_SESSION_GC` | Cleanup of stale session files (#1082) is **opt-in**: set to `1`/`true`/`on` to enable — off by default, because session files are user data (exportable, resumable) and there is no silent deletion policy. When enabled, the sweep (boot + hourly) deletes a file only when BOTH conditions hold: older than `BILI_SESSION_GC_MAX_AGE_DAYS`, AND small in the lossless sense — the session was **never compressed** (zero folded blocks) and its newest request body ≤ the token ceiling below, so resuming it costs one cold rebuild from the client's own history and nothing else. Safety rails: compressed sessions are NEVER deleted (their summaries cannot be rebuilt losslessly); a session still held in memory is skipped unless idle since its last disk write; unreadable/corrupt files are left in place; every deletion is audit-logged individually (path, size, age) plus one summary line per non-empty sweep; only the sessions dir is ever touched; emptied protocol subdirectories are removed. Note the resident guard is per-process: another proxy instance sharing `BILI_SESSIONS_DIR` that does not persist (e.g. `BILI_PERSIST=0`) never refreshes file mtimes, so its still-live session files can age out and be swept — the cost is the same bounded cold rebuild, backstopped by the age gate. CCR content stores (#1097) share the session's lifecycle (#1180): a `.content-store.json` companion is deleted together with its session file, an orphaned companion (session file already gone) is swept once past the age gate, and an unreadable companion keeps its session file too (never guessed at). | | `BILI_SESSION_GC_MAX_AGE_DAYS` | Minimum age (days) before a session file becomes a GC candidate (default `7`). Keep it far beyond any plausible resume window: after deletion a resumed session restarts message numbering from m00001 while a resuming agent's transcript may still cite old numbers (kernel contract: ids are never reused). | -| `BILI_SESSION_GC_MAX_TOKENS` | Size ceiling (tokens) for GC eligibility (default `1000000` = 1M, owner-set in #1082). Judged against the **decoded** context, never file bytes (encrypted/zstd files are far smaller on disk): the token estimate of the newest request body (`rawInputTokens`, recorded per turn) wins when present; unrecorded legacy files use `stats.contextTokens`. Applies only to never-compressed sessions — files with folded blocks are always kept regardless of size, since their summaries cannot be rebuilt losslessly from a re-send. | +| `BILI_SESSION_GC_MAX_TOKENS` | Size ceiling (tokens) for GC eligibility (default `1000000` = 1M, owner-set in #1082). Judged against the **decoded** context, never file bytes (encrypted/zstd files are far smaller on disk): the token estimate of the newest request body (`rawInputTokens`, recorded per turn) wins when present; unrecorded legacy files use `stats.contextTokens`; and the companion content store's footprint (#1097: unique-content chars ÷ 4, #1180) is added on top, so a small session carrying a huge store does not slip under the ceiling. Applies only to never-compressed sessions — files with folded blocks are always kept regardless of size, since their summaries cannot be rebuilt losslessly from a re-send. | | `BILI_SESSION_GC_INTERVAL_MS` | Background GC sweep interval in ms (default `3600000` = 1h). A sweep also runs once at boot. | | `BILI_ENCRYPTION_KEY` | Encrypt session files at rest (#708) for deployments on untrusted nodes. Exactly 32 bytes, hex (64 chars) or base64; unset = unencrypted plain-JSON files (or `BILIZSTD1` when `BILI_PERSIST_ZSTD=1` — see `BILI_PERSIST_ZSTD`). When set: every session file is written as `BILIENC1` AES-256-GCM over JSON that is zstd-compressed only when `BILI_PERSIST_ZSTD=1` (zstd on Node ≥ 22.15, raw body otherwise) — enabling compression also shrinks the file ~5–10×. Encryption and compression are now independent knobs (#1080). The key comes ONLY from this environment variable — never written to disk or logs — so keep it out of the same filesystem's reach. Invalid values abort startup (fail fast, never silently unencrypted). Booting with the wrong key skips the affected sessions as corrupt (logged, no crash). Losing the key makes encrypted sessions permanently unreadable. Symmetric by design (the same process encrypts and decrypts). Existing unencoded files are never rewritten at boot — they encrypt organically on their next save (downgrade safety; see `BILI_PERSIST_ZSTD`). Threat model (#708, owner-confirmed): it defends against **offline/mechanical** file acquisition — provider disk swaps, offline disk snapshots after node-image drift, stolen volumes, leaked backups, cloud-synced state dirs — where an offline third party cannot read the content without the key. It does NOT defend against targeted adversaries with live access to the node; for that tier move the trust root out of the proxy (KMS / TEE / confidential VMs, hardened permissions) instead of solving it inside the proxy — at that level far more than the key is exposed, so proxy-level key handling is not the boundary to hold (`BILI_PERSIST=0` disables persistence entirely). Double-encrypting the key with a second key from the same process/environment adds nothing: in every offline-theft scenario the attacker lacks exactly one artifact — your off-disk secret — whether it is called the data key or the wrapping key; only a wrapping key in a different trust domain (KMS/TPM/TEE) raises the bar, and that is scenario 2 above. | | `BILLION_CONTEXT_PROXY` | Exported by the launcher; client-side bili plugins/extensions detect it and self-disable their own compression (no double compression). | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 35e6d4777f..a482c37cc5 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -575,9 +575,9 @@ | `BILI_PERSIST_EPERM_ALERT_REPEAT_MS` | persist EPERM 告警的重复窗口(毫秒)。`0`(默认)= 只告警一次后静默;`>0` = 失败持续期间最多每这么久重复告警一次。 | | `BILI_MAX_SESSIONS` | 内存中最多保留的会话数(默认 `256`;LRU 淘汰 —— 磁盘是事实源)。 | | `BILI_SESSIONS_DIR` | 会话持久化目录(默认 XDG data 目录)。 | -| `BILI_SESSION_GC` | 过期会话文件清理(#1082)为**可选开启**:设 `1`/`true`/`on` 启用 —— 默认关闭,因为会话文件是用户数据(可导出、可续聊),不应有静默删除策略。启用后,扫描(启动 + 每小时)只在**两个条件同时满足**时删除一个文件:年龄超过 `BILI_SESSION_GC_MAX_AGE_DAYS`,并且"小"到无损 —— 该会话**从未被压缩过**(零折叠块)且最近一次请求体 ≤ 下述 token 上限,这样继续对话只损失一次冷重建(用客户端自己的历史重建),别无其他。安全边界:被压缩过的会话永不删除(其摘要无法无损重建);内存中仍持有的会话会被跳过,除非该会话自上次落盘后一直空闲;不可读/损坏的文件原地保留;每次删除逐条写审计日志(路径、大小、年龄),另有一次非空扫描的汇总日志;只触碰会话目录;清空后的协议子目录一并删除。注意 resident 守卫是进程内的:共享 `BILI_SESSIONS_DIR` 但不落盘的另一实例(如 `BILI_PERSIST=0`)不会刷新文件 mtime,其仍活跃的会话文件可能老化被扫 —— 代价同样是有限的一次冷重建,且有年龄门兜底。 | +| `BILI_SESSION_GC` | 过期会话文件清理(#1082)为**可选开启**:设 `1`/`true`/`on` 启用 —— 默认关闭,因为会话文件是用户数据(可导出、可续聊),不应有静默删除策略。启用后,扫描(启动 + 每小时)只在**两个条件同时满足**时删除一个文件:年龄超过 `BILI_SESSION_GC_MAX_AGE_DAYS`,并且"小"到无损 —— 该会话**从未被压缩过**(零折叠块)且最近一次请求体 ≤ 下述 token 上限,这样继续对话只损失一次冷重建(用客户端自己的历史重建),别无其他。安全边界:被压缩过的会话永不删除(其摘要无法无损重建);内存中仍持有的会话会被跳过,除非该会话自上次落盘后一直空闲;不可读/损坏的文件原地保留;每次删除逐条写审计日志(路径、大小、年龄),另有一次非空扫描的汇总日志;只触碰会话目录;清空后的协议子目录一并删除。注意 resident 守卫是进程内的:共享 `BILI_SESSIONS_DIR` 但不落盘的另一实例(如 `BILI_PERSIST=0`)不会刷新文件 mtime,其仍活跃的会话文件可能老化被扫 —— 代价同样是有限的一次冷重建,且有年龄门兜底。CCR 内容存储(#1097)与会话共享生命周期(#1180):`.content-store.json` 伴随文件随其会话文件一起删除;孤儿伴随文件(会话文件已不存在)超过年龄门后被清扫;不可读的伴随文件会连同其会话文件一起保留(绝不猜测)。 | | `BILI_SESSION_GC_MAX_AGE_DAYS` | 会话文件成为清理候选的最小年龄(天,默认 `7`)。必须远超任何合理续聊窗口:文件删除后同会话再续聊,消息编号会从 m00001 重新分配,而续聊 agent 的转录里可能还引用着旧编号(内核契约:编号永不复用)。 | -| `BILI_SESSION_GC_MAX_TOKENS` | 清理资格的大小上限(token 数,默认 `1000000` = 1M,#1082 owner 拍板)。按**解码后**的上下文判断,绝不看文件字节数(加密/zstd 文件在盘上小得多):记录了最近一次请求体 token 估算值(`rawInputTokens`,每轮记录)时以它为准;未记录的旧文件用 `stats.contextTokens`。仅适用于从未被压缩过的会话 —— 含折叠块的文件无论多大都保留,因为其摘要无法从重新发送中无损重建。 | +| `BILI_SESSION_GC_MAX_TOKENS` | 清理资格的大小上限(token 数,默认 `1000000` = 1M,#1082 owner 拍板)。按**解码后**的上下文判断,绝不看文件字节数(加密/zstd 文件在盘上小得多):记录了最近一次请求体 token 估算值(`rawInputTokens`,每轮记录)时以它为准;未记录的旧文件用 `stats.contextTokens`;伴随的内容存储占用(#1097:唯一内容字符数 ÷ 4,#1180)叠加其上,防止小会话携带大存储钻过上限。仅适用于从未被压缩过的会话 —— 含折叠块的文件无论多大都保留,因为其摘要无法从重新发送中无损重建。 | | `BILI_SESSION_GC_INTERVAL_MS` | 后台清理扫描间隔(毫秒,默认 `3600000` = 1 小时)。启动时会先扫一次。 | | `BILI_ENCRYPTION_KEY` | 会话文件静态加密(#708),适用于部署在不可信节点的场景。密钥必须恰好 32 字节,hex(64 字符)或 base64;未设置 = 不加密的纯 JSON 文件(设 `BILI_PERSIST_ZSTD=1` 时为 `BILIZSTD1`——参见 `BILI_PERSIST_ZSTD`)。设置后:每个会话文件均以 `BILIENC1` 格式写入,即对 JSON 施加 AES-256-GCM 加密,JSON 仅在 `BILI_PERSIST_ZSTD=1` 时以 zstd 压缩(Node ≥ 22.15 使用 zstd,其余情况写入原始数据)——启用压缩还可将文件体积缩小约 5–10 倍。加密与压缩现为独立的配置项(#1080)。密钥只从该环境变量读取——永不落盘、永不进日志——请确保它不受同一文件系统上的其他进程触及。非法值会导致启动中止(快速失败,绝不静默明文运行)。用错误的密钥启动时,受影响的会话按损坏文件跳过(有日志,不崩溃)。丢失密钥将使已加密的会话永久不可读。对称加密为刻意设计(同一进程既加密又解密)。已有的未编码文件从不在启动时改写——在其下一次保存时自然加密(降级安全;参见 `BILI_PERSIST_ZSTD`)。威胁模型(#708,owner 确认):防的是**离线/机械性**的文件获取——云厂商换盘、节点镜像漂移后的离线磁盘快照、磁盘镜像失窃、备份泄露、被云同步的状态目录——离线第三方拿不到密钥即无法读取内容。不防御对活节点有访问权的定向攻击者;那一档应把信任根移出 proxy(KMS / TEE / 机密虚拟机 + 强化权限体系),而不是在 proxy 本身想办法——到了那个程度暴露的远不止密钥,proxy 层不是该守的边界(`BILI_PERSIST=0` 可彻底关闭持久化)。用同一进程/环境中的第二把密钥对密钥做二次加密不增加任何安全性:所有离线失窃场景里攻击者缺的始终只有一个工件——你的非落盘秘密——无论它叫数据密钥还是包裹密钥;只有把包裹密钥放进不同信任域(KMS/TPM/TEE)才能提高门槛,而那属于上面的场景 2。 | | `BILLION_CONTEXT_PROXY` | launcher 会导出它;客户端侧 bili 插件/扩展检测到后自禁用自身压缩(避免双重压缩)。 | diff --git a/README.md b/README.md index 1f574db4c8..be9459b8cd 100644 --- a/README.md +++ b/README.md @@ -1111,8 +1111,12 @@ compressed (no folded blocks) with its newest request body ≤ `BILI_SESSION_GC_MAX_TOKENS` tokens (default 1M; unrecorded legacy files use `contextTokens`) — so deletion loses nothing but bytes: resuming rebuilds the context from the client's own history at the cost of one cold rebuild. -Compressed sessions are never deleted (their summaries cannot be rebuilt -losslessly). Every deletion is audit-logged individually, plus one summary +CCR content stores (#1097) live next to their session file as +`.content-store.json` and follow the same lifecycle (#1180): a store is +deleted together with its session file, an orphaned store (session file +already gone) is swept once past the age gate, and the store's token footprint +(unique-content chars ÷ 4) counts toward the size ceiling above. Compressed +sessions are never deleted (their summaries cannot be rebuilt losslessly). Every deletion is audit-logged individually, plus one summary line per non-empty sweep. Live sessions, unreadable files, and encrypted files are handled conservatively (decoded via `BILI_ENCRYPTION_KEY` before judging). Details in [CONFIGURATION.md](CONFIGURATION.md#environment-variables). diff --git a/README.zh-CN.md b/README.zh-CN.md index 89866c04a6..d222691cac 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -514,7 +514,7 @@ Windows 下会自动发现常见 Clash/Mihomo 静态系统代理;Web UI 会显 ### 会话文件清理(#1082) -短命会话会留下永远不会再被恢复的小状态文件。清理是**可选开启(opt-in)**的:设 `BILI_SESSION_GC=1` 才启用(默认关闭 —— 会话文件属于用户数据,不应有静默删除策略)。启用且持久化开启时,bili 在启动时和每小时扫描一次会话目录,且只有**两个条件同时满足**才删除一个文件:年龄超过 `BILI_SESSION_GC_MAX_AGE_DAYS`(默认 7 天),并且该会话**从未被压缩过**(没有折叠块)、最近一次请求体 ≤ `BILI_SESSION_GC_MAX_TOKENS` token(默认 1M;未记录大小的旧文件用 `contextTokens`)—— 这样删除只丢字节不丢内容:继续对话会用客户端自己的历史重建上下文,代价只是一次冷重建。被压缩过的会话永不删除(其摘要无法无损重建)。每次删除都会逐条写审计日志,另有一次非空扫描的汇总日志。活会话、不可读文件和加密文件(判断前先用 `BILI_ENCRYPTION_KEY` 解码)都按保守策略处理。详见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md)。 +短命会话会留下永远不会再被恢复的小状态文件。清理是**可选开启(opt-in)**的:设 `BILI_SESSION_GC=1` 才启用(默认关闭 —— 会话文件属于用户数据,不应有静默删除策略)。启用且持久化开启时,bili 在启动时和每小时扫描一次会话目录,且只有**两个条件同时满足**才删除一个文件:年龄超过 `BILI_SESSION_GC_MAX_AGE_DAYS`(默认 7 天),并且该会话**从未被压缩过**(没有折叠块)、最近一次请求体 ≤ `BILI_SESSION_GC_MAX_TOKENS` token(默认 1M;未记录大小的旧文件用 `contextTokens`)—— 这样删除只丢字节不丢内容:继续对话会用客户端自己的历史重建上下文,代价只是一次冷重建。CCR 内容存储(#1097)以 `.content-store.json` 的形式存放在会话文件旁边,遵循同样的生命周期(#1180):存储随其会话文件一起删除;孤儿存储(会话文件已不存在)在超过年龄门后被清扫;存储的 token 占用(唯一内容字符数 ÷ 4)计入上述大小上限。被压缩过的会话永不删除(其摘要无法无损重建)。每次删除都会逐条写审计日志,另有一次非空扫描的汇总日志。活会话、不可读文件和加密文件(判断前先用 `BILI_ENCRYPTION_KEY` 解码)都按保守策略处理。详见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md)。 ## 状态 diff --git a/src/session-gc.ts b/src/session-gc.ts index e6cefe4076..6cb168fbf1 100644 --- a/src/session-gc.ts +++ b/src/session-gc.ts @@ -1,4 +1,5 @@ import { readdir, rm, rmdir, stat } from "node:fs/promises"; +import type { Stats } from "node:fs"; import path from "node:path"; import { log as loggerLog } from "./logger.js"; import { getStore, type SessionStore } from "./persist.js"; @@ -40,6 +41,20 @@ import { dropSessionForGc, peekSession } from "./session.js"; * are decoded (any codec-framed file — encrypted today, zstd-compressed * once #1083 lands — works via the store's format-agnostic reader). * Corrupt/unreadable files are left in place, never guessed at. + * + * #1180: the per-session CCR content store (#1097) lives next to its session + * file as `.content-store.json` and shares the session's lifecycle — + * it holds lossless payload bytes (originals of oversized tool results), so + * deleting the session loses exactly those bytes, the class of file this + * sweep exists to clean: + * - co-deleted with its session file (the sweep never leaves orphans); + * - swept directly when orphaned (session file already gone — leftovers + * from versions that deleted sessions without their stores); + * - its token footprint (unique-content chars ÷ 4) counts toward the size + * gate, so a tiny session with a huge store does not slip under it; + * - attached to a kept session → kept untouched; an unreadable/foreign + * companion next to an otherwise-eligible session → both kept (never + * guess at unreadable files). */ export interface GcConfig { @@ -82,6 +97,8 @@ interface FileView { contextTokens: number; everCompressed: boolean; rawInputTokens: number | null; + /** #1180: companion content-store (#1097) footprint folded into the size gate by isGcEligible; absent = no companion */ + storedTokens?: number; } function asRecord(v: unknown): Record | null { @@ -118,12 +135,30 @@ export function viewFromParsed(parsed: unknown): FileView | null { return { id, savedAt, contextTokens, everCompressed, rawInputTokens }; } +/** Approximate token footprint of a parsed CCR content-store envelope + * (#1097): unique-content chars (byHash values) ÷ 4, matching bili's default + * char-based estimator. Null when the value is not a store envelope — the + * caller keeps the session rather than guessing at an unknown companion. */ +export function contentStoreTokens(parsed: unknown): number | null { + const rec = asRecord(parsed); + if (!rec || rec.version !== 1) return null; + const byHash = asRecord(rec.byHash); + const byRef = asRecord(rec.byRef); + if (!byHash || !byRef) return null; + let chars = 0; + for (const text of Object.values(byHash)) { + if (typeof text === "string") chars += text.length; + } + return Math.ceil(chars / 4); +} + export function isGcEligible(view: FileView, now: number, cfg: Pick): boolean { if (now - view.savedAt < cfg.maxAgeMs) return false; if (view.everCompressed) return false; - return view.rawInputTokens !== null - ? view.rawInputTokens <= cfg.maxTokens - : view.contextTokens <= cfg.maxTokens; + // #1180: the companion store's lossless originals die with this file, so + // its footprint joins the re-send size in the gate. + const base = view.rawInputTokens !== null ? view.rawInputTokens : view.contextTokens; + return base + (view.storedTokens ?? 0) <= cfg.maxTokens; } async function walkSessionFiles(dir: string): Promise { @@ -145,10 +180,12 @@ export interface GcResult { kept: number; unreadable: number; bytesFreed: number; + /** #1180: content-store companion files removed (co-deletions + orphan sweeps) */ + companionsRemoved: number; } export async function gcSessionFiles(opts?: { dir?: string; store?: SessionStore; now?: number }): Promise { - const result: GcResult = { removed: 0, kept: 0, unreadable: 0, bytesFreed: 0 }; + const result: GcResult = { removed: 0, kept: 0, unreadable: 0, bytesFreed: 0, companionsRemoved: 0 }; const cfg = gcConfigFromEnv(); if (!cfg.enabled) return result; const store = opts?.store ?? getStore(); @@ -161,7 +198,18 @@ export async function gcSessionFiles(opts?: { dir?: string; store?: SessionStore } catch { return result; } - for (const file of files) { + // #1180: split sessions from CCR companions (#1097); companion path is the + // deterministic sibling per contentStoreRelPathFor — no decode to pair them. + const companionSuffix = ".content-store.json"; + const sessionFiles: string[] = []; + const companions: string[] = []; + for (const f of files) { + if (f.endsWith(companionSuffix)) companions.push(f); + else sessionFiles.push(f); + } + const deletedSessions = new Set(); + const coDeleted = new Set(); + for (const file of sessionFiles) { let st; try { st = await stat(file); @@ -178,6 +226,26 @@ export async function gcSessionFiles(opts?: { dir?: string; store?: SessionStore result.unreadable++; continue; } + // #1180: measure the companion BEFORE judging "small enough" — its + // lossless originals die with this file, so they are part of what a + // deletion loses. + const companion = file.slice(0, -".json".length) + companionSuffix; + let compSt: Stats | undefined; + try { + const s = await stat(companion); + if (s.isFile()) compSt = s; + } catch { /* no companion */ } + if (compSt) { + const stored = contentStoreTokens(await store.readRawFile(companion)); + if (stored === null) { + // Companion present but not a recognizable store envelope — + // cannot verify what deletion would lose. Keep both (same rule + // as unreadable session files: never guess). + result.kept++; + continue; + } + view.storedTokens = stored; + } if (!isGcEligible(view, now, cfg)) { result.kept++; continue; @@ -202,17 +270,75 @@ export async function gcSessionFiles(opts?: { dir?: string; store?: SessionStore result.kept++; continue; } - // Audit trail (owner requirement #1082): every deletion is individually - // traceable — which file, how big, how old. + // Audit trail (owner requirement #1082/#1180): every deletion is + // individually traceable — which file, how big, how old. loggerLog("info", `[gc] removed ${path.relative(dir, file)} (${st.size} B, age ${Math.round((now - view.savedAt) / DAY_MS)}d)`); result.removed++; result.bytesFreed += st.size; + deletedSessions.add(file); + if (compSt) { + // Co-delete the companion so the sweep never leaves orphans. On + // failure it surfaces as an orphan on the very next pass below. + try { + await rm(companion, { force: true }); + loggerLog("info", `[gc] removed content store ${path.relative(dir, companion)} (${compSt.size} B)`); + result.bytesFreed += compSt.size; + result.companionsRemoved++; + coDeleted.add(companion); + } catch { /* orphan pass retries */ } + } const parent = path.dirname(file); if (parent !== dir) await rmdir(parent).catch(() => {}); } - if (result.removed > 0 || result.unreadable > 0) { + // #1180: orphaned companions — the session file is already gone (leftovers + // from versions that deleted sessions without their stores). Unreferenced + // payload garbage once old enough; the mtime pre-filter keeps live saves safe. + for (const companion of companions) { + if (coDeleted.has(companion)) continue; + let st; + try { + st = await stat(companion); + } catch { + continue; + } + if (!st.isFile() || now - st.mtimeMs < cfg.maxAgeMs) { + result.kept++; + continue; + } + // Referenced when ANY surviving session file shares the hash stem — + // namespaced `host_.json` and flat `_unknown/.json` both end + // with `.json`, and meta fill-once can migrate a session between + // those namespaces without cleaning the old path: sibling-only matching + // would false-orphan (delete live store bytes) across that move. + const stem = path.basename(companion).slice(0, -companionSuffix.length); + let referenced = false; + for (const sf of sessionFiles) { + if (deletedSessions.has(sf)) continue; + if (path.basename(sf).endsWith(stem + ".json")) { + referenced = true; + break; + } + } + if (referenced) { + result.kept++; + continue; + } + try { + await rm(companion, { force: true }); + } catch { + result.kept++; + continue; + } + loggerLog("info", `[gc] removed orphaned content store ${path.relative(dir, companion)} (${st.size} B)`); + // Companions count in their own field — `removed` stays "session files". + result.companionsRemoved++; + result.bytesFreed += st.size; + const parent = path.dirname(companion); + if (parent !== dir) await rmdir(parent).catch(() => {}); + } + if (result.removed > 0 || result.unreadable > 0 || result.companionsRemoved > 0) { loggerLog(result.unreadable > 0 ? "warn" : "info", - `[gc] removed ${result.removed} stale session file(s) (age>${Math.round(cfg.maxAgeMs / DAY_MS)}d, ≤${cfg.maxTokens}tok), freed ${(result.bytesFreed / 1024).toFixed(1)} KB${result.unreadable > 0 ? `; left ${result.unreadable} unreadable file(s) in place` : ""}`); + `[gc] removed ${result.removed} stale session file(s)${result.companionsRemoved > 0 ? ` + ${result.companionsRemoved} content store file(s)` : ""} (age>${Math.round(cfg.maxAgeMs / DAY_MS)}d, ≤${cfg.maxTokens}tok), freed ${(result.bytesFreed / 1024).toFixed(1)} KB${result.unreadable > 0 ? `; left ${result.unreadable} unreadable file(s) in place` : ""}`); } return result; } diff --git a/tests/session-gc.test.ts b/tests/session-gc.test.ts index 599425735e..8f5ecfd7c1 100644 --- a/tests/session-gc.test.ts +++ b/tests/session-gc.test.ts @@ -15,7 +15,7 @@ import { _setForTest as setRegistryForTest } from "../src/registry.js"; import { createStorageCodec, parseEncryptionKey } from "../src/encrypt.js"; import { _resetSessionsForTest, getSession, markDirty, peekSession } from "../src/session.js"; import type { Session } from "../src/session.js"; -import { gcConfigFromEnv, gcSessionFiles, isGcEligible, viewFromParsed } from "../src/session-gc.js"; +import { contentStoreTokens, gcConfigFromEnv, gcSessionFiles, isGcEligible, viewFromParsed } from "../src/session-gc.js"; const DAY = 86_400_000; @@ -71,6 +71,12 @@ function flatLegacy(id: string, savedAt: number, blocks: unknown[], contextToken }; } +function contentStoreFile(dir: string, rel: string, chars: number, ageDays: number): string { + const text = "y".repeat(chars); + const store = { version: 1, byHash: { h1: text }, byRef: { m00001: { hash: "h1", rawId: "raw-1", kind: "tool output", chars, head: "y", tokens: Math.ceil(chars / 4) } } }; + return writeFile(dir, rel, JSON.stringify(store), ageDays); +} + function writeFile(dir: string, rel: string, content: string | Buffer, ageDays: number): string { const full = path.join(dir, rel); mkdirSync(path.dirname(full), { recursive: true }); @@ -138,6 +144,25 @@ after(() => { assert.equal(isGcEligible({ id: "c", savedAt: oldSavedAt, contextTokens: 8_000, everCompressed: true, rawInputTokens: null }, now, cfg), false, "compressed session keeps even when small"); }); + test("isGcEligible: companion store footprint folds into the size gate (#1180)", () => { + const cfg = { maxAgeMs: 7 * DAY, maxTokens: 1_000_000 }; + const now = Date.parse("2026-09-21T00:00:00Z"); + const oldSavedAt = now - 10 * DAY; + const base = { id: "a", savedAt: oldSavedAt, contextTokens: 0, everCompressed: false, rawInputTokens: 900_000 }; + assert.equal(isGcEligible(base, now, cfg), true, "900K alone fits under 1M"); + assert.equal(isGcEligible({ ...base, storedTokens: 200_000 }, now, cfg), false, "+200K store pushes over the gate"); + assert.equal(isGcEligible({ ...base, storedTokens: 0 }, now, cfg), true, "zero footprint changes nothing"); + }); + + test("contentStoreTokens: unique-content chars ÷ 4; null for anything that is not a store envelope (#1180)", () => { + assert.equal(contentStoreTokens({ version: 1, byHash: { h1: "aaaa", h2: "bbbb" }, byRef: { m00001: {} } }), 2, "sums byHash values, ÷4 rounded up"); + assert.equal(contentStoreTokens({ version: 1, byHash: {}, byRef: {} }), 0, "valid empty envelope → 0"); + assert.equal(contentStoreTokens({ version: 1, byHash: { h1: "x" } }), null, "missing byRef → not an envelope"); + assert.equal(contentStoreTokens(envelope("s1", 1234)), null, "session record (version 3) is not a store envelope"); + assert.equal(contentStoreTokens(null), null); + assert.equal(contentStoreTokens("garbage"), null); + }); + test("viewFromParsed: envelope v3, legacy flat, corrupt input", () => { const rec = viewFromParsed(envelope("s1", 1234, { metadata: { rawInputTokens: 4242 } })); assert.ok(rec); @@ -314,6 +339,99 @@ test("gcSessionFiles: pending in-memory saves are not deleted before they land", }); }); +test("gcSessionFiles: stale CCR session co-deletes its content-store companion (#1180)", async () => { + const dir = tmpDir("bili-gc-crs-"); + await withEnv({ BILI_SESSION_GC: "1" }, async () => { + const store = new SessionStore({ dir, debounceMs: 500 }); + const oldSavedAt = Date.now() - 10 * DAY; + const fSess = writeFile(dir, "anthropic/host_crs.json", JSON.stringify(envelope("gc-crs", oldSavedAt, { metadata: { rawInputTokens: 5000 } })), 10); + const fCmp = contentStoreFile(dir, "anthropic/host_crs.content-store.json", 8000, 10); + const res = await gcSessionFiles({ dir, store, now: Date.now() }); + assert.equal(res.removed, 1, JSON.stringify(res)); + assert.equal(res.companionsRemoved, 1, JSON.stringify(res)); + assert.ok(!existsSync(fSess)); + assert.ok(!existsSync(fCmp), "companion co-deleted — no orphan left behind"); + }); +}); + +test("gcSessionFiles: live session keeps its companion even when the companion is old (#1180)", async () => { + const dir = tmpDir("bili-gc-live-"); + await withEnv({ BILI_SESSION_GC: "1" }, async () => { + const store = new SessionStore({ dir, debounceMs: 500 }); + const fSess = writeFile(dir, "anthropic/host_live.json", JSON.stringify(envelope("gc-live", Date.now() - DAY, { metadata: { rawInputTokens: 5000 } })), 1); + // Companion last written 10 days ago (long idle tail) but still referenced. + const fCmp = contentStoreFile(dir, "anthropic/host_live.content-store.json", 8000, 10); + const res = await gcSessionFiles({ dir, store, now: Date.now() }); + assert.equal(res.removed, 0, JSON.stringify(res)); + assert.equal(res.companionsRemoved, 0, JSON.stringify(res)); + assert.ok(existsSync(fSess)); + assert.ok(existsSync(fCmp), "referenced companion never orphan-swept"); + }); +}); + +test("gcSessionFiles: companion in another namespace than its session is still referenced (#1180)", async () => { + const dir = tmpDir("bili-gc-xns-"); + await withEnv({ BILI_SESSION_GC: "1" }, async () => { + const store = new SessionStore({ dir, debounceMs: 500 }); + // Session re-homed to the namespaced layout (meta fill-once) while a + // store copy from before the move sits in _unknown/, aged out. + const stem = "deadbeefcafe1234"; + const fSess = writeFile(dir, `anthropic/api.example.com_${stem}.json`, JSON.stringify(envelope(`gc-xns-${stem}`, Date.now() - DAY, { metadata: { rawInputTokens: 5000 } })), 1); + const fCmp = contentStoreFile(dir, `_unknown/${stem}.content-store.json`, 8000, 10); + const res = await gcSessionFiles({ dir, store, now: Date.now() }); + assert.equal(res.removed, 0, JSON.stringify(res)); + assert.equal(res.companionsRemoved, 0, JSON.stringify(res)); + assert.ok(existsSync(fSess)); + assert.ok(existsSync(fCmp), "hash-stem match across namespaces prevents false-orphan deletion of live store bytes"); + }); +}); + +test("gcSessionFiles: orphaned content stores are swept once old, fresh ones kept (#1180)", async () => { + const dir = tmpDir("bili-gc-orph-"); + await withEnv({ BILI_SESSION_GC: "1" }, async () => { + const store = new SessionStore({ dir, debounceMs: 500 }); + const fOld = contentStoreFile(dir, "anthropic/host_orph_old.content-store.json", 8000, 10); + const fFresh = contentStoreFile(dir, "anthropic/host_orph_fresh.content-store.json", 8000, 1); + const res = await gcSessionFiles({ dir, store, now: Date.now() }); + assert.equal(res.removed, 0, "no session files were removed"); + assert.equal(res.companionsRemoved, 1, JSON.stringify(res)); + assert.ok(!existsSync(fOld), "aged orphan swept"); + assert.ok(existsSync(fFresh), "fresh orphan kept (still inside any resume window)"); + }); +}); + +test("gcSessionFiles: tiny session with a huge store does not slip under the token gate (#1180)", async () => { + const dir = tmpDir("bili-gc-hugestore-"); + await withEnv({ BILI_SESSION_GC: "1", BILI_SESSION_GC_MAX_TOKENS: "1000" }, async () => { + const store = new SessionStore({ dir, debounceMs: 500 }); + const oldSavedAt = Date.now() - 10 * DAY; + const fSmall = writeFile(dir, "anthropic/host_small.json", JSON.stringify(envelope("gc-small", oldSavedAt, { metadata: { rawInputTokens: 500 } })), 10); + const fBigStore = writeFile(dir, "anthropic/host_bigstore.json", JSON.stringify(envelope("gc-bigstore", oldSavedAt, { metadata: { rawInputTokens: 500 } })), 10); + const fCmp = contentStoreFile(dir, "anthropic/host_bigstore.content-store.json", 8000, 10); + const res = await gcSessionFiles({ dir, store, now: Date.now() }); + assert.equal(res.removed, 1, JSON.stringify(res)); + assert.equal(res.companionsRemoved, 0, JSON.stringify(res)); + assert.ok(!existsSync(fSmall), "same-size session without a store is deleted"); + assert.ok(existsSync(fBigStore), "store footprint (2000tok) + 500tok exceeds the 1000tok gate"); + assert.ok(existsSync(fCmp)); + }); +}); + +test("gcSessionFiles: unreadable companion next to an eligible session keeps both (#1180)", async () => { + const dir = tmpDir("bili-gc-badcmp-"); + await withEnv({ BILI_SESSION_GC: "1" }, async () => { + const store = new SessionStore({ dir, debounceMs: 500 }); + const oldSavedAt = Date.now() - 10 * DAY; + const fSess = writeFile(dir, "anthropic/host_badcmp.json", JSON.stringify(envelope("gc-badcmp", oldSavedAt, { metadata: { rawInputTokens: 5000 } })), 10); + const fCmp = writeFile(dir, "anthropic/host_badcmp.content-store.json", "{not json", 10); + const res = await gcSessionFiles({ dir, store, now: Date.now() }); + assert.equal(res.removed, 0, JSON.stringify(res)); + assert.equal(res.unreadable, 0, "the session file itself parsed fine"); + assert.ok(existsSync(fSess), "never guess at an unreadable companion — keep the session too"); + assert.ok(existsSync(fCmp)); + }); +}); + test("records rawInputTokens per turn and persists it (#1082)", async () => { const dir = tmpDir("bili-gc-rec-"); await withEnv({ BILI_SESSIONS_DIR: dir, BILI_SESSION_GC: "0" }, async () => { From 333135c8599899b37d68e714667a68d54295e22f Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 23 Sep 2026 23:24:20 +0800 Subject: [PATCH 2/4] fix: keep live fallback content stores when GC deletes a stale namespace duplicate (#1180) Meta fill-once (session.ts getSession) migrates a session _unknown/.json -> ns/host_.json without cleaning the old path (kernel StateStore writes never delete the previous relPath), and saveContentStore only rewrites when dirty. A moved CCR session whose store was not re-saved since the move therefore still reads its LIVE store from the stale duplicate's sibling (loadContentStore probes _unknown/ when the namespaced store is absent, stopping at the first existing candidate). The co-delete pairing is strictly same-directory, so sweeping the aged duplicate would unlink live lossless payload bytes. Guard: skip the companion unlink when another surviving session file shares the hash stem and has no store of its own. The bytes then stay referenced until that twin itself is swept, after which the orphan pass collects them. When the twin owns its own (shadowing) store the flat sibling is dead bytes and co-deletion proceeds as before. Adds 3 regression tests: duplicate + fresh twin without own store (store kept); duplicate + twin with own store (dead copy co-deleted, live one kept); both copies eligible (whole session incl. lone store swept, order-independent). --- src/session-gc.ts | 51 ++++++++++++++++++++++++++----- tests/session-gc.test.ts | 65 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+), 8 deletions(-) diff --git a/src/session-gc.ts b/src/session-gc.ts index 6cb168fbf1..004a952d1a 100644 --- a/src/session-gc.ts +++ b/src/session-gc.ts @@ -47,7 +47,12 @@ import { dropSessionForGc, peekSession } from "./session.js"; * it holds lossless payload bytes (originals of oversized tool results), so * deleting the session loses exactly those bytes, the class of file this * sweep exists to clean: - * - co-deleted with its session file (the sweep never leaves orphans); + * - co-deleted with its session file (the sweep never leaves orphans) — + * except when a surviving twin of the same id lacks its own store: after + * meta fill-once migrates _unknown/ -> ns/ without cleaning the old path + * (kernel writes never delete), the stale duplicate's sibling may still be + * the live fallback store; it is kept then and orphan-swept once the twin + * goes; * - swept directly when orphaned (session file already gone — leftovers * from versions that deleted sessions without their stores); * - its token footprint (unique-content chars ÷ 4) counts toward the size @@ -279,13 +284,43 @@ export async function gcSessionFiles(opts?: { dir?: string; store?: SessionStore if (compSt) { // Co-delete the companion so the sweep never leaves orphans. On // failure it surfaces as an orphan on the very next pass below. - try { - await rm(companion, { force: true }); - loggerLog("info", `[gc] removed content store ${path.relative(dir, companion)} (${compSt.size} B)`); - result.bytesFreed += compSt.size; - result.companionsRemoved++; - coDeleted.add(companion); - } catch { /* orphan pass retries */ } + // Cross-namespace exception: meta fill-once can migrate a session + // _unknown/.json -> ns/host_.json without cleaning the old + // path (kernel writes never delete the previous relPath), and + // saveContentStore only rewrites when dirty — so a moved session + // whose store was not re-saved since the move still reads its LIVE + // store from this stale duplicate's sibling (loadContentStore + // probes _unknown/ when the namespaced store is absent, and stops + // at the first EXISTING candidate). Co-deleting it here would lose + // retrievable originals. Skip when a surviving twin shares the + // hash stem and has no store of its own; the bytes stay referenced + // until the twin is swept, then the orphan pass collects them. + const stem = path.basename(file, ".json"); + let keepCompanion = false; + for (const sf of sessionFiles) { + if (sf === file || deletedSessions.has(sf)) continue; + if (!path.basename(sf).endsWith(stem + ".json")) continue; + let twinHasOwnStore = false; + try { + const s2 = await stat(sf.slice(0, -".json".length) + companionSuffix); + twinHasOwnStore = s2.isFile(); + } catch { /* no sibling */ } + if (!twinHasOwnStore) { + keepCompanion = true; + break; + } + } + if (keepCompanion) { + loggerLog("info", `[gc] kept content store ${path.relative(dir, companion)} (${compSt.size} B): live fallback store of a surviving twin`); + } else { + try { + await rm(companion, { force: true }); + loggerLog("info", `[gc] removed content store ${path.relative(dir, companion)} (${compSt.size} B)`); + result.bytesFreed += compSt.size; + result.companionsRemoved++; + coDeleted.add(companion); + } catch { /* orphan pass retries */ } + } } const parent = path.dirname(file); if (parent !== dir) await rmdir(parent).catch(() => {}); diff --git a/tests/session-gc.test.ts b/tests/session-gc.test.ts index 8f5ecfd7c1..f95e36bf47 100644 --- a/tests/session-gc.test.ts +++ b/tests/session-gc.test.ts @@ -386,6 +386,71 @@ test("gcSessionFiles: companion in another namespace than its session is still r }); }); +test("gcSessionFiles: stale duplicate keeps its companion while a namespaced twin still relies on it (#1180)", async () => { + const dir = tmpDir("bili-gc-twin-"); + await withEnv({ BILI_SESSION_GC: "1" }, async () => { + const store = new SessionStore({ dir, debounceMs: 500 }); + // Meta fill-once migrated the session _unknown/ -> namespaced without + // cleaning the old path; the store was never re-saved since the move + // (saveContentStore only writes when dirty), so the _unknown/ sibling + // is still the LIVE store — loadContentStore falls back to it when + // the namespaced one is absent. + const stem = "twinbeefcafe1234"; + const fDup = writeFile(dir, `_unknown/${stem}.json`, JSON.stringify(envelope(`gc-twin-${stem}`, Date.now() - 10 * DAY, { metadata: { rawInputTokens: 5000 } })), 10); + const fTwin = writeFile(dir, `anthropic/api.example.com_${stem}.json`, JSON.stringify(envelope(`gc-twin-${stem}`, Date.now() - DAY, { metadata: { rawInputTokens: 5000 } })), 1); + const fCmp = contentStoreFile(dir, `_unknown/${stem}.content-store.json`, 8000, 10); + const res = await gcSessionFiles({ dir, store, now: Date.now() }); + assert.equal(res.removed, 1, JSON.stringify(res)); + assert.equal(res.companionsRemoved, 0, JSON.stringify(res)); + assert.ok(!existsSync(fDup), "stale duplicate deleted"); + assert.ok(existsSync(fTwin), "live twin untouched"); + assert.ok(existsSync(fCmp), "live fallback store of the surviving twin is never co-deleted"); + }); +}); + +test("gcSessionFiles: stale duplicate's companion IS co-deleted once the twin owns its own store (#1180)", async () => { + const dir = tmpDir("bili-gc-twinown-"); + await withEnv({ BILI_SESSION_GC: "1" }, async () => { + const store = new SessionStore({ dir, debounceMs: 500 }); + // The store was re-saved after the namespace move: the namespaced copy + // shadows the flat one (loadContentStore stops at the first existing + // candidate), so the flat sibling is dead bytes and co-deletion is safe. + const stem = "twincafedeadbeef"; + const fDup = writeFile(dir, `_unknown/${stem}.json`, JSON.stringify(envelope(`gc-twinown-${stem}`, Date.now() - 10 * DAY, { metadata: { rawInputTokens: 5000 } })), 10); + const fTwin = writeFile(dir, `anthropic/api.example.com_${stem}.json`, JSON.stringify(envelope(`gc-twinown-${stem}`, Date.now() - DAY, { metadata: { rawInputTokens: 5000 } })), 1); + const fDead = contentStoreFile(dir, `_unknown/${stem}.content-store.json`, 8000, 10); + const fLive = contentStoreFile(dir, `anthropic/api.example.com_${stem}.content-store.json`, 8000, 1); + const res = await gcSessionFiles({ dir, store, now: Date.now() }); + assert.equal(res.removed, 1, JSON.stringify(res)); + assert.equal(res.companionsRemoved, 1, JSON.stringify(res)); + assert.ok(!existsSync(fDup)); + assert.ok(existsSync(fTwin)); + assert.ok(!existsSync(fDead), "shadowed dead copy co-deleted with its duplicate"); + assert.ok(existsSync(fLive), "the live namespaced store stays referenced"); + }); +}); + +test("gcSessionFiles: both copies eligible → whole session incl. its lone store is swept (#1180)", async () => { + const dir = tmpDir("bili-gc-twogone-"); + await withEnv({ BILI_SESSION_GC: "1" }, async () => { + const store = new SessionStore({ dir, debounceMs: 500 }); + // Both copies aged out; the lone store sits next to the flat duplicate. + // Whichever copy is processed first, the sweep ends with everything + // gone: if the duplicate goes first the guard keeps the store, then + // the twin deletion leaves it an unreferenced orphan swept in the + // same pass; if the twin goes first the duplicate's sibling has no + // surviving reference-holder left and is co-deleted directly. + const stem = "twogonecafe1234"; + const fDup = writeFile(dir, `_unknown/${stem}.json`, JSON.stringify(envelope(`gc-twogone-${stem}`, Date.now() - 10 * DAY, { metadata: { rawInputTokens: 5000 } })), 10); + const fTwin = writeFile(dir, `anthropic/api.example.com_${stem}.json`, JSON.stringify(envelope(`gc-twogone-${stem}`, Date.now() - 10 * DAY, { metadata: { rawInputTokens: 5000 } })), 10); + const fCmp = contentStoreFile(dir, `_unknown/${stem}.content-store.json`, 8000, 10); + const res = await gcSessionFiles({ dir, store, now: Date.now() }); + assert.equal(res.removed, 2, JSON.stringify(res)); + assert.equal(res.companionsRemoved, 1, JSON.stringify(res)); + assert.ok(!existsSync(fDup) && !existsSync(fTwin) && !existsSync(fCmp)); + }); +}); + test("gcSessionFiles: orphaned content stores are swept once old, fresh ones kept (#1180)", async () => { const dir = tmpDir("bili-gc-orph-"); await withEnv({ BILI_SESSION_GC: "1" }, async () => { From a3ec90f96d927aa989b4197492478291cb384f24 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Thu, 24 Sep 2026 22:12:10 +0800 Subject: [PATCH 3/4] =?UTF-8?q?review=20follow-up=20=E2=80=94=20CJK-aware?= =?UTF-8?q?=20store=20footprint,=20shape-probe=20twin=20guard,=20foreign-c?= =?UTF-8?q?ompanion=20audit=20log=20(#1180)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/session-gc.ts | 22 +++++++++++++++------- tests/session-gc.test.ts | 3 ++- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/session-gc.ts b/src/session-gc.ts index 004a952d1a..48f352209a 100644 --- a/src/session-gc.ts +++ b/src/session-gc.ts @@ -2,6 +2,7 @@ import { readdir, rm, rmdir, stat } from "node:fs/promises"; import type { Stats } from "node:fs"; import path from "node:path"; import { log as loggerLog } from "./logger.js"; +import { defaultCountTokens } from "acp-kernel"; import { getStore, type SessionStore } from "./persist.js"; import { sessionsDir } from "./paths.js"; import { dropSessionForGc, peekSession } from "./session.js"; @@ -141,8 +142,10 @@ export function viewFromParsed(parsed: unknown): FileView | null { } /** Approximate token footprint of a parsed CCR content-store envelope - * (#1097): unique-content chars (byHash values) ÷ 4, matching bili's default - * char-based estimator. Null when the value is not a store envelope — the + * (#1097): unique-content (byHash values) tokens via the kernel's CJK-aware + * defaultCountTokens — the same estimator rawInputTokens uses (persist.ts), + * so the size gate never mixes estimators (chars÷4 undercounts CJK-heavy + * stores up to 4×). Null when the value is not a store envelope — the * caller keeps the session rather than guessing at an unknown companion. */ export function contentStoreTokens(parsed: unknown): number | null { const rec = asRecord(parsed); @@ -150,11 +153,11 @@ export function contentStoreTokens(parsed: unknown): number | null { const byHash = asRecord(rec.byHash); const byRef = asRecord(rec.byRef); if (!byHash || !byRef) return null; - let chars = 0; + let tokens = 0; for (const text of Object.values(byHash)) { - if (typeof text === "string") chars += text.length; + if (typeof text === "string") tokens += defaultCountTokens(text); } - return Math.ceil(chars / 4); + return tokens; } export function isGcEligible(view: FileView, now: number, cfg: Pick): boolean { @@ -246,6 +249,7 @@ export async function gcSessionFiles(opts?: { dir?: string; store?: SessionStore // Companion present but not a recognizable store envelope — // cannot verify what deletion would lose. Keep both (same rule // as unreadable session files: never guess). + loggerLog("info", `[gc] kept session ${path.relative(dir, file)}: companion ${path.basename(companion)} is not a recognizable content store`); result.kept++; continue; } @@ -303,8 +307,12 @@ export async function gcSessionFiles(opts?: { dir?: string; store?: SessionStore let twinHasOwnStore = false; try { const s2 = await stat(sf.slice(0, -".json".length) + companionSuffix); - twinHasOwnStore = s2.isFile(); - } catch { /* no sibling */ } + // Existence alone is not adoption: loadContentStore falls + // through to _unknown/ when the namespaced store exists but + // is UNREADABLE — the stale sibling stays the twin's live + // store. Probe the shape, not the inode. + twinHasOwnStore = s2.isFile() && contentStoreTokens(await store.readRawFile(sf.slice(0, -".json".length) + companionSuffix)) !== null; + } catch { /* no sibling, or unreadable: keep — never guess */ } if (!twinHasOwnStore) { keepCompanion = true; break; diff --git a/tests/session-gc.test.ts b/tests/session-gc.test.ts index f95e36bf47..f5cadd3619 100644 --- a/tests/session-gc.test.ts +++ b/tests/session-gc.test.ts @@ -155,7 +155,8 @@ after(() => { }); test("contentStoreTokens: unique-content chars ÷ 4; null for anything that is not a store envelope (#1180)", () => { - assert.equal(contentStoreTokens({ version: 1, byHash: { h1: "aaaa", h2: "bbbb" }, byRef: { m00001: {} } }), 2, "sums byHash values, ÷4 rounded up"); + assert.equal(contentStoreTokens({ version: 1, byHash: { h1: "aaaa", h2: "bbbb" }, byRef: { m00001: {} } }), 2, "sums byHash values via the CJK-aware estimator"); + assert.equal(contentStoreTokens({ version: 1, byHash: { h1: "测试测试测试" }, byRef: { m00001: {} } }), 6, "CJK content counts per character (not chars÷4)"); assert.equal(contentStoreTokens({ version: 1, byHash: {}, byRef: {} }), 0, "valid empty envelope → 0"); assert.equal(contentStoreTokens({ version: 1, byHash: { h1: "x" } }), null, "missing byRef → not an envelope"); assert.equal(contentStoreTokens(envelope("s1", 1234)), null, "session record (version 3) is not a store envelope"); From 7321d7de67ed92cea56a68f31c0be84ee507485a Mon Sep 17 00:00:00 2001 From: ework-agent Date: Thu, 24 Sep 2026 22:22:59 +0800 Subject: [PATCH 4/4] docs: sync store-footprint estimator wording after defaultCountTokens switch (#1180) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit a3ec90f9 changed contentStoreTokens from chars÷4 to the kernel's CJK-aware defaultCountTokens but left five 'chars ÷ 4' descriptions behind (README en/zh, CONFIGURATION en/zh, session-gc module header). No behavior change. --- CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 2 +- README.md | 3 ++- README.zh-CN.md | 2 +- src/session-gc.ts | 5 +++-- tests/session-gc.test.ts | 2 +- 6 files changed, 9 insertions(+), 7 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 73f6d89f18..4018ea9466 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -579,7 +579,7 @@ Environment variables take precedence over the config file. They are useful for | `BILI_SESSIONS_DIR` | Directory for persisted session state (default XDG data dir). | | `BILI_SESSION_GC` | Cleanup of stale session files (#1082) is **opt-in**: set to `1`/`true`/`on` to enable — off by default, because session files are user data (exportable, resumable) and there is no silent deletion policy. When enabled, the sweep (boot + hourly) deletes a file only when BOTH conditions hold: older than `BILI_SESSION_GC_MAX_AGE_DAYS`, AND small in the lossless sense — the session was **never compressed** (zero folded blocks) and its newest request body ≤ the token ceiling below, so resuming it costs one cold rebuild from the client's own history and nothing else. Safety rails: compressed sessions are NEVER deleted (their summaries cannot be rebuilt losslessly); a session still held in memory is skipped unless idle since its last disk write; unreadable/corrupt files are left in place; every deletion is audit-logged individually (path, size, age) plus one summary line per non-empty sweep; only the sessions dir is ever touched; emptied protocol subdirectories are removed. Note the resident guard is per-process: another proxy instance sharing `BILI_SESSIONS_DIR` that does not persist (e.g. `BILI_PERSIST=0`) never refreshes file mtimes, so its still-live session files can age out and be swept — the cost is the same bounded cold rebuild, backstopped by the age gate. CCR content stores (#1097) share the session's lifecycle (#1180): a `.content-store.json` companion is deleted together with its session file, an orphaned companion (session file already gone) is swept once past the age gate, and an unreadable companion keeps its session file too (never guessed at). | | `BILI_SESSION_GC_MAX_AGE_DAYS` | Minimum age (days) before a session file becomes a GC candidate (default `7`). Keep it far beyond any plausible resume window: after deletion a resumed session restarts message numbering from m00001 while a resuming agent's transcript may still cite old numbers (kernel contract: ids are never reused). | -| `BILI_SESSION_GC_MAX_TOKENS` | Size ceiling (tokens) for GC eligibility (default `1000000` = 1M, owner-set in #1082). Judged against the **decoded** context, never file bytes (encrypted/zstd files are far smaller on disk): the token estimate of the newest request body (`rawInputTokens`, recorded per turn) wins when present; unrecorded legacy files use `stats.contextTokens`; and the companion content store's footprint (#1097: unique-content chars ÷ 4, #1180) is added on top, so a small session carrying a huge store does not slip under the ceiling. Applies only to never-compressed sessions — files with folded blocks are always kept regardless of size, since their summaries cannot be rebuilt losslessly from a re-send. | +| `BILI_SESSION_GC_MAX_TOKENS` | Size ceiling (tokens) for GC eligibility (default `1000000` = 1M, owner-set in #1082). Judged against the **decoded** context, never file bytes (encrypted/zstd files are far smaller on disk): the token estimate of the newest request body (`rawInputTokens`, recorded per turn) wins when present; unrecorded legacy files use `stats.contextTokens`; and the companion content store's footprint (#1097: unique-content via the kernel's CJK-aware `defaultCountTokens`, same estimator as `rawInputTokens`, #1180) is added on top, so a small session carrying a huge store does not slip under the ceiling. Applies only to never-compressed sessions — files with folded blocks are always kept regardless of size, since their summaries cannot be rebuilt losslessly from a re-send. | | `BILI_SESSION_GC_INTERVAL_MS` | Background GC sweep interval in ms (default `3600000` = 1h). A sweep also runs once at boot. | | `BILI_ENCRYPTION_KEY` | Encrypt session files at rest (#708) for deployments on untrusted nodes. Exactly 32 bytes, hex (64 chars) or base64; unset = unencrypted plain-JSON files (or `BILIZSTD1` when `BILI_PERSIST_ZSTD=1` — see `BILI_PERSIST_ZSTD`). When set: every session file is written as `BILIENC1` AES-256-GCM over JSON that is zstd-compressed only when `BILI_PERSIST_ZSTD=1` (zstd on Node ≥ 22.15, raw body otherwise) — enabling compression also shrinks the file ~5–10×. Encryption and compression are now independent knobs (#1080). The key comes ONLY from this environment variable — never written to disk or logs — so keep it out of the same filesystem's reach. Invalid values abort startup (fail fast, never silently unencrypted). Booting with the wrong key skips the affected sessions as corrupt (logged, no crash). Losing the key makes encrypted sessions permanently unreadable. Symmetric by design (the same process encrypts and decrypts). Existing unencoded files are never rewritten at boot — they encrypt organically on their next save (downgrade safety; see `BILI_PERSIST_ZSTD`). Threat model (#708, owner-confirmed): it defends against **offline/mechanical** file acquisition — provider disk swaps, offline disk snapshots after node-image drift, stolen volumes, leaked backups, cloud-synced state dirs — where an offline third party cannot read the content without the key. It does NOT defend against targeted adversaries with live access to the node; for that tier move the trust root out of the proxy (KMS / TEE / confidential VMs, hardened permissions) instead of solving it inside the proxy — at that level far more than the key is exposed, so proxy-level key handling is not the boundary to hold (`BILI_PERSIST=0` disables persistence entirely). Double-encrypting the key with a second key from the same process/environment adds nothing: in every offline-theft scenario the attacker lacks exactly one artifact — your off-disk secret — whether it is called the data key or the wrapping key; only a wrapping key in a different trust domain (KMS/TPM/TEE) raises the bar, and that is scenario 2 above. | | `BILLION_CONTEXT_PROXY` | Exported by the launcher; client-side bili plugins/extensions detect it and self-disable their own compression (no double compression). | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index a482c37cc5..37631fc58f 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -577,7 +577,7 @@ | `BILI_SESSIONS_DIR` | 会话持久化目录(默认 XDG data 目录)。 | | `BILI_SESSION_GC` | 过期会话文件清理(#1082)为**可选开启**:设 `1`/`true`/`on` 启用 —— 默认关闭,因为会话文件是用户数据(可导出、可续聊),不应有静默删除策略。启用后,扫描(启动 + 每小时)只在**两个条件同时满足**时删除一个文件:年龄超过 `BILI_SESSION_GC_MAX_AGE_DAYS`,并且"小"到无损 —— 该会话**从未被压缩过**(零折叠块)且最近一次请求体 ≤ 下述 token 上限,这样继续对话只损失一次冷重建(用客户端自己的历史重建),别无其他。安全边界:被压缩过的会话永不删除(其摘要无法无损重建);内存中仍持有的会话会被跳过,除非该会话自上次落盘后一直空闲;不可读/损坏的文件原地保留;每次删除逐条写审计日志(路径、大小、年龄),另有一次非空扫描的汇总日志;只触碰会话目录;清空后的协议子目录一并删除。注意 resident 守卫是进程内的:共享 `BILI_SESSIONS_DIR` 但不落盘的另一实例(如 `BILI_PERSIST=0`)不会刷新文件 mtime,其仍活跃的会话文件可能老化被扫 —— 代价同样是有限的一次冷重建,且有年龄门兜底。CCR 内容存储(#1097)与会话共享生命周期(#1180):`.content-store.json` 伴随文件随其会话文件一起删除;孤儿伴随文件(会话文件已不存在)超过年龄门后被清扫;不可读的伴随文件会连同其会话文件一起保留(绝不猜测)。 | | `BILI_SESSION_GC_MAX_AGE_DAYS` | 会话文件成为清理候选的最小年龄(天,默认 `7`)。必须远超任何合理续聊窗口:文件删除后同会话再续聊,消息编号会从 m00001 重新分配,而续聊 agent 的转录里可能还引用着旧编号(内核契约:编号永不复用)。 | -| `BILI_SESSION_GC_MAX_TOKENS` | 清理资格的大小上限(token 数,默认 `1000000` = 1M,#1082 owner 拍板)。按**解码后**的上下文判断,绝不看文件字节数(加密/zstd 文件在盘上小得多):记录了最近一次请求体 token 估算值(`rawInputTokens`,每轮记录)时以它为准;未记录的旧文件用 `stats.contextTokens`;伴随的内容存储占用(#1097:唯一内容字符数 ÷ 4,#1180)叠加其上,防止小会话携带大存储钻过上限。仅适用于从未被压缩过的会话 —— 含折叠块的文件无论多大都保留,因为其摘要无法从重新发送中无损重建。 | +| `BILI_SESSION_GC_MAX_TOKENS` | 清理资格的大小上限(token 数,默认 `1000000` = 1M,#1082 owner 拍板)。按**解码后**的上下文判断,绝不看文件字节数(加密/zstd 文件在盘上小得多):记录了最近一次请求体 token 估算值(`rawInputTokens`,每轮记录)时以它为准;未记录的旧文件用 `stats.contextTokens`;伴随的内容存储占用(#1097:唯一内容经内核 CJK-aware `defaultCountTokens` 计数,与 `rawInputTokens` 同一估算器,#1180)叠加其上,防止小会话携带大存储钻过上限。仅适用于从未被压缩过的会话 —— 含折叠块的文件无论多大都保留,因为其摘要无法从重新发送中无损重建。 | | `BILI_SESSION_GC_INTERVAL_MS` | 后台清理扫描间隔(毫秒,默认 `3600000` = 1 小时)。启动时会先扫一次。 | | `BILI_ENCRYPTION_KEY` | 会话文件静态加密(#708),适用于部署在不可信节点的场景。密钥必须恰好 32 字节,hex(64 字符)或 base64;未设置 = 不加密的纯 JSON 文件(设 `BILI_PERSIST_ZSTD=1` 时为 `BILIZSTD1`——参见 `BILI_PERSIST_ZSTD`)。设置后:每个会话文件均以 `BILIENC1` 格式写入,即对 JSON 施加 AES-256-GCM 加密,JSON 仅在 `BILI_PERSIST_ZSTD=1` 时以 zstd 压缩(Node ≥ 22.15 使用 zstd,其余情况写入原始数据)——启用压缩还可将文件体积缩小约 5–10 倍。加密与压缩现为独立的配置项(#1080)。密钥只从该环境变量读取——永不落盘、永不进日志——请确保它不受同一文件系统上的其他进程触及。非法值会导致启动中止(快速失败,绝不静默明文运行)。用错误的密钥启动时,受影响的会话按损坏文件跳过(有日志,不崩溃)。丢失密钥将使已加密的会话永久不可读。对称加密为刻意设计(同一进程既加密又解密)。已有的未编码文件从不在启动时改写——在其下一次保存时自然加密(降级安全;参见 `BILI_PERSIST_ZSTD`)。威胁模型(#708,owner 确认):防的是**离线/机械性**的文件获取——云厂商换盘、节点镜像漂移后的离线磁盘快照、磁盘镜像失窃、备份泄露、被云同步的状态目录——离线第三方拿不到密钥即无法读取内容。不防御对活节点有访问权的定向攻击者;那一档应把信任根移出 proxy(KMS / TEE / 机密虚拟机 + 强化权限体系),而不是在 proxy 本身想办法——到了那个程度暴露的远不止密钥,proxy 层不是该守的边界(`BILI_PERSIST=0` 可彻底关闭持久化)。用同一进程/环境中的第二把密钥对密钥做二次加密不增加任何安全性:所有离线失窃场景里攻击者缺的始终只有一个工件——你的非落盘秘密——无论它叫数据密钥还是包裹密钥;只有把包裹密钥放进不同信任域(KMS/TPM/TEE)才能提高门槛,而那属于上面的场景 2。 | | `BILLION_CONTEXT_PROXY` | launcher 会导出它;客户端侧 bili 插件/扩展检测到后自禁用自身压缩(避免双重压缩)。 | diff --git a/README.md b/README.md index be9459b8cd..063e7e45ec 100644 --- a/README.md +++ b/README.md @@ -1115,7 +1115,8 @@ CCR content stores (#1097) live next to their session file as `.content-store.json` and follow the same lifecycle (#1180): a store is deleted together with its session file, an orphaned store (session file already gone) is swept once past the age gate, and the store's token footprint -(unique-content chars ÷ 4) counts toward the size ceiling above. Compressed +(unique-content counted with the kernel's CJK-aware `defaultCountTokens` — the +same estimator as `rawInputTokens`) counts toward the size ceiling above. Compressed sessions are never deleted (their summaries cannot be rebuilt losslessly). Every deletion is audit-logged individually, plus one summary line per non-empty sweep. Live sessions, unreadable files, and encrypted files are handled conservatively (decoded via `BILI_ENCRYPTION_KEY` before diff --git a/README.zh-CN.md b/README.zh-CN.md index d222691cac..39bcee3698 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -514,7 +514,7 @@ Windows 下会自动发现常见 Clash/Mihomo 静态系统代理;Web UI 会显 ### 会话文件清理(#1082) -短命会话会留下永远不会再被恢复的小状态文件。清理是**可选开启(opt-in)**的:设 `BILI_SESSION_GC=1` 才启用(默认关闭 —— 会话文件属于用户数据,不应有静默删除策略)。启用且持久化开启时,bili 在启动时和每小时扫描一次会话目录,且只有**两个条件同时满足**才删除一个文件:年龄超过 `BILI_SESSION_GC_MAX_AGE_DAYS`(默认 7 天),并且该会话**从未被压缩过**(没有折叠块)、最近一次请求体 ≤ `BILI_SESSION_GC_MAX_TOKENS` token(默认 1M;未记录大小的旧文件用 `contextTokens`)—— 这样删除只丢字节不丢内容:继续对话会用客户端自己的历史重建上下文,代价只是一次冷重建。CCR 内容存储(#1097)以 `.content-store.json` 的形式存放在会话文件旁边,遵循同样的生命周期(#1180):存储随其会话文件一起删除;孤儿存储(会话文件已不存在)在超过年龄门后被清扫;存储的 token 占用(唯一内容字符数 ÷ 4)计入上述大小上限。被压缩过的会话永不删除(其摘要无法无损重建)。每次删除都会逐条写审计日志,另有一次非空扫描的汇总日志。活会话、不可读文件和加密文件(判断前先用 `BILI_ENCRYPTION_KEY` 解码)都按保守策略处理。详见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md)。 +短命会话会留下永远不会再被恢复的小状态文件。清理是**可选开启(opt-in)**的:设 `BILI_SESSION_GC=1` 才启用(默认关闭 —— 会话文件属于用户数据,不应有静默删除策略)。启用且持久化开启时,bili 在启动时和每小时扫描一次会话目录,且只有**两个条件同时满足**才删除一个文件:年龄超过 `BILI_SESSION_GC_MAX_AGE_DAYS`(默认 7 天),并且该会话**从未被压缩过**(没有折叠块)、最近一次请求体 ≤ `BILI_SESSION_GC_MAX_TOKENS` token(默认 1M;未记录大小的旧文件用 `contextTokens`)—— 这样删除只丢字节不丢内容:继续对话会用客户端自己的历史重建上下文,代价只是一次冷重建。CCR 内容存储(#1097)以 `.content-store.json` 的形式存放在会话文件旁边,遵循同样的生命周期(#1180):存储随其会话文件一起删除;孤儿存储(会话文件已不存在)在超过年龄门后被清扫;存储的 token 占用(唯一内容经内核 CJK-aware `defaultCountTokens` 计数,与 `rawInputTokens` 同一估算器)计入上述大小上限。被压缩过的会话永不删除(其摘要无法无损重建)。每次删除都会逐条写审计日志,另有一次非空扫描的汇总日志。活会话、不可读文件和加密文件(判断前先用 `BILI_ENCRYPTION_KEY` 解码)都按保守策略处理。详见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md)。 ## 状态 diff --git a/src/session-gc.ts b/src/session-gc.ts index 48f352209a..71339eed46 100644 --- a/src/session-gc.ts +++ b/src/session-gc.ts @@ -56,8 +56,9 @@ import { dropSessionForGc, peekSession } from "./session.js"; * goes; * - swept directly when orphaned (session file already gone — leftovers * from versions that deleted sessions without their stores); - * - its token footprint (unique-content chars ÷ 4) counts toward the size - * gate, so a tiny session with a huge store does not slip under it; + * - its token footprint (unique-content via the kernel's CJK-aware + * defaultCountTokens, same estimator as rawInputTokens) counts toward the + * size gate, so a tiny session with a huge store does not slip under it; * - attached to a kept session → kept untouched; an unreadable/foreign * companion next to an otherwise-eligible session → both kept (never * guess at unreadable files). diff --git a/tests/session-gc.test.ts b/tests/session-gc.test.ts index f5cadd3619..750f092d27 100644 --- a/tests/session-gc.test.ts +++ b/tests/session-gc.test.ts @@ -154,7 +154,7 @@ after(() => { assert.equal(isGcEligible({ ...base, storedTokens: 0 }, now, cfg), true, "zero footprint changes nothing"); }); - test("contentStoreTokens: unique-content chars ÷ 4; null for anything that is not a store envelope (#1180)", () => { + test("contentStoreTokens: unique-content via CJK-aware estimator; null for anything that is not a store envelope (#1180)", () => { assert.equal(contentStoreTokens({ version: 1, byHash: { h1: "aaaa", h2: "bbbb" }, byRef: { m00001: {} } }), 2, "sums byHash values via the CJK-aware estimator"); assert.equal(contentStoreTokens({ version: 1, byHash: { h1: "测试测试测试" }, byRef: { m00001: {} } }), 6, "CJK content counts per character (not chars÷4)"); assert.equal(contentStoreTokens({ version: 1, byHash: {}, byRef: {} }), 0, "valid empty envelope → 0");