Large read_file results survive compaction as unsummarized delta and abort the turn
Bug Description
Large read_file results can abort a turn even when history summarization succeeds. The newly returned tool results are outside the accepted-history prefix, so compaction preserves them unchanged. They can still exceed the input budget after the old history is replaced by a small summary.
This is distinct from #5849: the reproduction below has negligible fixed overhead and a successful summary. The oversized part is the new tool-result delta, not the history sent to the summarizer. It does not claim a permanent session deadlock; the observed failure aborts the affected turn.
Confirmed against the context-governance and token-estimation source at official main d149232621367c4f7f9b634d9ef590eaf696f30d.
Steps to Reproduce
- Use
contextWindowTokens=200000,maxTokens=8192, andmaxToolResultChars=16000(input budget: 190784). - Return three
read_fileresults of 80000 characters each in one tool round. Each fits the reader's 128000-character limit, butread_filebypasses the generic 16000-character result budget. - Make tokenizer initialization fail, exercising the existing UTF-8-byte fallback. This makes the example deterministic without an API key or network access. The same compaction limitation applies whenever the preserved delta alone exceeds the budget.
- Summarize the accepted history successfully. The next request still exceeds the budget and emits
started -> failed.
The following module-level probe uses synthetic tool outputs and a successful stub summarizer. Save it as repro_read_file_compaction.py and run it from a checkout with nanobot dependencies installed using python repro_read_file_compaction.py:
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import nanobot.utils.helpers as helpers
from nanobot.agent.context_governance import (
ContextCompactionState, ContextGovernanceConfig, ContextGovernor,
ContextWindowExceededError, ModelRequestState,
)
from nanobot.events import EventSink
from nanobot.providers.base import LLMProvider
from nanobot.providers.conversation_state import ProviderConversationStateController
async def main():
provider = MagicMock(spec=LLMProvider)
config = ContextGovernanceConfig(
provider=provider, model="repro", tools=MagicMock(), workspace=None,
session_key="repro", max_tool_result_chars=16000,
context_window_tokens=200000, max_tokens=8192,
)
history = [
{"role": "system", "content": "system"},
{"role": "user", "content": "analyze data"},
{"role": "assistant", "content": "working"},
]
calls = [
{"id": f"call-{i}", "type": "function", "function": {
"name": "read_file", "arguments": "{}",
}} for i in range(3)
]
messages = history + [{"role": "assistant", "content": None, "tool_calls": calls}]
messages += [
{"role": "tool", "tool_call_id": f"call-{i}", "name": "read_file",
"content": "record, " * 10000} for i in range(3)
]
summarize = AsyncMock(return_value="short summary")
phases = []
async def observe(event):
phases.append(event.phase)
state = ModelRequestState(
config=config,
conversation=ProviderConversationStateController(
provider=provider, model="repro", messages=messages,
),
compaction=ContextCompactionState.from_messages(history, summarize, None),
events=EventSink(observe),
)
governor = ContextGovernor()
normalized = governor.prepare_messages_for_model(config, messages)
assert [len(m["content"]) for m in normalized if m["role"] == "tool"] == [80000] * 3
print("normal estimate:", helpers._estimate_prompt_tokens_with_source(normalized))
with patch.object(helpers, "_get_token_encoding", side_effect=RuntimeError("unavailable")):
try:
await governor.prepare_request(state, messages, tool_definitions=[])
except ContextWindowExceededError as exc:
print(type(exc).__name__ + ": " + str(exc))
else:
raise AssertionError("Expected the current failure path")
summarize.assert_awaited_once()
assert not any(m.get("role") == "tool" for m in summarize.await_args.args[0])
assert phases == ["started", "failed"], phases
print("events:", phases)
asyncio.run(main())Observed output with the normal tokenizer available before the simulated failure:
normal estimate: (60149, 'tiktoken')
ContextWindowExceededError: Model input exceeds the local context budget for repro: 240507/190784 via heuristic
events: ['started', 'failed']Expected Behavior
File-read output should be admitted according to the remaining request budget, or returned with an actionable way to read/process smaller portions, so a tool round does not leave the agent with an oversized delta it cannot consume or summarize.
Please preserve the context-limit guard and complete source data. Simply removing the read_file exemption risks reintroducing the persist/read/persist loop fixed by #4155. Line-count pagination alone is insufficient for long single-line JSON.
Relevant Logs
A Windows deployment based on v0.3.5 encountered this after three consecutive read_file(limit=20) calls on persisted JSON tool results. Sanitized exception from 2026-09-23:
ContextWindowExceededError: Model input still exceeds the local context budget
after request fitting for <redacted-session>: 268742/190784 via heuristicThe stack ends in prepare_request -> _compact_request_history -> ensure_request_fits. The deployment uses a downstream Desktop host; the synthetic upstream-source reproduction above does not depend on that host or its tools. The original tokenizer exception was not logged, so via heuristic does not establish a vocabulary download/packaging failure.
nanobot Version
- Observed deployment: downstream build reporting v0.3.5.
- Upstream-source reproduction: official main
d149232621367c4f7f9b634d9ef590eaf696f30d.
Python Version
Reproduction: Python 3.12. Deployment's bundled Python version was not confirmed.
Operating System
Windows.
Channel / Platform
Observed on WebSocket/WebUI. Reproduction calls the shared context governor directly.
LLM Provider
No live provider required for the reproduction. The deployment's provider/model was not confirmed.
Additional Context
- read_file offload exemption.
- Compaction preserves the delta, then checks the rewritten request.
- Related #5849 / #5857 concern the history presented to the summarizer; bounding that history does not bound this new delta.
- #4153 / merged #4155 explain why the reader exemption exists.
- #5861 improves tokenizer initialization/observability, but does not add a budget for new file-read results.
Customer files, business records, credentials, local paths, and session identifiers are omitted. No live-provider test or full upstream test suite was run for this report.
Source: HKUDS/nanobot