perf(tools): recover scoped grep throughput

This commit is contained in:
Xubin Ren committed 2026-11-14 22:09:21 +08:00
1 parent 0efe7b2eb4
commit cdb3fd835f
3 files changed
+229 -90

No files matched your search

+91 -72
View File
@@ -18,7 +18,7 @@ from typing import Any, Iterable, Iterator, TypeVar
from nanobot.agent.tools._search_content import ContentPage, MatchTooLargeError from nanobot.agent.tools._search_content import ContentPage, MatchTooLargeError
from nanobot.agent.tools.base import ToolResult from nanobot.agent.tools.base import ToolResult
from nanobot.agent.tools.filesystem import ListDirTool, _FsTool from nanobot.agent.tools.filesystem import ListDirTool, _FsTool
from nanobot.execution.files import FileSearch, NotRegularFileError, ReadableFile from nanobot.execution.files import FileSearch, NotRegularFileError
from nanobot.utils.document import ( from nanobot.utils.document import (
DocumentLineSource, DocumentLineSource,
LocatedDocumentLine, LocatedDocumentLine,
@@ -28,6 +28,7 @@ from nanobot.utils.document import (
_DEFAULT_HEAD_LIMIT = 250 _DEFAULT_HEAD_LIMIT = 250
_DEFAULT_FILE_HEAD_LIMIT = 200 _DEFAULT_FILE_HEAD_LIMIT = 200
_DOCUMENT_EXTENSIONS = frozenset({".pdf", ".docx", ".xlsx", ".pptx"}) _DOCUMENT_EXTENSIONS = frozenset({".pdf", ".docx", ".xlsx", ".pptx"})
_NON_TEXT_BYTES = re.compile(rb"[\x01-\x08\x0e-\x1f]")
T = TypeVar("T") T = TypeVar("T")
_TYPE_GLOB_MAP = { _TYPE_GLOB_MAP = {
"py": ("*.py", "*.pyi"), "py": ("*.py", "*.pyi"),
@@ -120,11 +121,19 @@ def _match_glob(rel_path: str, name: str, pattern: str) -> bool:
return any(_match_path_glob(rel_path, name, item) for item in _glob_patterns(pattern)) return any(_match_path_glob(rel_path, name, item) for item in _glob_patterns(pattern))
@lru_cache(maxsize=128)
def _glob_path_parts(pattern: str) -> tuple[str, ...]:
return PurePosixPath(pattern).parts
def _match_path_glob(rel_path: str, name: str, normalized: str) -> bool: def _match_path_glob(rel_path: str, name: str, normalized: str) -> bool:
if not normalized: if not normalized:
return False return False
if "/" in normalized: if "/" in normalized:
pattern_parts = PurePosixPath(normalized).parts pattern_parts = _glob_path_parts(normalized)
if len(pattern_parts) == 2 and pattern_parts[0] == "**" and pattern_parts[1] != "**":
# Any directory prefix is allowed, so only the basename matters.
return rel_path != "." and fnmatch.fnmatchcase(name, pattern_parts[1])
path_parts = PurePosixPath(rel_path).parts path_parts = PurePosixPath(rel_path).parts
matched = [True] + [False] * len(path_parts) matched = [True] + [False] * len(path_parts)
for part in pattern_parts: for part in pattern_parts:
@@ -146,8 +155,7 @@ def _is_binary(raw: bytes) -> bool:
sample = raw[:4096] sample = raw[:4096]
if not sample: if not sample:
return False return False
non_text = sum(byte < 9 or 13 < byte < 32 for byte in sample) return len(_NON_TEXT_BYTES.findall(sample)) / len(sample) > 0.2
return (non_text / len(sample)) > 0.2
def _paginate(items: list[T], limit: int | None, offset: int) -> tuple[list[T], bool]: def _paginate(items: list[T], limit: int | None, offset: int) -> tuple[list[T], bool]:
@@ -674,13 +682,7 @@ class GrepTool(_SearchTool):
} }
@staticmethod @staticmethod
def _open_source(source: ReadableFile, pages: str | None, max_bytes: int) -> DocumentLineSource | None: def _text_source(raw: bytes, max_bytes: int) -> DocumentLineSource | None:
if source.suffix in _DOCUMENT_EXTENSIONS:
return source.document_lines(pages=pages)
with source.open() as (file, size):
if size > max_bytes:
return None
raw = file.read(max_bytes + 1)
if len(raw) > max_bytes or _is_binary(raw): if len(raw) > max_bytes or _is_binary(raw):
return None return None
try: try:
@@ -794,72 +796,89 @@ class GrepTool(_SearchTool):
self._MAX_FILE_BYTES if tree.is_directory else self._MAX_EXPLICIT_FILE_BYTES self._MAX_FILE_BYTES if tree.is_directory else self._MAX_EXPLICIT_FILE_BYTES
) )
for file_path in self._iter_files(tree, budget): workspace = self._files.display_workspace
rel_path = file_path.relative_to(root).as_posix() with tree.search_bytes_reader() as read_bytes:
if glob and not _match_glob(rel_path, file_path.name, glob): for file_path in self._iter_files(tree, budget):
continue rel_path = file_path.relative_to(root).as_posix()
if not _matches_type(file_path.name, type): if glob and not _match_glob(rel_path, file_path.name, glob):
continue
display_path = self._display_path(file_path, root)
try:
file = tree.read_file(file_path)
except OSError:
skipped_binary += 1
continue
if file.size > max_file_bytes:
skipped_large += 1
continue
source_iterator: Iterator[LocatedDocumentLine] | None = None
is_document = file.suffix in _DOCUMENT_EXTENSIONS
try:
source = self._open_source(file, pages, max_file_bytes)
if source is None:
skipped_binary += 1
continue continue
source_iterator = source.lines if not _matches_type(file_path.name, type):
if source.continuation: continue
document_continuations.append( display_path = rel_path
f"({display_path}: continue PDF search with {source.continuation})" if workspace is not None and workspace != root:
) with suppress(ValueError):
source_lines = checked_lines(source_iterator) display_path = file_path.relative_to(workspace).as_posix()
file_had_match = False source_iterator: Iterator[LocatedDocumentLine] | None = None
if output_mode == "content": is_document = file_path.suffix.lower() in _DOCUMENT_EXTENSIONS
content_page.scan(display_path, source_lines, regex, context_before, context_after) try:
else: if is_document:
for line in source_lines: try:
if not line.searchable or regex.search(line.text) is None: file = tree.read_file(file_path)
except OSError:
skipped_binary += 1
continue continue
file_had_match = True if file.size > max_file_bytes:
if output_mode == "count": skipped_large += 1
counts[display_path] = counts.get(display_path, 0) + 1
continue continue
break mtime = file.modified
except (_SearchCancelledError, _SearchBudgetExceededError, MatchTooLargeError): source = file.document_lines(pages=pages)
raise else:
except Exception as e: contents = read_bytes(file_path, max_file_bytes)
if not is_document: if contents is None:
raise skipped_binary += 1
if not tree.is_directory: continue
if isinstance(e, PdfPageRangeError): if contents.data is None:
return ToolResult.error( skipped_large += 1
f"Error: Invalid PDF page range '{pages}': {e!s}." continue
mtime = contents.modified
source = self._text_source(contents.data, max_file_bytes)
if source is None:
skipped_binary += 1
continue
source_iterator = source.lines
if source.continuation:
document_continuations.append(
f"({display_path}: continue PDF search with {source.continuation})"
) )
return ToolResult.error( source_lines = checked_lines(source_iterator)
f"Error searching document {display_path}: {e!s}"
) file_had_match = False
skipped_binary += 1 if output_mode == "content":
document_errors.append(f"{display_path}: {e!s}") content_page.scan(display_path, source_lines, regex, context_before, context_after)
continue else:
finally: for line in source_lines:
close = getattr(source_iterator, "close", None) if not line.searchable or regex.search(line.text) is None:
if close is not None: continue
close() file_had_match = True
if file_had_match: if output_mode == "count":
file_mtimes[display_path] = file.modified counts[display_path] = counts.get(display_path, 0) + 1
if content_page.stopped: continue
break break
except (_SearchCancelledError, _SearchBudgetExceededError, MatchTooLargeError):
raise
except Exception as e:
if not is_document:
raise
if not tree.is_directory:
if isinstance(e, PdfPageRangeError):
return ToolResult.error(
f"Error: Invalid PDF page range '{pages}': {e!s}."
)
return ToolResult.error(
f"Error searching document {display_path}: {e!s}"
)
skipped_binary += 1
document_errors.append(f"{display_path}: {e!s}")
continue
finally:
close = getattr(source_iterator, "close", None)
if close is not None:
close()
if file_had_match:
file_mtimes[display_path] = mtime
if content_page.stopped:
break
no_matches = f"No matches found for pattern '{pattern}' in {path}" no_matches = f"No matches found for pattern '{pattern}' in {path}"
notes: list[str] = [] notes: list[str] = []
+107 -17
View File
@@ -6,7 +6,7 @@ import os
import re import re
import stat import stat
from collections.abc import Callable, Generator, Iterable from collections.abc import Callable, Generator, Iterable
from contextlib import AbstractContextManager, contextmanager from contextlib import AbstractContextManager, ExitStack, contextmanager
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import TYPE_CHECKING, BinaryIO from typing import TYPE_CHECKING, BinaryIO
@@ -24,16 +24,18 @@ class NotRegularFileError(OSError):
@contextmanager @contextmanager
def _open_regular_file(resolved_path: Path) -> Generator[tuple[BinaryIO, int]]: def _open_regular_file(
resolved_path: Path | str, *, dir_fd: int | None = None,
) -> Generator[tuple[BinaryIO, int]]:
"""Own one descriptor for the entire read and report its initial size. """Own one descriptor for the entire read and report its initial size.
Callers must resolve the path under the current access policy first. Callers must supply an authorized path or a child of an authorized directory handle.
Where supported, refuse a swapped-in final symlink and avoid waiting on Where supported, refuse a swapped-in final symlink and avoid waiting on
a swapped-in FIFO. This does not protect ancestor path components. a swapped-in FIFO. This does not protect ancestor path components.
""" """
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
flags |= getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) flags |= getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0)
with os.fdopen(os.open(resolved_path, flags), "rb") as stream: with os.fdopen(os.open(resolved_path, flags, dir_fd=dir_fd), "rb") as stream:
opened = os.fstat(stream.fileno()) opened = os.fstat(stream.fileno())
if not stat.S_ISREG(opened.st_mode): if not stat.S_ISREG(opened.st_mode):
raise NotRegularFileError raise NotRegularFileError
@@ -183,6 +185,24 @@ class SearchEntry:
is_directory_link: bool is_directory_link: bool
@dataclass(frozen=True, slots=True)
class SearchBytes:
"""A bounded read; no data means the regular file exceeds the size limit."""
data: bytes | None
modified: float
def _supports_directory_handles() -> bool:
return (
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")
)
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
class FileSearch: class FileSearch:
"""An authorized search root; links are not recursive directories.""" """An authorized search root; links are not recursive directories."""
@@ -223,13 +243,16 @@ class FileSearch:
@contextmanager @contextmanager
def _open_search_directory(self, directory: Path) -> Generator[int]: def _open_search_directory(self, directory: Path) -> Generator[int]:
relative = directory.relative_to(self.root)
if ".." in relative.parts:
raise ValueError("Expected a directory within the search root")
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
root_info = self.root.stat(follow_symlinks=False) root_info = self.root.stat(follow_symlinks=False)
fd = os.open(self.root, flags) fd = os.open(self.root, flags)
try: try:
if not os.path.samestat(root_info, os.fstat(fd)): if not os.path.samestat(root_info, os.fstat(fd)):
raise PermissionError("Search root changed") raise PermissionError("Search root changed")
for part in directory.relative_to(self.root).parts: for part in relative.parts:
child = os.open(part, flags, dir_fd=fd) child = os.open(part, flags, dir_fd=fd)
os.close(fd) os.close(fd)
fd = child fd = child
@@ -237,6 +260,13 @@ class FileSearch:
finally: finally:
os.close(fd) os.close(fd)
@staticmethod
def _directory_is_current(directory: Path, fd: int) -> bool:
return (
Path(os.path.realpath(directory, strict=True)) == directory
and os.path.samestat(os.fstat(fd), directory.stat(follow_symlinks=False))
)
def modified_children( def modified_children(
self, directory: Path, names: list[str], *, checkpoint: Callable[[], None], self, directory: Path, names: list[str], *, checkpoint: Callable[[], None],
) -> list[float]: ) -> list[float]:
@@ -247,14 +277,7 @@ class FileSearch:
raise ValueError("Expected direct child names") raise ValueError("Expected direct child names")
# A small match set does not amortize opening and rechecking the directory. # A small match set does not amortize opening and rechecking the directory.
if ( if len(names) >= 4 and _supports_directory_handles():
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: try:
with self._open_search_directory(directory) as fd: with self._open_search_directory(directory) as fd:
times: list[float] = [] times: list[float] = []
@@ -271,10 +294,7 @@ class FileSearch:
) )
# An open directory survives a rename. Do not use its batch if # An open directory survives a rename. Do not use its batch if
# the authorized path no longer points to that directory. # the authorized path no longer points to that directory.
if ( if self._directory_is_current(directory, fd):
Path(os.path.realpath(directory, strict=True)) == directory
and os.path.samestat(os.fstat(fd), directory.stat(follow_symlinks=False))
):
return times return times
except OSError: except OSError:
pass # Reauthorize each child if the directory could not be pinned. pass # Reauthorize each child if the directory could not be pinned.
@@ -288,6 +308,76 @@ class FileSearch:
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())
def _read_search_bytes(self, path: Path, limit: int, fd: int | None = None) -> SearchBytes | None:
if fd is None:
try:
file = self.read_file(path)
except OSError:
return None
size, modified = file.size, file.modified
opened_path = file.path
else:
try:
info = os.stat(path.name, dir_fd=fd, follow_symlinks=False)
except OSError:
return None
if stat.S_ISLNK(info.st_mode):
return self._read_search_bytes(path, limit)
if not stat.S_ISREG(info.st_mode):
return None
size, modified = info.st_size, info.st_mtime
opened_path = path.name
if size > limit:
return SearchBytes(None, modified)
with _open_regular_file(opened_path, dir_fd=fd) as (stream, opened_size):
if opened_size > limit:
return None
return SearchBytes(stream.read(limit + 1), modified)
@contextmanager
def search_bytes_reader(self) -> Generator[Callable[[Path, int], SearchBytes | None]]:
"""Read consecutive files using one pinned parent; no handle leaves execution."""
if not self.is_directory or not _supports_directory_handles():
yield self._read_search_bytes
return
parent: Path | None = None
fd: int | None = None
attempted = False
with ExitStack() as handle:
def check_parent() -> None:
if parent is not None and fd is not None:
try:
if self._directory_is_current(parent, fd):
return
except OSError:
pass
raise PermissionError("Search directory changed during the scan; retry the search.")
def read(path: Path, limit: int) -> SearchBytes | None:
nonlocal parent, fd, attempted
if path.parent != parent:
check_parent()
handle.close()
parent, fd, attempted = path.parent, None, False
return self._read_search_bytes(path, limit)
if not attempted:
attempted = True
# Only open directories with multiple candidates. If the host
# cannot pin this path, keep using per-file authorization.
if parent is not None and parent.is_relative_to(self.root):
try:
_reject_device(parent, resolved=True)
fd = handle.enter_context(self._open_search_directory(parent))
except (OSError, ValueError):
pass
if path.name in ("", ".", ".."):
return self._read_search_bytes(path, limit)
return self._read_search_bytes(path, limit, fd)
yield read
check_parent()
def _regular_file(target: Path, *, suffix: str | None = None) -> ReadableFile: def _regular_file(target: Path, *, suffix: str | None = None) -> ReadableFile:
_reject_device(target, resolved=True) _reject_device(target, resolved=True)
+31 -1
View File
@@ -295,7 +295,7 @@ async def test_find_files_scan_keeps_event_loop_responsive(
async def test_grep_authorizes_the_targets_of_links_found_during_traversal(tmp_path: Path): async def test_grep_authorizes_the_targets_of_links_found_during_traversal(tmp_path: Path):
workspace = tmp_path / "workspace" workspace = tmp_path / "workspace"
workspace.mkdir() workspace.mkdir()
inside = workspace / "inside.txt" inside = workspace / "a.txt"
inside.write_text("needle allowed", encoding="utf-8") inside.write_text("needle allowed", encoding="utf-8")
outside = tmp_path / "outside.txt" outside = tmp_path / "outside.txt"
outside.write_text("needle outside contents", encoding="utf-8") outside.write_text("needle outside contents", encoding="utf-8")
@@ -312,6 +312,36 @@ async def test_grep_authorizes_the_targets_of_links_found_during_traversal(tmp_p
assert "needle outside contents" not in result assert "needle outside contents" not in result
@pytest.mark.skipif(os.open not in os.supports_dir_fd, reason="requires native directory handles")
async def test_grep_discards_partial_results_when_a_pinned_directory_moves(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
workspace = (tmp_path / "workspace").resolve()
directory = workspace / "src"
directory.mkdir(parents=True)
for name in ("a.txt", "b.txt", "c.txt"):
(directory / name).write_text("needle inside\n", encoding="utf-8")
outside = tmp_path / "outside"
outside.mkdir()
(outside / "b.txt").write_text("needle outside\n", encoding="utf-8")
original = FileSearch._open_search_directory
@contextmanager
def replace_after_open(tree, path):
with original(tree, path) as fd:
if path == directory:
directory.rename(tmp_path / "moved")
directory.symlink_to(outside, target_is_directory=True)
yield fd
monkeypatch.setattr(FileSearch, "_open_search_directory", replace_after_open)
tool = GrepTool(workspace=workspace, allowed_dir=workspace)
# The first result is already buffered when the second file pins the parent.
# Even a page that stops early must not return the old directory's results.
result = await tool.execute(pattern="needle", head_limit=1)
assert result == "Error: Search directory changed during the scan; retry the search."
async def test_exact_read_grant_does_not_authorize_a_directory_tree(tmp_path: Path): async def test_exact_read_grant_does_not_authorize_a_directory_tree(tmp_path: Path):
workspace = tmp_path / "workspace" workspace = tmp_path / "workspace"
workspace.mkdir() workspace.mkdir()