fix: recover oversized pending file reads after compaction

This commit is contained in:
Zhou authored and Xubin Ren committed 2026-10-25 12:37:34 +08:00
1 parent 3bd67254ba
commit c9bd5ebb45
3 files changed
+277 -6

No files matched your search

+4
View File
@@ -57,6 +57,10 @@ Keep this split in mind when debugging. If a problem is about channel routing, s
After a terminal tool-iteration limit, the next ordinary turn receives a short runtime-context note to follow the current request and resume unfinished work only when asked. `session/turn_continuation.py` owns this budget-stop context; a queued Goal continuation is not a terminal stop. The note is stored with that input for stable model-history replay but is hidden from display history. Tool calls and results remain intact. New or forked histories do not inherit the pending note. This is model guidance, not a tool-execution ban or a fix for sudo authentication.
## Context Budgets
When file reads make a request exceed the context budget, the runner first summarizes history that the model has already received. If the new file results still do not fit, it replaces only the necessary unread text results with a budget error that asks the model to read a smaller range. It saves that same error for replay; it does not restore the oversized result on the next turn. Source files, accepted history, tool call IDs, and tool schemas stay unchanged. This recovery does not bypass the budget limit or offload `read_file` results to more files.
## Providers
Provider metadata is centralized in `nanobot/providers/registry.py`. Configuration fields live in `nanobot/config/schema.py`.
+61 -6
View File
@@ -196,7 +196,7 @@ class ContextCompactionState:
consolidate_provider_compaction: ProviderCompactionConsolidator | None,
) -> ContextCompactionState:
"""Create compaction state for a standalone runner transcript."""
raw_messages = list(messages)
raw_messages = messages
instruction_prefix: list[dict[str, Any]] = []
for message in raw_messages:
if message.get("role") not in {"system", "developer"}:
@@ -455,6 +455,54 @@ class ContextGovernor:
source=source,
)
def _fit_pending_file_reads(
self,
config: ContextGovernanceConfig,
messages: list[dict[str, Any]],
delta_messages: list[dict[str, Any]],
*,
tool_definitions: list[dict[str, Any]] | None,
) -> tuple[list[dict[str, Any]], dict[str, str]]:
"""Make oversized, unread file results recoverable after history compaction."""
notice = (
"Error: read_file result was not sent because the combined request exceeds "
"the context budget. No file was modified by this recovery. Read one file at a time "
"with a smaller offset/limit range; for large single-line JSON, use exec "
"to select only the needed records or fields."
)
pending_ids = {
message.get("tool_call_id") for message in delta_messages
if message.get("role") == "tool" and message.get("name") == "read_file"
and isinstance(message.get("tool_call_id"), str)
}
candidates = iter(sorted(
(
index for index, message in enumerate(messages)
if message.get("role") == "tool"
and message.get("tool_call_id") in pending_ids
and isinstance(message.get("content"), str)
and len(message["content"].encode("utf-8")) > len(notice)
),
key=lambda index: len(messages[index]["content"].encode("utf-8")),
reverse=True,
))
prepared = list(messages)
replacements: dict[str, str] = {}
while True:
try:
fitted = self.ensure_request_fits(
config, prepared, tool_definitions=tool_definitions,
)
return fitted, replacements
except ContextWindowExceededError:
index = next(candidates, None)
if index is None:
raise
# Only unread results can change. Record the same text for replay,
# so a later turn does not restore content the model never received.
replacements[prepared[index]["tool_call_id"]] = notice
prepared[index] = {**prepared[index], "content": notice}
def request_pressure(
self,
config: ContextGovernanceConfig,
@@ -626,16 +674,23 @@ class ContextGovernor:
*delta_messages,
],
)
prepared, replacements = await self.prepare_in_background(
self._fit_pending_file_reads, state.config,
prepared,
delta_messages,
tool_definitions=tool_definitions,
)
# Commit only after the complete request fits, on the owning loop.
# Source files remain available for a narrower read. Previously
# accepted results and all tool call/result pairs remain unchanged.
for message in compaction.raw_messages[compaction.raw_accepted_boundary:]:
if message.get("role") == "tool" and message.get("tool_call_id") in replacements:
message["content"] = replacements[message["tool_call_id"]]
# Responses-style state is append-only. Replacing H with a
# checkpoint requires a fresh request; a successful response may
# establish a new provider-owned state at the rewritten boundary.
state.conversation.replace_transcript(compaction.raw_messages)
state.usage = None
prepared = await self.prepare_in_background(
self.ensure_request_fits, state.config,
prepared,
tool_definitions=tool_definitions,
)
compaction.summary_checkpoint = SessionSummaryCheckpoint(
summary=summary,
transcript_boundary=compaction.raw_accepted_boundary,
+212
View File
@@ -6,6 +6,7 @@ import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
import tiktoken
from agent.runner_helpers import make_run_spec
from agent.session_helpers import mock_session_manager
@@ -628,6 +629,217 @@ async def test_runner_refuses_checkpoint_that_cannot_fit_with_delta(monkeypatch)
provider.chat_stream_with_retry.assert_not_awaited()
@pytest.mark.parametrize("context_window, omitted_count, fallback", [
(200_000, 1, True), (100_000, 2, True), (40_000, 2, False),
])
async def test_runner_recovers_oversized_file_read_delta(
tmp_path, monkeypatch, context_window, omitted_count, fallback,
):
from nanobot.agent.tools.filesystem import ReadFileTool
from nanobot.agent.tools.registry import ToolRegistry
# A cold/offline tokenizer must exercise the same conservative count as #5879.
if fallback:
monkeypatch.setattr(
"nanobot.utils.helpers._get_token_encoding",
MagicMock(side_effect=RuntimeError("tokenizer unavailable")),
)
else:
encoding = tiktoken.get_encoding("cl100k_base")
monkeypatch.setattr("nanobot.utils.helpers._get_token_encoding", lambda: encoding)
paths = [tmp_path / f"result-{index}.json" for index in range(3)]
for path in paths:
path.write_text("record, " * 10_000, encoding="utf-8")
tools = ToolRegistry()
tools.register(ReadFileTool(workspace=tmp_path, allowed_dir=tmp_path))
provider = MagicMock(spec=LLMProvider)
provider.can_resume_conversation_state.return_value = True
provider_state = ProviderConversationState(
kind="openai_responses", provider="openai:test", model="test-model",
version=1, payload={"items": []},
)
calls = [
ToolCallRequest(id=f"read-{index}", name="read_file", arguments={
"path": str(path), "limit": 20,
})
for index, path in enumerate(paths)
]
# Retrying the omitted file alone must return its content, not "unchanged".
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=calls, provider_state=provider_state),
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="reread", name="read_file", arguments=calls[0].arguments,
)], provider_state=provider_state),
LLMResponse(content="done"),
])
consolidate = AsyncMock(return_value="small checkpoint")
phases = []
async def observe(event):
if isinstance(event, ContextCompactionEvent):
phases.append(event.phase)
result = await AgentRunner().run(make_run_spec(
provider, tools=tools, model="test-model", workspace=tmp_path,
initial_messages=None,
transcript_input=TranscriptInput(history=[], current_message="inspect the files"),
transcript_builder=_build_transcript,
consolidate_history=consolidate,
context_window_tokens=context_window, max_tokens=8192, max_iterations=3,
max_tool_result_chars=16_000, concurrent_tools=True,
events=EventSink(observe),
))
assert result.final_content == "done"
requests = provider.chat_stream_with_retry.await_args_list
delivered = [m for m in requests[1].kwargs["messages"] if m["role"] == "tool"]
assert all("read_file result was not sent" in m["content"] for m in delivered[:omitted_count])
assert "offset" in delivered[0]["content"] and "JSON" in delivered[0]["content"]
assert all("record, " * 10_000 in m["content"] for m in delivered[omitted_count:])
assert all(r.kwargs["provider_context"].conversation_state is None for r in requests[1:])
assert "record, " * 10_000 in requests[2].kwargs["messages"][-1]["content"]
saved_results = [m for m in result.messages if m["role"] == "tool"]
assert [m["content"] for m in saved_results[:3]] == [m["content"] for m in delivered]
assert "record, " * 10_000 in saved_results[3]["content"]
assert phases == ["started", "succeeded", "started", "succeeded"]
assert consolidate.await_count == 2
assert not any(m["role"] == "tool" for m in consolidate.await_args_list[0].args[0])
assert all(path.read_text(encoding="utf-8") == "record, " * 10_000 for path in paths)
assert not (tmp_path / ".nanobot" / "tool-results").exists()
@pytest.mark.parametrize("fallback, same_round, context_window", [
(False, True, 200_000),
(False, False, 40_000),
(True, False, 200_000),
])
async def test_file_reads_that_fit_each_round_are_not_omitted(
tmp_path, monkeypatch, fallback, same_round, context_window,
):
from nanobot.agent.tools.filesystem import ReadFileTool
from nanobot.agent.tools.registry import ToolRegistry
encoding = None if fallback else tiktoken.get_encoding("cl100k_base")
monkeypatch.setattr("nanobot.utils.helpers._get_token_encoding", lambda: encoding)
paths = [tmp_path / f"result-{index}.json" for index in range(3)]
for path in paths:
path.write_text("record, " * 10_000, encoding="utf-8")
tools = ToolRegistry()
tools.register(ReadFileTool(workspace=tmp_path, allowed_dir=tmp_path))
calls = [
ToolCallRequest(id=f"read-{index}", name="read_file", arguments={"path": str(path)})
for index, path in enumerate(paths)
]
provider = MagicMock(spec=LLMProvider)
provider.chat_stream_with_retry = AsyncMock(side_effect=[
*(LLMResponse(content=None, tool_calls=batch)
for batch in ([calls] if same_round else [[call] for call in calls])),
LLMResponse(content="done"),
])
result = await AgentRunner().run(make_run_spec(
provider, tools=tools, model="test-model", workspace=tmp_path,
initial_messages=None,
transcript_input=TranscriptInput(history=[], current_message="inspect the files"),
transcript_builder=_build_transcript,
consolidate_history=AsyncMock(return_value="small checkpoint"),
context_window_tokens=context_window, max_tokens=8192, max_iterations=4,
max_tool_result_chars=16_000,
))
assert result.final_content == "done"
delivered = [
message
for request in provider.chat_stream_with_retry.await_args_list
for message in request.kwargs["messages"]
if message["role"] == "tool"
]
assert {message["tool_call_id"] for message in delivered} == {call.id for call in calls}
assert all("record, " * 10_000 in message["content"] for message in delivered)
assert all("record, " * 10_000 in m["content"] for m in result.messages if m["role"] == "tool")
assert all(request.kwargs["tools"] == tools.get_definitions()
for request in provider.chat_stream_with_retry.await_args_list)
@pytest.mark.parametrize("structured_transcript", [True, False])
async def test_recovered_file_read_results_survive_session_replay(
tmp_path, monkeypatch, structured_transcript,
):
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.filesystem import ReadFileTool
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.session.manager import SessionManager
monkeypatch.setattr(
"nanobot.utils.helpers._get_token_encoding",
MagicMock(side_effect=RuntimeError("tokenizer unavailable")),
)
workspace = tmp_path / "workspace"
workspace.mkdir()
paths = [workspace / f"result-{index}.json" for index in range(3)]
for path in paths:
path.write_text("record, " * 10_000, encoding="utf-8")
tools = ToolRegistry()
tools.register(ReadFileTool(workspace=workspace, allowed_dir=workspace))
provider = MagicMock(spec=LLMProvider)
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=[
ToolCallRequest(id=f"read-{index}", name="read_file", arguments={
"path": str(path), "limit": 20,
})
for index, path in enumerate(paths)
]),
LLMResponse(content="Please select one file to inspect first."),
])
consolidate = AsyncMock(return_value="small checkpoint")
transcript = TranscriptInput(history=[], current_message="inspect the files")
result = await AgentRunner().run(make_run_spec(
provider, tools=tools, model="test-model", workspace=workspace,
initial_messages=None if structured_transcript else _build_transcript(transcript),
transcript_input=transcript if structured_transcript else None,
transcript_builder=_build_transcript if structured_transcript else None,
consolidate_history=consolidate,
context_window_tokens=200_000, max_tokens=8192, max_iterations=2,
max_tool_result_chars=16_000, concurrent_tools=True,
))
assert result.final_content == "Please select one file to inspect first."
assert consolidate.await_count == 1
delivered = [
message for message in provider.chat_stream_with_retry.await_args.kwargs["messages"]
if message["role"] == "tool"
]
assert "read_file result was not sent" in delivered[0]["content"]
manager = SessionManager(workspace, sessions_root=tmp_path / "sessions")
session = manager.get_or_create("test:file-replay")
AgentLoop.__new__(AgentLoop)._save_turn(
session, result.messages, skip=1, summary_checkpoint=result.summary_checkpoint,
)
manager.save(session)
reopened = SessionManager(workspace, sessions_root=tmp_path / "sessions").get_existing(session.key)
assert reopened is not None
replayed = [message for message in reopened.get_history() if message["role"] == "tool"]
assert replayed == delivered
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="ready"))
consolidate.reset_mock()
followup = await AgentRunner().run(make_run_spec(
provider, tools=tools, model="test-model", workspace=workspace,
initial_messages=None,
transcript_input=TranscriptInput(
history=reopened.get_history(), current_message="which files are still pending?",
session_summary=reopened.metadata["_last_summary"],
),
transcript_builder=_build_transcript,
consolidate_history=consolidate,
context_window_tokens=200_000, max_tokens=8192, max_iterations=1,
max_tool_result_chars=16_000,
))
assert followup.final_content == "ready"
consolidate.assert_not_awaited()
request = provider.chat_stream_with_retry.await_args.kwargs
assert [m for m in request["messages"] if m["role"] == "tool"] == delivered
assert request["tools"] == tools.get_definitions()
assert all(path.read_text(encoding="utf-8") == "record, " * 10_000 for path in paths)
@pytest.mark.asyncio
async def test_runner_governs_messages_added_by_before_iteration_hook(monkeypatch):
from nanobot.agent.hook import AgentHook, AgentHookContext