fix(tools): scope file-read dedup to model context (#5775)

* fix(tools): scope file-read dedup to model context

* refactor(tools): narrow file-read context and build results lazily
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-15 16:09:56 +08:00
1 parent 47f77bdbcc
commit d386ba138e
10 files changed
+417 -176

No files matched your search

+1 -1
View File
@@ -253,7 +253,7 @@ async def test_restricted_project_can_read_only_enabled_plugin_skill(
reset_workspace_scope(token)
assert "plugin reference" in read_result
assert "File unchanged since last read" in repeated_read_result
assert repeated_read_result == read_result
assert activation_checks == 1
assert "outside allowed directory" in write_result
assert "outside allowed directory" in disabled_result
+258
View File
@@ -0,0 +1,258 @@
"""File-read deduplication follows the model request, including context rewrites."""
import asyncio
from copy import deepcopy
from unittest.mock import AsyncMock, MagicMock
import pytest
from agent.runner_helpers import make_run_spec
from nanobot.agent.context import TranscriptInput
from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.agent.runner import AgentRunner
from nanobot.agent.tools.execution import execute_tool_calls
from nanobot.agent.tools.file_state import FileStates, bind_file_states, reset_file_states
from nanobot.agent.tools.filesystem import ListDirTool, ReadFileTool
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
def _tools(tmp_path):
(tmp_path / "data.txt").write_text("alpha\nbeta\n", encoding="utf-8")
tools = ToolRegistry()
tools.register(ReadFileTool(workspace=tmp_path))
return tools
async def _read(tools, call_id, history=None, **kwargs):
provider = MagicMock(spec=LLMProvider)
requests = []
async def request(*, messages, **_kwargs):
requests.append(deepcopy(messages))
if len(requests) == 1:
return LLMResponse(content=None, tool_calls=[
ToolCallRequest(id=call_id, name="read_file", arguments={"path": "data.txt"}),
])
return LLMResponse(content="done")
provider.chat_stream_with_retry = request
initial = None if "transcript_input" in kwargs else [
*(history or []), {"role": "user", "content": "Read data.txt again."},
]
result = await AgentRunner().run(make_run_spec(
provider, model="test-model", tools=tools, initial_messages=initial,
max_iterations=2, max_tool_result_chars=128_000, **kwargs,
))
observation = next(
message["content"] for message in result.messages
if message.get("role") == "tool" and message.get("tool_call_id") == call_id
)
return result, observation, requests
@pytest.mark.parametrize("retained", ["original", "summary", "truncated", "stub_only", "orphan"])
async def test_repeat_requires_original_read_result_in_current_context(tmp_path, retained):
tools = _tools(tmp_path)
first, contents, _ = await _read(tools, "read-1")
second, stub, _ = await _read(tools, "read-2", first.messages)
assert "1| alpha" in contents
assert stub == "[File unchanged since last read: data.txt]"
history = deepcopy(second.messages)
if retained == "summary":
history = [{"role": "user", "content": "Summary: data.txt contains alpha and beta."}]
elif retained == "truncated":
for message in history:
if message.get("tool_call_id") == "read-1":
message["content"] = "1| alpha\n[truncated]"
elif retained in {"stub_only", "orphan"}:
history = [
message for message in history
if not any(call["id"] == "read-1" for call in message.get("tool_calls", []))
and (retained == "orphan" or message.get("tool_call_id") != "read-1")
]
_, repeated, _ = await _read(tools, "read-3", history)
assert repeated == (stub if retained == "original" else contents)
@pytest.mark.parametrize("rewrite", ["compact", "snip"])
async def test_dedup_uses_governed_request_instead_of_raw_transcript(tmp_path, monkeypatch, rewrite):
tools = _tools(tmp_path)
first, contents, _ = await _read(tools, "read-1")
def estimate(_provider, _model, messages, _tools):
contains_original = any(message.get("tool_call_id") == "read-1" for message in messages)
return (600 if contains_original else 100), "test-counter"
monkeypatch.setattr("nanobot.agent.context_governance.estimate_prompt_tokens_chain", estimate)
monkeypatch.setattr("nanobot.agent.context_governance.estimate_message_tokens", lambda _: 300)
consolidate = AsyncMock(return_value="The file was inspected; its original text was omitted.")
def build(transcript):
system = transcript.session_summary["text"] if transcript.session_summary else "system"
messages = [{"role": "system", "content": system}, *transcript.history]
if transcript.current_message is not None:
messages.append({"role": "user", "content": transcript.current_message})
return messages
options = {}
if rewrite == "compact":
options = {
"transcript_input": TranscriptInput(
history=first.messages, current_message="Read data.txt again.",
),
"transcript_builder": build,
"consolidate_history": consolidate,
}
result, repeated, requests = await _read(
tools, "read-2", first.messages, context_window_tokens=1_624, max_tokens=100, **options,
)
assert any(message.get("tool_call_id") == "read-1" for message in result.messages)
assert not any(message.get("tool_call_id") == "read-1" for message in requests[0])
assert repeated == contents
if rewrite == "compact":
consolidate.assert_awaited_once()
assert result.summary_checkpoint is not None
async def test_direct_read_without_model_context_never_omits_contents(tmp_path):
tools = _tools(tmp_path)
first = await tools.execute("read_file", {"path": "data.txt"})
second = await tools.execute("read_file", {"path": "data.txt"})
assert second == first
assert "1| alpha" in second
@pytest.mark.parametrize("operation", ["list_dir", "first_read", "forced_read", "repeat_batch"])
async def test_only_repeat_reads_scan_model_results_once_per_batch(tmp_path, operation):
tools = _tools(tmp_path)
tools.register(ListDirTool(workspace=tmp_path))
first, contents, _ = await _read(tools, "read-1")
class CountedMessages(list):
scans = 0
def __iter__(self):
self.scans += 1
return super().__iter__()
messages = CountedMessages(first.messages)
name, arguments = "read_file", {"path": "data.txt"}
if operation == "list_dir":
name, arguments = "list_dir", {"path": "."}
elif operation == "first_read":
(tmp_path / "fresh.txt").write_text("alpha\nbeta\n", encoding="utf-8")
arguments = {"path": "fresh.txt"}
elif operation == "forced_read":
arguments["force"] = True
calls = [ToolCallRequest(id="batch-1", name=name, arguments=arguments)]
if operation == "repeat_batch":
calls.append(ToolCallRequest(id="batch-2", name=name, arguments=arguments))
results, _ = await execute_tool_calls(
tools, calls, concurrent=True, external_lookup_counts={}, workspace_violation_counts={},
hook=AgentHook(), context=AgentHookContext(iteration=0, messages=[]),
model_messages=messages,
)
if operation == "repeat_batch":
assert results == ["[File unchanged since last read: data.txt]"] * 2
assert messages.scans == 1
else:
assert messages.scans == 0
if operation == "list_dir":
assert "data.txt" in results[0]
else:
assert results == [contents]
# A later direct read has no model input proving that its contents are visible.
assert await tools.execute("read_file", {"path": "data.txt"}) == contents
@pytest.mark.parametrize("error", [RuntimeError, asyncio.CancelledError])
async def test_failed_file_read_restores_context(tmp_path, monkeypatch, error):
tools = _tools(tmp_path)
first, contents, _ = await _read(tools, "read-1")
tool = tools.get("read_file")
original_execute = tool.execute
async def fail(**_kwargs):
raise error("read interrupted")
monkeypatch.setattr(tool, "execute", fail)
request = execute_tool_calls(
tools, [ToolCallRequest(id="failed-read", name="read_file", arguments={"path": "data.txt"})],
concurrent=False, external_lookup_counts={}, workspace_violation_counts={},
hook=AgentHook(), context=AgentHookContext(iteration=0, messages=[]),
model_messages=first.messages,
)
if error is asyncio.CancelledError:
with pytest.raises(asyncio.CancelledError):
await request
else:
results, _ = await request
assert results[0].startswith("Error: RuntimeError: read interrupted")
monkeypatch.setattr(tool, "execute", original_execute)
assert await tools.execute("read_file", {"path": "data.txt"}) == contents
async def test_native_compaction_invalidates_old_results_but_new_reads_can_dedup(tmp_path):
tools = _tools(tmp_path)
provider = MagicMock(spec=LLMProvider)
requests = []
async def request(*, messages, **_kwargs):
requests.append(deepcopy(messages))
if len(requests) <= 3:
return LLMResponse(
content=None,
tool_calls=[ToolCallRequest(
id=f"read-{len(requests)}", name="read_file", arguments={"path": "data.txt"},
)],
provider_compaction_applied=len(requests) == 2,
provider_compaction_scope="current_request" if len(requests) == 2 else None,
)
return LLMResponse(content="done")
provider.chat_stream_with_retry = request
result = await AgentRunner().run(make_run_spec(
provider, model="test-model", tools=tools,
initial_messages=[{"role": "user", "content": "Read data.txt."}],
max_iterations=4, max_tool_result_chars=128_000,
))
observations = [message["content"] for message in result.messages if message.get("role") == "tool"]
assert "1| alpha" in observations[0]
assert observations[1] == observations[0]
assert observations[2] == "[File unchanged since last read: data.txt]"
assert any(message.get("tool_call_id") == "read-1" for message in requests[2])
async def test_concurrent_sessions_keep_separate_read_contexts(tmp_path, monkeypatch):
tools = _tools(tmp_path)
session_a, session_b = FileStates(), FileStates()
async def session_read(states, call_id, history=None):
token = bind_file_states(states)
try:
return await _read(tools, call_id, history)
finally:
reset_file_states(token)
first, contents, _ = await session_read(session_a, "read-a1")
tool = tools.get("read_file")
execute = tool.execute
async def interleave(**kwargs):
await asyncio.sleep(0)
return await execute(**kwargs)
monkeypatch.setattr(tool, "execute", interleave)
(_, repeated, _), (_, other_session, _) = await asyncio.gather(
session_read(session_a, "read-a2", first.messages),
session_read(session_b, "read-b1"),
)
assert repeated == "[File unchanged since last read: data.txt]"
assert other_session == contents
+15 -9
View File
@@ -1,4 +1,4 @@
"""Tests for EditFileTool enhancements: read-before-edit tracking, path suggestions,
"""Tests for EditFileTool enhancements: read-independent editing, path suggestions,
notebook JSON editing, and create-file semantics."""
import os
@@ -22,11 +22,11 @@ def _clear_file_state():
# ---------------------------------------------------------------------------
# Read-before-edit tracking
# Read-independent editing
# ---------------------------------------------------------------------------
class TestEditReadTracking:
"""edit_file warns only when a recorded file version has changed."""
"""edit_file validates current contents independently of prior reads."""
@pytest.fixture()
def file_states(self):
@@ -58,7 +58,7 @@ class TestEditReadTracking:
assert f.read_text() == "hello earth"
@pytest.mark.asyncio
@pytest.mark.parametrize("reread", [False, True])
@pytest.mark.parametrize("reread", ["none", "read_file", "shell"])
async def test_edit_after_file_modified_since_read(
self, read_tool, edit_tool, tmp_path, reread,
):
@@ -69,14 +69,20 @@ class TestEditReadTracking:
mtime = f.stat().st_mtime
f.write_text("hello universe", encoding="utf-8")
os.utime(f, (mtime + 2, mtime + 2))
if reread:
if reread == "read_file":
assert "hello universe" in await read_tool.execute(path=str(f))
elif reread == "shell":
import subprocess
import sys
read = subprocess.run(
[sys.executable, "-c", "from pathlib import Path; import sys; print(Path(sys.argv[1]).read_text())", str(f)],
capture_output=True, text=True, check=True,
)
assert read.stdout.strip() == "hello universe"
result = await edit_tool.execute(path=str(f), old_text="universe", new_text="earth")
summary = "Patch applied:\n- update a.py (+1/-1)"
assert result == (
summary if reread
else "Warning: file was modified since the last recorded read or write.\n" + summary
)
assert result == summary
assert f.read_text() == "hello earth"
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
from nanobot.agent.tools.file_state import file_read_context
from nanobot.agent.tools.filesystem import EditFileTool, ReadFileTool
@@ -10,9 +11,11 @@ def test_read_file_force_bypasses_dedup(tmp_path):
target.write_text("alpha\n")
tool = ReadFileTool(workspace=tmp_path)
first = asyncio.run(tool.execute(path=str(target)))
second = asyncio.run(tool.execute(path=str(target)))
forced = asyncio.run(tool.execute(path=str(target), force=True))
with file_read_context("read-1", lambda: {}):
first = asyncio.run(tool.execute(path=str(target)))
with file_read_context("read-2", lambda: {"read-1": first}):
second = asyncio.run(tool.execute(path=str(target)))
forced = asyncio.run(tool.execute(path=str(target), force=True))
assert "alpha" in first
assert "unchanged" in second.lower()
+30 -28
View File
@@ -46,7 +46,7 @@ class TestReadDescriptionFix:
# ---------------------------------------------------------------------------
class TestReadDedup:
"""Same file + same offset/limit + unchanged mtime -> short stub."""
"""Only reads whose original result remains in context may return a stub."""
@pytest.fixture()
def tool(self, tmp_path):
@@ -60,9 +60,11 @@ class TestReadDedup:
async def test_second_read_returns_unchanged_stub(self, tool, tmp_path):
f = tmp_path / "data.txt"
f.write_text("\n".join(f"line {i}" for i in range(100)), encoding="utf-8")
first = await tool.execute(path=str(f))
with file_state.file_read_context("read-1", lambda: {}):
first = await tool.execute(path=str(f))
assert "line 0" in first
second = await tool.execute(path=str(f))
with file_state.file_read_context("read-2", lambda: {"read-1": first}):
second = await tool.execute(path=str(f))
assert "unchanged" in second.lower()
# Stub should not contain file content
assert "line 0" not in second
@@ -71,18 +73,22 @@ class TestReadDedup:
async def test_read_after_external_modification_returns_full(self, tool, tmp_path):
f = tmp_path / "data.txt"
f.write_text("original", encoding="utf-8")
await tool.execute(path=str(f))
with file_state.file_read_context("read-1", lambda: {}):
first = await tool.execute(path=str(f))
# Modify the file externally
f.write_text("modified content", encoding="utf-8")
second = await tool.execute(path=str(f))
with file_state.file_read_context("read-2", lambda: {"read-1": first}):
second = await tool.execute(path=str(f))
assert "modified content" in second
@pytest.mark.asyncio
async def test_different_offset_returns_full(self, tool, tmp_path):
f = tmp_path / "data.txt"
f.write_text("\n".join(f"line {i}" for i in range(1, 21)), encoding="utf-8")
await tool.execute(path=str(f), offset=1, limit=5)
second = await tool.execute(path=str(f), offset=6, limit=5)
with file_state.file_read_context("read-1", lambda: {}):
first = await tool.execute(path=str(f), offset=1, limit=5)
with file_state.file_read_context("read-2", lambda: {"read-1": first}):
second = await tool.execute(path=str(f), offset=6, limit=5)
# Different offset → full read, not stub
assert "line 6" in second
@@ -121,8 +127,8 @@ class TestReadDedup:
# ---------------------------------------------------------------------------
# Each session must keep its own read cache. When session A reads a file,
# session B reading the same file must still receive the full content, not
# the "[File unchanged since last read]" dedup stub. The stub is only valid
# within the session that first cached the read.
# the "[File unchanged since last read]" dedup stub. Within each session,
# the original result must also remain in the current model context.
class TestReadDedupSessionIsolation:
@@ -159,8 +165,10 @@ class TestReadDedupSessionIsolation:
token = file_state.bind_file_states(session_a)
try:
first = await shared_tool.execute(path=str(f))
repeat = await shared_tool.execute(path=str(f))
with file_state.file_read_context("read-a1", lambda: {}):
first = await shared_tool.execute(path=str(f))
with file_state.file_read_context("read-a2", lambda: {"read-a1": first}):
repeat = await shared_tool.execute(path=str(f))
finally:
file_state.reset_file_states(token)
@@ -285,35 +293,29 @@ class TestReadDeviceBlacklist:
# ---------------------------------------------------------------------------
# file_state: mtime-unchanged / content-changed fallback
# File changes with preserved mtime
# ---------------------------------------------------------------------------
# On filesystems with coarse mtime resolution (NTFS ~100ms, FAT 2s) a fast
# write-after-read can leave mtime unchanged. The content-hash fallback is
# what protects against stale-read warnings being false-negative on those
# platforms. Lock that behavior down here so nobody reverts it silently.
# An editor can preserve mtime while replacing contents. Deduplication must
# compare the file snapshot even when the original result remains in context.
class TestFileStateHashFallback:
def test_check_read_warns_when_content_changed_but_mtime_same(self, tmp_path):
async def test_read_returns_changed_content_when_mtime_same(self, tmp_path):
f = tmp_path / "data.txt"
f.write_text("original", encoding="utf-8")
file_state.record_read(f)
tool = ReadFileTool(workspace=tmp_path)
with file_state.file_read_context("read-1", lambda: {}):
first = await tool.execute(path=str(f))
original_mtime = os.path.getmtime(f)
f.write_text("modified", encoding="utf-8")
os.utime(f, (original_mtime, original_mtime))
assert os.path.getmtime(f) == original_mtime
warning = file_state.check_read(f)
assert warning is not None
assert "modified" in warning.lower()
def test_check_read_passes_when_content_and_mtime_unchanged(self, tmp_path):
f = tmp_path / "data.txt"
f.write_text("stable", encoding="utf-8")
file_state.record_read(f)
assert file_state.check_read(f) is None
with file_state.file_read_context("read-2", lambda: {"read-1": first}):
second = await tool.execute(path=str(f))
assert "modified" in second
assert "unchanged" not in second.lower()
# ---------------------------------------------------------------------------