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:
1 parent
47f77bdbcc
commit
d386ba138e
10 files changed
+417
-176
No files matched your search
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass, replace
|
||||
from dataclasses import dataclass, field, replace
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
@@ -200,6 +200,7 @@ class ModelRequestState:
|
||||
tool_definitions: list[dict[str, Any]] | None = None
|
||||
compaction: ContextCompactionState | None = None
|
||||
provider_compaction_applied: bool = False
|
||||
compacted_tool_results: set[str] = field(default_factory=set)
|
||||
events: EventSink = NO_EVENTS
|
||||
|
||||
|
||||
@@ -444,6 +445,19 @@ class ContextGovernor:
|
||||
) -> None:
|
||||
"""Materialize the exact input replaced by provider-native compaction."""
|
||||
compaction = state.compaction
|
||||
if response.provider_compaction_applied:
|
||||
# Native compaction can omit results while the local transcript keeps
|
||||
# their full text. They no longer prove what the model can read.
|
||||
replaced_messages = (
|
||||
compaction.accepted_messages
|
||||
if response.provider_compaction_scope == "prior_context" and compaction is not None
|
||||
else state.messages or []
|
||||
)
|
||||
state.compacted_tool_results.update(
|
||||
message["tool_call_id"] for message in replaced_messages
|
||||
if message.get("role") == "tool"
|
||||
and isinstance(message.get("tool_call_id"), str)
|
||||
)
|
||||
if (
|
||||
not response.provider_compaction_applied
|
||||
or response.provider_compaction_state is None
|
||||
|
||||
@@ -517,6 +517,8 @@ class AgentRunner:
|
||||
workspace_violation_counts=workspace_violation_counts,
|
||||
hook=hook,
|
||||
context=context,
|
||||
model_messages=messages_for_model,
|
||||
compacted_tool_results=request_state.compacted_tool_results,
|
||||
)
|
||||
tool_events.extend(new_events)
|
||||
tools_used.extend(
|
||||
|
||||
@@ -4,11 +4,14 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
from contextlib import nullcontext
|
||||
from functools import cache
|
||||
from typing import Any, cast
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.agent.hook import AgentHook, AgentHookContext
|
||||
from nanobot.agent.tools.file_state import file_read_context
|
||||
from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
|
||||
from nanobot.providers.base import ToolCallRequest
|
||||
from nanobot.utils.runtime import (
|
||||
@@ -59,8 +62,21 @@ async def execute_tool_calls(
|
||||
workspace_violation_counts: dict[str, int],
|
||||
hook: AgentHook,
|
||||
context: AgentHookContext,
|
||||
model_messages: list[dict[str, Any]] | None = None,
|
||||
compacted_tool_results: set[str] | None = None,
|
||||
) -> tuple[list[Any], list[dict[str, str]]]:
|
||||
"""Execute one model response's tool calls in stable result order."""
|
||||
@cache
|
||||
def read_results() -> dict[str, str]:
|
||||
"""Index once, on the first read-dedup check in this batch."""
|
||||
return {
|
||||
message["tool_call_id"]: message["content"]
|
||||
for message in model_messages or []
|
||||
if message.get("role") == "tool"
|
||||
and isinstance(message.get("tool_call_id"), str)
|
||||
and isinstance(message.get("content"), str)
|
||||
and message["tool_call_id"] not in (compacted_tool_results or ())
|
||||
}
|
||||
tool_results: list[tuple[Any, dict[str, str]]] = []
|
||||
for batch in _partition_tool_batches(tools, tool_calls, concurrent=concurrent):
|
||||
if concurrent and len(batch) > 1:
|
||||
@@ -72,6 +88,7 @@ async def execute_tool_calls(
|
||||
workspace_violation_counts,
|
||||
hook,
|
||||
context,
|
||||
read_results,
|
||||
)
|
||||
for tool_call in batch
|
||||
))
|
||||
@@ -85,6 +102,7 @@ async def execute_tool_calls(
|
||||
workspace_violation_counts,
|
||||
hook,
|
||||
context,
|
||||
read_results,
|
||||
)
|
||||
tool_results.append(result)
|
||||
|
||||
@@ -100,6 +118,7 @@ async def _execute_tool_call(
|
||||
workspace_violation_counts: dict[str, int],
|
||||
hook: AgentHook,
|
||||
context: AgentHookContext,
|
||||
read_results: Callable[[], dict[str, str]],
|
||||
) -> tuple[Any, dict[str, str]]:
|
||||
lookup_error = repeated_external_lookup_error(
|
||||
tool_call.name,
|
||||
@@ -145,10 +164,14 @@ async def _execute_tool_call(
|
||||
|
||||
await hook.before_execute_tool(context, tool_call, tool, params)
|
||||
try:
|
||||
if tool is not None:
|
||||
result = await tool.execute(**params)
|
||||
else:
|
||||
result = await tools.execute(tool_call.name, params)
|
||||
with (
|
||||
file_read_context(tool_call.id, read_results)
|
||||
if tool_call.name == "read_file" else nullcontext()
|
||||
):
|
||||
if tool is not None:
|
||||
result = await tool.execute(**params)
|
||||
else:
|
||||
result = await tools.execute(tool_call.name, params)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
|
||||
@@ -1,22 +1,46 @@
|
||||
"""Track file-read state for read-before-edit warnings and read deduplication."""
|
||||
"""Track file reads whose original results may still be in model context."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Callable, Generator, Mapping
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar, Token
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _FileReadContext:
|
||||
call_id: str
|
||||
tool_results: Callable[[], Mapping[str, str]]
|
||||
|
||||
|
||||
_current_file_read: ContextVar[_FileReadContext | None] = ContextVar(
|
||||
"nanobot_file_read_context", default=None,
|
||||
)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def file_read_context(
|
||||
call_id: str, tool_results: Callable[[], Mapping[str, str]],
|
||||
) -> Generator[None]:
|
||||
"""Bind one file read; resolve visible results only when checking a prior read."""
|
||||
token = _current_file_read.set(_FileReadContext(call_id, tool_results))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_current_file_read.reset(token)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ReadState:
|
||||
mtime: float
|
||||
offset: int
|
||||
limit: int | None
|
||||
content_hash: str | None
|
||||
can_dedup: bool
|
||||
call_id: str | None
|
||||
result_hash: str | None
|
||||
|
||||
|
||||
def _hash_file(p: str) -> str | None:
|
||||
@@ -27,101 +51,50 @@ def _hash_file(p: str) -> str | None:
|
||||
|
||||
|
||||
class FileStates:
|
||||
"""Per-session read/write tracker.
|
||||
|
||||
Owns its own state dict so read-dedup ("File unchanged since last read")
|
||||
and read-before-edit warnings stay scoped to one agent session and do
|
||||
not leak across sessions sharing this process.
|
||||
"""
|
||||
"""Cache read receipts per session; deduplicate only while their results are visible."""
|
||||
|
||||
__slots__ = ("_state",)
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._state: dict[str, ReadState] = {}
|
||||
|
||||
def record_read(self, path: str | Path, offset: int = 1, limit: int | None = None) -> None:
|
||||
"""Record that a file was read (called after successful read)."""
|
||||
def record_read(
|
||||
self, path: str | Path, offset: int = 1, limit: int | None = None, *,
|
||||
content_hash: str | None = None, result: str | None = None,
|
||||
) -> None:
|
||||
"""Record the file snapshot and complete result of a successful text read."""
|
||||
p = str(Path(path).resolve())
|
||||
try:
|
||||
mtime = os.path.getmtime(p)
|
||||
except OSError:
|
||||
return
|
||||
context = _current_file_read.get()
|
||||
self._state[p] = ReadState(
|
||||
mtime=mtime,
|
||||
offset=offset,
|
||||
limit=limit,
|
||||
content_hash=_hash_file(p),
|
||||
can_dedup=True,
|
||||
content_hash=content_hash if content_hash is not None else _hash_file(p),
|
||||
call_id=context.call_id if context is not None else None,
|
||||
result_hash=hashlib.sha256(result.encode("utf-8")).hexdigest() if result else None,
|
||||
)
|
||||
|
||||
def record_write(self, path: str | Path) -> None:
|
||||
"""Record that a file was written (updates mtime in state)."""
|
||||
p = str(Path(path).resolve())
|
||||
try:
|
||||
mtime = os.path.getmtime(p)
|
||||
except OSError:
|
||||
self._state.pop(p, None)
|
||||
return
|
||||
self._state[p] = ReadState(
|
||||
mtime=mtime,
|
||||
offset=1,
|
||||
limit=None,
|
||||
content_hash=_hash_file(p),
|
||||
can_dedup=False,
|
||||
)
|
||||
"""Invalidate a prior read after a write; a write summary is not file content."""
|
||||
self._state.pop(str(Path(path).resolve()), None)
|
||||
|
||||
def check_read(self, path: str | Path) -> str | None:
|
||||
"""Warn when a file differs from its recorded read/write state.
|
||||
|
||||
Returns None if OK, or a warning string.
|
||||
When mtime changed but file content is identical (e.g. touch, editor save),
|
||||
the check passes to avoid false-positive staleness warnings.
|
||||
"""
|
||||
def is_unchanged(
|
||||
self, path: str | Path, offset: int = 1, limit: int | None = None, *,
|
||||
content_hash: str | None = None,
|
||||
) -> bool:
|
||||
"""Check both file identity and the original result in the actual model input."""
|
||||
p = str(Path(path).resolve())
|
||||
entry = self._state.get(p)
|
||||
if entry is None:
|
||||
# Shell reads and content already in context may not be recorded here.
|
||||
return None
|
||||
try:
|
||||
current_mtime = os.path.getmtime(p)
|
||||
except OSError:
|
||||
return None
|
||||
if current_mtime != entry.mtime:
|
||||
if entry.content_hash and _hash_file(p) == entry.content_hash:
|
||||
entry.mtime = current_mtime
|
||||
return None
|
||||
return "Warning: file was modified since the last recorded read or write."
|
||||
# mtime unchanged - still check content hash to detect quick modifications
|
||||
if entry.content_hash and _hash_file(p) != entry.content_hash:
|
||||
return "Warning: file was modified since the last recorded read or write."
|
||||
return None
|
||||
|
||||
def is_unchanged(self, path: str | Path, offset: int = 1, limit: int | None = None) -> bool:
|
||||
"""Return True if file was previously read with same params and content is unchanged."""
|
||||
p = str(Path(path).resolve())
|
||||
entry = self._state.get(p)
|
||||
if entry is None:
|
||||
return False
|
||||
if not entry.can_dedup:
|
||||
context = _current_file_read.get()
|
||||
if entry is None or context is None or not entry.call_id or not entry.result_hash:
|
||||
return False
|
||||
if entry.offset != offset or entry.limit != limit:
|
||||
return False
|
||||
try:
|
||||
current_mtime = os.path.getmtime(p)
|
||||
except OSError:
|
||||
result = context.tool_results().get(entry.call_id)
|
||||
if result is None or hashlib.sha256(result.encode("utf-8")).hexdigest() != entry.result_hash:
|
||||
self._state.pop(p, None)
|
||||
return False
|
||||
if current_mtime != entry.mtime:
|
||||
# mtime changed - check if content also changed
|
||||
current_hash = _hash_file(p)
|
||||
if current_hash != entry.content_hash:
|
||||
# Content actually changed - don't dedup
|
||||
entry.can_dedup = False
|
||||
return False
|
||||
# Content identical despite mtime change (e.g. touch) - mark as not dedupable to force full read next time
|
||||
entry.can_dedup = False
|
||||
return True
|
||||
# mtime unchanged - content must be identical
|
||||
return True
|
||||
current_hash = content_hash if content_hash is not None else _hash_file(p)
|
||||
return current_hash is not None and current_hash == entry.content_hash
|
||||
|
||||
def get(self, path: str | Path) -> ReadState | None:
|
||||
"""Return the raw ReadState entry for a path, or None."""
|
||||
@@ -199,10 +172,6 @@ def record_write(path: str | Path) -> None:
|
||||
_default.record_write(path)
|
||||
|
||||
|
||||
def check_read(path: str | Path) -> str | None:
|
||||
return _default.check_read(path)
|
||||
|
||||
|
||||
def is_unchanged(path: str | Path, offset: int = 1, limit: int | None = None) -> bool:
|
||||
return _default.is_unchanged(path, offset=offset, limit=limit)
|
||||
|
||||
|
||||
@@ -3,15 +3,15 @@
|
||||
# pyright: reportPrivateUsage=false, reportUnusedFunction=false
|
||||
|
||||
import difflib
|
||||
import hashlib
|
||||
import mimetypes
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
|
||||
from nanobot.agent.tools.context import ToolContext
|
||||
from nanobot.agent.tools.file_state import FileStates, _hash_file, current_file_states
|
||||
from nanobot.agent.tools.file_state import FileStates, current_file_states
|
||||
from nanobot.agent.tools.path_utils import resolve_workspace_path
|
||||
from nanobot.agent.tools.schema import (
|
||||
BooleanSchema,
|
||||
@@ -343,44 +343,11 @@ class ReadFileTool(_FsTool):
|
||||
if mime and mime.startswith("image/"):
|
||||
return build_image_content_blocks(raw, mime, str(fp), f"(Image file: {path})")
|
||||
|
||||
# Read dedup: same path + offset + limit + unchanged mtime → stub
|
||||
# Always check for external modifications before dedup
|
||||
entry = self._file_states.get(fp)
|
||||
try:
|
||||
current_mtime = os.path.getmtime(fp)
|
||||
except OSError:
|
||||
current_mtime = 0.0
|
||||
if (
|
||||
not force
|
||||
and entry
|
||||
and entry.can_dedup
|
||||
and entry.offset == offset
|
||||
and entry.limit == limit
|
||||
content_hash = hashlib.sha256(raw).hexdigest()
|
||||
if not force and self._file_states.is_unchanged(
|
||||
fp, offset=offset, limit=limit, content_hash=content_hash,
|
||||
):
|
||||
if current_mtime != entry.mtime:
|
||||
# File was modified externally - force full read and mark as not dedupable
|
||||
entry.can_dedup = False
|
||||
self._file_states.record_read(fp, offset=offset, limit=limit) # Update state with new mtime
|
||||
# Continue to read full content (don't return dedup message)
|
||||
else:
|
||||
# File unchanged - return dedup message
|
||||
# But only if content is actually unchanged (not just mtime)
|
||||
current_hash = _hash_file(str(fp))
|
||||
if current_hash == entry.content_hash:
|
||||
return f"[File unchanged since last read: {path}]"
|
||||
else:
|
||||
# Content changed despite same mtime - force full read
|
||||
entry.can_dedup = False
|
||||
self._file_states.record_read(fp, offset=offset, limit=limit)
|
||||
else:
|
||||
# No previous state or marked as not dedupable - read full content
|
||||
self._file_states.record_read(fp, offset=offset, limit=limit)
|
||||
# Force full read by setting can_dedup to False for this read
|
||||
if entry:
|
||||
entry.can_dedup = False
|
||||
|
||||
# Read the file content after dedup check
|
||||
raw = fp.read_bytes()
|
||||
return f"[File unchanged since last read: {path}]"
|
||||
try:
|
||||
text_content = raw.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
@@ -438,7 +405,9 @@ class ReadFileTool(_FsTool):
|
||||
result += f"\n\n(Showing lines {offset}-{end} of {total}. Use offset={end + 1} to continue.)"
|
||||
else:
|
||||
result += f"\n\n(End of file — {total} lines total)"
|
||||
self._file_states.record_read(fp, offset=offset, limit=limit)
|
||||
self._file_states.record_read(
|
||||
fp, offset=offset, limit=limit, content_hash=content_hash, result=result,
|
||||
)
|
||||
return result
|
||||
except PermissionError as e:
|
||||
return ToolResult.error(f"Error: {e}")
|
||||
@@ -914,7 +883,7 @@ class EditFileTool(_FsTool):
|
||||
|
||||
def _format_summary(
|
||||
self, resolved_path: Path, before: str, after: str, *,
|
||||
created: bool = False, warning: str | None = None,
|
||||
created: bool = False,
|
||||
) -> FileEditResult:
|
||||
diff = FileDiff.from_text(before, after)
|
||||
added, deleted = diff.added, diff.deleted
|
||||
@@ -922,8 +891,6 @@ class EditFileTool(_FsTool):
|
||||
stats = f" (+{added}/-{deleted})" if added or deleted else ""
|
||||
path = display_file_edit_path(resolved_path, self._display_workspace())
|
||||
text = f"Patch applied:\n- {action} {path}{stats}"
|
||||
if warning:
|
||||
text = f"{warning}\n{text}"
|
||||
return FileEditResult(text, {resolved_path: diff})
|
||||
|
||||
async def execute(
|
||||
@@ -978,9 +945,6 @@ class EditFileTool(_FsTool):
|
||||
self._file_states.record_write(fp)
|
||||
return self._format_summary(fp, content, fp.read_bytes().decode("utf-8"))
|
||||
|
||||
# Read-before-edit check
|
||||
warning = self._file_states.check_read(fp)
|
||||
|
||||
raw = fp.read_bytes()
|
||||
uses_crlf = b"\r\n" in raw
|
||||
content = raw.decode("utf-8").replace("\r\n", "\n")
|
||||
@@ -1069,7 +1033,7 @@ class EditFileTool(_FsTool):
|
||||
|
||||
fp.write_bytes(new_content.encode("utf-8"))
|
||||
self._file_states.record_write(fp)
|
||||
return self._format_summary(fp, content, new_content, warning=warning)
|
||||
return self._format_summary(fp, content, new_content)
|
||||
except PermissionError as e:
|
||||
return ToolResult.error(f"Error: {e}")
|
||||
except Exception as e:
|
||||
|
||||
Reference in new issue
Block a user