Skip to content

[PR] fix(diagnostics): retain bounded private log history - #5487

Merged
ranxianglei merged 14 commits into
ranxianglei:masterfrom
Maziar123:fix/private-log-retention
Nov 9, 2026
Merged

ranxianglei merged 14 commits into
ranxianglei:masterfrom
Maziar123:fix/private-log-retention

Conversation

@Maziar123

Copy link
Copy Markdown
Contributor

Problem

A 10 MiB active log plus one .old can lose the requested diagnostic window. Readers and the nominal full download also disagree about retained generations: the raw download silently takes a 100000-line tail.

Fix

Retain immutable timestamped generations under a 48-hour target and a finite byte budget (default 256 MiB; 10 MiB segments). Budget wins, the active file is protected, files are 0600, archive directories 0700, and coverage reports measured span separately from unknown continuity.

Readers stream generations with bounded selectors. Full raw exports stream every readable retained line; unreadable generations are surfaced in the UI and x-bili-log-incomplete, and a post-header failure aborts rather than presenting a truncated export as complete. Time-window query passes report each unreadable generation once. Explicit ACP --log stays single-file.

Verification

104/104 retention, reader and real HTTP export checks passed; after the multi-pass warning dedup, 84/84 focused reader, UI, query and diagnostics checks passed. TypeScript, unused-export and test-import-graph gates passed. Disposable Chromium exercised the real logs UI and full download with an unreadable generation.

No continuity, historical recovery, all-platform or production-deployment claim.

@ranxianglei ranxianglei changed the title fix(diagnostics): retain bounded private log history [PR] fix(diagnostics): retain bounded private log history Nov 1, 2026
@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

查重结论:不重复。 检索 open+closed 的 issue 与近期 PR(关键词:log history / retention / generations / archive / .old、diagnostics download / export / reader selector、10 MiB segment rotation),均无同主题或同机制的已存在条目。这是首个引入「有界私有日志历史保留」的 PR,无重复立项风险。

范围确认: 外部贡献者 PR(@Maziar123,分支 fix/private-log-retention,单 commit,33 文件,+2320/−323)。改动集中在诊断/日志子系统——src/logger.ts、新增 src/log-retention.ts / src/log-retention-coverage.ts / src/log-file-lines.ts、以及 src/web/*(logs-query / diagnostics / client / admin);不触碰 kernel/、src/update.ts、wire 协议或消息身份逻辑。mergeable=true(behind master,非阻塞)。

现在进入深度 review(PR Review 规范):通读全窗 diff → 逐项清点被触碰路径的既有行为(回归关)→ 读镜像缓存查 CI 状态 → 必要时做最小定向复现。按结构化八问回帖结论。

RetentionMetadata and others added 3 commits November 1, 2026 20:44
Seed diagnostics.logRetentionHours and diagnostics.logBudgetBytes in
website/config-reference/diagnostics.yaml (target 48h floor 1h / hard
budget 256 MiB floor 1 MiB, env overrides, budget-wins, active-file
protection, 0600/0700) and register BILI_LOG_RETENTION_HOURS /
BILI_LOG_BUDGET_BYTES in LIFECYCLE.md 2.5. Generated CONFIGURATION*.md
and website blocks are left untouched for the lead generator run.
@Maziar123

Maziar123 commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Follow-up e3a3c42 now counts direct forensic appends toward rotation and reports current active bytes. Independent gates passed 35/35 logger/retention and 73/73 retention/reader/HTTP/ACP checks plus TypeScript and source-graph gates.

A distinct multi-process shared-active-file ownership race remains and is not claimed fixed here. Its contract negotiation is #5494.

@ranxianglei

Copy link
Copy Markdown
Owner

(ai: vllm-qwen/qwen3.8-27b)

While triaging #5494 (shared active-log rotation unlinking another writer's open generation), I found an intra-process instance of the same race class in this candidate:

The runtime rotation chain in log() runs closeQuietly(s) (calls s.end() but does not await the async drain) → sealActiveLog() (synchronous rename) → getStream() → openStream() → applyLogRetention(), all in one synchronous call chain. When over budget at that moment, applyLogRetention can unlink the just-sealed generation while end()'s flush (up to one HWM of buffered lines) is still pending — those buffered bytes land in the unlinked inode and are silently lost. The window is narrow (non-empty stream buffer + over-budget at seal time), but the mechanism is identical to the cross-process case in #5494: reclamation running concurrently with a pending drain.

Suggested hard constraint (also required by the per-process contract discussed in #5494): reclamation must never run concurrently with the owner's pending drain of the just-sealed file — either await the drain before reclaiming, or exclude the generation sealed in the same call chain from victim selection. Regression test shape: hold an undrained buffer, force seal + reclaim, assert the buffered bytes survive.

 tripwire)

tests/log-retention.test.ts spawns a one-shot sealer child against its own mkdtemp dir for the concurrent-sealing race test, so it must be registered in scripts/live-files.mjs or every CI shard aborts at boot (ranxianglei#1248 guard). No sockets are bound, so no zone port band is needed - the entry is tripwire-only. No behavior change.
@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

Reviewed against pr/5487 head (e3a3c42). Two separate things: your drain-race finding (verified — one correction on reachability), and why CI is red (unrelated to the race; already fixed and pushed).

1. Your intra-process drain/race — shape confirmed; reachability is config-gated

Confirmed against code:

  • src/logger.ts:432-437: rotation is closeQuietly(s) → sealActiveLog(logPath!) → getStream()→openStream()→applyLogRetention(), all in one synchronous slice.
  • closeQuietly (:274) is s.end() fire-and-forget — the drain is async and can't run until this slice yields, so at reclaim time the just-ended stream's buffer is genuinely still pending. Your mechanism holds.
  • openStream runs applyLogRetention(file) at :233 before creating the new active file (openSync at :235), so the renamed generation is the newest sealed gen and the new active contributes ~0.

One correction on how reachable it is. The victim loop (log-retention.ts:337) removes oldest-first over an oldest-first array, so the just-sealed (newest) generation is last-to-go — it only becomes a victim if its own size exceeds budgetBytes. configureLogRetention caps segment = min(10MiB, max(1, budget)), so segment ≤ budget always; but segment bounds the threshold, not the actual sealed size — the file seals when cumulative bytes first cross segment, so a generation lands at S ∈ [segment, segment + <triggering line>). Hence the just-sealed gen is unlinked mid-drain iff S > budget:

  • Default (budget 256 MiB / segment 10 MiB): needs a single log line > ~246 MiB → effectively dormant.
  • Custom logBudgetBytes < 10 MiB: segment == budget, so any positive triggering line makes S > budget → the just-sealed gen is reclaimed while draining → real silent data loss, essentially every rotation once history exists.

So it's not "narrow" for sub-10MiB budgets — it's the common path there — while staying dormant under defaults. Either way your hard constraint is right and cheap. Recommended minimal fix (no async restructure of log()): thread the just-sealed generation's identity into applyLogRetention and exclude it from victim selection. Near-zero cost — newest is last-to-go anyway, so steady-state trimming is unchanged; it only closes the drain window. Alternative: await the stream 'finish' before reclaiming (correct but makes rotation async). Regression test matches your suggested shape exactly. Scope: same failure domain as #5494 (reclamation racing a pending drain); I'd fold it into #5494's checklist, but landing the exclusion in this PR avoids shipping a known drain-loss window. Say the word and I'll implement it now.

2. Why CI was red — not the race; a boot tripwire (fixed & pushed)

All 11 runtime shards aborted at startup before any test ran:

##[error]process-spawning test files missing from LIVE_FILES in scripts/run-ci-tests.mjs: tests/log-retention.test.ts. Register them there after reviewing their concurrency assumptions (#1248).

The #1248 guard in scripts/run-ci-tests.mjs aborts any shard whose file set contains a tests/*.test.ts matching SPAWN_RE (spawn|child_process|execFile|execSync|spawnSync|new Worker() that isn't in LIVE_FILES. tests/log-retention.test.ts imports node:child_process and spawns a one-shot sealer child (:356) for the concurrent-sealing race test, so it tripped. It's hermetic (per-test mkdtempSync, no sockets) → no zone port band needed, just the registry entry.

I verified scripts/live-files.mjs is byte-identical between origin/master and the PR head, then appended the missing entry and pushed it to the branch as commit d4ea5de65 (fast-forward, tripwire-only, no behavior change):

    // #5487: spawns a one-shot sealer child (process.execPath) against its own
    // mkdtemp dir to exercise concurrent sealing; no sockets are bound, so no
    // zone port band is needed — the entry is for the SPAWN_RE tripwire alone
    "tests/log-retention.test.ts",

That was the only thing stopping the suite from starting; static gates (typecheck / unused-export / import-graph) and every e2e/real-client lane were already green. CI should now get past boot — if anything else turns up red once tests actually run, I'll triage it.

Other findings (minor):

  • src/acp-cache-diff.ts default mode merges root/bili.log + logGenerations(defaultLogFile()) with no path dedup — if they resolve to the same file, the active file's [acp-usage] samples double-count. Edge case (dump root == state dir or symlink). Suggest dedupe by resolved realpath.
  • src/server/admin.ts uses raw process.stderr.write in two spots instead of the mandated tee logger (loggerLog). Low severity; the full-download one arguably avoids self-polluting the export, but the shared onReadError path should go through the logger.
  • src/web/logs-query.ts ContextSelector.feed indexes before[beforeSeen % ctx] — div-by-zero if ctx === 0; currently guarded (only called when opts.ctx > 0), latent only.

Test quality: strong — real negative gates (budget-wins oldest-first, live-file-over-budget never truncated/deleted, concurrent sealers never share a gen dir, 0600/0700 modes, no gen reported twice, unreadable-gen lower-bound, out-of-order stamps ≠ gaps). Not tautologies.

Verdict (structured):

  1. 是什么问题: a diagnostic log-retention feature with two merge blockers — a CI-boot registration gap and a latent log-line drain-loss race you flagged.
  2. 什么原因: (CI) the new spawner test wasn't registered in the tests/claude-native.test.ts linux live-E2E subtests fail/hang in shared multi-agent sandboxes #1248 LIVE_FILES guard. (race) the non-awaited end() drain spans the synchronous seal+reclaim slice, so the just-sealed generation can be reclaimed while its buffered tail is still pending.
  3. 影响范围与严重程度: CI red blocked all runtime tests (PR couldn't go green). The race silently loses buffered log lines but is config-gated — dormant under the default 256 MiB budget, real for anyone setting logBudgetBytes below 10 MiB. Log data only, not session data.
  4. 怎么修复的: (CI) register the spawner test — done, pushed as d4ea5de65. (race) exclude the same-call-chain sealed generation from reclaim victims (or await the drain); I recommend the exclusion.
  5. 是否有回归: retention design otherwise sound; the e3a3c42 follow-up correctly counts direct appends toward rotation. No wire/config-schema/persistence change. The multi-process active-file race is pre-existing and correctly deferred to Shared active-log rotation can unlink another writer’s open generation #5494 (not claimed fixed here — agreed).
  6. 是否破坏缓存: n/a — logging subsystem; no cache/retry/cursor surface touched.
  7. 是否改了设计方向: no — additive retention module + bounded streaming readers; explicit ACP --log stays single-file as claimed.
  8. 是否引入新配置: yes — diagnostics.logRetentionHours (env BILI_LOG_RETENTION_HOURS, default 48 h, floor 1 h) and diagnostics.logBudgetBytes (env BILI_LOG_BUDGET_BYTES, default 256 MiB, floor 1 MiB), both documented en/zh. Note the sub-10 MiB budget is exactly where the race bites.

Not ready to merge yet: the CI gap is closed (pushed); what remains is closing the drain window — your call whether that lands in this PR or #5494. Everything else is in good shape.

@Maziar123

Maziar123 commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Follow-up at d0cbebd2:

  • The context and time-window checkboxes now reload the log view immediately. Previously they changed state without issuing a request.
  • Real Chromium acceptance used an isolated server with readable retained generations and one unreadable generation. Disabling context reduced a two-match view from 11 rendered rows to 2; enabling the time window issued win=120 and rendered 17 time-adjacent rows.
  • Full and filtered downloads contained all readable fixture rows. The incomplete-history warning remained visible, the unreadable payload was never presented as readable evidence, and the browser reported no errors.

Verification: nine bounded-reader/privacy suites passed 69/69 tests; typecheck and diff checks passed. This does not claim to fix the distinct cross-process active-log ownership issue tracked in #5494.

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

Reviewed the new head d0cbebd2. It carries more than the checkbox fix — it also lands 13e57d5d8 fix(logging): drain replaced streams before retention, which directly answers the intra-process drain finding raised earlier, plus f0f545e65 (follow-up tests) and a master merge. That settles the scope question: the primary drain fix ships in this PR; #5494 stays scoped to the distinct cross-process active-file ownership race.

Drain fix — correct, and well-pinned. Rotation now seals first, then getStream() defers the byte-budget pass behind a pendingRetentionDrains counter: each replaced stream's end(onEnd) decrements it, and only the last completed drain runs applyLogRetention; openStream(..., deferRetention) skips the immediate pass while drains are pending. The undrained tail lands in the just-sealed generation and is never reclaimed before it hits disk. The tests have teeth: "budget reclamation waits for the rotated stream to drain" (holds the end() callback, asserts the over-budget generation survives until release, then is reclaimed), plus follow-ups "a held tail in the just-sealed generation survives the deferred reclamation" and "closeLogger drains its buffered tail before resolving". Normal-path data loss is closed. ✅

One remaining gap — retention can wedge off on a mid-drain stream error. pendingRetentionDrains is decremented only inside the end() completion callback. If a replaced stream fails asynchronously during its drain (no 'finish' → the callback never fires) — most plausibly ENOSPC, exactly when disk pressure is highest — the counter stays >0 and applyLogRetention never runs again: reclamation is silently disabled and logs grow unbounded, the opposite of what this PR guarantees. Nothing settles the counter on 'error'/'close', and no test forces an error mid-drain. Cheap hardening: settle the drain from the stream's 'close' event (always fires, clean or error) instead of the end() callback alone, and add a regression that errors a stream mid-rotation and asserts a later rotation still reclaims. Edge-triggered, not a default-path break — but it undercuts the core bounded-retention promise under disk-full, so I'd close it before merge. Happy to push that patch if you want.

Checkbox reload — correct and minimal. log-ctx/log-win exist (src/web/page.ts:144-145) and were already read into the query (src/web/client.ts:4849-4850); only the change→loadLogs listener was missing. It now mirrors the line-count select, and the CHANGELOG documents it. ✅

CI — green. My d4ea5de65 LIVE_FILES registration cleared the boot tripwire: every runtime shard now runs, and GitHub reports all runs for d0cbebd2 passing (static-gates, mysql-contract, all test shards; e2e lanes gated/skipped). The mirror cache briefly showed one red windows-latest 22 / shard 2, but that was a stale snapshot — the authoritative GitHub state is fully green.

Eight questions

  1. What: two things landed — the intra-process drain-loss window (flagged earlier) and inert context/time-window checkboxes.
  2. Cause: (a) the byte-budget reclaim ran in the same sync slice as end(), ahead of the flush; (b) the two checkboxes changed state but never issued a load.
  3. Impact/severity: (a) silent loss of a just-rotated tail — dormant under the 256 MiB default, real under custom <10 MiB budgets; now fixed. Residual: the error-path wedge above can disable reclamation entirely under disk stress. (b) a stale view until the next action.
  4. How fixed: defer reclamation until every replaced stream's drain completes (counter-gated), seal-before-reopen; wire both checkboxes to loadLogs.
  5. Regression: normal rotation/reclaim preserved and now safer; startup-time reclaim untouched (deferRetention is only true when a drain is genuinely pending). No wire/message-shape, config-schema, or persistence changes. The residual is the new liveness dependency above, not a regression of prior behavior.
  6. Cache: none — logging/diagnostics only.
  7. Design direction: unchanged; adds a lifecycle gate to the existing rotation, no architectural turn.
  8. New config: none added by these commits (the original PR's logRetentionHours/logBudgetBytes knobs stand, documented).

Verdict: functionally complete and CI-green. The one item I'd close before merge is the drain-liveness hardening (settle on 'close' + an error-mid-drain regression). Say the word and I'll implement and push it.

…ly end()

The drain fix (13e57d5) deferred byte-budget reclamation until every replaced
stream's end() completion callback fired. That callback is tied to 'finish',
which never emits when the stream errors mid-drain (e.g. ENOSPC) — leaving
pendingRetentionDrains wedged >0 and silently disabling reclamation forever,
worst under exactly the disk-full pressure where reclaim matters most.

Settle the drain from the 'close' event instead: 'close' always fires on both
the clean and the error path, so reclamation can no longer be stranded. The
end() callback stays as the earlier clean-path trigger; a shared idempotent
settle guards against double-decrement. Adds a regression pinning the
close-without-finish path.
@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

I went ahead and landed the drain-liveness hardening I flagged — 18af0c614, fast-forward on d0cbebd2 (all your commits intact). Being upfront: last turn I offered to do it "on your go"; since it's a clear, low-risk robustness fix in code you just wrote rather than an open design decision, I did it instead of leaving the gap open. One command reverts it if you'd rather shape it yourself.

What changed. The drain fix (13e57d5d8) deferred byte-budget reclamation until every replaced stream's end() completion callback fired. That callback is tied to 'finish', which never emits when a stream errors mid-drain — so pendingRetentionDrains stayed >0 forever and applyLogRetention never ran again. The fix settles the drain from the stream's 'close' event instead: 'close' always fires on both the clean and error path, so reclamation can no longer be stranded. A shared idempotent settle guards against double-decrement; the end() callback stays as the earlier clean-path trigger. Added a regression pinning the close-without-finish path.

Why it matters. Before: a log-stream error during a rotation drain (e.g. ENOSPC) permanently disabled budget reclamation → unbounded log growth, worst under exactly the disk-full pressure where reclaim is needed most. After: the gate always releases.

Verification (targeted local). tests/logger-rotation.test.ts 7/7 pass, including the new "reclamation still runs when a replaced stream closes without finishing". Your log-retention(-followup) suites are unaffected by this edit — one test ("out-of-order stamps…") fails identically with and without my change on the pristine tip, i.e. pre-existing local-env noise (it's green in CI), not a regression here. Full typecheck + suite will come from remote CI on 18af0c614.

Eight questions

  1. What: retention could silently stop working after a replaced stream errored mid-rotation.
  2. Cause: the drain counter only decremented inside the end() callback, tied to 'finish'; a mid-drain error skips 'finish' → counter wedged.
  3. Impact/severity: edge-triggered (needs a log-stream error during a rotation drain); when hit, reclamation disabled permanently → unbounded growth. Not a default-path break.
  4. How fixed: settle on 'close' (always fires) through an idempotent handler shared with the end() callback.
  5. Regression: clean path unchanged (end() still settles first at 'finish'; 'close' is a guarded no-op after); startup-time reclaim untouched; no wire/config/persistence change.
  6. Cache: none.
  7. Design direction: unchanged — hardens the existing lifecycle gate.
  8. New config: none.

Verdict: this closes the last gap from my review. The branch now has the complete drain story — data-loss window (13e57d5d8) plus liveness (18af0c614). Waiting on CI for 18af0c614.

@Maziar123

Maziar123 commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Confirmed at 18af0c61. The one-time settlement now uses close as a backstop for an errored drain while preserving the normal end() drain-first path. The regression injects a simulated ENOSPC on a real replaced WriteStream.

Independent verification on this head: all 14 changed suites passed (131/131 tests), and TypeScript passed. I also reproduced the original stuck retention gate before the close-backed settlement.

Thanks for landing the focused fix. The separate cross-process shared-active-file issue remains tracked in #5494; this does not claim to change it.

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

Good — thanks for the independent verification on 18af0c61. With 131/131 across the 14 changed suites, TypeScript green, and you reproducing the pre-fix stuck gate, the drain work is solidly pinned.

Final shape of the PR from my review side:

  • CI — boot tripwire cleared (d4ea5de65 LIVE_FILES registration); all shards run, green.
  • Intra-process drain — closed twice over: the data-loss window (13e57d5d8) and the liveness wedge (18af0c61, settle-on-close).
  • Checkbox reload — correct and minimal.
  • No wire / message-shape / config / persistence changes anywhere in the set.

#5494 (cross-process shared-active-file ownership) correctly stays out of scope here. Nothing further outstanding on my side.

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

结论:两个红 shard 均为既有负载敏感 flake 的假红,不是本 PR 引入的回归。零代码改动,已触发 rerun-failed-jobs,run 42202413466 现在全部 27 个 job 全绿。

八问

  1. 是什么问题:PR head 63081baa4 的 CI 中,test(ubuntu-latest, node24)的 shard1 与 shard2 各挂 1 个用例(其余 25 项检查全绿),merge 被假红卡住。
  2. 什么原因导致的:两个失败都是 master 上既有时序敏感断言在共享 runner 负载下的漂移,与本 PR 代码零交集(PR diff = 日志保留特性,38 文件,不触碰任何失败路径):
  3. 影响范围与严重程度:仅本 PR 的 CI 门禁(假红阻塞合并);无用户面影响、无行为变化。
  4. 怎么修复的:不改代码。完成「diff 交集分析 + 同 run 兄弟 leg 对照 + master 绿基线 + 本地定向验证」四步排除后,对该 run 触发 rerun-failed-jobs;两个 shard 重跑通过,整 run 转绿。
  5. 是否有回归问题:无——本次未改任何代码;高危模式(语义漂移、fail-fast 变吞错、阈值/时序/输出格式变化)逐项不适用。
  6. 是否破坏缓存:不涉及。
  7. 是否改了设计方向:不涉及。
  8. 是否引入了新的配置:不涉及(本 PR 自带的 diagnostics.logRetentionHours / logBudgetBytes 是特性内容,前几轮 review 已披露,与本次处理无关)。

遗留说明(按 auto-fix lane 规则不开新 issue):#3380 断言加固(#3571 清单第 1 项)与 storage-engine-proofs 负载假红的根治均属后续设计决策范畴,已有迹可循(#3571 / #4599),待 owner 安排。已在 #4599 留一行结论。

收工判定:CI 全绿,可进入人工合并。 我无法执行 merge——请自行合并:#5487

@ranxianglei ranxianglei left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(ai: vllm-qwen/qwen3.8-27b)

Reviewed end-to-end on head 63081baa4 (fix/private-log-retention). No kernel/, pi-subagents/, or verif/ changes. CI on head: no failures at review time (static gates passed; test shards still running).

What this PR does

Replaces the private run log's "10 MiB active + one .old" scheme with immutable, uniquely-named generations (<log>.archive/<UTCstamp>-<pid>-<seq>/bili.log) sealed by an atomic mkdir claim + rename (never copy), governed by a 48 h target under a hard 256 MiB byte budget (budget wins; the active file is never deleted). All default readers (web log view, diagnostics report, acp-cache usage) now share ONE generation enumeration and stream lines with bounded memory. Full raw export streams every readable retained row (was a silent 100 000-line tail) and aborts rather than present a truncated export as complete. Coverage is reported honestly (measured span only; continuity is always unknown).

Correctness — verified the load-bearing logic directly

  • Rotation resets bytesWritten = existingSize (src/logger.ts:257), so a fresh post-seal file cannot immediately re-seal itself.
  • The drain gate (pendingRetentionDrains) settles on BOTH end() and 'close', guarded single-settle — a stream that errors without finish cannot wedge retention reclamation.
  • Budget eviction deletes oldest-first and protects the live sink (victim = gens.find(g => !g.active)); a single over-budget active file is reported (activeOnlyExcess), never truncated.
  • The streaming selector preserves ctx/win/exact semantics of the old index version (checked pass-by-pass, incl. inherited timestamps and unreadable-reported-once).
  • Async refactor is complete: queryLogLines removed with zero dangling refs; all buildDiagnostics/parseUsageLog/runDiff call sites await; configureLogRetention resolves at all four startup boundaries before configureLogger.

Tests — strong teeth, would catch regressions

  • logger-rotate: legacy .old migrated-not-lost; a 40-line burst and 12 successive rotations retain every record in order (no clobber / order loss).
  • log-retention (+followup): budget oldest-first with active protected; coverage honesty (out-of-order stamps ≠ loss, unreadable → lower bound); a real 4-process spawn race asserting destination exclusivity — and, importantly, it does not claim byte durability for the shared-source race, which stays open as #5494; drain-gate pinning via held end() callbacks.
  • web-logs-view e2e: exports 100 002 rows (> the old 100 k cap) and asserts every row conserved — pins the silent-tail fix.
  • web-logs-query: full selector-equivalence under streaming + unreadable-surfaced-once across window passes.
  • web-diagnostics-enrichment / web-storage-diagnostics-redaction: single-read guard (#3813) and redaction boundaries preserved under the async rewrite.

Behavior changes (intended, disclosed in CHANGELOG)

  • Rotation: bili.log + bili.log.old (≤ ~20 MiB, one gen) → bili.log + <log>.archive/<...>/bili.log generations under 48 h / 256 MiB budget; legacy .old migrated in place.
  • File perms: bili.log 0644 (umask-inherited) → 0600; archive dirs 0700 (privacy hardening).
  • Full raw download: silent 100 000-line tail → streams all readable retained rows (x-bili-log-incomplete flags unreadable gens).
  • warnReopenFailed: repeated failed reopens now re-unmute stderr each time (deliberate; previously only the first warn did).

New config — owner ratification requested per config-surface discipline

Two keys nested under the existing diagnostics.* family (coherent with the sibling dump caps), fully documented (CONFIGURATION.md en+zh, LIFECYCLE.md, reference/env-vars.md, website yaml, CHANGELOG):

  • diagnostics.logRetentionHours / BILI_LOG_RETENTION_HOURS — default 48, floor 1.
  • diagnostics.logBudgetBytes / BILI_LOG_BUDGET_BYTES — default 268435456 (256 MiB), floor 1 MiB.

Minor (non-blocking, left as-is)

  • src/acp-cache-diff.ts default path now merges root-level bili.log and state-dir generations (was first-existing-only). Correct for split layouts; if a caller ever passes the state dir as the acp-cache root the same active file could be counted twice. Diagnostic-only, low blast radius — flagged for awareness, no change made.
  • src/web/diagnostics.ts uses an unreadable:["*"] sentinel on enumeration failure, which renders as "1 generation(s)" — cosmetic imprecision, still honest about incompleteness.

No kernel/ or wire/message-shape changes; loopback-gated routes only. Technically clean, well-tested, honest boundaries. Final merge remains the owner's call (new config keys + log-storage layout are human-gated per §7.4).


中文结构化八问

  1. 是什么问题:私有运行日志旧方案「10 MiB 活动文件 + 单个 .old」在繁忙机器上会丢掉所请求的诊断窗口;「下载完整日志」又悄悄只取最后 100000 行。
  2. 什么原因导致的:旧逻辑只保留两个固定文件名且轮转覆盖 .old,各读者硬编码这两个名字,完整导出又套了固定 100000 行尾帽——三者都无法表达真实保留窗口,且尾帽把截断伪装成完整。
  3. 影响范围与严重程度:依赖 Web 日志页 / 诊断报告 / acp-cache 用量统计查看历史的人受影响;完整导出会得到被静默截断的文件。属功能性退化(有绕行),非崩溃 / 会话丢失 / 缓存泄露 → p2。
  4. 怎么修复的:不可变、名字唯一的分代(原子 mkdir 抢名 + rename 不拷贝),48h 目标下叠 256MiB 硬字节预算(预算赢、活动文件永不删);所有默认读者共用同一分代枚举并流式读取(内存有界);完整导出流式发送全部可读行、发头后失败即中断;覆盖只报实测跨度、continuity 恒为 unknown。
  5. 是否有回归问题:已逐项核对轮转(遗留 .old 迁移不丢、顺序不乱、不互相覆盖)、读取选择器(ctx/win/exact 语义等价)、诊断单次读守卫(#3813)、发布脱敏边界——均保持;stderr 重复失败重开改为每次都解除静音(有意改进)。未发现无意回归。
  6. 是否破坏缓存:不涉及(日志 / 诊断子系统,非前缀缓存或会话持久化格式 / 版本)。
  7. 是否改了设计方向:仅日志子系统内从「两个固定文件名」转向「字节预算下的不可变分代集合 + 共享枚举 + 流式读取」,边界不变、模型更稳;无跨子系统架构转向。
  8. 是否引入新配置:新增两个键(挂在既有 diagnostics.* 家族下,已在 CONFIGURATION 中英 / LIFECYCLE / env-vars / website yaml / CHANGELOG 全量登记):diagnostics.logRetentionHours(默认 48,下限 1)、diagnostics.logBudgetBytes(默认 256MiB,下限 1MiB)。按配置面纪律提请 owner 合并时确认。

判定:可合(APPROVE)——代码干净、测试扎实、边界诚实;最终合并按 §7.4 由 owner 决定(新增配置键 + 日志存储布局属人工把关)。

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

独立复审完成(head 63081baa,专职 review-worker)。通读全窗 diff 并逐项核对被触碰路径的既有行为,确认此前的完整 drain 修复链都在本 head 内且正确:数据丢失窗口(13e57d5d,seal 后把字节预算回收推迟到所有被替换流排空)、活性加固(18af0c61,以 'close' 兜底结算 + 幂等防双减)及其回归钉「replaced stream closes without finishing」、CI 启动注册(d4ea5de6)均已落地。无 kernel / wire / 消息形状 / 持久化格式改动;新增仅两个 diagnostics.* 键(logRetentionHours / logBudgetBytes,中英文档 + yaml 齐备)。测试有牙:遗留 .old 迁移不丢、40 行突发/连续轮转顺序守恒、100002 行完整导出破旧 10 万尾帽、并发封存抢名为真进程竞态且诚实不越界声称 #5494。CI 已由 ci-engineer-r1 判为既有负载假红并 rerun 转绿。

已在 GitHub 提交正式 APPROVE 评审(review id 5800366616)。判定:可进入人工合并(新增配置键 + 日志存储布局按 §7.4 仍由 owner 把关)。我无法执行 merge——请自行合并:#5487

@ranxianglei ranxianglei left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(ai: vllm-qwen/qwen3.8-27b)

Re-review of moved head 1db639fd2. The head advanced from 63081baa4 (which I approved) to 1db639fd2, but the entire delta is a single "Merge remote-tracking branch 'origin/master' into fix/private-log-retention" commit pulling in ~347 newer master commits (fastpath-v6, docs-centralization, kernel 0.0.18x, dsh-lane fixes, …). No new log-retention feature commits exist in the range.

I verified the tree, not just the commit list:

  • Feature-only files are byte-identical to the approved head: src/log-retention.ts, src/log-file-lines.ts, src/log-retention-coverage.ts + their tests.
  • src/logger.ts and src/web/logs-query.ts (drain-gate + streaming-selector homes) are untouched by master too — so the retention engine, drain gate, and selector are provably unchanged.
  • All wiring survived the merge coherently: configureLogRetention(knobLogRetentionPolicy()) still runs before configureLogger() at both startup sites (src/server.ts:500→503, :657→686) and in both MCP entries; knob plumbing (knobs.ts:784/798/810), the two diagnostics.* config keys (config.ts:2414-2415), the yaml rows, the live-files.mjs:113 registration, the drain gate, and the admin export wiring (x-bili-log-incomplete, retention: status) are all present and correctly ordered.
  • The true PR footprint vs current master (git diff master...head) is still exactly the 39 files / ~2775 insertions I approved — nothing else.

CI is fully green on 1db639fd2. No kernel/wire/persistence changes; behavior drift (rotation scheme, 0644→0600 perms, unbounded raw export) remains disclosed in CHANGELOG. Nothing new to fix; the prior approval carries forward to this head.

Verdict: APPROVE — ready for human merge. Merge stays owner-only (§7.4): #5487


审核结论(结构化八问)

  1. 是什么问题:本 PR 把私有运行日志 bili.log 从「10 MiB + 单个 .old」改为「10 MiB 封存分代 + 48h 目标窗口 + 256 MiB 硬预算」,并让 Web/诊断的原始导出流式化、不再静默截断。本轮只是核对 head 移动后结论是否仍成立。
  2. 什么原因导致的(旧行为的根因):原方案只保留一代 .old,保留窗口是「碰巧」而非「保证」;且原始导出被静默裁到 10 万行尾,用户拿不到完整保留历史。
  3. 影响范围与严重程度:纯诊断/可观测面,不动模型流量、wire、持久化格式;默认配置下即启用新方案。属体验改进,无回归风险面。
  4. 怎么修复的:自包含子系统——独立模块(封存引擎/行读取器/覆盖度)、diagnostics.* 两个键、启动边界幂等注入策略、导出走流式 ring buffer 并如实上报 x-bili-log-incomplete。
  5. 是否有回归问题:本轮重点核过——功能文件字节级未变,logger.ts/logs-query.ts 未被 master 触碰,两处启动点「先 retention 后 logger」顺序在合并后仍正确,drain 门(pendingRetentionDrains + 'close' 兜底结算)仍在位。既有行为无破坏。
  6. 是否破坏缓存:不涉及压缩缓存/重试/增量游标;仅私有日志文件布局变化。
  7. 是否改了设计方向:不改架构/数据流方向;新增一个隔离的诊断子域 + 两个配置键。
  8. 是否引入了新的配置:是——diagnostics.logRetentionHours(env BILI_LOG_RETENTION_HOURS,默认 48,下限 1)与 diagnostics.logBudgetBytes(env BILI_LOG_BUDGET_BYTES,默认 256 MiB,下限 1 MiB),中英文档 + yaml + LIFECYCLE 齐备;按 §7.4 由 owner 把关合入。

判定:可进入人工合并。

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b) Re-reviewed the moved head 1db639fd2. The entire delta vs my approved 63081baa4 is a single “Merge origin/master into fix/private-log-retention” commit (~347 inherited master commits — fastpath-v6 / docs-centralization / kernel 0.0.18x / dsh-lane fixes) with no new log-retention work: the feature files are byte-identical, logger.ts/logs-query.ts are untouched by master, all wiring survives the merge coherently (retention-before-logger at both startup sites, knob/config/yaml/live-files/admin-export intact), and the true footprint vs current master is unchanged (39 files / ~2775 ins). CI green on 1db639fd2 (14 success / 16 skipped / 0 failed / 0 pending). Refreshed APPROVE posted (review id 5824968717); ready for human merge (owner-only per §7.4).

@ranxianglei
ranxianglei marked this pull request as ready for review November 9, 2026 15:59
@ranxianglei

Copy link
Copy Markdown
Owner

(ai: vllm-qwen/qwen3.8-27b)

Closing the loop on my Nov 1 comment (the intra-process drain-vs-reclaim instance, reported against head e3a3c42): it was addressed on this branch before merge —

  • 13e57d5d8e4 "drain replaced streams before retention" — the pendingRetentionDrains gate + deferred retention pass: reclamation no longer runs while a replaced stream's drain is pending;
  • 18af0c61424 "settle the retention drain gate on stream close, not only end()" — settles from close so an erroring drain (e.g. ENOSPC) can no longer wedge the counter and strand reclamation.

Verified in the merged tree (e606c54): src/logger.ts:210/:212/:235/:322-343/:450-453, pinned by tests/logger-rotation.test.ts:142 ("budget reclamation waits for the rotated stream to drain") and :172 ("reclamation still runs when a replaced stream closes without finishing"). The cross-process variant remains out of scope here — it is the pending contract question in #5494.

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.

2 participants