TL;DR: Slicing by message count cuts through call-and-result pairs. When the window happens to start on a tool result whose assistant call fell off the front, the result is an orphan: some providers reject the request with 400, others accept it and the model misreads it. The fix is to trim in whole units (a user turn, or an assistant turn plus every result that answers it), pin the system message, count in tokens, and validate the list before every send.
How to approach it
Treat it as the debugging round it is: reproduce, explain the intermittency, fix the mechanism, add the check that prevents a recurrence. Ask what the 400 body says, because providers usually name the problem ("tool result without a preceding tool call"). Then explain what the model actually receives from a list of messages, so the interviewer hears that you know why the structure matters and not just that you found a bug.
A strong answer
Reproduce it with the shape of the history. An agent that calls tools produces runs of messages like user, assistant with tool calls, tool result, tool result, assistant text, user, and so on. A fixed-size slice of that list starts wherever the arithmetic lands. When it lands on a tool result, the assistant turn that requested it is gone:
a(c1,c2) = assistant turn calling c1 and c2; t(c1) = result for c1
full history: sys u1 a(c1,c2) t(c1) t(c2) a u2 a(c3) t(c3) a u3
last ten: u1 a(c1,c2) t(c1) t(c2) a u2 a(c3) t(c3) a u3 valid, by luck
one turn later: a(c1,c2) t(c1) t(c2) a u2 a(c3) t(c3) a u3 a(c4) valid
two turns later: t(c1) t(c2) a u2 a(c3) t(c3) a u3 a(c4) t(c4) orphans t(c1) t(c2)
That is the intermittency. Whether the request is valid depends on where the window falls, so the bug appears and disappears as the conversation grows. The system message has also been sliced off in every case, which is a second bug hiding behind the first: the agent is running without its instructions whenever the history is longer than ten messages.
Explain the rule the list has to obey. Every tool result names the call id it answers, and that call must be in the assistant turn immediately before. A call and its results are one unit, kept or dropped together. Providers differ in how strictly they enforce it: some return 400, which is the symptom here; others accept the list and the model reads an answer to a question nobody asked, which is worse because it fails silently.
Fix the mechanism rather than the symptom:
- Group the history into units: a user turn is a unit, an assistant turn with tool calls plus all its results is a unit, an assistant text turn is a unit.
- Pin the system message outside the trimming entirely.
- Trim from the oldest unit, and count in tokens rather than messages, because ten messages can be 400 tokens or 40,000.
- Validate before every send: no tool result without its call, no call without a result, system first.
def units(msgs):
out, i = [], 0
while i < len(msgs):
m = msgs[i]
if m["role"] == "tool":
raise ValueError(f"orphan result {m['id']}")
unit, i = [m], i + 1
if m["role"] == "assistant" and m.get("calls"):
while i < len(msgs) and msgs[i]["role"] == "tool":
unit.append(msgs[i]); i += 1
if {r["id"] for r in unit[1:]} != set(m["calls"]):
raise ValueError("call without result")
out.append(unit)
return out
def trim(msgs, budget, size=lambda m: len(m.get("text", "")) // 4 + 8):
system = [m for m in msgs if m["role"] == "system"]
kept, used = [], sum(size(m) for m in system)
for u in reversed(units([m for m in msgs if m["role"] != "system"])):
cost = sum(size(m) for m in u)
if used + cost > budget:
break
kept.insert(0, u); used += cost
return system + [m for u in kept for m in u]
h = [{"role": "system", "text": "rules"}, {"role": "user", "text": "q1"},
{"role": "assistant", "calls": ["c1"]}, {"role": "tool", "id": "c1", "text": "r1"},
{"role": "assistant", "text": "a1"}, {"role": "user", "text": "q2"}]
print([m["role"] for m in trim(h, budget=30)]) # => ['system', 'assistant', 'user']
try:
units(h[3:])
except ValueError as e:
print(e) # => orphan result c1
With a budget of thirty token-ish units, the trimmer keeps the system message and the two newest whole units; it never produces a list that starts on a result. The validator turns the production bug into a test failure.
Finish by saying what trimming cannot do. Dropping old units loses what was in them. For a long run the real design is clearing old tool results to placeholders, moving durable facts into notes, and compacting the conversation deliberately rather than by truncation (Clearing, Compaction and Notes).
What interviewers probe next
"The provider accepts the orphaned result instead of rejecting it. Is that better?" Worse. The request succeeds and the model reads a result with no request, which it may ignore, misattribute to a later call, or treat as user text. Validate on your side so the behaviour does not depend on how strict the provider is.
"Why count in tokens rather than messages?" Because messages are not a unit of size. One tool result can be 20,000 tokens of rows. A message count gives no control over the budget that matters.
"The model requested two tools and one failed. What goes in the list?" A result for both, including a structured error for the failure. One call without a result is the same malformed list from the other side.
What if?
What if · interview follow-ups
Hold your answer as the constraints change
Your support agent's requests fail with 400 about one time in twenty, and on other days the model answers as if a lookup never happened. The history is trimmed to the last ten messages.
Start here
Why is the failure intermittent?
Where does a fixed-size window land?
The slice starts at a different message each turn. When it starts on a tool result whose call was cut off, the list is malformed; when it starts on a user turn, it is fine. The bug comes and goes with the arithmetic.
Carry it forwardMessage count is not a unit the model or the provider understands.
Weak answerChanging ten to twelve and watching it go away for a while.
Constraint changes
What if the provider never returned 400 at all?
What does the model see then?
The orphaned result still reaches the model as an answer to nothing. It may be ignored or misread, which produces the second symptom: the model behaves as if the lookup never happened. The silent version is worse than the 400.
Carry it forwardValidate the list yourself; do not rely on the provider to reject a bad one.
Weak answerTreating the absence of errors as correctness.
Constraint changes
What if the system message is also inside the slice?
Who pins it?
It is cut off as soon as the history exceeds the window, so the agent runs without its instructions and the cache prefix changes every turn. Pin it outside trimming and keep it byte-identical.
Carry it forwardThe system message is pinned, stable and first.
Weak answerRe-adding instructions as a user message each turn.
Constraint changes
What if the conversation is six hours long and whole-unit trimming drops facts the customer gave at the start?
Trimming is the crude tool.
Move to deliberate context management: clear old tool results to short placeholders, write durable facts (ids, constraints, decisions) into notes that are re-injected each turn, and compact the conversation on a threshold rather than by truncation.
Carry it forwardTrim in units for safety; manage context on purpose for quality.
Weak answerA bigger window as the fix for a design problem.
Now defend it
State the rule the message list must obey before every send.
System first and pinned; every tool result answers a call id in the assistant turn immediately before it; every call has a result; a call and its results are kept or dropped together; and the whole list fits a token budget.
How it's scored
Weak: Blames the provider or raises the message count, with no account of why the failure is intermittent.
Hire: Finds the cut through a call-and-result pair, explains the intermittency, trims in whole units and pins the system message.
Strong Hire: Also counts in tokens, adds a pre-send validator, names the silent variant where the provider accepts the orphan, and points to clearing, notes and compaction as the real long-run design.
Common mistakes
- Slicing the list by count and treating "it worked in testing" as evidence.
- Forgetting the system message is in the slice too.
- Appending results only for successful calls, leaving a call unanswered.
- Trusting a lenient provider: a request that succeeds with an orphaned result is a silent misread.
- Using truncation as the long-run context strategy instead of clearing, notes and compaction.