copilot-cli icon indicating copy to clipboard operation
copilot-cli copied to clipboard

Reasoning models compact at 30 to 40% of the window because the context estimate keeps counting old reasoning tokens

Open felipecrs opened this issue 4 days ago • 3 comments

Describe the bug

I'm using a bring-your-own-key reasoning model (chat completions, thinking on) through the Copilot CLI agent host in VS Code. During tool-heavy work my sessions compact every few minutes: 19 compactions in 107 minutes. Each one fires when the runtime thinks the context is about 80% full, but by then the model server has only seen 30 to 40% of the window. So I keep losing context while there's plenty of room left.

From what I can tell, the local context estimate counts each earlier assistant turn at its full output token count, and for a thinking model nearly all of that is reasoning. Most reasoning-model servers drop old reasoning when they build the prompt (Qwen3- and DeepSeek-R1-style chat templates do this), so it never takes up space in the real prompt. The estimate also doesn't seem to use the provider's reported inputTokens, so nothing pulls it back down.

The model has a real window of 262,144 tokens, and I set maxPromptTokens to 223,232. In my sessions:

  • session.compaction_start fires with trigger: "threshold" and currentTokens between about 180k and 205k. session.compaction_complete says tokenAccountingBasis: "local_full_context_estimate".
  • For the request right before each compaction, the provider reports about 65k to 110k input tokens. Across 513 compactions, the estimate is a median 2.2 times the provider's number.
  • The provider's number is the right one. I sent an over-limit request on purpose, and the server's "request resolved to N input tokens" matched a linear fit of the reported usage.
  • Usage does reach the runtime. 105,258 of 105,265 session.usage_record events have usage.inputTokens, and 105,247 of those are above 0. My gateway includes cached tokens in inputTokens (only 481 records have cacheReadTokens above 0), so the provider totals aren't understated.
  • Between two compactions, the estimate grows by about 100k tokens while the provider's prompt grows by 10k to 50k.
  • I regressed that growth on content type over 23 cycles. Reasoning text adds about 0.21 tokens per character to the estimate and roughly nothing to the provider's count. Tool results add about 0.16 to the estimate and 0.09 to the provider's count.

Affected version

The runtime that ships with VS Code 1.148 (Copilot CLI agent host). I also reproduced it outside VS Code with runtime 1.0.117 from @microsoft/copilot-sdk 2.0.4.

Steps to reproduce the behavior

I wrote a small OpenAI-compatible mock server and an SDK script for this, and I'm happy to share them.

  1. Point a BYOK model at the mock with maxPromptTokens: 64000, which puts the threshold at 51,200.
  2. Have every model step return about 12,000 characters of reasoning and one tool call, with a 2,000-character tool result. Report the reasoning as about 3,020 output tokens, as a thinking model would. Report the prompt size as chars/4 of the request without the old reasoning, which is what a server with one of those templates actually tokenizes.
  3. Run 30 steps and watch tool.execution_complete.toolTelemetry.metrics.context_current_tokens, which carries the runtime's running estimate.

What happens:

  • Each step adds 3,283 to the estimate and about 570 to the provider's count. Compaction fires at an estimate of 52.6k while the provider reports 21.3k, a ratio of 2.46. Chat completions and the Responses API behave the same way.
  • If the mock reports 50 output tokens instead, each step adds 313 and nothing compacts. The difference of 2,970 per step is exactly the extra output tokens.
  • If the mock reports input_tokens: 0 instead of the real number, the estimate hardly moves (13,260, 13,573, 13,886 against 13,263, 13,576, 13,889). That's why I think the estimate doesn't use the provider's input count at all.
  • The runtime does resend the old reasoning (reasoning_content on chat completions, reasoning items on Responses). It's the server that leaves it out.

Expected behavior

Compaction should start when the real prompt gets close to the limit. Some ideas for getting there:

  1. After each response, take the provider's prompt count (prompt_tokens or input_tokens, plus cached tokens when the provider reports them separately) as the base, and only estimate locally what was added since.
  2. When there's no provider count, don't charge old reasoning at its full output token count. At most, count what the request actually contains.
  3. Say which basis triggered the compaction in tokenAccountingBasis, and put both numbers on compaction_start, so a mismatch like this shows up in the logs.

Additional context

This looks related to #5517, where a pasted PDF was counted at its encoded size (620k estimated against 31k real). In both cases the local estimate drifts far from the provider's count and nothing corrects it.

I also looked at the VS Code side. The agent host's BYOK bridge passes provider usage through to the runtime, so the estimate and the decision to compact seem to live entirely in the runtime.

The repro ran on Windows 11, x64.

felipecrs avatar Nov 27 '26 23:11 felipecrs

Two of the numbers in this report are settings, and their product is the 30 to 40 percent.

All three are documented in this build's own help (copilot help environment, 1.0.117):

  • COPILOT_BACKGROUND_COMPACTION_THRESHOLD: fraction of the model's context window at which the CLI starts compacting in the background; defaults to 0.8
  • COPILOT_BUFFER_EXHAUSTION_THRESHOLD: the fraction at which compaction blocks the turn; default 0.95
  • COPILOT_PROVIDER_MAX_PROMPT_TOKENS: maximum prompt tokens for the BYOK model, overriding catalog and default values

Your trigger floor is the first times the third: 0.8 x 223,232 = 178,586, which is where your 180k to 205k band starts.

I ran it before writing this. Mock OpenAI-compatible endpoint, COPILOT_PROVIDER_MAX_PROMPT_TOKENS=20000, every response reporting 3,020 output tokens with a large reasoning body and one bash tool call. The run compacted on the third model call and wrote this into $COPILOT_HOME/session-state/<id>/events.jsonl:

{"systemTokens":4619,"conversationTokens":6183,"toolDefinitionsTokens":8198,
 "currentTokens":19000,"tokenLimit":20000,"trigger":"threshold","execution":"turn_blocking"}

tokenLimit equals my env value to the token, and 19,000 is exactly 0.95 of it. That run took the blocking path instead of the background one because a single turn added more than the 15 percent gap between the two thresholds, which is the same shape as 19 compactions in 107 minutes.

The same harness also settles what the trigger reads. My mock reported prompt_tokens: 1000 on every request no matter how long the conversation got. The client compacted at its own 19,000 estimate anyway. The provider's count never entered the decision, exactly as your input_tokens: 0 probe implied.

Arithmetic for the real window. With firing threshold t, prompt limit p, real window W and ratio r, provider tokens at the trigger are t·p/r, so the share of W you actually get is t·p/(r·W). Yours is 0.8 × 223,232 / (2.2 × 262,144) = 0.31.

The ceiling is the part worth adding to the title. t cannot exceed 1, so the most any threshold setting can reach is p/r real tokens, and with p at your true window and r = 2.2 that is 45 percent of the window, permanently. 0.8 to 0.9 buys you 38 to 45 percent and then stops, and past 0.95 you block turns to compact context that was never there. Threshold tuning cannot buy the inflation back.

What the event already reports, and the one number it does not.

CompactionStartData in the shipped schemas/session-events.schema.json carries systemTokens, conversationTokens, toolDefinitionsTokens, currentTokens as their sum, tokenLimit described as the model context window limit the compaction is targeting, plus trigger and execution. Ask 3 is half built. The missing half is the provider's prompt count, the one number that can disagree with the other four.

tokenAccountingBasis exists on CompactionCompleteData, and the schema describes it as an "open accounting-basis identifier for trustworthy paired pre/post token measurements", closing with "The current runtime emits local_full_context_estimate". That wording is a placeholder with room left in it. The runtime also carries anchor names it never puts in events: provider_prompt_tokens, anchored_tokens, provider_adjusted_tokens, ledger_tokens, anchor_growth_tokens, fallback_reason, usage_anchored. So there is a half-built reconciliation and a schema written to accept a second basis. Connecting the two is the fix, and emitting the provider count on compaction_start plus a provider_reported basis is additive, not a version break.

One floor for anyone reaching for maxPromptTokens as a workaround. At 6,000 the same harness refused before the first request with "Static system messages and tool definitions exceed this model's usable context budget". At 262,144 that static block is about 5 percent of your window, so it is not your limit, but the lever has a hard stop underneath it.

For the 513 compactions you already have, this reads any session's events.jsonl and prints per compaction the estimate, the last provider prompt count, the ratio, the real share of the window and the ceiling:

// node compaction-estimate-audit.mjs <events.jsonl> [window] [maxPromptTokens]
import { readFileSync } from "node:fs";
const file = process.argv[2];
const W = Number(process.argv[3] || 262144);
const P = Number(process.argv[4] || 0);
let last = null, basis = "(none)", rows = [];
for (const line of readFileSync(file, "utf8").split("\n")) {
  if (!line.trim()) continue;
  let e; try { e = JSON.parse(line); } catch { continue; }
  const d = e.data || {};
  if (e.type === "session.usage_record") {
    const u = d.usage || d, i = Number(u.inputTokens || 0), c = Number(u.cacheReadTokens || 0);
    if (i > 0) last = i + c;
  } else if (e.type === "session.compaction_start") {
    rows.push({ est: Number(d.currentTokens ?? d.tokens), prov: last });
  } else if (e.type === "session.compaction_complete" && d.tokenAccountingBasis) {
    basis = d.tokenAccountingBasis;
  }
}
if (!rows.length) { console.log("no compaction events"); process.exit(0); }
const r = rows.map(x => x.est / x.prov).filter(Number.isFinite).sort((a, b) => a - b);
const med = r[Math.floor(r.length / 2)];
console.log("basis: " + basis + (P ? ", trigger at 0.8 x " + P + " = " + Math.round(0.8 * P) : ""));
for (const x of rows) console.log(
  String(Math.round(x.est)).padStart(8) + " est  " + String(Math.round(x.prov)).padStart(8) +
  " provider  " + (x.est / x.prov).toFixed(2) + "x  " + (100 * x.prov / W).toFixed(1) + "% of real window");
console.log(rows.length + " compactions, median " + med.toFixed(2) + "x");
if (med > 1) console.log("ceiling: no threshold below 1.0 reaches more than " + (100 / med).toFixed(0) + "% of the real window");

On a fixture built from your four numbers it prints a 2.20 median and "no threshold below 1.0 reaches more than 45% of the real window", and exits 1. On a real 1.0.117 log with no compaction it prints one line and exits 0.

Narrowed ask: charge what the server tokenizes. A client cannot know an old reasoning block was dropped, and that is exactly why the provider count has to come back into the estimate instead of being estimated locally forever. The reporting and the fix are the same change.

Nineteen summaries in 107 minutes is nineteen rewrites of the only thing carrying the work. MemoryRouter keeps a conversation's memory outside the window, so the summary stops being the sole carrier and the memory survives the rewrite: https://docs.memoryrouter.ai/mcp?utm_source=github&utm_medium=issue&utm_campaign=github-copilot-cli

John-Rood avatar Nov 29 '26 17:11 John-Rood

A quick note for whoever triages this: I'd set the comment above aside. It starts from a misreading of the numbers, and the product it links at the end doesn't change how the runtime estimates context.

About the misreading: the settings alone put the trigger at 0.8 × 223,232 = 178,586, which is 68% of the 262,144 window, and that part works as intended. The drop to 30 to 40% comes from the 2.2x gap between the local estimate and the provider's count, so no threshold setting fixes it. Raising maxPromptTokens to make up for the gap isn't safe either, because the ratio moves within a session depending on how much of the history is reasoning. A value that compensates for a reasoning-heavy stretch would overflow the server once the history is mostly tool output.

One thing I did find while checking: runtime 1.0.117 contains a feature flag called copilot_cli_usage_anchored_context_tokens (USAGE_ANCHORED_CONTEXT_TOKENS), which sounds like exactly this fix. I tried enabling it from the SDK through experiments.flags, and through the COPILOT_FEATURE_FLAGS and COPILOT_EXPERIMENTS environment variables, but my repro compacted at the same point every time (an estimate of 52.6k against 21.3k from the provider). Is that flag meant to cover this, and does it apply to BYOK providers? If there's a way to turn it on locally, I'm happy to rerun the repro with it.

felipecrs avatar Nov 30 '26 17:11 felipecrs

Two things worth separating.

The env var is COPILOT_CLI_ENABLED_FEATURE_FLAGS, bare uppercase names, comma separated: COPILOT_CLI_ENABLED_FEATURE_FLAGS=USAGE_ANCHORED_CONTEXT_TOKENS. The CLI name strips the copilot_cli_ prefix and uppercases the rest, the same way github/copilot-cli#5298's workaround reaches DYNAMIC_AUTO_TIERS. COPILOT_FEATURE_FLAGS and COPILOT_EXPERIMENTS are not read by the CLI, and the SDK's experiments.flags is a separate surface that will not move a CLI-side flag.

I ran your repro on 1.0.117 with that flag set: mock OpenAI-compatible endpoint, COPILOT_PROVIDER_MAX_PROMPT_TOKENS=20000, every response reporting prompt_tokens: 1000 and 3,020 output tokens. Compaction started with:

{"systemTokens":4838,"conversationTokens":3140,"toolDefinitionsTokens":9603,
 "currentTokens":17581,"tokenLimit":20000,"trigger":"threshold","execution":"background"}

17,581 is exactly the three local components summed. tokenLimit is my env value. The provider's 1,000 appears only in session.usage_record.inputTokens. Flag off, the same run gave 17,577 on the same sum. So on BYOK over the completions wire this build does not put the provider count into the trigger, and the flag changes neither the arithmetic nor the event shape. Two candidates, and the difference matters for your rerun: the flag may be server-assigned and ignored without an account-backed assignment, or the anchored path may only be wired for Copilot-routed models.

What to look at when you rerun: whether compaction_start gains any provider-count field, and whether compaction_complete.tokenAccountingBasis ever reads anything other than local_full_context_estimate. If currentTokens still equals the sum of the three local parts, the anchor is off whatever the env var says.

On the misreading: the 2.2 divide is in the comment, the 0.31 line is 0.8 x 223,232 / (2.2 x 262,144). What it should have said more carefully is that the thresholds set the 68 percent and the ratio takes the rest. That is your paragraph.

John-Rood avatar Nov 30 '26 21:11 John-Rood