Skip to content

fix: GC the CCR content-store companions (#1180) - #1189

Merged
ranxianglei merged 4 commits into
masterfrom
2026-09-23_gc-content-store-companions
Sep 25, 2026
Merged

ranxianglei merged 4 commits into
masterfrom
2026-09-23_gc-content-store-companions

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

What

Session-file GC (#1082) ignored the per-session CCR content stores added by #1097:

  1. Companions miscounted as unreadable. walkSessionFiles accepts any *.json, so <hash>.content-store.json entered the sweep, but viewFromParsed requires a top-level savedAt, which the store envelope {version, byHash, byRef} lacks → counted unreadable, kept forever.
  2. No companion deletion. The deletion path only rm'd the session file; the sibling store was never unlinked, orphaning potentially large lossless payload files with no code path to clean them.

Changes (src/session-gc.ts + tests + docs)

  • Co-deletion: when GC deletes a session file, its companion .content-store.json (deterministic sibling per contentStoreRelPathFor) is unlinked too.
  • Orphan sweep: companions whose session file is already gone (pre-fix leftovers) are deleted once past the age gate. The reference check matches the shared hash stem across namespaces — meta fill-once (session.ts) can migrate a session _unknown/ → namespaced without cleaning the old path, so sibling-only matching would false-orphan live store bytes across that move.
  • Size accounting: the store footprint (unique-content chars ÷ 4, same convention as bili's default token estimator and the kernel's totalChars) is folded into the BILI_SESSION_GC_MAX_TOKENS gate, so a tiny session carrying a huge store cannot slip under the ceiling.
  • Conservative edges: unreadable/foreign companion next to an otherwise-eligible session keeps both files (same never-guess rule [Feature] Default state file cleanup strategy #1082 uses for unreadable session files); live/resident sessions untouched.
  • Audit: per-file audit lines for companion deletions (path + size), consistent with [Feature] Default state file cleanup strategy #1082's logging; GcResult gains companionsRemoved (removed stays "session files").
  • Docs: companion lifecycle noted in README + CONFIGURATION (en/zh).

Deliberately NOT done: treating "has content-store entries" like everCompressed (would permanently exempt CCR sessions from GC — the population with the biggest files — contradicting the lossless-bytes argument of the issue).

Behavior changes (flagged per owner policy)

All behind the existing opt-in BILI_SESSION_GC (default off):

Area Old New Why
Companion on session delete left behind forever co-deleted the leak this issue fixes
Orphaned companion (session gone) kept forever swept once > MAX_AGE_DAYS pre-fix leftovers
Size gate for sessions with a store store bytes ignored store footprint (chars÷4) added to rawInputTokens/contextTokens before comparing to MAX_TOKENS small session + huge store must not slip under the gate; tightening is intentional
Unreadable companion next to eligible session n/a (companion unseen) both kept never guess at unreadable data
Summary log line unchanged when no companions removed gains + N content store file(s) when some are accurate accounting

No wire/message-shape, config-schema, persistence-format, or acp-kernel changes.

Tests

8 new cases in tests/session-gc.test.ts: stale CCR session → both files removed; live session + aged companion → untouched; cross-namespace companion still referenced (no false-orphan); orphan sweep (aged removed, fresh kept); tiny session + huge store → ineligible while its store-less twin is deleted; unreadable companion → both kept; plus unit tests for contentStoreTokens and the folded size gate.

Pre-flight on rebased head (master 03dd9c78): typecheck clean · full suite 2359 pass / 0 fail / 2 skipped (pre-existing e2e gates) · build success.

Fixes #1180

@github-actions

github-actions Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-23_gc-content-store-companions (7321d7d)

Option A — Install from npm PR tag (recommended)

npm install -g billion-context@pr-1189

Each push to this PR publishes a new version under the pr-1189 npm tag.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr1189.tgz
npm install -g package

Install instructions are refreshed on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Picking up the review for this PR. Plan: fetch the branch, verify it's on current master, audit the diff line-by-line against the existing GC behavior (#1082) and the CCR content-store contract (#1097), run the full pre-flight (typecheck / test / build) on the head, and report a mergeability verdict with the required regression checklist. Will follow up here.

ework-agent added 2 commits September 23, 2026 22:46
Session-file GC (#1082) ignored the per-session CCR content stores added
by #1097: walkSessionFiles picked up <hash>.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
…ace duplicate (#1180)

Meta fill-once (session.ts getSession) migrates a session _unknown/<h>.json -> ns/host_<h>.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).
@ranxianglei
ranxianglei force-pushed the 2026-09-23_gc-content-store-companions branch from 86c5e01 to 333135c Compare September 23, 2026 15:25
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 PR review — #1189 "fix: GC the CCR content-store companions"

Pre-flight (on rebased head)

Base was 3 commits behind master (#1187 native-fetch-guard); I rebased onto current master (882c30ed) — clean, no conflicts, no semantic overlap. On the fixed head: typecheck clean · full suite 2367 pass / 0 fail / 2 skipped (pre-existing e2e gates) · build success. GitHub CI on the pushed head is also fully green (8/8 checks incl. both OS × Node test matrices and the zero-token codex e2e).

Diff cleanliness

Clean. 6 files, every line serves the purpose: src/session-gc.ts (sweep logic), tests/session-gc.test.ts (8 cases), README/CONFIGURATION en+zh (lifecycle notes, consistent with the code). No whitespace churn, no lock/generated-file drift. My fix commit adds ~100 lines across the same two code files only.

Regression audit — existing behaviors on touched paths

Existing behavior Conclusion
Opt-in default (BILI_SESSION_GC unset → no-op sweep) Preserved — gcConfigFromEnv untouched
Session deletion criteria (age gate + never-compressed + size ≤ MAX_TOKENS) Preserved byte-identical for store-less sessions (storedTokens ?? 0). For readable-store sessions: intentional tightening, disclosed in your behavior table (store chars÷4 added before comparison; rationale correct — a tiny session must not slip under the ceiling carrying a huge store)
Unreadable/corrupt session files left in place, never guessed Preserved; new conservative edge (unreadable/foreign companion → keep both) is additive and matches the #1082 rule
Resident/in-flight/pending-save guard Preserved unchanged
Audit log format for session deletions Preserved; companion lines are new; summary line gains + N content store file(s) only when N>0 (no-change case byte-identical)
GcResult.removed = "session files" semantics Preserved; companionsRemoved is additive. Verified the only consumers are the two fire-and-forget call sites in src/server.ts (boot + hourly)
Empty-dir rmdir cleanup Preserved, harmlessly extended to companion parent dirs
Both compression modes / wire shape / config schema / persistence format / acp-kernel Not touched — GC is disk-side housekeeping

Problem found & fixed directly on the branch (commit 333135c8)

The cross-namespace guard covered the orphan pass but not the co-delete pass — an adjacent-path gap with a real data-loss window:

  • Meta fill-once (getSession, src/session.ts) migrates a session _unknown/<h>.json → ns/host_<h>.json without cleaning the old path — I verified in the kernel's StateStore that writes never delete the previous relPath, so the stale duplicate remains on disk with frozen mtime.
  • saveContentStore only rewrites when dirty. A moved CCR session whose store wasn't 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 — and stops at the first existing candidate, so a corrupted namespaced copy can't shadow it either way).
  • Co-delete pairing is strictly same-directory: sweeping the aged duplicate would unlink live lossless payload bytes (future acp_retrieve misses). Window is narrow (opt-in GC + migrated CCR session + no store re-save since move + cold at sweep + aged + never-compressed + small) but real.

Fix: skip the companion unlink when another surviving session file shares the hash stem and has no store of its own (audit-logged); the bytes stay referenced until that twin is swept, then 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. Added 3 regression tests, including an order-independent "both copies eligible" case proving the whole session ends up fully swept either way (no new leak path).

Behavior change vs the previously-pushed PR version: co-deletion old = unconditional same-dir unlink → new = conditional on no surviving reference-less twin; strictly narrower deletion, logged. No other deltas.

Minor residuals (report-only, not blocking)

  1. A shadowed dead flat store (namespaced store now exists) stays referenced by stem-match until the session itself is GC'd — for never-GC'd compressed sessions it lingers forever. Conservative trade-off baked into the PR's stem-matching design ("never guess"); acceptable.
  2. The stale duplicate session file itself lingers for compressed (never-deletable) sessions — pre-existing since fill-once, out of scope here.

Verdict

Diff clean, all existing behaviors accounted for, the one adjacent-path data-loss gap is now closed with tests, local pre-flight + full CI green on the rebased head. Mergeable — merge is yours to do: #1189

中文摘要:修复了 CCR 内容存储随会话 GC 时的一处跨命名空间数据丢失隐患(meta fill-once 迁移后旧路径旁挂的存储可能仍是活存储,原实现会误删),已在 PR 分支补上守卫逻辑和 3 个回归测试,全量测试与 CI 均绿,可以合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

复核完成(人工 + 独立 reviewer 双轨),两个 SHOULD-FIX 已修并推回(a3ec90f,门禁:2367/0/2skip、typecheck 0、build ✓):

修复 1 — 估算器混用:contentStoreTokens 从 chars÷4 改为内核 defaultCountTokens(CJK-aware)——rawInputTokens 用的就是它(persist.ts:848),chars÷4 对 CJK 重 store 低估至 4×,会让本不该过尺寸门的会话被删。新增 CJK 断言("测试测试测试"→6)。

修复 2 — 孪生守卫 inode 探测改为形状探测:loadContentStore 在 namespaced store 存在但不可读时会穿透到 _unknown/(persist.ts:286-291 catch { continue }),原 stat-存在性判断在这个角落会把孪生会话的真实活 store 当冗余删掉。改为 contentStoreTokens(readRawFile(...)) !== null 形状探测,不可读按保守处理(keep)。

顺带:外族/不可识别伴生文件的永久保留现在有审计日志(#1082 精神:每个保留决定可追溯)。

复核确认(review 裁定无阻塞):两个根因属实;删除安全通过对抗审计——年龄门分层正确、无 stat→rm 间 await(无 TOCTOU)、24-hex stem 无碰撞、不跟随符号链接、Windows basename 后缀判断保守。

可合并。Fixes #1180。

… switch (#1180)

a3ec90f 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.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 复核验证完成 — a3ec90f 两个修复独立确认,另补了一个 docs 同步提交(7321d7d)

独立验证(不是转述,是逐条查证)

修复 1(估算器混用)— 成立且必要。 我追了完整链条:rawInputTokens 在 src/server.ts:1542 由 estimateRawBodyTokens(parsed) 记录,后者(src/preflight.ts:172-176)对每个文本值调 defaultCountTokens;src/persist.ts:833/838 的持久化视图预算也用同一个。所以原 chars÷4 确实是跨估算器相加 —— CJK-heavy store 被低估至多 4×,尺寸门可被钻过。改后 gate 两侧同估算器,方向正确。新增的 CJK 断言("测试测试测试"→6)钉住了语义。

修复 2(形状探测)— 你抓到了我守卫里的真实角落。 我之前只验证了「malformed JSON → return null 不穿透」,漏了 readFileSync 的 catch { continue } 对存在但读取失败(EACCES/EIO 等)同样穿透到 _unknown/ —— 那种情况下 stat 存在性判断会把孪生的活 store 当冗余删掉。改为 contentStoreTokens(readRawFile(...)) !== null 后双向都保守:不可读 → keep;malformed JSON → loadContentStore 实际不穿透(flat 是死字节),但探测也判为"无有效 store"而 keep —— 偏保留侧,无数据丢失路径。readRawFile 永不抛错(返回 null),探测不会炸。

顺带审计日志 — 已确认:外族/不可识别伴生文件导致的双保留现在逐条留痕,符合 #1082「每个保留决定可追溯」精神。

增量行为审查(本轮 diff = a3ec90f + 7321d7d)

变化 旧 → 新 判定
Store footprint 估算 chars÷4(CJK 低估至 4×)→ kernel defaultCountTokens(与 rawInputTokens 同一估算器) 有意收紧:CJK-heavy store 会话更可能留在门内;只增保留、不增删除路径
孪生守卫探测 stat 存在性 → 形状探测(可读且是合法 envelope) 有意收紧:存在但不可读/畸形的孪生 store 不再遮蔽 flat 活 store 的保护
外族伴生保留 静默 keep → 逐条 info 审计行 纯增量日志

无 wire/schema/persistence/kernel 触碰;删除安全性(年龄分层、无 stat→rm 间 await、stem 唯一性、不跟符号链接)与上轮对抗审计结论一致。

我补的提交 7321d7d(docs 同步,无行为变更)

a3ec90f 改了估算器但留下 6 处 "chars ÷ 4" 旧描述:README en/zh、CONFIGURATION en/zh、src/session-gc.ts 模块头注释、以及 tests/session-gc.test.ts:157 的测试标题(断言消息你们改了,标题没跟上)。已全部同步为「内核 CJK-aware defaultCountTokens,与 rawInputTokens 同一估算器」。

门禁(我在 a3ec90f 和 7321d7d 上各跑一遍本地 + CI)

typecheck clean · full suite 2367 pass / 0 fail / 2 skipped(pre-existing e2e gates)· build ✓ —— 与你们报告的数字一致。GitHub CI 在最终 head 7321d7d 上 9/9 全绿。PR 分支现为 a3ec90f → 7321d7d(fast-forward 推入)。

结论:可合并(merge 仍归人工):#1189

中文摘要:独立验证了两个 SHOULD-FIX(估算器混用确属跨估算器相加已对齐内核 CJK-aware 计数;孪生守卫确实漏了"存在但不可读则穿透"的角落,形状探测修复正确且双向保守),另补了 6 处文档/注释/测试标题的旧描述同步,全部门禁绿,可以合并。

@ranxianglei
ranxianglei merged commit c8e6ffd into master Sep 25, 2026
9 checks passed
ranxianglei pushed a commit that referenced this pull request Sep 25, 2026
…ema legitimately shifts the recent-window boundary (#1207 rebase onto #1189/#1273/#1270)
@github-actions github-actions Bot mentioned this pull request Sep 25, 2026
@ranxianglei
ranxianglei deleted the 2026-09-23_gc-content-store-companions branch October 15, 2026 05:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Session-file GC (#1082) never removes #1097 .content-store.json companions — orphaned ref files accumulate

1 participant