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

+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()
# ---------------------------------------------------------------------------