Context as a Bounded Resource
Compare context selection strategies at fixed budgets and check retention of task-critical facts.
Project 01 never had a context problem, and that was deliberate. Its
fixture admits at most 16 files and 64 KiB of text. A single read returns
at most 100 lines or 8 KiB. Compaction is switched off
(OFFLINE-IMPLEMENTATION-CONTRACT.md §§1–2). Everything the model could
ever need fits comfortably in one request, so every failure the reviews
found was a failure of interface, evidence or lifecycle, never of
capacity.
Now replace the six-file synthetic repository with a real one: thousands of files, hundreds of megabytes, long histories of tool output piling up over a forty-turn run. The model cannot see it all. Something has to choose what the model sees at each step, and that choice can lose the one line the answer depends on. Part II begins here. Its subject is the information a harness puts in front of the model and keeps for later, and how a harness knows whether it chose well.
Evidence status. Draft manuscript. This chapter has no project checkpoint. The educational context-selection demonstration D07-CTX-01 is implemented and executed (
examples/pi-harness-lab/src/context.ts,test/context.test.ts; 8/8 selection tests pass offline). Pi facts are from the R02 source inspection of the 1.6.0 artifact (DOCUMENTED/OBSERVED; Established for that artifact; TEST NOT RUN). One external study is cited as DOCUMENTED. The formal live-model comparison of strategies (§7.8, Phase 2) is PROPOSED and remains EXPERIMENT PENDING; the offline presence-test phase is now executed rather than hypothetical.
7.1 What “context” is, concretely
“Context” is used loosely enough to hide the engineering, so it is worth pinning down. In a Pi-based harness, a model request is assembled from several sources:
- System-prompt bytes and loaded resources. These include context files, skills and appended prompts, unless an inert loader excludes them, as Project 01’s does (R02 C05/C06).
- Session history. Prior user messages, assistant messages, tool calls and tool results, drawn from the session’s canonical record.
- Projections of that history. R02 records that Pi’s
SessionManagerholds the canonical finalized context, and that branch selection and compaction project the context sent to the model without erasing the raw history (R02-PI.mdC07). - Transformations by extensions. Pi 1.6.0 exposes context transforms and context edits through extension hooks (C12; context edits already exist in 1.0.4).
Book I covers context admission and compaction as runtime features (Book I, Chapters 28 and 23). This book is interested in the harness questions around them. Who decides what enters a request? How is that decision recorded? And how do we tell whether the decision lost something that mattered?
One detail sets the tone. Pi’s session statistics aggregate every entry,
including compactions, summaries, tool usage and assistant usage. R02
notes that they are “neither current-context usage nor an invoice” (C10).
A harness that wants to know how full a particular request was, or what it
contained, must measure that at the model-request boundary, where the
assembled request is actually visible. It cannot infer it from session
totals. Project 01’s offline qualification already intercepts that
boundary to compare the requests of arms A and B (PROJECT-01-EXPERIMENT-PLAN.md).
The same interception point is where context measurement belongs.
7.2 Three budgets, not one
A context window is usually described as a single capacity limit. In practice a harness manages three budgets, and they fail differently.
Capacity is the hard limit. A request larger than the model’s window is rejected or truncated. Capacity failures are loud, and in that sense they are the easy ones.
Spend is the cumulative cost of what is sent. An agent loop typically resends its history on every turn, so total input across a run grows with the sum of the history lengths at each turn, not with the final length. As a hypothetical piece of arithmetic, not a measurement: if every turn adds 2,000 tokens and the full history is resent each time, a 40-turn run sends 2,000 × (1 + 2 + … + 40) = 1,640,000 input tokens, against a final history of 80,000. Provider caching can change the price of that total, and its accounting is a separate question (Chapter 17). The structure, though, is quadratic, and it is the reason selection matters even when capacity does not.
Attention is whether material that fits is actually used. Liu and colleagues found that model performance on multi-document question answering and key-value retrieval can degrade significantly depending on where in a long input the relevant information appears, with better use of the beginning and end than the middle (Lost in the Middle: How Language Models Use Long Contexts, TACL 12, 2024, doi:10.1162/tacl_a_00638; DOCUMENTED for the models and tasks they studied). This book does not assume that the effect holds for any particular current model. The general point does not depend on it. Presence in context does not imply use. A selection strategy that keeps a fact present but buries it among distractors may fail as surely as one that drops the fact.
These three budgets explain why “use a bigger window” is not a harness strategy. A bigger window relaxes capacity, increases the spend that the same history can accumulate, and does nothing to guarantee attention.
7.3 Task-critical facts and the presence test
The chapter brief asks whether selection strategies retain task-critical facts. That term needs a definition that a harness can check mechanically.
A fact is task-critical for a task if the acceptance oracle’s expected answer depends on it. In a fixture with sealed evidence loci, a task-critical fact has an address: the file, line range and content digest that the oracle accepts as support.
For Project 01’s T2, the task-critical fact is max_attempts at line 3 of
retry-config (Chapter 3, §3.8). For T1 it is the declaration of
execute_with_retry in worker, lines 12–16.
Once task-critical facts have addresses, one property of a selection strategy can be measured without any model at all. At the model request where the deciding step happens, is the critical locus present in the assembled context? Call this the presence test. It is a property of the harness: a deterministic function of the tool transcript, the selection policy and the budget. It can be computed offline by replaying a scripted tool sequence through each policy and checking the assembled requests for the locus bytes.
The presence test separates two questions that are usually merged:
| Question | Whose property | Measurable offline? |
|---|---|---|
| Was the critical fact in the request when the decision was made? | Harness (selection policy) | Yes, by replaying a fixed transcript |
| Did the model use it correctly? | Model, given that context | No. Requires live runs |
When a live run fails, the presence test tells you which question to ask. If the locus was absent, the failure belongs to selection. If it was present, the failure belongs to use: attention, reasoning, or a misleading distractor. Without the test, both appear as “the model got it wrong.”
The test has a limit that should be stated. It checks that the cited bytes are present. It does not check that the model could recognize them as relevant, and it says nothing about facts the oracle did not anticipate. For questions with a single, sealed locus it is exact. For open research questions (Chapter 8) it becomes a lower bound.
7.4 Who selects? Five strategies
Every harness that faces more evidence than budget uses some selection strategy, even if only by accident. Five families cover most designs. The classification is PROPOSED for this book; the failure signatures are the reason to make it.
| Strategy | Who selects | What gets lost | Failure signature |
|---|---|---|---|
| S0 Truncate (keep everything until the limit, then cut) | Nobody; position decides | Whatever lies beyond the cut, usually the oldest or the newest material | Silent and position-dependent; looks like the model forgot |
| S1 Recency window (keep the last k turns or bytes) | The clock | Early evidence, often the first and most foundational reads | The answer cites the right file but with stale or missing details |
| S2 Retrieval (host retrieves chunks by query similarity) | A ranking function | Evidence phrased unlike the query; context around a chunk | Plausible but wrong chunks (decoys) ranked above the true locus |
| S3 Agent navigation (model fetches what it asks for through bounded tools) | The model, constrained by the interface | Whatever the model does not think to ask for | Missed reads; budget spent on wrong reads |
| S4 Compaction (older history replaced by a model-written summary) | A summarizing model | Detail and provenance the summary omits | Confident claims without source addresses (Chapter 8) |
Project 01 is an S3 design. The host never decides what the model sees beyond the system prompt. The model asks for catalogues and line ranges, and the host enforces only the bounds. That is a legitimate strategy, not an absence of one. Its budget is enforced through tool byte limits rather than through a context limit, and its failure mode is a missed read, not a truncation. Chapter 5’s interface work is what makes S3 viable: numbered lines, IDs and self-describing results let the model navigate cheaply.
Real harnesses mix strategies. A typical coding agent uses navigation for the current step, a recency window for the conversation, and compaction when the window fills. Mixing makes attribution harder, which is a further reason for the presence test. If a run with three selection layers fails, the test tells you at which layer the critical locus disappeared.
7.5 Selection must also exclude
It is natural to think of selection as a problem of keeping the right
material. It is equally a problem of keeping out plausible wrong
material. Project 01’s fixture contains a deliberate decoy, a scratch file
that mentions retry-policy in two unrelated senses (“The deploy-freeze
owner is release-captain, not retry-policy”; “Lunch orders use a
different retry-policy with no shared config”). A retrieval strategy keyed
on the phrase “retry policy” would rank that file highly. A navigation
strategy might read it and be misled.
The R03 dossier’s registered negative controls include exactly this:
“irrelevant plausible files, and contradictory stale documentation”
(R03-HARNESS-RESEARCH.md R03-H03; PROPOSED). It also proposes an
equal-length neutral checklist as a control, so that a gain from adding
material can be separated from a gain from adding the right material.
The same logic applies to context selection. A strategy comparison should
include arms where the budget is filled with irrelevant text of the same
length. Otherwise “more relevant context helped” cannot be distinguished
from “more context of any kind changed behaviour.”
There is also a trust dimension, which Chapter 8 develops. Selected
material is untrusted data. Published demonstrations show that text
retrieved into an application’s context can carry instructions that
redirect it (Greshake et al., cited in R04-SECURITY-RECOVERY.md R04-C09;
DOCUMENTED; no local reproduction). Selection decides what the model
reads. It does not, and cannot, decide what the model obeys. That is an
authority question for Chapters 11–12.
7.6 Pi’s defaults are a selection policy
A Pi session constructed with defaults already has a selection policy:
compaction is enabled by default (R02-PI.md C13). For ordinary use this
is sensible. For a measured run it is a hidden treatment. Whether and when
compaction fires depends on the history’s length, which depends on the
model’s behaviour, which differs between arms. Two arms of a comparison
could therefore receive different context projections without anyone
choosing that difference.
Project 01 resolves this by disabling compaction and asserting the effective setting before the first request (Chapter 3). A context-selection study cannot simply turn everything off, because selection is the thing being studied. The rule becomes the familiar one from Chapter 3: exactly one selection policy varies between arms, and it is declared, effective and bound. If compaction is not the treatment, it is off in every arm. If it is the treatment, it is on in one arm, with its trigger and parameters registered.
7.7 Worked example: the presence test at a fixed budget
This section is an executed educational demonstration, D07-CTX-01
(examples/pi-harness-lab/src/context.ts; selection suites in
test/context.test.ts, 8/8 pass offline). It scales the Project 01 task
up just enough to create pressure: the same six-file fixture plus
distractor reads’ worth of competing content, and a fixed tool-result
budget of 400 scripted tokens per request. (Token counting here is a
scripted budget unit — UTF-8 bytes/4, ceiling — not a claim about any
provider tokenizer.) A scripted transcript for T2 makes these reads, in
order: the catalogue, the retry-config read containing the T2 locus
(line 3), a decoy, then twelve distractor reads.
Measured outcomes at the 400-token budget (reproduce with
npm --prefix examples/pi-harness-lab test):
| Policy | Request tokens | Included | T2 locus present? |
|---|---|---|---|
| S0, admit-until-full | 311 | catalogue, locus read | Yes — but only because the critical read happened early |
| S1, recency window | 300 | two newest distractors | No — the early locus is excluded (BUDGET_EXCEEDED, window closed) |
| S2, relevance-ranked | 284 | locus, decoy, one distractor | Yes — the catalogue is excluded as LOWER_RELEVANCE |
| S3, pinned + recency | 309 | locus (pinned) + two newest | Yes — if the model pins the locus |
Two simple policies keep whole excerpts only, and never split one. The window policies stop at the first excerpt that does not fit.
- S1, recency window. Walk backwards from the newest result, keeping
results while the total stays within budget, then stop. The two newest
distractors fill 300 of 400 tokens; the third would exceed it, so the
window closes and everything older — including the locus read — is
excluded with reason
BUDGET_EXCEEDED. Presence: fails. The critical read happened early, and later reads pushed it out. - S0, admit-until-full. Walk forwards, admitting results until the next one would exceed the budget, then refuse the rest. Catalogue plus locus fill 311 tokens; the decoy would exceed it. Presence: passes, but only because the critical read happened early. A second scripted transcript moves the locus read last, and S0’s window closes on the catalogue: S0 fails while S1 would pass it.
Neither policy is wrong in general. Each fails on a predictable class of transcripts without the model doing anything wrong. A third design moves the decision to the model:
- S3 with a working set. The selection policy lets the model pin a
read it has judged important, so the pinned locus stays resident while
unpinned results age out. Presence: passes, if the model pins the
locus. Presence is now a model behaviour to measure, not a harness
guarantee. The demonstration implements pinning as a policy flag; a
production
pintool would move the same decision to the model-facing interface. Either way, the choice moves responsibility between harness and model, and it is not proposed for Project 01.
The S0, S1 and S2 outcomes are computed by replaying fixed transcripts through each policy. No model is involved. That is the value of the presence test. It does not show which strategy is best. It shows which strategies can lose a critical fact on which transcripts, before any model is blamed. Only the S3 case needs a live study, and changing the policy changes the request (different projection digests) without changing durable history: selection never mutates the stored transcript.
7.8 A study design
The brief for this chapter asks to compare context-selection strategies at fixed budgets and check the retention of task-critical facts. The design below is PROPOSED; EXPERIMENT PENDING. It has no checkpoint of its own; it prepares Project 03 (Chapter 8).
- Fixture. A scaled variant of a frozen synthetic fixture with sealed
loci, decoys and distractors. It is a new versioned fixture, not an edit
of
repo-scout-v1, and the T4 ambiguity is not carried over. - Arms. S0, S1 and S2 as harness policies; S3 as the Project 01-style navigation baseline; and an equal-length irrelevant-filler control at each budget.
- Budgets. At least three fixed context budgets, registered in advance, with the same budget for every arm at each level.
- Phase 1, offline (no model). Presence-test every policy against scripted transcripts, including transcripts that read the critical locus early, late and twice. This phase can falsify strategies outright. A policy that loses the locus on a scripted transcript will lose it in live runs too.
- Phase 2, live. Verified task completion, presence at decision time (measured at the request boundary), tokens and calls, with task-grouped paired analysis following Chapter 3. A failure is classified as absent at decision or present but unused.
The registered predictions are: S0 and S1 fail presence whenever the critical read is early and the budget is tight. S2’s failures concentrate on decoy-heavy tasks. S3’s failures are missed reads rather than losses. Present-but-unused failures increase with distractor volume at a fixed budget, which would be consistent with, though it would not replicate, the positional effects in §7.2. The falsifier for the presence test itself is any live failure classified “absent” in which the model’s answer nonetheless quotes the locus. That would mean the request-boundary measurement is wrong.
7.9 Failure modes
- Unmeasured selection. Context is assembled by defaults and nobody records what was in each request. Defence: capture assembled requests, or their digests and locus-presence flags, at the request boundary.
- Session totals mistaken for context. Pi’s aggregated statistics are read as request size (R02 C10). Defence: measure per request.
- Hidden compaction treatment. Compaction fires in one arm and not another because history lengths differ. Defence: off, or the declared treatment.
- Presence mistaken for use. The locus was in context, so the strategy “worked.” Defence: report presence and use separately.
- Volume mistaken for relevance. More context helps, and the gain is attributed to selection quality. Defence: equal-length irrelevant filler control.
- Selection mistaken for authority. Excluding instructions from context is treated as preventing their effect. Defence: enforcement happens elsewhere (Chapters 11–12).
7.10 What you can build and test now
D07-CTX-01 already implements the core loop: S0, S1, S2 and S3-pinned as
pure functions from (transcript, budget) to a selected context with
exclusion reasons, projection digests and locus-presence flags, plus a
late-locus counterexample transcript. Extend it with an equal-length
filler control (Chapter 8’s Filler arm) and a scaled synthetic fixture
with sealed loci as a new version that leaves repo-scout-v1 untouched.
7.11 What remains unverified
- Live-model strategy performance: whether present-but-unused failures grow with distractor volume, and whether positional effects of the kind Liu and colleagues reported appear for the models this book will use (UNKNOWN). Only the offline presence-test phase is executed.
- How Pi 1.6.0’s compaction decides when to fire and what its projections contain in detail. R02 establishes that compaction projects context without erasing raw history (C07), not its policy.
- Provider caching and its effect on the spend budget (Chapter 17).
EXPERIMENT PENDING. The formal live-model strategy comparison (§7.8, Phase 2) has not run; the offline presence-test phase is executed in D07-CTX-01 rather than hypothetical.
Selection decides what enters a request. It does not record where that material came from, what was dropped to make room, or whether a summary standing in for old evidence still says what the evidence said. Those are provenance questions. Chapter 8 makes them concrete with Project 03, a researcher that must produce a source-grounded note under the same budgets.
Previous: Chapter 6: Reliable Editing and Stale Preconditions.
Next: Chapter 8: Evidence Selection, Provenance, and Compaction.