Pasted PDF is counted at its encoded size in the context estimate and triggers an unnecessary compaction (620k estimated vs 31k real)
Describe the bug
Pasting a PDF into the prompt triggers an immediate automatic compaction because the context estimate counts the PDF at roughly its encoded file size, not what it costs the model. A 1.9 MB PDF added ~620k to the estimate but ~31k real input tokens.
Similar to #2936 (images), closed in April; this is the PDF/document case.
Affected version
GitHub Copilot CLI 1.0.114-0
Steps to reproduce the behavior
- Start a session on
gpt-6.2-astrawith thelong_contexttier (tokenLimit 922000). - Work until the context is ~200k (estimate
conversationTokens~202k). - Paste a 1.9 MB PDF into the prompt (attachment type
file) and submit. session.compaction_startfires 10 ms afteruser.message:trigger "threshold",currentTokens 845092,conversationTokens 821857,tokenLimit 922000.- Compaction is applied: 276 of 283 messages removed, ~41k tokens left.
session.usage_recordfor the call carrying the PDF:inputTokens 234816(previous call204065), so the PDF cost ~31k real tokens.
Expected behavior
The compaction threshold uses the attachment's model token cost (~31k here), not an estimate from the raw or base64 file size. No compaction at ~235k of 922k.
Additional context
- macOS (Darwin), arm64, zsh; terminal: xterm.js inside tmux
- The ~620k estimate ≈ the base64 size of the file (1.9 MB × 4/3 ÷ 4 chars per token)
- Evidence is in the session's
events.jsonl:user.message,session.compaction_start,session.compaction_complete,session.usage_record
Your diagnosis holds in the build you are on, and the reason it keeps happening to documents is a resize step that images have and PDFs do not.
The number that fired is a local estimate, and the schema says so
session.compaction_complete carries tokenAccountingBasis. In the shipped 1.0.114 package (@github/copilot-darwin-arm64, buildMetadata.gitCommit 780b7b25) the field description reads:
Open accounting-basis identifier for trustworthy paired pre/post token measurements. The current runtime emits
local_full_context_estimate.
So the 845,092 that crossed the threshold is a client-side estimate of the full context. None of it came from the provider's accounting of the payload it was about to receive.
Why 1.9 MB became 620k
AttachmentFile carries assetId, byteLength and mimeType. The mimeType description names the missing step: "MIME type of the file's model-facing bytes (post-resize for images)". Images are resized before they are interned as an asset, which is why #2936 could be fixed by bounding the resize. A PDF is not resized, so byteLength is the file, and the estimate is taken over the interned base64 payload at 4 characters per token:
estimate ~= byteLength * 4/3 / 4 = byteLength / 3
That is 333,333 estimated tokens per MB of document. For your 619,857 the predicted byteLength is 1,859,571, so the user.message carrying the attachment in your events.jsonl should show a byteLength near that.
The part nobody has decomposed
currentTokens - conversationTokens = 845,092 - 821,857 = 23,235, and that is system plus tool definitions. Compaction cannot get it back. The native compaction module says so in native_compaction/manual.rs, in the static-context warning it raises when that block gets large:
Static context is using N% of available input tokens. Automatic compaction will wait longer because system messages and tool definitions cannot be reclaimed. Run /context and reduce context by disabling unused MCP servers or tools, trimming custom instructions, or switching to a larger-context model.
So /context is worth a look too, but it will not save you from a phantom charge. It reports the same estimate.
The trigger is therefore only ever reachable through the conversation count, and an attachment charged at 20x its wire cost carries that count 620k past a window holding 202k of real work.
Your numbers, decomposed
The request carrying the PDF measured 234,816 input tokens against 204,065 on the previous one, so the document's true cost was 30,751. That is a 20.2x overcharge.
Utilization when it fired: 91.7% of 922,000. Utilization of the work you actually had: 202,000 + 23,235 = 225,235, or 24.4%.
If the threshold is 0.9, which is what 845,092 against 922,000 implies, then a single document attachment crosses it from a fresh session at 2,419,695 bytes. A 2.3 MiB PDF gets no first answer on this tier. triggerThreshold is recorded on the completion's attempt metrics, so read the fraction there instead of taking mine.
There is no knob
history.setCompactionConfig takes HistorySetCompactionConfigRequest, and in the shipped copilot-sdk/generated/rpc.d.ts that is model, prompt, reasoningEffort. No threshold, no estimate override, no way to tell the client what the provider will charge. The only user-side control is the input side: send the path and let the agent read it with its own tool, or convert first (pdftotext -layout filing.pdf -) and attach the text, which takes the bounded inline text route (taggedFilesEntry) instead of the asset route.
Finding this in any session
Save as cop-audit.mjs, run node cop-audit.mjs events.jsonl:
// node cop-audit.mjs events.jsonl
// Read-only. Reports what each compaction was judged on, and whether a
// document attachment inflated the estimate that fired it.
import { readFileSync } from 'node:fs';
const ev = readFileSync(process.argv[2], 'utf8')
.split('\n').filter(Boolean)
.map((l) => { try { return JSON.parse(l); } catch { return null; } })
.filter(Boolean);
const n = (x) => (typeof x === 'number' ? x : null);
const k = (x) => (x === null ? 'n/a' : x.toLocaleString('en-US'));
const p = (a, b) => (a === null || !b ? 'n/a' : ((100 * a) / b).toFixed(1) + '%');
const charge = (a) => (n(a.byteLength) === null ? null : Math.round((a.byteLength * 4) / 3 / 4));
let found = 0;
for (let i = 0; i < ev.length; i++) {
if (ev[i].type !== 'session.compaction_start') continue;
const d = ev[i].data || {};
let carrier = null;
for (let j = i - 1; j >= 0 && j > i - 12; j--) if (ev[j].type === 'user.message') { carrier = ev[j]; break; }
const docs = (carrier?.data?.attachments || []).filter((a) => a.type === 'file' || a.type === 'blob');
const paid = docs.map(charge).filter((x) => x !== null).reduce((a, b) => a + b, 0) || null;
let after = null, before = null, done = null;
for (let j = i + 1; j < ev.length && j < i + 60; j++) {
if (after === null && ev[j].type === 'assistant.usage') after = n(ev[j].data?.inputTokens);
if (!done && ev[j].type === 'session.compaction_complete') { done = ev[j].data || {}; break; }
}
const ci = carrier ? ev.indexOf(carrier) : i;
for (let j = ci - 1; j >= 0 && j > ci - 40; j--) {
if (ev[j].type === 'assistant.usage' && n(ev[j].data?.inputTokens) !== null) { before = n(ev[j].data.inputTokens); break; }
}
const fixed = (n(d.systemTokens) || 0) + (n(d.toolDefinitionsTokens) || 0);
const conv = n(d.conversationTokens), cur = n(d.currentTokens), lim = n(d.tokenLimit);
found++;
console.log(`compaction ${found} ${ev[i].timestamp || ''} trigger=${d.trigger ?? '?'} basis=${done?.tokenAccountingBasis ?? 'not on start'}`);
console.log(` estimate: current=${k(cur)} conversation=${k(conv)} system=${k(n(d.systemTokens))} tools=${k(n(d.toolDefinitionsTokens))} limit=${k(lim)}`);
console.log(` fixed overhead ${k(fixed)} (${p(fixed, lim)} of the window; compaction cannot reclaim it)`);
console.log(` fired at ${p(cur, lim)} utilization`);
if (docs.length) {
for (const a of docs) console.log(` attachment ${a.type} ${a.path || a.displayName || ''} bytes=${k(n(a.byteLength))} mime=${a.mimeType ?? 'n/a'} predicted=${k(charge(a))} tokens`);
if (paid && after !== null && conv !== null) {
console.log(` without it: conversation ~${k(conv - paid)}, ${p(conv - paid + fixed, lim)} of the window`);
if (before !== null) console.log(` measured: ${k(before)} before, ${k(after)} after, so the doc cost ${k(after - before)}; overcharge ${(paid / Math.max(1, after - before)).toFixed(1)}x`);
console.log(` verdict: ${(conv - paid + fixed) / lim < (cur / lim) * 0.75 ? 'PHANTOM-TRIGGERED' : 'near-genuine'}`);
}
} else if (after !== null) console.log(` measured input ${k(after)}`);
if (done) console.log(` result: ${done.outcome ?? done.success} removed ${k(n(done.messagesRemoved))}/${k(n(done.preCompactionMessagesLength))} messages, ${k(n(done.preCompactionTokens))} -> ${k(n(done.postCompactionTokens))}`);
console.log('');
}
if (!found) console.log('no compaction events in this file');
On a fixture built from your numbers it prints:
compaction 1 2026-11-18T21:21:00.000Z trigger=threshold basis=local_full_context_estimate
estimate: current=845,092 conversation=821,857 system=20,800 tools=2,435 limit=922,000
fixed overhead 23,235 (2.5% of the window; compaction cannot reclaim it)
fired at 91.7% utilization
attachment file /Users/me/filing.pdf bytes=1,859,571 mime=application/pdf predicted=619,857 tokens
without it: conversation ~202,000, 24.4% of the window
measured: 204,065 before, 234,816 after, so the doc cost 30,751; overcharge 20.2x
verdict: PHANTOM-TRIGGERED
result: applied removed 276/283 messages, 845,092 -> 41,233
Controls: a session with no compaction prints no compaction events in this file, and a compaction with no attachment prints the breakdown and skips the verdict line, so it does not manufacture a phantom anywhere it has no evidence.
Your 276 removed messages are still in events.jsonl, because compaction replaces what the model is sent, not the event journal:
const fs = require('node:fs');
const ev = fs.readFileSync('events.jsonl', 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l));
const cut = ev.findIndex((e) => e.type === 'session.compaction_start');
const kept = ev.slice(0, cut).filter((e) => e.type === 'user.message' || e.type === 'assistant.message');
fs.writeFileSync('handoff.md', kept.map((e) => `## ${e.type} ${e.timestamp}\n\n${e.data.content}`).join('\n\n'));
Point cut at the boundary you care about and that rebuilds the work as text you can paste back into a fresh session.
Fix surface
Charge an asset-backed document at the model's own document cost, or cap a single attachment's estimate to what the model's document limit can charge. Stamp each attachment's estimated charge into session.compaction_start beside conversationTokens, so a compaction that fired on a phantom number is identifiable months later without this arithmetic.
The transcript survives here and the working state does not, which is the failure mode MemoryRouter exists for: it gives an agent conversational memory across sessions that survives compaction, so the context that decided the task is not one bad estimate away from being summarized into a paragraph. https://docs.memoryrouter.ai/mcp?utm_source=github&utm_medium=issue&utm_campaign=github-copilot-cli