perf(tools): batch scoped search timestamps by directory

This commit is contained in:
Xubin Ren committed 2026-11-14 22:09:21 +08:00
1 parent 66b8c447dc
commit 0efe7b2eb4
3 files changed
+253 -37

No files matched your search

+76 -35
View File
@@ -8,6 +8,7 @@ import heapq
import re import re
import threading import threading
import time import time
from collections.abc import Callable
from contextlib import suppress from contextlib import suppress
from dataclasses import dataclass from dataclasses import dataclass
from functools import lru_cache from functools import lru_cache
@@ -319,6 +320,27 @@ class FindFilesTool(_SearchTool):
is_dir=is_dir, is_dir=is_dir,
) )
def _directory_entries(
self,
tree: FileSearch,
directory: Path,
root: Path,
budget: _SearchBudget,
) -> Iterator[_FindFilesEntry]:
budget.checkpoint()
try:
for raw_entry in tree.entries(directory):
budget.visit_path()
is_dir = raw_entry.is_directory
if raw_entry.is_directory_link or (is_dir and self._ignore_directory(raw_entry.name)):
continue
yield self._entry(directory / raw_entry.name, root, is_dir=is_dir)
except OSError:
# os.walk silently skips directories that cannot be listed. Preserve
# that behavior while still allowing cancellation and budget errors
# to propagate from the explicit checkpoints above.
pass
def _push_directory_entries( def _push_directory_entries(
self, self,
tree: FileSearch, tree: FileSearch,
@@ -328,22 +350,10 @@ class FindFilesTool(_SearchTool):
sequence: int, sequence: int,
budget: _SearchBudget, budget: _SearchBudget,
) -> int: ) -> int:
budget.checkpoint() for entry in self._directory_entries(tree, directory, root, budget):
try: sort_path = entry.display_path + ("/" if entry.is_dir else "")
for raw_entry in tree.entries(directory): heapq.heappush(frontier, (sort_path, sequence, entry))
budget.visit_path() sequence += 1
is_dir = raw_entry.is_directory
if raw_entry.is_directory_link or (is_dir and self._ignore_directory(raw_entry.name)):
continue
entry = self._entry(directory / raw_entry.name, root, is_dir=is_dir)
sort_path = entry.display_path + ("/" if is_dir else "")
heapq.heappush(frontier, (sort_path, sequence, entry))
sequence += 1
except OSError:
# os.walk silently skips directories that cannot be listed. Preserve
# that behavior while still allowing cancellation and budget errors
# to propagate from the explicit checkpoints above.
pass
return sequence return sequence
def _iter_paths( def _iter_paths(
@@ -382,6 +392,44 @@ class FindFilesTool(_SearchTool):
else: else:
yield entry yield entry
def _iter_modified(
self,
tree: FileSearch,
*,
include_dirs: bool,
matches: Callable[[_FindFilesEntry], bool],
budget: _SearchBudget,
) -> Iterator[tuple[str, float]]:
budget.checkpoint()
root = tree.root
if not tree.is_directory or include_dirs:
if not tree.is_directory:
budget.visit_path()
entry = self._entry(root, root if tree.is_directory else root.parent, is_dir=tree.is_directory)
if matches(entry):
yield entry.display_path + ("/" if entry.is_dir else ""), tree.modified(root)
if not tree.is_directory:
return
# Modified order needs a full scan; only the final selection needs a heap.
pending = [root]
while pending:
directory = pending.pop()
selected: list[_FindFilesEntry] = []
for entry in self._directory_entries(tree, directory, root, budget):
if entry.is_dir:
pending.append(entry.path)
if not include_dirs:
continue
if matches(entry):
selected.append(entry)
if selected:
times = tree.modified_children(
directory, [entry.name for entry in selected], checkpoint=budget.checkpoint,
)
for entry, mtime in zip(selected, times, strict=True):
yield entry.display_path + ("/" if entry.is_dir else ""), mtime
@staticmethod @staticmethod
def _matches_entry( def _matches_entry(
entry: _FindFilesEntry, entry: _FindFilesEntry,
@@ -473,44 +521,37 @@ class FindFilesTool(_SearchTool):
max_paths=self._MAX_SCAN_PATHS, max_paths=self._MAX_SCAN_PATHS,
) )
def matching_entries() -> Iterator[tuple[str, float]]: def matches_entry(entry: _FindFilesEntry) -> bool:
return self._matches_entry(entry, query=query, glob=glob, file_type=file_type)
def matching_paths() -> Iterator[tuple[str, float]]:
for entry in self._iter_paths( for entry in self._iter_paths(
tree, tree,
include_dirs=include_dirs, include_dirs=include_dirs,
budget=budget, budget=budget,
): ):
if not self._matches_entry( if matches_entry(entry):
entry, yield entry.display_path + ("/" if entry.is_dir else ""), 0.0
query=query,
glob=glob,
file_type=file_type,
):
continue
mtime = 0.0
if sort == "modified":
try:
mtime = tree.modified(entry.path)
except OSError:
pass
suffix = "/" if entry.is_dir else ""
yield entry.display_path + suffix, mtime
matches: list[tuple[str, float]] matches: list[tuple[str, float]]
try: try:
if sort == "modified": if sort == "modified":
by_modified = self._iter_modified(
tree, include_dirs=include_dirs, matches=matches_entry, budget=budget,
)
if limit is None: if limit is None:
matches = sorted(matching_entries(), key=lambda item: (-item[1], item[0])) matches = sorted(by_modified, key=lambda item: (-item[1], item[0]))
else: else:
selection_size = offset + limit + 1 selection_size = offset + limit + 1
matches = heapq.nsmallest( matches = heapq.nsmallest(
selection_size, selection_size,
matching_entries(), by_modified,
key=lambda item: (-item[1], item[0]), key=lambda item: (-item[1], item[0]),
) )
else: else:
selection_size = None if limit is None else offset + limit + 1 selection_size = None if limit is None else offset + limit + 1
matches = [] matches = []
for match in matching_entries(): for match in matching_paths():
matches.append(match) matches.append(match)
if selection_size is not None and len(matches) >= selection_size: if selection_size is not None and len(matches) >= selection_size:
break break
+68 -1
View File
@@ -216,7 +216,74 @@ class FileSearch:
return self._authorize_read(path) return self._authorize_read(path)
def modified(self, path: Path) -> float: def modified(self, path: Path) -> float:
return self._candidate(path).stat().st_mtime try:
return self._candidate(path).stat().st_mtime
except OSError:
return 0.0
@contextmanager
def _open_search_directory(self, directory: Path) -> Generator[int]:
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
root_info = self.root.stat(follow_symlinks=False)
fd = os.open(self.root, flags)
try:
if not os.path.samestat(root_info, os.fstat(fd)):
raise PermissionError("Search root changed")
for part in directory.relative_to(self.root).parts:
child = os.open(part, flags, dir_fd=fd)
os.close(fd)
fd = child
yield fd
finally:
os.close(fd)
def modified_children(
self, directory: Path, names: list[str], *, checkpoint: Callable[[], None],
) -> list[float]:
"""Get timestamps for direct children without transferring the directory handle."""
if not self.is_directory or not directory.is_relative_to(self.root) or ".." in directory.parts:
raise ValueError("Expected a directory within the search root")
if any(not name or name in (".", "..") or os.path.basename(name) != name for name in names):
raise ValueError("Expected direct child names")
# A small match set does not amortize opening and rechecking the directory.
if (
len(names) >= 4
and os.open in os.supports_dir_fd
and os.stat in os.supports_dir_fd
and os.stat in os.supports_follow_symlinks
and hasattr(os, "O_DIRECTORY")
and hasattr(os, "O_NOFOLLOW")
):
try:
with self._open_search_directory(directory) as fd:
times: list[float] = []
for name in names:
checkpoint()
try:
info = os.stat(name, dir_fd=fd, follow_symlinks=False)
except OSError:
times.append(0.0)
else:
times.append(
self.modified(directory / name) if stat.S_ISLNK(info.st_mode)
else info.st_mtime
)
# An open directory survives a rename. Do not use its batch if
# the authorized path no longer points to that directory.
if (
Path(os.path.realpath(directory, strict=True)) == directory
and os.path.samestat(os.fstat(fd), directory.stat(follow_symlinks=False))
):
return times
except OSError:
pass # Reauthorize each child if the directory could not be pinned.
times = []
for name in names:
checkpoint()
times.append(self.modified(directory / name))
return times
def read_file(self, path: Path) -> ReadableFile: def read_file(self, path: Path) -> ReadableFile:
return _regular_file(self._candidate(path), suffix=path.suffix.lower()) return _regular_file(self._candidate(path), suffix=path.suffix.lower())
+109 -1
View File
@@ -1,9 +1,11 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
import errno
import os import os
import re import re
import threading import threading
from contextlib import contextmanager
from pathlib import Path from pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock from unittest.mock import AsyncMock, MagicMock
@@ -19,6 +21,7 @@ from nanobot.agent.tools.search import FindFilesTool, GrepTool
from nanobot.agent.tools.web import WebSearchTool from nanobot.agent.tools.web import WebSearchTool
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.config.schema import WebSearchConfig from nanobot.config.schema import WebSearchConfig
from nanobot.execution.files import FileSearch
from nanobot.providers.base import GenerationSettings from nanobot.providers.base import GenerationSettings
from nanobot.security.workspace_access import ( from nanobot.security.workspace_access import (
bind_workspace_scope, bind_workspace_scope,
@@ -128,6 +131,109 @@ async def test_find_files_supports_modified_sort_and_pagination(tmp_path: Path)
assert "pagination: limit=1, offset=1" in result assert "pagination: limit=1, offset=1" in result
async def test_find_files_modified_order_uses_only_authorized_link_timestamps(tmp_path: Path) -> None:
workspace = tmp_path / "workspace"
workspace.mkdir()
for name, timestamp in (("target.txt", 20), ("z.txt", 20), ("other.txt", 10)):
path = workspace / name
path.write_text("ordinary\n", encoding="utf-8")
os.utime(path, (timestamp, timestamp))
outside = tmp_path / "outside.txt"
outside.write_text("outside\n", encoding="utf-8")
os.utime(outside, (30, 30))
try:
(workspace / "alias.txt").symlink_to(workspace / "target.txt")
(workspace / "private.txt").symlink_to(outside)
except (NotImplementedError, OSError):
pytest.skip("symlinks unavailable")
tool = FindFilesTool(workspace=workspace, allowed_dir=workspace)
result = await tool.execute(sort="modified", head_limit=0)
assert result.splitlines() == ["alias.txt", "target.txt", "z.txt", "other.txt", "private.txt"]
sparse = await tool.execute(sort="modified", glob="{alias,private}.txt", head_limit=0)
assert sparse.splitlines() == ["alias.txt", "private.txt"]
@pytest.mark.skipif(os.open not in os.supports_dir_fd, reason="requires native directory handles")
async def test_find_files_discards_timestamps_when_open_directory_is_replaced(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
workspace = tmp_path / "workspace"
parent = workspace / "parent"
directory = parent / "src"
directory.mkdir(parents=True)
for name in ("a.txt", "b.txt", "c.txt", "d.txt"):
file = directory / name
file.write_text("inside\n", encoding="utf-8")
os.utime(file, (30, 30))
stable = workspace / "stable.txt"
stable.write_text("inside\n", encoding="utf-8")
os.utime(stable, (20, 20))
outside = tmp_path / "outside"
(outside / "src").mkdir(parents=True)
sentinel = outside / "src" / "a.txt"
sentinel.write_text("outside\n", encoding="utf-8")
os.utime(sentinel, (40, 40))
original = FileSearch._open_search_directory
@contextmanager
def replace_after_open(tree, path):
with original(tree, path) as fd:
if path == directory:
parent.rename(workspace / "moved")
parent.symlink_to(outside, target_is_directory=True)
yield fd
monkeypatch.setattr(FileSearch, "_open_search_directory", replace_after_open)
tool = FindFilesTool(workspace=workspace, allowed_dir=workspace)
result = await tool.execute(sort="modified", head_limit=0)
assert result.splitlines() == [
"stable.txt", "parent/src/a.txt", "parent/src/b.txt", "parent/src/c.txt", "parent/src/d.txt",
]
@pytest.mark.skipif(os.open not in os.supports_dir_fd, reason="requires native directory handles")
async def test_find_files_modified_cancellation_closes_directory_handle(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
for i in range(4):
(tmp_path / f"{i}.txt").write_text("ordinary\n", encoding="utf-8")
opened = threading.Event()
resume = threading.Event()
closed = threading.Event()
original = FileSearch._open_search_directory
@contextmanager
def pause_after_open(tree, path):
fd = None
try:
with original(tree, path) as fd:
opened.set()
if not resume.wait(timeout=3):
raise TimeoutError("scan was not released")
yield fd
finally:
if fd is not None:
try:
os.fstat(fd)
except OSError as exc:
if exc.errno == errno.EBADF:
closed.set()
monkeypatch.setattr(FileSearch, "_open_search_directory", pause_after_open)
tool = FindFilesTool(workspace=tmp_path, allowed_dir=tmp_path)
task = asyncio.create_task(tool.execute(sort="modified"))
try:
assert await asyncio.to_thread(opened.wait, 2)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
finally:
resume.set()
assert await asyncio.to_thread(closed.wait, 2)
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_find_files_rejects_paths_outside_workspace(tmp_path: Path) -> None: async def test_find_files_rejects_paths_outside_workspace(tmp_path: Path) -> None:
outside = tmp_path.parent / "outside-find-files.txt" outside = tmp_path.parent / "outside-find-files.txt"
@@ -283,16 +389,18 @@ async def test_find_files_path_limit_stops_after_pagination_lookahead(
@pytest.mark.asyncio @pytest.mark.asyncio
@pytest.mark.parametrize("sort", ["path", "modified"])
async def test_find_files_path_budget_counts_directories( async def test_find_files_path_budget_counts_directories(
tmp_path: Path, tmp_path: Path,
monkeypatch: pytest.MonkeyPatch, monkeypatch: pytest.MonkeyPatch,
sort: str,
) -> None: ) -> None:
(tmp_path / "one").mkdir() (tmp_path / "one").mkdir()
(tmp_path / "two").mkdir() (tmp_path / "two").mkdir()
monkeypatch.setattr(FindFilesTool, "_MAX_SCAN_PATHS", 1) monkeypatch.setattr(FindFilesTool, "_MAX_SCAN_PATHS", 1)
tool = FindFilesTool(workspace=tmp_path, allowed_dir=tmp_path) tool = FindFilesTool(workspace=tmp_path, allowed_dir=tmp_path)
result = await tool.execute(path=".") result = await tool.execute(path=".", sort=sort)
assert result.startswith("Error: find_files scan exceeded 1 paths") assert result.startswith("Error: find_files scan exceeded 1 paths")