CompactionHook over-counts context tokens when no assistant message is in the conversation
CompactionHook over-counts context tokens when no assistant message is in the conversation
Bug
haystack/hooks/compaction/utils.py:136 (_estimated_context_tokens) assumes the conversation contains at least one assistant message when context_tokens > 0. The current code:
def _estimated_context_tokens(
messages: list[ChatMessage], context_tokens: int, token_counter: TokenCounter, tools: ToolsType | None = None
) -> int:
if context_tokens == 0:
return token_counter.count(messages=messages, tools=tools)
tool_result_messages = messages[_last_assistant_index(messages=messages) + 1 :]
return context_tokens + token_counter.count(messages=tool_result_messages)
_last_assistant_index returns -1 when there is no assistant message. messages[-1 + 1:] then slices from the start, so the entire messages list is fed back to the token counter and added on top of context_tokens. The function double-counts the prior context.
The trigger for the buggy path is context_tokens > 0 and no assistant message. That combination is reachable in three concrete ways:
- A
before_runhook restores a savedStateand trims the messages (the agent'sbefore_runhook docs explicitly call this out as a supported flow). The savedcontext_tokenscarries over, but the assistant message may be filtered. - A
before_llmhook rewritesstate["messages"]between the chat generator's response and the next compaction pass. Abefore_llmhook can remove the most recent assistant message (e.g. a guard against leaking tool-call-only content) while leavingcontext_tokensset from that very call. - A user-supplied custom chat generator that records
context_tokensbut returns an emptyreplieslist. The agent still stores the token count; the messages list has no assistant message.
Reproduction
from haystack.dataclasses import ChatMessage, ToolCall
from haystack.token_counters import ApproximateTokenCounter
from haystack.hooks.compaction.utils import _estimated_context_tokens
counter = ApproximateTokenCounter()
tool_msg = ChatMessage.from_tool(
tool_result="Tool result that is several words long",
origin=ToolCall(tool_name="t", arguments={}, id="c1"),
)
# Normal case: user + assistant + tool. context_tokens=1000 should give 1000 + tokens(tool).
normal = [
ChatMessage.from_user("Hello there, general Kenobi"),
ChatMessage.from_assistant("General Grievous, I presume"),
tool_msg,
]
print(_estimated_context_tokens(normal, 1000, counter)) # 1011 (correct)
# Bug: no assistant message. context_tokens=1000 should still give 1000 + tokens(tool),
# but the code returns 1000 + tokens(user) + tokens(tool) = 1020 (double counts the user).
no_assistant = [
ChatMessage.from_user("Hello there, general Kenobi"),
tool_msg,
]
print(_estimated_context_tokens(no_assistant, 1000, counter)) # 1020 (BUG: expected ~1011)
# Same shape with a system message instead of a user message.
no_assistant_2 = [
ChatMessage.from_system("You are a helpful assistant"),
tool_msg,
]
print(_estimated_context_tokens(no_assistant_2, 1000, counter)) # 1021 (BUG: expected ~1009)
Output on main:
1011 # normal case
1020 # bug: user + tool with prior context_tokens=1000
1021 # bug: system + tool with prior context_tokens=1000
The non-buggy cases are also reachable in production (state restoration, a before_llm hook filtering the assistant message, or a chat generator that records context_tokens but returns no replies).
Why this matters
CompactionHook._target_tokens calls _estimated_context_tokens to decide whether the conversation is large enough to compact and to compute the target token count. When the estimate is too high:
- The compaction trigger fires too early (the conversation has not actually filled the window).
- The target token count for the compactor is too low, so the compactor throws away more history than necessary.
Both are silent: the user has no signal that the compactor ran on a wrong estimate, just that the next LLM call lost context. The CompactionHook is _experimental and ships behind a feature flag, but it is documented in the public API and used in the new ToolResultOffloadHook flow.
Proposed fix
Treat the "no assistant message" case explicitly:
def _estimated_context_tokens(
messages: list[ChatMessage], context_tokens: int, token_counter: TokenCounter, tools: ToolsType | None = None
) -> int:
if context_tokens == 0:
return token_counter.count(messages=messages, tools=tools)
last_assistant_index = _last_assistant_index(messages=messages)
if last_assistant_index < 0:
# No assistant message to anchor on; the prior context_tokens already accounts for
# every message the model has seen. New messages (if any) cannot be measured separately.
return context_tokens
tool_result_messages = messages[last_assistant_index + 1 :]
return context_tokens + token_counter.count(messages=tool_result_messages)
This matches the original intent: count only the unaccounted-for trailing tool-result messages on top of the prior count. When there is no anchor, the prior count is the best estimate we have.
Acceptance criteria
_estimated_context_tokensreturnscontext_tokensexactly when there is no assistant message andcontext_tokens > 0(instead ofcontext_tokens + count(messages)).- A regression test pins the new behavior in
test/hooks/compaction/test_utils.py(or the existing test file for compaction utilities), covering:- empty messages,
context_tokens=0->0 - one user message,
context_tokens=0-> count(user) - one user + one assistant,
context_tokens=0-> count(user + assistant) - one user + one assistant + one tool,
context_tokens=1000->1000 + count(tool) - one user + one tool,
context_tokens=1000->1000(the bug case) - one system + one tool,
context_tokens=1000->1000(the bug case)
- empty messages,
- The fix is local to
_estimated_context_tokens; no other call sites change.
Backward compatibility
Pure bug fix. Any caller that today gets a double-counted estimate is silently getting an inflated number. Returning the prior context_tokens (or the full count when context_tokens == 0) is strictly more accurate.
Risks
The bug is in a function with one caller (CompactionHook._target_tokens). Tightening the estimate could change the trigger point for compaction: pipelines that relied on the over-count to compact earlier would now compact later. This is the correct direction (less premature compaction, more context preserved) but worth noting in the release notes.
Hi! I opened PR #12581 with a fix and regression tests. Let me know if anything needs adjusting.