IamBishal

Module 1Lesson 1 of 2

1.1 What fills the window, and what actually goes wrong

Breaks a long copilot session into what each request carries (tools, system prompt, a growing message history with every tool result) and reads window size and cost from window.py over a 24-ticket shift. Tool results are 79% of the last request; the shift costs $2.6657 on Sonnet 5.5 without caching and $0.3097 with it. Experiment 7 found no context rot up to 73k tokens, so the failures to plan for are the bill, cache-busting edits, misleading placeholders and summaries that fail quietly.

A support rep's shift is 24 tickets. Run that shift through one conversation with a Claude-backed copilot, and every request re-sends everything before it: the tool definitions, the system prompt, every earlier reply and every ticket the tools fetched. By the last ticket, the copilot is paying again for the first. Over a long session the window fills with tool results, not instructions, and the bill grows with every request. At the window sizes experiment 7 measured, the problem to plan for is cost, not context rot.

By the end you will be able to:

  • name what a request in a long session carries, in the order the API reads it, and explain why all of it is re-sent on every request
  • read per-ticket window size and shift cost from window.py's output
  • explain what experiment 7 (Ticket Thirty) measured about context rot, and what it did not test
  • name the failures the rest of this tutorial handles: the growing bill, cache-busting edits, misleading placeholders and summaries that fail quietly

Before you start. You need Python 3.12, uv 0.12 and a clone of the companion repository. You should know the shape of a Claude tool-use loop: the model answers with tool_use blocks, you run the tools and send tool_result blocks back in a user message. No API key is needed; a scripted copilot replays the shift.

This lesson is a read-along: you run one script and read what it prints.

1. What one request carries

The context window is everything sent to the model on one request: the tool definitions, the system prompt and the message history. The API reads them in that order, tools first, then the system prompt, then the messages. That order matters later, because prompt caching matches the rendered request as a strict prefix in the same order; lesson 2 builds on it.

Tool results have no separate channel. When the copilot calls get_ticket, the result goes back to the model as a tool_result block inside a user message, and from then on it is ordinary history that every later request carries again.

So a request in a long session has four kinds of content, in three parts:

PartContentSize over a shift
toolsthe tool definitionsfixed
systemthe system promptfixed
messagesthe conversation: user turns and assistant turnsgrows
messagestool results, inside user turnsgrows fastest

The Messages API is stateless. The model keeps nothing between calls, so each request carries the whole conversation so far, and request N pays again for everything in requests 1 to N-1. In this tutorial a request is one model call; a ticket takes several.

flowchart LR
  subgraph R1["Request 1"]
    direction TB
    T1["tools (fixed)"]:::fixed --> S1["system (fixed)"]:::fixed --> U1["user: ticket"]:::grows
  end
  subgraph R2["Request 2"]
    direction TB
    T2["tools"]:::fixed --> S2["system"]:::fixed --> U2["user: ticket"]:::grows --> A2["assistant: tool_use"]:::grows --> X2["user: tool_result"]:::result
  end
  subgraph R3["Request 3"]
    direction TB
    T3["tools"]:::fixed --> S3["system"]:::fixed --> U3["user: ticket"]:::grows --> A3a["assistant: tool_use"]:::grows --> X3a["user: tool_result"]:::result --> A3b["assistant: tool_use"]:::grows --> X3b["user: tool_result"]:::result
  end
  R1 --> R2 --> R3
  classDef fixed fill:#e8eef7,stroke:#5b7db1
  classDef grows fill:#f3f3f3,stroke:#888
  classDef result fill:#fbe9d7,stroke:#c2783a

The top two layers stay the same size. Everything below them gets longer with each request, and nothing in this loop ever removes it.

2. The shift: 24 tickets under two standing instructions

A shift is one conversation in which the copilot works through 24 synthetic Helpline tickets, the way a support rep would over a working day. For each ticket it reads the ticket with get_ticket, looks up knowledge-base articles with search_kb, issues a refund or hands the ticket to a person when it asks for money back, and drafts a reply. The next ticket arrives in the same conversation, after everything the earlier ones left behind.

Two standing instructions are set in the first message of the shift and must hold for every ticket after it:

  1. No refunds for Corvid Analytics this week: their account is under billing review. Hand Corvid refund requests to a person instead.
  2. End every reply with the shift code SHIFT-B7.

They arrive once, at the top. By ticket 24 they sit behind 23 tickets of history.

copilot/grading.py checks both from what the tools recorded, with no model involved: did any Corvid refund ticket get a refund, and does every draft end with SHIFT-B7? The grade for a given shift is the same every time.

The copilot here is a scripted model, not Claude. ShiftModel in copilot/model.py reacts only to what is in its window: it follows a standing instruction only while that instruction's text is somewhere in the request. CacheSim works out the usage the API would report from each request's own bytes, counting 4 characters per token. Together they reproduce the behaviours experiment 7 observed with real models, so a failure in this tutorial is a consequence of what the window holds. They are a model of Claude, not Claude. Tests and CI never call the API. Lessons 3 and 5 add optional scripts that run a shift against Claude itself, with a spend cap.

3. How the copilot builds each request

The window grows because of one loop. run_shift in copilot/shift.py announces a ticket, sends a request, appends the assistant turn, runs the tools it asked for, appends their results as the next user message and sends again. When the copilot answers without asking for a tool, the ticket is done and the next one is announced into the same conversation.

python
async def run_shift(
    model: ModelClient, *, system: str = SYSTEM_PROMPT, tickets: list[dict[str, Any]] = TICKETS
) -> ShiftResult:
    result = ShiftResult()
    messages = result.messages
    for i, ticket in enumerate(tickets):
        _user(messages, opening_for(ticket["id"]) if i == 0 else announce(ticket["id"]))
        for turn in range(1, MAX_TURNS_PER_TICKET + 1):
            reply = await model.complete(system=system, messages=messages, tools=TOOLS)
            price = price_for(model.model, reply.usage.prompt_tokens)
            u = reply.usage
            usd = (
                u.input_tokens * price.input
                + u.output_tokens * price.output
                + u.cache_write_tokens * price.cache_write
                + u.cache_read_tokens * price.cache_read
            ) / 1e6
            result.requests.append(Request(ticket["id"], turn, u, usd))
            messages.append({"role": "assistant", "content": reply.content})
            calls = reply.tool_calls()
            if not calls:
                break
            messages.append(
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "tool_result",
                            "tool_use_id": c["id"],
                            "content": result.tools.run(c["name"], c["input"]),
                        }
                        for c in calls
                    ],
                }
            )
    return result

Two details matter for the rest of the tutorial. The assistant content is appended exactly as it came back, and earlier messages are never edited: the history is only appended to. And every request is priced from its own usage, with each of the four usage buckets (uncached input, output, cache writes, cache reads) at its own rate from copilot/pricing.py. Lesson 2 explains the cache buckets.

The bulk comes from the tools. ticket_payload in copilot/tools.py returns what a real ticketing API tends to send:

python
def ticket_payload(ticket_id: str) -> dict[str, Any]:
    """The full API response for a ticket, bulk included."""
    t = BY_ID[ticket_id]
    return {
        "ticket": {
            "id": t["id"],
            "subject": t["subject"],
            "kind": t["kind"],
            "customer_name": t["customer_name"],
            "refund_amount": t["refund_amount"],
            "status": "open",
            "priority": "normal",
            "channel": "email",
            "sla": {"first_response_due": "2026-11-21T12:00:00Z", "breached": False},
            "tags": ["billing" if t["kind"] == "refund" else "product", t["customer"]],
            "messages": t["messages"],
        },
        "customer": {
            "id": t["customer"],
            "name": t["customer_name"],
            "plan": t["plan"],
            "seats": 40,
            "billing_contact": "billing@" + t["customer"] + ".example",
            "created_at": "2024-03-02T10:00:00Z",
            "health_score": 0.82,
            "notes": "Synthetic account. " * 6,
        },
        "audit": [
            {"at": m["at"], "event": "message_received", "actor": "customer", "via": "email"}
            for m in t["messages"]
        ]
        * 3,
    }

The copilot acts on a handful of these fields: the subject, the kind of request, the customer, the refund amount and the messages. The SLA, the customer record and the audit trail ride along. Once they are in a tool result they stay in the history and are re-sent on every later request, so a field the copilot ignored on HL-2001 is still paid for on HL-2024. Lesson 3 trims them before they reach the history.

4. Run window.py

From the root of your clone:

bash
cd build-a-long-running-support-copilot
uv sync
cd 01-foundations/01-what-fills-the-window
uv run python window.py

The script replays the whole shift twice, once with prompt caching and once without, and prints a row per ticket. These are rows from the output:

text
ticket   calls  window cache read cache write        $
HL-2001      4    1402       2304        1882   0.0098
HL-2002      4    2346       7053         944   0.0080
HL-2003      5    3355      14073        1009   0.0097
HL-2011      5   11139      52860        1051   0.0137
HL-2012      4   12070      45984         931   0.0118
HL-2023      5   22705     110773        1022   0.0194
HL-2024      4   23646      92258         941   0.0165

calls is the number of requests for that ticket, and window is the size of the last of them, in tokens. The shift makes 104 requests in all.

Look at the shape. HL-2001 and HL-2024 each take 4 requests: the copilot does the same work on both. The window on HL-2024 is about 17 times larger because every request there still carries the 23 tickets before it. The work per ticket is flat; the window is not.

5. Tool results are 79% of the last request

After the per-ticket rows, window.py splits the last request of the shift by what put each part there:

text
What the last request carried:
  get_ticket results       9800 tokens   53%
  search_kb results        4891 tokens   26%
  assistant turns          3007 tokens   16%
  tool definitions          307 tokens    2%
  user turns                230 tokens    1%
  draft_reply results       216 tokens    1%
  hand_to_person results     52 tokens    0%
  system prompt              40 tokens    0%
  issue_refund results       40 tokens    0%

Tool results from get_ticket and search_kb are 79% of the content. The system prompt is 40 tokens, about 0.2%.

The breakdown adds up to about 18,600 tokens, while the same request's window is 23,646. The other 5,000 or so are the JSON around the blocks: roles, ids, keys, quotes and the escaping of tool results that are themselves JSON. The request carries them too, so the real share of tool results is, if anything, higher. The standing instructions live in the first user turn, inside the 1% of user turns.

That tells you where the levers are. Halving the system prompt would change nothing you could measure. The large layer is whatever the tools return, and in this shift that is mostly the bulk in ticket_payload.

Tool results are 79% of the last request; the system prompt is 0.2%.

It also raises the obvious worry. The two standing instructions are now a sliver of the window, with 23 tickets of tool results between them and the latest request. Do they still hold that far back? First the cost, then what experiment 7 measured.

6. What the shift costs on Sonnet 5.5

Cost per shift is the sum of what each of the 104 requests cost. Sonnet 5.5's rates in pricing.py were pinned on 2026-11-21: $2 per million input tokens, $10 per million output tokens, and $0.10 per million for cache reads.

window.py prices the same shift both ways:

text
shift: 104 requests, $0.3097 with caching, $2.6657 without; standing instructions held on 100% of tickets

Same tickets, same tool calls, same replies, and the uncached run costs more than eight times as much. Without caching, every request pays the full input rate for the whole re-sent prefix, so cost per request climbs with the window and the shift total climbs faster still. That is the first failure mode: the growing bill. One shift at $2.67 is not alarming; a team of reps running several shifts a week is a budget line, which is the calculation The Unit Economics of an Agent walks through.

Prompt caching closes most of that gap by billing the repeated prefix at the cache-read rate instead of the full rate. For now that is all you need. Lesson 2 explains how it works and how a careless change breaks it.

7. What experiment 7 measured about context rot

Context rot is the name for worse answers as the window grows. Chroma's July 2025 report tested 18 models, Claude 4 among them, and Anthropic describes long-context performance as a gradient rather than a cliff. Whether it bites on your workload is something you can measure.

Experiment 7, Ticket Thirty, measured it on a support workload (results). It ran Haiku 5.5 and Sonnet 5.5 through 30 queues of 24 tickets each, 720 tickets in all. With nothing removed, the window grew to 72–73k tokens by the last ticket, and neither model got worse from the first third of a queue to the last. The two standing instructions held: one was kept on 719 of 720 tickets and the other was never broken.

The remedies it tested changed the bill, not the answers. Trimming tool results cut Sonnet's cost per queue by 56% and a fresh window per ticket by 61%. Clearing old results shrank the window by about half but cut cost far less, 27% on Sonnet: clearing changes the prefix, so the cache is rebuilt once per ticket, and it wrote 1.7 times as much to the cache per call as keeping everything.

The limits matter as much as the result. The window stayed under 75k tokens, the instructions were short, explicit and labelled, and the tickets were independent. Rot can happen outside those conditions: much longer windows, instructions mentioned in passing mid-conversation, or tickets that depend on each other. Experiment 7 does not show that long windows are always safe.

What it does show is that fear is a poor reason to pick a remedy. Measure two things on your own workload, the window and whether your standing instructions hold. If they look like experiment 7's, you are choosing a remedy for cost, and you should judge it on cost.

8. The failures this tutorial plans for

Put the measurements together and the list is short. Each item has a lesson.

The growing bill. Every request re-sends the whole prefix. Every remedy that follows is judged on two numbers: cost per shift, and whether both standing instructions still hold. A remedy that saves money and loses an instruction has failed. Context Engineering for AI Agents covers the design side of what belongs in the window.

Cache-busting edits (lesson 2). Caching pays only while the prefix stays byte-identical. A timestamp in the system prompt turns every would-be cache read into a full-price write, and reordering the tools invalidates everything after them. Nothing raises an error; cache reads just fall while the bill rises.

Misleading placeholders (lesson 3). When an old tool result is cleared, something stands in its place, and its wording steers the model. In experiment 7's pilot the placeholder read "[cleared after T-Q005 closed: ... Call it again if needed.]" It said the result was cleared and how to fetch it, yet Haiku took it to mean it had never received any real data and took no action on 9 of 24 tickets. The lesson is that a placeholder must also say the model already had the result and acted on it. Lesson 3 shows a wording that fails the other way.

Summaries that fail quietly (lesson 4). A running summary can drop a standing instruction, or carry a finished ticket forward as still open. In experiment 7 a summary kept a self-made "pending approval" item, and the agent later stopped to ask about it. Neither raises an error, so each needs a test.

Lesson 5 runs every remedy on the same shift and picks one with numbers. Context rot is not on this list: at the sizes experiment 7 measured it was not the problem. If your windows grow well past that, measure it before you plan around it.

9. Exercise: read the shift like an operator

Use only your window.py output.

  1. Where did the growth come from? Subtract HL-2001's window from HL-2024's, then use the breakdown to name the content that accounts for most of the difference.
  2. Halve the system prompt? A teammate proposes it to save money. Explain why the bill barely moves, and name what you would look at instead.
  3. Name the failure. Which failure is each of these: (a) a teammate adds the current time to the system prompt; (b) a cleared result is replaced with a terse note the model misreads; (c) a summary still lists a ticket as open after it was finished?
  4. Read experiment 7 carefully. Give one condition of your own workload under which you would not rely on its "no rot" result.

How to check. (1) The window grew by 22,244 tokens; nearly all of it is get_ticket and search_kb results, which together are 79% of the last request. (2) The system prompt is 40 tokens; the lever is what ticket_payload returns. (3) A cache-busting edit, a misleading placeholder, a summary failing quietly. (4) Any of: windows well past 75k tokens, instructions given casually mid-conversation, or tickets that depend on earlier ones.

10. Summary

A long session sends three parts in a fixed order on every request: tools, system prompt and a growing message history that carries every tool result. In the recorded shift, tool results were 79% of the last request and the system prompt 0.2%, and the same shift cost $2.6657 without caching and $0.3097 with it. Experiment 7 found no context rot up to 73k tokens with short, labelled instructions and independent tickets; its remedies changed what a queue cost. So the plan is cost first: keep the cache working (lesson 2), shrink what the tools add (lesson 3), replace history carefully (lesson 4), and choose with numbers (lesson 5).

Next, Lay out the prompt for the cache explains where the gap between $2.67 and $0.31 comes from, and how to keep a silent change from reopening it.

Key Takeaways

  • Name the three parts of a request in API order (tools, system prompt, messages) and explain why the stateless Messages API re-sends all of them on every request
  • Explain how a tool result becomes ordinary history that every later request carries
  • Read per-ticket window size and shift cost from window.py's output
  • Explain why tool results (79% of the last request), not the system prompt (0.2%), drive the window
  • State what experiment 7 measured about context rot up to 73k tokens and the limits of that result
  • Name the failures to plan for: the growing bill, cache-busting edits, misleading placeholders and summaries that fail quietly

Discussion

Ask questions, share what you learned, and help others.

    Loading discussion…

    Bishal SahaLet's build together

    Have a system to design, or an AI feature to get right?

    Tell me about the problem. You'll get a clear, honest view of the best way forward.

    • Reply within 24 hoursOn business days, with my honest view and a next step.
    • Accepting select engagementsArchitecture, AI features and full builds.
    • Remote, worldwideWorking with startups, SMEs and enterprises.