Dayward AI
Week 1 · D5About 3 hours

Measuring and Tuning: the Token Bill, Context Utilization, Failure-Mode Triage, and a Comprehensive Interview Deep Dive

Fold the previous four days' techniques into one measurable loop: work out the token bill and cache hits, watch two utilization metrics, locate the problem against four failure modes, then work through a comprehensive context-engineering interview deep dive.

Today's goals 0/3

Sign in to tick these off and save your progress.

Today's Goals

  1. Work out a task's token bill, and split it into cache writes, cache hits, and new input
  2. Use the window-occupancy rate and the useful-information ratio to locate which part of the context is the problem
  3. Match a symptom against four typical failure modes, and give a triage path from symptom to fix

The first four days taught techniques: trimming, pruning, compaction, isolation. Today teaches which technique when — and when to stop. Come back when you have read it and tick off the three goals.

Plain-Language Walkthrough

Weighing the bag on the way home: the bill is not the last weigh-in

Back at the airport you put your bag on the scale, and the number is how heavy the case is at this moment. But if the airline charged by weighing separately on each leg, what you actually pay is the sum of four legs' weights — and you kept adding things along the way, so the later legs are certainly heavier than the first.

A model's bill works exactly that way. Many people quote cost as "how many tokens per request," which is a weigh-in, not a bill. The bill is the running sum of every turn's input across the whole session, because the model has no memory and every turn resends everything before it.

How big is that difference? Work it out on the 20-turn e-commerce support task from today's lab: the stable prefix per turn is 1,612 tokens (system prompt 881 plus tool definitions 731), history grows about 55 per turn, and a tool is called roughly every 3 turns at about 1,424 each time. That adds up to this table:

ComponentGrowth patternTotal over 20 turns
Stable prefixResent verbatim every turn32240
Conversation historyLinear growth11550
Tool resultsStep growth89712
Total133502

The single input on the last turn is 11,256 tokens while the session's bill is 133,502 — nearly 12 times apart. Anyone reporting only the single input understates the cost by an order of magnitude.

That table also answers where to change first: tool results take 67%, so do D3's pruning first; the prefix takes 24%, so D2's trimming comes next; history is only 9%, so D4's compaction comes last. The four days' order is not sorted by difficulty but by this table.

But the table left one thing out, and it turns the conclusion inside out — caching. That is where we start.

How caching rewrites the bill

A stable, unchanging prefix can hit the prompt cache. The economics are simple: writing to the cache costs slightly more than the base price, and hitting it costs an order of magnitude less. The common figures are 1.25 times for a write (2 times for a one-hour lifetime) and 0.1 times for a hit.

So 20 turns of prefix cost go from twenty full-price sends to one at 1.25 times plus nineteen at 0.1 times:

  • Without caching: 1,612 times 20, or 32,240 effective tokens
  • With caching: 1,612 times 1.25, plus 1,612 times 0.1 times 19, or 5,078 effective tokens

84% cheaper, without one line of business code changed. That is also why day two stressed layering by stability with the stable content up front — layering is not only for legibility, it directly determines how long the cached prefix can be.

But caching has a threshold: the prefix must reach the minimum cacheable length, or it simply does not apply, and no error is raised. That length depends on the model; Claude Sonnet 5, for example, is 1,024 tokens, while Claude Opus 5 and Fable 5.1 are 512.

Now add D2's and D3's optimizations and see what happens: the system prompt goes from 881 to 425, the tools are pruned from 8 to 3 so definitions go from 731 to 308, and the total prefix goes from 1,612 to 733.

733 is below 1,024. The cache stops applying. The prefix's effective cost rises from 5,078 to 14,660 — nearly three times more expensive after the optimization.

With all three optimizations counted, the total bill goes from 133,502 to 21,620, a saving of 83.8%; with caching factored in, from 106,340 to 21,620, a saving of 79.7%. Report both numbers; reporting only the first is flattery.

Two utilization metrics

The bill tells you how much was spent, and metrics tell you whether it was spent well. Two are enough, and more go unread.

The window-occupancy rate = a single turn's input tokens divided by the window limit. It governs whether things will burst, and it is the leading indicator of context rot. The rule of thumb: act above 50%, rather than waiting to approach the limit.

The useful-information ratio = the tokens later steps genuinely use divided by total tokens. It governs whether the spending was worth it. How to measure it? A workable approximation is to run D3's pruner over the context, and what survives the prune is the numerator.

These two often move out of step, and the moments they do are precisely the dangerous ones. Take the scenario from today's lab:

MetricBeforeAfterThreshold
Window-occupancy rate5.6%0.7%Act above 50%
Useful-information ratio19.1%100%Below 20% means you are hauling garbage

The occupancy rate is only 5.6%, nowhere near bursting, and looks entirely fine; but the useful-information ratio is only 19.1%, meaning eighty percent of the tokens are generating interference for the model while being billed at full price. Anyone watching only occupancy will wait until the day something breaks before optimizing.

Four failure modes

With metrics in hand, triage no longer relies on guessing. Context problems present in basically only four ways:

ModeTypical symptomMetric that firesFirst technique
Too fullMisses early instructions, violating constraints written plainly in the system promptHigh window-occupancy rateCompact the history, clear tool results
Cannot find itThe information is in the window and the model says it does not have itLow useful-information ratioPrune tool results, return structured data
Cannot say whyAnswers to the same class of question are unstable, varying between runsOccupancy not high but error rate isFix the system prompt's altitude, merge overlapping tools
Drifting offFine for twenty turns, then starts violating the original constraints❌ appears in the retention check around compactionIncrease retained turns, put hard constraints in the must-keep section of the summary

The most misdiagnosed of the four is "cannot find it," because its symptom looks so much like insufficient model capability — you start thinking about a stronger model when the real problem is that the line was buried among eighteen audit log records. The criterion is: print the context and search it by hand for that line. If it is there, it is a context problem, not a model problem.

The second most misdiagnosed is "cannot say why." It usually gets blamed on model instability, but if answers to one class of question waver between two runs, it is most likely two rules fighting inside the system prompt, or two tools with overlapping responsibilities making the model flip-flop at a decision point. Searching for contradictory rules is far more useful than switching models.

The tuning loop: change one thing at a time

With the bill, the metrics, and the mode table, what remains is a very plain loop:

  1. Fix a set of cases. Not many — 10 to 20 covering the normal, the edge, and the longest path is enough — but they must be fixed, since swapping cases midway voids every earlier measurement.
  2. Measure the baseline: run once and record the bill, both metrics, and the count of each failure class.
  3. Pick one change from the mode table, and change one thing at a time.
  4. Re-measure with the same cases, recording both the expected change and the actual change — especially the ones that disagree.
  5. When they disagree, go back and work out why. That step is where the learning is, and skipping it degrades this loop into blind tuning.

The actual-change column of step four is where the whole table's value sits. In today's reference answer, one of three changes came out opposite to expectation: pruning the tools from 8 to 3 did lower the token count, but the prefix fell below the minimum cacheable length and the bill rose. Had we watched only the token count, that step would have been recorded as an unqualified win.

Last comes the stopping criterion. Context engineering is work that can go on forever, so decide in advance when to stop:

  1. The useful-information ratio holds above 50%, with no room to rise across three consecutive measurements.
  2. The single-turn window-occupancy rate stays under 50% on the longest case.
  3. The most recent change brought the bill down by under 5%.

The third is the real brake: a saving under 5% means what is left is necessary overhead, and squeezing further trades accuracy for money.

The comprehensive interview deep dive: how to answer context engineering questions

Finally, the interview angle. Context engineering questions almost all probe the same thing — whether you treat it as a bag of tricks or as a measurable engineering problem. Three general principles for answering:

First, always give the breakdown before the conclusion. Asked what to do about a context that is too long, answering "compact it" is the worst answer, because it skips looking at which piece is long. The right opening lays out the four pieces, explains that they grow differently and must be treated separately, and only then says which one you would touch first and why.

Second, pair every technique with its cost. Pruning's cost is possibly cutting a field needed later, so you leave a retrieval identifier; compaction's cost is losing things without a marker, so you have a retention check; subagent isolation's cost is total tokens rising to a dozen-odd times chat. Give benefits without costs and you will be pressed on it, and when you are, you will be on the back foot.

Third, give numbers. "Tool results are usually the bulk" is weaker than "I measured an e-commerce support session where tool results were 72.9%, and I had guessed conversation history beforehand." A specific number plus the sentence "and I guessed wrong" is the most persuasive combination in this kind of question — it proves both that you actually measured and that you know intuition is unreliable here.

If the interviewer keeps digging, it usually lands in three directions: the relationship between caching and the bill (today's second section), how to verify compaction (D4), and when to reach for multi-agent (D4, where the answer is usually "most of the time you should not"). All three have specific numbers you can cite, so when preparing, memorize the numbers rather than the conclusions.

Source Reading

Hands-On Lab

🧪 D5 lab: a context tuning report

Code location: labs/context-engineering-5days/day-05-tuning-report

Acceptance criteria:

  1. All six sections of the report are filled in, with no placeholders left.
  2. Section 1's profile table has four shares summing to 100%, and you can name the largest piece.
  3. Section 2 computes the totals before and after, plus the cache-adjusted effective prefix cost separately; if the prefix crossed the minimum cacheable length, state which direction it crossed.
  4. Section 4 settles on one failure mode, and the basis for that judgment cites specific numbers from the earlier sections.
  5. Of the three change records in section 5, at least one has an actual change that disagrees with the expectation.

The fifth criterion is not a trick. Three changes all matching expectation usually means you did not actually re-measure but copied the expectation into the actual column. This report's entire value is that it accepts only numbers; the moment you start filling in impressions, it degrades into a status update.

  1. Run the D1, D3, and D4 labs each once and keep the outputs at hand.
  2. Open the starter's report template and fill it from section 0 downward, with every placeholder traceable to an actual run.
  3. Do not skip the caching column in section 2: look up the minimum cacheable length of the model you use first, then compute the effective cost.
  4. Pick one of the four modes in section 4, and write the basis as "because such-and-such metric is such-and-such" rather than as an impression.
  5. Open the solution and compare, focusing on the metric-improved-bill-worsened example in its fifth change record.

Interview Questions

Today's 3 questions are in the question bank below, weighted toward the relationship between the token bill and caching, the definition of the context utilization metrics, and the triage path for failure modes. Expand each one and read the analysis before the key points — practicing the derivation beats memorizing bullets. The high-frequency labels for the domestic and overseas markets are there so you can pick by target market.

Checklist and Tomorrow

  • Work out a task's token bill, and split it into cache writes, cache hits, and new input
  • Use the window-occupancy rate and the useful-information ratio to locate which part of the context is the problem
  • Match a symptom against four typical failure modes, and give a triage path from symptom to fix
  • Explain how trimming a system prompt can make the bill more expensive, and name three fixes
  • All 5 acceptance criteria of the lab pass, including the one requiring at least one change to defy expectation
  • Answer at least 2 of the 3 interview questions without looking at the key points
  • Look back over the five days' artifacts: the profiler script, the trimmed instruction file, the pruner, the compactor, and the tuning report — together they are a presentable context engineering portfolio

This is the course's last day, so there is no preview of tomorrow, only a reminder: these five days taught trade-offs, not configuration. The numbers — thresholds, retained turns, allowlisted fields — all have to be re-measured on a different project; what you take away is the practice of measuring first, ordering by share, changing one thing at a time, and pairing every technique with a verification.

To keep expanding outward, two directions live in the same batch of courses: where tools come from and how to wire them cleanly is day 1 of MCP in 7 Days; how to package working experience into on-demand capability bundles is day 1 of Agent Skills in 7 Days. One sentence for the three courses' division of labor: MCP handles the wiring, Skills handle the experience, and context engineering handles the trade-offs.

Interview questions

  • How do you compute the token bill for one agent task, and which parts can be cached away?怎么给一个 Agent 算一次任务的 token 账单?哪些部分是可以被缓存掉的?
    Common in ChinaCommon overseasDeep dive#token-accounting#prompt-caching

    How to reason about it · think before answering

    1. The first trap is the phrase one task. Many people quote a single request's input size, which is a weight reading, not a bill. Stateless models resend everything each turn, so the bill is the sum of every turn's input.
    2. Sum the four buckets by their growth patterns. The stable prefix (system prompt plus tool definitions) is resent verbatim, so multiply by turn count. History grows linearly, so it is an arithmetic series. Tool results grow in steps, so estimate calls times size. For scale: a twenty-turn support task whose final request is 11256 tokens totals 133502 across the session, nearly twelve times larger.
    3. Then caching. The cacheable part is the stable prefix, ordered tools, system, messages, where editing anything earlier invalidates everything after. Writes cost about 1.25 times base (about 2 times for a one-hour lifetime) and hits about 0.1 times, so twenty full-price prefixes become one write plus nineteen hits, an eighty percent saving.
    4. State the threshold: the prefix must reach the model's minimum cacheable length or caching silently does nothing. That produces the counterintuitive result where halving your system prompt lowers token count but raises the bill, because the prefix fell below the threshold.
    5. Expect the follow-up on whether to trim anyway. Yes, but report two numbers: the raw token reduction and the cache-adjusted effective reduction, and check whether the prefix crossed the threshold. If it did, add stable reference content back into the prefix or move to a model with a lower threshold.

    分析过程 · 先想清楚再作答

    1. 这题的第一个坑在「一次任务」四个字。很多人报的是单次请求的输入量,那是称重不是账单——模型没有记忆,每一轮都要把前面全部重发,账单是整场会话每轮输入的累加值。
    2. 怎么拆:按四块各自的增长方式分别求和。稳定前缀(系统提示加工具定义)每轮原样重发,乘轮数;对话历史线性增长,是等差数列求和;工具结果阶梯增长,按调用次数与每次体积估。举个量级:一个 20 轮的客服任务,最后一轮单次输入 11256,整场累加是 133502,差了将近 12 倍。
    3. 再谈缓存。可缓存的是稳定前缀这一段,顺序是工具定义、系统提示、消息,改前面的会让后面全部失效。经济学是写入约 1.25 倍原价(一小时存活期约 2 倍)、命中约 0.1 倍,所以 20 轮的前缀从 20 次全价变成一次写入加十九次命中,能便宜八成以上。
    4. 结论要带上那条门槛:前缀必须达到模型的最小可缓存长度才生效,达不到既不报错也不告警。这直接导致一个反直觉现象——把系统提示精简掉一半,token 数降了,账单反而可能涨,因为前缀掉到门槛以下、缓存静默失效。
    5. 可预期的追问:那还该不该精简?该,但要同时报两个数——不含缓存的 token 降幅与含缓存的等效开销降幅,并检查前缀有没有跨过门槛。跨过了就把稳定的引用内容放回前缀抬回去,或者换一个门槛更低的模型。

    Key points

    • The bill is the sum of every turn's input across the session, not the last request's size.
    • Sum by growth pattern: prefix times turns, history as an arithmetic series, tool results by call count.
    • The cacheable part is the stable prefix ordered tools, system, messages; editing earlier segments invalidates later ones.
    • Writes cost about 1.25 times base and hits about 0.1 times, but only above the model's minimum cacheable length, which fails silently.
    • So trimming can lower tokens while raising cost; always report both cached and uncached figures.

    答题要点

    • 账单是整场会话每轮输入的累加值,不是最后一次请求的输入量。
    • 按四块的增长方式分别求和:前缀乘轮数、历史等差求和、工具结果按调用次数估。
    • 可缓存的是稳定前缀,顺序是工具定义、系统提示、消息,改前面会让后面全失效。
    • 写入约 1.25 倍、命中约 0.1 倍;但前缀必须达到最小可缓存长度,否则静默失效。
    • 所以精简可能让 token 降而账单涨,必须同时报含缓存与不含缓存两个口径。
  • When context is the problem, how do you localize which of the four buckets is at fault?上下文出问题的时候,你怎么定位是四块里的哪一块?
    Common in ChinaCommon overseasIntermediate#diagnostics#metrics

    How to reason about it · think before answering

    1. This tests a diagnostic path. Answering with check the logs or try again reads as having no method; interviewers want a fixed chain from symptom to metric to change.
    2. Start with two metrics. Window occupancy is per-turn input over the window limit and governs whether you will overflow. Useful-token share is the tokens later steps actually use over total tokens and governs whether the spend is worth it. Approximate the latter with your trimmer: whatever survives trimming is the numerator.
    3. Then four failure modes with their fingerprints: overstuffed (early instructions ignored, high occupancy), buried (the fact is in the window yet the model denies it, low useful share), underspecified (answers waver across identical questions, low occupancy but high error rate), and drifting (original constraints violated late in the session, retention checks failing after compaction).
    4. Highlight the two most misdiagnosed. Buried is routinely blamed on model capability; the test is to print the context and search for the fact by hand, and if it is there the problem is context, not the model. Underspecified is blamed on instability, when it usually means contradictory rules in the system prompt or two overlapping tools making the model waver.
    5. Expect the follow-up on conflicting metrics. Low occupancy with a low useful share is the dangerous combination, because nothing looks urgent while you pay full price to move noise and dilute attention. Trust the useful-token share there.

    分析过程 · 先想清楚再作答

    1. 这题在考排查路径。答「先看日志」「多试几次」的会被判成没有方法论,面试官想听的是从现象到指标再到改动的一条固定链路。
    2. 怎么拆:先给两个指标。窗口占用率是单轮输入除以窗口上限,管的是会不会撑爆;有效信息占比是后续步骤真正用到的 token 除以总 token,管的是值不值。后者可以用裁剪器近似量:裁完还剩的那部分就是分子。
    3. 再给四种失败模式与各自的指纹:塞太满(漏读早期指令,占用率高)、找不到(信息在窗口里但模型说没有,有效信息占比低)、说不清(同类问题答法摇摆,占用率不高但错误率高)、越走越偏(跑久了违反最初约束,压缩前后的保留检查出现失败项)。
    4. 结论给最容易误判的两种。「找不到」常被误判成模型能力不足,判据是把上下文打印出来人肉搜一遍那条信息在不在——在就是上下文问题,不是模型问题。「说不清」常被误判成模型不稳定,实际多半是系统提示里有互相矛盾的规则,或者两个职责重叠的工具让模型在决策点上横跳。
    5. 可预期的追问:两个指标冲突时听谁的?答:占用率低但有效信息占比也低的情况最危险,因为看起来毫无压力却在按原价搬运垃圾,同时还在稀释注意力。这时应该以有效信息占比为准。

    Key points

    • Two metrics: occupancy for overflow risk, useful-token share for whether the spend earns its place, approximated with a trimmer.
    • Each mode has a fingerprint: occupancy for overstuffed, useful share for buried, error rate for underspecified, post-compaction retention checks for drifting.
    • Buried is most often misdiagnosed as model capability; print the context and search by hand.
    • Underspecified usually means contradictory rules or overlapping tools; hunt the contradiction rather than swapping models.

    答题要点

    • 两个指标:窗口占用率管会不会撑爆,有效信息占比管值不值,后者可用裁剪器近似量。
    • 四种模式各有指纹:塞太满看占用率、找不到看有效信息占比、说不清看错误率、越走越偏看压缩后的保留检查。
    • 找不到最容易被误判成模型能力问题,判据是把上下文打印出来人肉搜一遍。
    • 说不清多半是规则互相矛盾或工具职责重叠,去搜矛盾比换模型有用。
  • How much context engineering is enough, and how do you know when to stop?上下文工程做到什么程度算够?你怎么知道该停手了?
    Common in ChinaCommon overseasIntermediate#tuning#stopping-criteria

    How to reason about it · think before answering

    1. This is open-ended but has a clear right shape. Saying more optimization is always better reads as lacking cost awareness, because context work is unbounded and will be overdone without a stopping rule.
    2. Name the concrete cost of overdoing it rather than stopping at wasted time. Trim too hard and you cut fields needed later; compact too hard and you lose hard requirements that do not read like conclusions; cut tools too far and the agent cannot finish the task. None of these raise errors; they show up only in accuracy, the most expensive bill.
    3. Give at least three checkable stopping conditions: useful-token share stable in a healthy band such as above fifty percent with no headroom across several measurements; per-turn occupancy under fifty percent on your longest case; and the last change delivering less than a five percent bill reduction.
    4. Land on the third: a sub-five-percent gain means what remains is necessary overhead, and squeezing further trades accuracy for money. It matters most because it is the only condition that transfers across projects unchanged.
    5. Expect the follow-up on preventing regression. Freeze the measurement into a regression suite: fixed cases, rerun on every change, bill and both metrics under monitoring. Model upgrades, tool churn, and downstream field changes each degrade it again.

    分析过程 · 先想清楚再作答

    1. 这题是开放题,但它有明确的好坏。答「越优化越好」的人会被判成没有成本意识,因为上下文工程是个能无限做下去的活,不定停手判据就一定会做过头。
    2. 怎么拆:先说清过度优化的具体代价,不要停在「浪费时间」。裁得太狠会把后面才用得上的字段裁掉,压得太狠会丢掉不像结论的硬性要求,工具裁得太少会让模型没法完成任务。这些都不报错,只在正确率上体现,而正确率是最贵的一笔账。
    3. 给可核对的停手条件,至少三条:有效信息占比稳定在一个合理区间(比如 50% 以上)且连续几次测量没有上升空间;最长那条用例上的单轮窗口占用率不超过 50%;最近一次改动带来的账单降幅低于 5%。
    4. 结论落在第三条:降幅低于 5% 说明剩下的都是必要开销,继续压就是在拿正确率换钱。这条比前两条更重要,因为它是唯一一条与具体项目无关、可以直接复用的判据。
    5. 可预期的追问:那怎么保证停手之后不退化?把这套度量固化成回归:一批固定用例、每次改动都重跑、账单与两个指标进监控。上下文工程不是一次性项目,模型换代、工具增减、下游接口改字段,任何一件都会让它重新变差。

    Key points

    • Overdoing it fails silently in accuracy: fields needed later get cut, hard requirements get summarized away, and too few tools leave the task unfinishable.
    • Three stopping conditions: a stable useful-token share with no headroom, per-turn occupancy under fifty percent on the longest case, and a last change worth under five percent of the bill.
    • The third transfers best: under five percent means what remains is necessary overhead and further squeezing trades accuracy for money.
    • After stopping, freeze it into regression: fixed cases, rerun on every change, and monitor the bill plus both metrics.

    答题要点

    • 过度优化的代价不报错,只在正确率上体现:裁掉后面才用的字段、压掉不像结论的硬性要求、工具少到做不完任务。
    • 三条停手判据:有效信息占比稳定且无上升空间、最长用例的单轮占用率不超过 50%、最近一次改动账单降幅低于 5%。
    • 第三条最通用:降幅低于 5% 说明剩下的是必要开销,再压就是拿正确率换钱。
    • 停手后要固化成回归:固定用例、每次改动重跑、账单与两个指标进监控。

Comments