Skip to content

fix(context): read the answering model's window from modelUsage, not the first entry (#1840) - #1843

Merged
vybe merged 2 commits into
devfrom
fix/1840-1m-context-window
Jul 28, 2026
Merged

vybe merged 2 commits into
devfrom
fix/1840-1m-context-window

Conversation

@dolho

@dolho dolho commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

What

Reads the context window of the model that answered the turn out of modelUsage, instead of whichever entry happened to come first.

Related to #1840

The bug is not where the issue says it is

I filed #1840 blaming the fallback catalog and proposed giving Sonnet 5 / Fable 5 a 1M entry. That diagnosis was wrong — the raw payloads show the runtime reported 1M on every run; it was never read.

run   metadata.context_window   contextWindow values present in the result event
R1    200000                    ['200000', '1000000']
R2    200000                    ['200000', '1000000']
R3    200000                    ['200000', '1000000']
S5    1000000                   ['1000000']

modelUsage carries one entry per model the turn touched. Claude Code bills side work (tool-permission classification, title generation) to a cheap Haiku:

{"claude-haiku-4-5-20251001": {"contextWindow":  200000, "inputTokens": 522},
 "claude-sonnet-5":           {"contextWindow": 1000000, "inputTokens": 2}}

and the parser took the first one:

for _, model_data in model_usage.items():
    if "contextWindow" in model_data:
        metadata.context_window = model_data["contextWindow"]
    break  # Use first model found

Dict order is insertion order, and the side model is recorded first whenever one runs — so the reported window tracked whether a side model happened to fire, not the model in use. The single clean run was just the turn where none did. Second defect in the same five lines: the break is outside the if, so a first entry lacking contextWindow ends the scan before a usable one is reached. jsonl_recovery.py repeats the pattern on the #678 salvage path.

Scope is wider than the title. This was never Sonnet-5-specific — any turn with a side model reported the side model's window, so a 1M-configured Opus agent has been mis-reporting identically.

Approach

pick_context_window lands in the vendored catalog module (re-synced byte-identically, Invariant #5) and is used at all three sites. It matches the entry to metadata.model_name — the id from the latest assistant message, which precedes the result event in both parsers — by exact key, then by the entry's own canonicalModel, then falls back to the sole entry when the turn is unambiguous.

It returns None rather than guessing. If the answering model isn't identifiable, the caller keeps its seeded catalog value. The tempting alternative — take the largest window — is precisely the direction #1521 decision A exists to prevent: a 1M side model beside a 200K main model would hide an imminent compaction wall. So the safe floor is untouched, no model id is promoted, and decision A stands as written. The module docstring gains a pointer explaining that reading the runtime value correctly is this helper's job.

Verification

pytest tests/unit/test_model_context_catalog.py tests/unit/test_model_context_parity.py
53 passed

10 new cases, built from the verbatim live payload: side-model-first, order-independence, the larger-side-window guard (must not inflate a 200K main model), unidentifiable-model-keeps-the-seed, single-entry, the break-outside-if scan, plus direct unit coverage of the selection rule including junk input.

Reverted the parser to its pre-fix form with the tests in place — 3 failed, including the exact regression and the dangerous-direction guard:

FAILED TestMultiModelUsageSelection::test_side_model_does_not_win
FAILED TestMultiModelUsageSelection::test_larger_side_window_never_inflates_a_smaller_main_model
FAILED TestMultiModelUsageSelection::test_entry_without_context_window_does_not_abort_the_scan

Full unit suite result posted below.

Deployment note

The seed and the parser both live in the agent image. Existing agents keep the old behaviour until the base image is rebuilt (./scripts/deploy/build-base-image.sh) and their containers recreated — worth calling out in release notes, since the symptom is user-visible and the fix looks inert until then.

🤖 Generated with Claude Code

Fixes #1840

…the first entry (#1840)

A Sonnet-5 agent recorded context_max=200000 on 4 of 5 identical turns and
1000000 on the fifth. The runtime reported the right value every time; the
parser read the wrong entry.

`modelUsage` carries one entry PER MODEL the turn touched. Claude Code bills
side work (tool-permission classification, title generation) to a cheap Haiku,
so a Sonnet-5 turn typically reports:

  {"claude-haiku-4-5-20251001": {"contextWindow":  200000, "inputTokens": 522},
   "claude-sonnet-5":           {"contextWindow": 1000000, "inputTokens": 2}}

and stream_parser took the first entry ("Use first model found"). Dict order is
insertion order and the side model lands first whenever one runs, so the window
followed whether a side model happened to fire — the one clean run was simply
the turn where none did. The same five lines had a second defect: the `break`
sat outside the `if`, so a first entry lacking contextWindow ended the scan
before a usable one was reached. jsonl_recovery repeated the pattern on the
#678 salvage path.

Add `pick_context_window` to the vendored catalog module (re-synced
byte-identically per Invariant #5) and use it at all three sites. It matches the
entry to the model that ANSWERED — `metadata.model_name`, captured from the
latest assistant message, which precedes the result event in both parsers — by
exact key then by the entry's own canonicalModel, and falls back to the sole
entry when a turn is unambiguous.

When the turn's model cannot be identified it returns None and the caller keeps
its seeded catalog value. Guessing would mean taking the largest window, which
is the direction #1521 decision A exists to prevent: a 1M side model beside a
200K main model would hide an imminent compaction wall. The safe floor stays
exactly as documented — no model id is promoted, and the catalog is untouched.

Not Sonnet-5-specific: any turn with a side model reported the side model's
window, so a 1M-configured Opus agent was mis-reporting the same way. The error
ran in the over-reporting direction here (35,977 tokens shown as 18% of 200K
rather than 3.6% of 1M), which invites needless compaction and model switches.

Tests: 10 cases including the verbatim live payload, order-independence, the
larger-side-window guard (must NOT inflate a 200K main model), unidentifiable
model keeps the seed, and the break-outside-if scan. Verified failing 3/3
against the pre-fix parser.

Note for deployment: the seed and the parser both live in the agent image, so
existing agents keep the old behaviour until the base image is rebuilt and their
containers recreated.

Related to #1840
@dolho

dolho commented Jul 28, 2026

Copy link
Copy Markdown
Contributor Author

Full unit suite on this branch:

5056 passed, 16 skipped, 4 failed  (14:17)

The 4 are the environment's pre-existing set (ModuleNotFoundError: No module named 'tzdata' in test_1472, plus 3 in test_admin_email_login) — they reproduce on an untouched checkout at the same base and appear identically on #1845/#1847. Worth noting the admin-email-login three trace to a bcrypt has no attribute '__about__' version mismatch that also shows in the backend boot log; that's an environment pin to fix separately, not a test defect.

/review finding on this PR: the fix touched three call sites but the tests drove
only stream_parser. The recovery path (#678 salvage) had the same "first
modelUsage entry wins" bug and now the same fix, with zero coverage — the one
changed path nothing exercised.

Three cases against the real recovery helper: the answering model's window is
picked out of a two-model map (fails against the pre-fix code, verified), an
unidentifiable model keeps the seeded catalog value rather than guessing, and the
pre-existing single-entry case still works without an assistant record.

The middle test also settles the review's open question about the narrowed
`populated` rule: recovery still returns True there, because cost/duration/turns
populate independently. So refusing to guess a window cannot turn a partial
salvage into a reported total failure — which was the concern, and it does not
hold.

Related to #1840

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Validated via /validate-pr: diff reviewed, security greps clean, touched unit tests pass locally on a combined worktree with all four post-release fix PRs (167 passed). Merging.

@vybe
vybe merged commit bf68659 into dev Jul 28, 2026
22 checks passed
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