context-mode icon indicating copy to clipboard operation
context-mode copied to clipboard

[Bug]: ctx_stats self-contradicts within one render — per-chat 'kept out' (2.7 MB) exceeds all-projects total (868 KB), and 100% savings reported for a session with zero ctx_execute calls

Open likebear1968 opened this issue 4 months ago • 6 comments

Summary

A single ctx_stats render contains internally contradictory numbers — most notably a part > whole impossibility: the current chat reports more "kept out of context" than the all-time total across every project. Because the MCP tool works (unlike the statusline in #894), these numbers are what users actually read, so the contradiction directly undermines trust in the savings figures.

Environment

  • Platform: Claude Code
  • context-mode version: v1.0.169 (confirmed latest via ctx upgrade → "Already on latest")
  • ctx doctor: all checks [OK] (install/hooks/FTS5/SQLite healthy — this is not an install problem)
  • Locale ja-JP / timezone Asia/Tokyo

Actual output (verbatim, trimmed to the relevant lines)

─── 1. Where you are now ───
This conversation started 11 7 2026 at 11:24 (Asia/Tokyo) in ~/DEV/local_rag_cc.

Without context-mode    1.9 MB  ...    498.6K tokens
With context-mode          1 B  ...         1 tokens
                        100.0% kept out of context · your AI ran 498611× longer before /compact fired

How that 2.7 MB built up — 1 days, 1 active:

─── 3. The scope, getting wider ───
This chat: 2.7 MB kept out · 42 captures · started 2026年7月11日.
All your work: 868 KB kept out · 1,485 captures across 19 projects · since 2026年7月8日.

─── 4. The bottom line ───
$6.58 of Opus 4.7 tokens your team didn't burn.

Concrete inconsistencies

  1. Part > whole (impossible). Section 3 says this chat kept out 2.7 MB, but all your work (1,485 captures across 19 projects) kept out only 868 KB. A single chat cannot exceed the all-project total. Likely a unit bug (MB vs KB) or a scope/aggregation error — 2.7 MB vs 868 KB looks like a mislabeled unit somewhere.

  2. Same chat, two different totals. Section 1 header shows Without context-mode 1.9 MB, while Section 1's histogram caption right below says How that 2.7 MB built up. 1.9 MB vs 2.7 MB for the same conversation.

  3. "100.0% kept out" overstates this session. In this session I used only native Claude Code tools (Bash / Read / Edit); their outputs entered context normally. I invoked ctx_* MCP tools only for ctx_stats / ctx_doctor / ctx_upgrade, and never routed any large command output through ctx_execute/ctx_batch_execute. So "1 B with context-mode / 100.0% kept out / 498.6K tokens saved" credits savings that did not occur — the counterfactual "without context-mode 1.9 MB" appears to be the auto-capture journal size, not tool output that context-mode actually diverted from the window.

  4. 498611× is just 498.6K tokens ÷ 1 token, i.e. the divide-by-tiny artifact of the "1 B / 1 token" baseline above — not a meaningful multiplier.

  5. Minor: Opus 4.7 label (current model is Opus 4.8); pricing is already flagged "for illustration only", so low priority.

Expected

  • Per-chat "kept out" must never exceed the all-projects total (fix the scope/aggregation or unit labeling).
  • The header total and the histogram caption for the same chat should agree (1.9 MB vs 2.7 MB).
  • "% kept out" and "tokens saved" should reflect output that context-mode actually diverted from the window, not the size of the passive capture journal — otherwise a session that used zero ctx_execute calls should not report ~100% savings.

Related

  • #893 (closed) — run-to-run variance / believability of ctx stats. This report is distinct: a single-render internal contradiction, not variance across runs.
  • #894 (open) — statusline stuck on hardcoded ~98%; its write-up states "the MCP ctx_stats tool works". This issue is a counter-example: ctx_stats itself emits contradictory numbers.

likebear1968 avatar Jul 11 '26 03:07 likebear1968

The statistics need a documented invariant explaining whether per-chat values are subsets of or independent from all-project totals. A focused regression case for a fresh session with zero executions should ensure savings is zero or unavailable rather than 100%, and that byte totals obey the stated relationship.

hiSandog avatar Jul 11 '26 10:07 hiSandog

Invariant (which relationship we expect).

Per-chat is a strict subset of the all-projects total, not independent. The "all your work" figure aggregates every capture across all projects including the current chat, so for any single render the following must hold:

  • chat.kept_out_bytes ≤ all_projects.kept_out_bytes
  • chat.captures ≤ all_projects.captures

This is exactly what pinpoints the bug: in the reported render the captures obey the subset relation (42 ≤ 1,485) but the bytes violate it (2.7 MB > 868 KB). So the defect is isolated to the byte accounting/units path, not the capture counter — the two are computed from different sources and only the byte side is wrong (unit mislabel or per-scope aggregation).

Additionally, within a single render the same-scope totals must agree: the Section 1 header (1.9 MB) and the Section 1 histogram caption (2.7 MB) describe the same chat and should be one number.

Regression case (fresh session, zero routed executions).

Seed a session that makes no ctx_execute / ctx_batch_execute calls (only passive auto-capture, as in the reported session). Expected:

  • savings_ratio == 0%, never 100.0%. A session that routed no ctx_execute* calls diverted zero bytes, so the numerator of the savings ratio is exactly zero — the value is 0%, not undefined. The reported 100.0% kept out / 498.6K tokens saved comes from dividing the passive-journal size by the 1 B / 1 token floor and must not be counted as savings. Savings must be gated on actual ctx_execute* routing, not journal size.
  • Byte totals obey the invariant above: chat.kept_out_bytes ≤ all_projects.kept_out_bytes, and the header total equals the histogram caption total for the same chat.

(Captures may still be non-zero — passive capture is expected — but savings must be gated on actual ctx_execute* routing, not journal size.)

likebear1968 avatar Jul 11 '26 10:07 likebear1968

Hi! Used context-mode for ~3 weeks on a long-running solo mobile app project (large evolving docs: an architecture/context file + a changelog). Sharing honest feedback thanks for building this.

What worked well for me:

  • Recalling project state in new/long sessions without re-reading the full docs. This is the real value: the assistant pulled the relevant section instead of loading ~100KB of notes.
  • Survived a context compaction without losing project context.
  • Zero friction: installed fine, never broke anything, no maintenance.

Where I struggled (measurement, not the core idea):

  1. The lifetime counter always shows 0. I checked all 67 of my local session files tokens_saved_lifetime is 0 in every single one, even though the per-session numbers add up to ~89k tokens. So ctx_stats keeps showing "$0.00 lifetime".
  2. Savings seem to be counted as (indexed bytes / 4) i.e. only indexing is credited. Re-indexing the same file after each edit counts its full size again, which inflates the total.
  3. Sessions where I only used ctx_search reported 0 tokens saved. That feels backwards: search is exactly where the saving happens (you avoid loading the whole document), but it gets no credit.

Net: I think the mechanism genuinely helps for "remember my project docs", but with the current stats I can't verify the 98% claim either way. If the counter credited retrieval (search) and de-duplicated repeat indexing, the numbers would be much more convincing.

Also honest about my side: I only actively used it in ~10% of my sessions, so part of the low benefit is on me, not the tool.

theruneduck avatar Jul 27 '26 09:07 theruneduck

Follow-up to @theruneduck — I checked all three of your measurement points against my own environment, then went into the v1.0.169 source to find out why. Two of your three reproduce, the first does not — and while chasing it I found what I believe is the root cause of the part > whole contradiction in the original report of this issue.

Data: 96 files ~/.claude/context-mode/sessions/stats-pid-*.json (all version 1.0.169, schemaVersion 2, 2026-07-08 → 2026-07-28) plus read-only queries against the sessions/*.db sidecars. Snapshot 2026-07-28 08:51 JST; two of the 96 belonged to a live session and were still being written, so exact totals will drift for anyone re-running. Source line references are to 1.0.169/src/ as shipped in the plugin cache.


0. Root cause of the original part > whole (2.7 MB chat vs 868 KB all-projects)

renderNarrative5Section prints the two "kept out" figures four lines apart (src/session/analytics.ts:2268, :2271), but computes them from different sources with independent fallbacks (:2105-2110):

const lifetimeBytes = (multiAdapter?.totalBytes && multiAdapter.totalBytes > 0)
  ? multiAdapter.totalBytes
  : lifetimeTokensWithout * 4;                       // = (totalEvents * 256 + rescueBytes/4) * 4
const convBytes = realBytes?.conversation
  ? (realBytes.conversation.eventDataBytes + realBytes.conversation.bytesAvoided + realBytes.conversation.snapshotBytes)
  : conversationTokens * 4;

Nothing constrains convBytes <= lifetimeBytes. When the chat scope takes its measured-bytes branch while the lifetime scope falls back to its event-count × 256 × 4 branch, the per-chat figure can exceed the all-projects figure — which would produce exactly the 2.7 MB vs 868 KB pattern in the report above. (I can't prove that branch split is what fired in that particular render — it is 17 days gone — but it is the only path in this function that makes part > whole reachable at all.) The Math.max(legacy, real) at :2084 / :2090 enforces monotonic growth within a scope (the comment at :2079 says as much) but gives no subset relation between scopes.

Suggested fix shape: derive both scopes from one source, or fall back for both together — never let one scope use measured bytes while the other uses the events estimate in the same render. A cheap assertion before printing (convBytes <= lifetimeBytes) would have caught this.

This also explains why the capture counts obeyed the subset relation (42 ≤ 1,485) while the bytes did not: counts come from one source (:2266, :2268), bytes from two.


1. tokens_saved_lifetime always 0 — does not reproduce, and the field is an event counter

All 96 of my files carry a non-zero tokens_saved_lifetime, so "always 0" is not universal at v1.0.169. But it does not measure savings. From the same persistStats() that writes these files:

const keptOut = sessionStats.bytesIndexed + sessionStats.bytesSandboxed + sessionStats.cacheBytesSaved;  // server.ts:1032
const tokensSaved = Math.round(keptOut / 4);                                                             // server.ts:1041
lifetimeTokens = (life?.totalEvents ?? 0) * TOKENS_PER_EVENT;   // TOKENS_PER_EVENT = 256 (:987)          // server.ts:1051

getLifetimeStats (analytics.ts:710) sums SELECT COUNT(*) FROM session_events over every sessions/*.db (:737, :755). I verified this end to end — counting rows across all my sidecars and reading the newest stats file in the same script, seconds apart:

SELECT COUNT(*) FROM session_events, summed over sessions/*.db  = 7,744
7,744 * 256                                                     = 1,982,464
tokens_saved_lifetime in stats-pid-71136.json (written 9s prior) = 1,982,464   <- residual 0

So tokens_saved is bytes ÷ 4 and tokens_saved_lifetime is event count × 256 — two unrelated quantities, one presented as the lifetime of the other. That single fact accounts for what otherwise look like three separate bugs in my data:

Observation Explanation
Sum of per-session tokens_saved (587,024,292) is 204x the largest tokens_saved_lifetime (2,866,432) different quantities; the comparison is meaningless
3 files show lifetime below their own tokens_saved — worst 578,152,946 vs 2,628,864 (220x) same
25 pairs of files consecutive in updated_at order, with total_calls = 0 on both sides, still show lifetime moving events are hook-captured machine-wide, so a global gauge should move in a PID with zero ctx_* calls

The user-visible defect: a decaying window labelled "lifetime"

tokens_saved_lifetime decreases in 9 of 95 transitions ordered by updated_at, by as much as −762,368 (−26.6%) in one step. I initially read that as an invariant violation and was wrong: the Claude Code SessionStart hook calls db.cleanupOldSessions(7) (hooks/sessionstart.mjs:306) on a fresh start, which deletes sessions older than 7 days along with their events (db.ts:1696 → deleteSession → DELETE FROM session_events WHERE session_id = ?, db.ts:1081). So the shrinkage is, at least in part, retention working as designed. (There is a second candidate — a swallowed read of a locked sidecar — which I ran into by accident and describe under Reproduction below; I cannot tell the two apart per drop.)

The defect is what the UI does with it. That quantity is rendered as lifetime savings and lifetime dollars, next to a since <date> line derived from MIN(created_at) over the surviving rows (analytics.ts:786-791 → :851 → :2118 → :2261). So the "lifetime" total silently decays while its start date marches forward — a user who saves twice as much this week can watch the number go down. Either label it what it is (a ~7-day rolling window) or persist a monotonic counter that retention cannot touch.


2. Savings credited from raw byte throughput — reproduces

tokens_saved == round(kept_out / 4) holds in all 96 files, matching server.ts:1041 exactly. Because keptOut sums bytesIndexed + bytesSandboxed + cacheBytesSaved (:1032), anything that streams through the sandbox is credited whether or not it could ever have entered a context window. Your re-indexing observation is the everyday form; here is the extreme form, one session from my set:

total_calls            = 28
bytes_sandboxed        = 2,312,174,448     by_tool ctx_execute: 25 calls, 76,900 bytes returned
kept_out               = 2,312,611,783
tokens_saved           = 578,152,946
dollars_saved_session  = 2,890.76

$2,890.76 claimed saved by 28 tool calls. The 2.3 GB is bytes_sandboxed — data the sandbox streamed past — while the tools actually returned 76,900 bytes to the model.

One caveat on my own evidence so nobody over-reads it: this is n = 1. Only 2 of 96 sessions report reduction_pct = 100, the next-largest kept_out is 84x smaller, and the other active sessions spread across 0–96%. The defect is that the metric has no ceiling tied to a context window, not that every session is inflated.


3. ctx_search-only sessions credited zero — reproduces, and it is structural

My one session whose by_tool contains nothing but ctx_search:

by_tool        = {"ctx_search": {"calls": 8, "bytes": 38126}}
total_calls    = 8      bytes_returned = 38,126
bytes_indexed  = 0      bytes_sandboxed = 0
kept_out       = 0      tokens_saved = 0      reduction_pct = 0

To be precise about this one: zero is arithmetically correct under the current definition. keptOut deliberately excludes bytes_returned (server.ts:1032), and ctx_search returns everything it retrieves into the window — so kept_out = 0 follows by identity, not by accident.

The problem is that the definition cannot express the saving you are actually getting. The value of retrieval is the ~100 KB of notes you did not load, a counterfactual about the un-retrieved remainder; the metric can only see bytes that physically moved. So the one path where the product's core benefit lives is the one path structurally incapable of scoring — while sandbox throughput scores with no ceiling (§2). The two errors point in opposite directions, which is why neither of us can validate the headline percentage from these files.


Summary

Field Label implies Actually computed from Status
This chat vs All your work bytes same metric, nested scopes two different branches with independent fallbacks (analytics.ts:2105-2110) part > whole possible by construction
tokens_saved tokens kept out of the window (indexed + sandboxed + cache) / 4, unbounded over-credits; $2,890 for 28 calls
tokens_saved_lifetime lifetime of the above session_events row count × 256, subject to 7-day retention different quantity, and decays under a "lifetime" label
ctx_search contribution — bytes_returned, excluded from kept_out by identity structurally always 0

If only one thing gets fixed, I would make it §0 — it is a single-render contradiction users see directly, it has an obvious assertion to guard it, and it is the one that started this issue.

Reproduction

Both scripts below are the whole of my measurement — no ctx_* tooling was involved. The SQLite one only ever issues COUNT(*) / MIN / MAX; it never reads session_events.data or project_dir, which hold captured conversation content.

# Everything in sections 1 and 2, from the stats files alone.
import json, glob, os
files = sorted(glob.glob(os.path.expanduser("~/.claude/context-mode/sessions/stats-pid-*.json")))
rows  = sorted((json.load(open(f)) for f in files), key=lambda d: d["updated_at"])

print("files:", len(rows))
print("sum tokens_saved:", sum(d["tokens_saved"] for d in rows))
print("max tokens_saved_lifetime:", max(d["tokens_saved_lifetime"] for d in rows))
# (n + 2) // 4 reproduces JS Math.round(n / 4) exactly for n >= 0
print("rows where tokens_saved != Math.round(kept_out/4):",
      sum(1 for d in rows if d["tokens_saved"] != (d["kept_out"] + 2) // 4))

drops = [(a, b) for a, b in zip(rows, rows[1:])
         if b["tokens_saved_lifetime"] < a["tokens_saved_lifetime"]]
print("lifetime decreases:", len(drops), "of", len(rows) - 1,
      "| largest:", min(b["tokens_saved_lifetime"] - a["tokens_saved_lifetime"] for a, b in drops),
      "| min gap between the two writes (min):",
      round(min((b["updated_at"] - a["updated_at"]) / 60000 for a, b in drops), 1))
files: 96
sum tokens_saved: 587024292
max tokens_saved_lifetime: 2866432
rows where tokens_saved != Math.round(kept_out/4): 0
lifetime decreases: 9 of 95 | largest: -762368 | min gap between the two writes (min): 16.5
# Section 1's event-count check. Note the `|| exit` — see the caveat below.
cd ~/.claude/context-mode/sessions
total=0
for f in *.db; do
  n=$(sqlite3 "file:$f?mode=ro" "SELECT COUNT(*) FROM session_events;") \
    || { echo "UNREADABLE: $f" >&2; exit 1; }
  total=$((total + n))
done
echo "events=$total  events*256=$((total * 256))"

A caveat that turned into a data point. My first version of that loop had 2>/dev/null and treated a failed read as 0 — the same shape as the try { … } catch { /* skip */ } around each database open in getLifetimeStats (analytics.ts:752). On one pass it returned 3,031 events where the passes immediately before and after returned 7,744 and 7,759. The difference is exactly one sidecar's contents (7,759 − 4,728 = 3,031): a single database briefly failed to open — it is the live session's own DB, with a hot -shm/-wal — and silently contributed zero. I could not reproduce it on demand afterwards (6 consecutive clean passes) and did not capture the error text, so I offer this as an observation rather than a diagnosis. But it does show the failure mode is reachable on real files, and a swallowed read there feeds straight into a lifetime figure that is then cached for 30 s and written to disk. Failing loudly, as the || exit above does, seems worth more than a silently smaller total.

I cannot attribute any individual one of the 9 drops to retention versus a swallowed read; both are live explanations in this data.

Environment: source references read from ~/.claude/plugins/cache/context-mode/context-mode/1.0.169/src/.

likebear1968 avatar Jul 28 '26 00:07 likebear1968

Adding a fourth mechanism to this issue: the source of the phantom "kept out" bytes themselves. The issue body's point 3 suspected the counterfactual was wrong ("credits savings that did not occur"); here is the code path that manufactures it. Verified on v1.0.169 as shipped in the plugin cache, cross-checked against the live session sidecar DB.

bytesAvoided is booked on NON-blocking decisions

hooks/core/routing.mjs:854-861 (the Read branch): when a Read of a large file is intercepted, the hook resolves to a guidance decision — { action: "context", additionalContext: readGuidance } — which only injects advice and lets the Read proceed. The file's bytes enter the model context normally. But the same branch still attaches:

decision.redirectMeta = {
  tool: "Read",
  type: "read-redirected",
  bytesAvoided: st.size,   // full on-disk size
  ...
};

hooks/posttooluse.mjs (redirect-marker branch, ~line 94-135) then emits a category='redirect' event carrying those bytes, and analytics.ts sums them into bytesAvoided — the "Without context-mode" side of the Section 1 bar. So every large Read that context-mode merely commented on is accounted as if it had been diverted. That is exactly the "1.9 MB without / 1 B with" render in the issue body: the counterfactual is real bytes, all of which entered context anyway.

Three aggravators, all reproduced in my sidecar DB:

  1. Whole-file size for windowed reads. bytesAvoided: st.size books the full on-disk size even when the Read used limit/offset and returned a small window.
  2. Duplicate rows. The same file appears multiple times: in my DB one 337,864-byte file is booked 4×, one 1,040,566-byte file 2×. 17 read-redirected rows claim 4.96 MB "avoided"; zero were actual diversions (session made no ctx_execute/ctx_batch_execute/ctx_search data calls at all — same shape as the issue body's point 3).
  3. The genuine redirects are flat estimates, not measurements. curl/wget denials book a constant 8192 (routing.mjs:779), WebFetch a constant 16384 (routing.mjs:886). Fine as heuristics, but they are summed into the same figure presented as measured bytes.

The 1 B / 100.0% / N× line then follows mechanically from analytics.ts:2210: convBytesWith = Math.max(1, measuredReturned) with measuredReturned = 0, and convMult = tokensWithout / 1. (#1023 covers the "N× longer" framing; this explains why its denominator is 1.)

Bonus: cross-session contamination in "this conversation"

The sidecar DB for my session also contains read-redirected rows for files this session never touched. Environment: multiple concurrent Claude Code sessions running in the same project directory (same ~/.claude/projects/<dir> key). Section 1 is labeled "Where you are now / this conversation" but appears to aggregate whichever sessions share the key — worth a separate issue if not already known, but it compounds the Section 1 overstatement.

Suggested fix shape

  • Emit redirectMeta/bytesAvoided only when action actually blocks or replaces the tool output (deny), never for context/guidance decisions.
  • For windowed Reads, book min(st.size, bytesActuallyReturned) — or measure in PostToolUse from the real tool response size rather than pre-estimating in PreToolUse.
  • Dedupe per (tool, target, turn) before summing.
  • The empty-state branch at analytics.ts:2203 ("No measurable redirect activity yet") already embodies the right instinct — with the guidance-decision booking removed, sessions like mine and the issue body's would correctly hit that branch instead of rendering 100%.

Happy to provide the sidecar-DB queries used, they are two lines of sqlite.

sergiopadure avatar Aug 25 '26 15:08 sergiopadure

Thank you for the sharp report. 2.0 rebuilt ctx_stats so the numbers come from one source: session is never above project, and project is never above all-time. With no calls the savings are 0. Tests: GP10/stats-totals-consistent and GP10/zero-calls-zero-savings.

Context Mode 2.0 is out. To try it:

claude plugin marketplace add mksglu/context-mode
claude plugin install context-mode@context-mode

Please test it. If it still happens, reopen this issue or open a new one with your ctx_doctor output.

mksglu avatar Nov 04 '26 22:11 mksglu