perf: reduce memory copies across files, sessions, and model requests (#6581)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-06 17:50:25 +08:00
1 parent e40d2e5027
commit 1a89a25abd
16 files changed
+3080 -427

No files matched your search

+14 -23
View File
@@ -36,16 +36,9 @@ def file_read_context(
class ReadState:
offset: int
limit: int | None
content_hash: str | None
content_hash: str
call_id: str | None
result_hash: str | None
def _hash_file(p: str) -> str | None:
try:
return hashlib.sha256(Path(p).read_bytes()).hexdigest()
except OSError:
return None
result_hash: str
class FileStates:
@@ -58,7 +51,7 @@ class FileStates:
def record_read(
self, path: str | Path, offset: int = 1, limit: int | None = None, *,
content_hash: str | None = None, result: str | None = None,
content_hash: str, result: str,
) -> None:
"""Record the file snapshot and complete result of a successful text read."""
p = str(Path(path).resolve())
@@ -66,33 +59,31 @@ class FileStates:
self._state[p] = ReadState(
offset=offset,
limit=limit,
content_hash=content_hash if content_hash is not None else _hash_file(p),
content_hash=content_hash,
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,
result_hash=hashlib.sha256(result.encode("utf-8")).hexdigest(),
)
def record_write(self, path: str | Path) -> None:
"""Invalidate a prior read after a write; a write summary is not file content."""
self._state.pop(str(Path(path).resolve()), None)
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."""
def visible_read_hash(
self, path: str | Path, offset: int = 1, limit: int | None = None,
) -> str | None:
"""Return a matching receipt's hash only while its result is in the model input."""
p = str(Path(path).resolve())
entry = self._state.get(p)
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 is None or context is None or not entry.call_id:
return None
if entry.offset != offset or entry.limit != limit:
return False
return None
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
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
return None
return entry.content_hash
def get(self, path: str | Path) -> ReadState | None:
"""Return the raw ReadState entry for a path, or None."""
+278 -95
View File
@@ -1,11 +1,15 @@
# pyright: reportPrivateUsage=false, reportUnusedFunction=false
import codecs
import difflib
import hashlib
import mimetypes
import os
import stat
from copy import deepcopy
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from typing import Any, BinaryIO
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import ToolContext
@@ -232,6 +236,111 @@ def _builtin_skill_read_path(path: str) -> Path | None:
return candidate if candidate.is_file() else None
_LINE_BREAKS = frozenset("\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029")
class _TextRange:
"""Count splitlines and retain only the requested, displayable text."""
def __init__(self, offset: int, limit: int, max_chars: int):
self.offset = offset
self.limit = limit
self.max_chars = max_chars
self.total = 0
self.numbered: list[str] = []
self.line_truncated = False
self._output_chars = 0
self._fragments: list[str] = []
self._fragment_chars = 0
self._stopped = False
self._incomplete = False
self._normalize_cr = False
self._pending_cr = False
def feed(self, text: str) -> None:
if not text:
return
# The existing CRLF replacement runs before splitlines: for example,
# CR-CR-LF becomes CR-LF and therefore counts as one separator.
if self._normalize_cr:
text = "\r" + text
self._normalize_cr = text.endswith("\r")
if self._normalize_cr:
text = text[:-1]
self._feed_normalized(text.replace("\r\n", "\n"))
def _feed_normalized(self, text: str) -> None:
if not text:
return
if self._pending_cr and text.startswith("\n"):
text = text[1:]
self._pending_cr = False
if not text:
return
self._pending_cr = text.endswith("\r")
self._incomplete = text[-1] not in _LINE_BREAKS
parts = text.splitlines(keepends=True)
completed = len(parts) - int(self._incomplete)
if not self._stopped:
first = max(0, self.offset - self.total - 1)
last = min(len(parts), self.offset + self.limit - self.total - 1)
for i in range(first, last):
line_no = self.total + i + 1
part = parts[i]
if i < completed:
part = part[:-2] if part.endswith("\r\n") else part[:-1]
self._accept(part, line_no, complete=i < completed)
if self._stopped:
break
self.total += completed
def _accept(self, part: str, line_no: int, *, complete: bool) -> None:
prefix = f"{line_no}| "
separator = 1 if self.numbered else 0
available = self.max_chars - self._output_chars - separator - len(prefix)
if self._fragment_chars + len(part) > available:
if not self.numbered:
fragment = part[:max(0, available - self._fragment_chars)]
self.numbered.append((prefix + "".join(self._fragments) + fragment)[:self.max_chars])
self.line_truncated = True
self._fragments.clear()
self._stopped = True
return
if part:
self._fragments.append(part)
self._fragment_chars += len(part)
if complete:
line = prefix + "".join(self._fragments)
self._output_chars += len(line) + separator
self.numbered.append(line)
self._fragments.clear()
self._fragment_chars = 0
if len(self.numbered) >= self.limit:
self._stopped = True
def finish(self) -> None:
if self._normalize_cr:
self._feed_normalized("\r")
if self._incomplete:
self.total += 1
if not self._stopped and self.offset <= self.total < self.offset + self.limit:
self._accept("", self.total, complete=True)
def _decode_error_message(error: UnicodeDecodeError, offset: int) -> str:
"""Render the whole-input decode error position for an incremental BOM decoder."""
start, end = offset + error.start, offset + error.end
if end - start == 1:
where = f"byte 0x{error.object[error.start]:02x} in position {start}"
else:
where = f"bytes in position {start}-{end - 1}"
return f"'{error.encoding}' codec can't decode {where}: {error.reason}"
@tool_parameters(
tool_parameters_schema(
path=StringSchema("The file path to read"),
@@ -257,6 +366,8 @@ class ReadFileTool(_FsTool):
_MAX_CHARS = 128_000
_MAX_FILE_SIZE_BYTES = 100 * 1024 * 1024
_READ_CHUNK_SIZE = 64 * 1024
_IMAGE_READ_CHUNK_SIZE = 1024 * 1024
_DEFAULT_LIMIT = 2000
_MAX_PDF_PAGES = 20
@@ -303,12 +414,7 @@ class ReadFileTool(_FsTool):
file_size = fp.stat().st_size
if file_size > self._MAX_FILE_SIZE_BYTES:
size_mib = file_size / (1024 * 1024)
max_mib = self._MAX_FILE_SIZE_BYTES // (1024 * 1024)
return ToolResult.error(
f"Error: File too large to read ({size_mib:.1f} MiB). "
f"Maximum is {max_mib} MiB."
)
return self._file_too_large(file_size)
if fp.suffix.lower() == ".pdf":
return self._read_pdf(fp, pages)
@@ -316,102 +422,179 @@ class ReadFileTool(_FsTool):
if fp.suffix.lower() in {".docx", ".xlsx", ".pptx"}:
return self._read_office_doc(fp, offset, limit)
raw = fp.read_bytes()
if not raw:
return f"(Empty file: {path})"
# Keep one open file description for detection, hashing, and decoding.
# Nonblocking/no-follow flags also avoid opening a swapped-in FIFO or
# final symlink on platforms that support them.
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
flags |= getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0)
with os.fdopen(os.open(fp, flags), "rb") as stream:
opened = os.fstat(stream.fileno())
if not stat.S_ISREG(opened.st_mode):
return ToolResult.error(f"Error: Not a file: {path}")
if opened.st_size > self._MAX_FILE_SIZE_BYTES:
return self._file_too_large(opened.st_size)
mime = detect_image_mime(raw) or mimetypes.guess_type(path)[0]
if mime and mime.startswith("image/"):
return build_image_content_blocks(raw, mime, str(fp), f"(Image file: {path})")
check_previous = not force
while True:
first = stream.read(min(max(16, self._READ_CHUNK_SIZE), self._MAX_FILE_SIZE_BYTES + 1))
if not first:
return f"(Empty file: {path})"
if len(first) > self._MAX_FILE_SIZE_BYTES:
return self._file_too_large(len(first))
content_hash = hashlib.sha256(raw).hexdigest()
if not force and self._file_states.is_unchanged(
fp, offset=offset, limit=limit, content_hash=content_hash,
):
return f"[File unchanged since last read: {path}]"
from nanobot.utils.document import _decode_bom_text
mime = detect_image_mime(first) or mimetypes.guess_type(path)[0]
if mime and mime.startswith("image/"):
chunks = [first]
bytes_read = len(first)
# Bound each read without preallocating from a size that
# may have become stale during the receipt check.
remaining = os.fstat(stream.fileno()).st_size - bytes_read
chunk_size = min(self._IMAGE_READ_CHUNK_SIZE, max(self._READ_CHUNK_SIZE, remaining))
while chunk := stream.read(min(
chunk_size, self._MAX_FILE_SIZE_BYTES + 1 - bytes_read,
)):
bytes_read += len(chunk)
if bytes_read > self._MAX_FILE_SIZE_BYTES:
return self._file_too_large(bytes_read)
chunks.append(chunk)
raw = b"".join(chunks)
del chunks
return build_image_content_blocks(raw, mime, str(fp), f"(Image file: {path})")
text_content = _decode_bom_text(raw)
if text_content is None:
try:
text_content = raw.decode("utf-8")
except UnicodeDecodeError:
# Match the former eager extractor for known text formats while
# keeping arbitrary binary files on the guarded error path.
from nanobot.utils.document import _is_text_extension
if _is_text_extension(fp.suffix.lower()):
text_content = raw.decode("latin-1")
else:
mime = detect_image_mime(raw) or mimetypes.guess_type(path)[0]
if mime and mime.startswith("image/"):
return build_image_content_blocks(
raw,
mime,
str(fp),
f"(Image file: {path})",
)
return ToolResult.error(
f"Error: Cannot read binary file {path} (MIME: {mime or 'unknown'}). "
"Only supported text files and images can be read."
)
if not text_content:
return f"(Empty file: {path})"
# Normalize CRLF -> LF before line-splitting. Primarily a Windows
# concern (git checkouts with autocrlf, editors saving CRLF) but
# applied on all platforms so downstream StrReplace/Grep behavior
# is consistent regardless of where the file was written.
text_content = text_content.replace("\r\n", "\n")
all_lines = text_content.splitlines()
total = len(all_lines)
if offset < 1:
offset = 1
if offset > total:
return ToolResult.error(f"Error: offset {offset} is beyond end of file ({total} lines)")
start = offset - 1
end = min(start + (limit or self._DEFAULT_LIMIT), total)
numbered = [f"{start + i + 1}| {line}" for i, line in enumerate(all_lines[start:end])]
result = "\n".join(numbered)
line_truncated = False
if len(result) > self._MAX_CHARS:
trimmed: list[str] = []
chars = 0
for line in numbered:
extra = len(line) + (1 if trimmed else 0)
if chars + extra > self._MAX_CHARS:
if not trimmed:
trimmed.append(line[: self._MAX_CHARS])
line_truncated = True
break
trimmed.append(line)
chars += extra
end = start + len(trimmed)
result = "\n".join(trimmed)
if line_truncated:
result += (
f"\n\n(Line {offset} truncated; its remaining characters are not shown. "
"Use exec with a targeted command to inspect the omitted content.)"
)
if end < total:
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, content_hash=content_hash, result=result,
)
return result
previous_hash = (
self._file_states.visible_read_hash(fp, offset=offset, limit=limit)
if check_previous else None
)
if previous_hash is None:
return self._read_text(stream, first, fp, path, mime, offset, limit)
digest = hashlib.sha256(first)
bytes_read = len(first)
while chunk := stream.read(min(
self._READ_CHUNK_SIZE, self._MAX_FILE_SIZE_BYTES + 1 - bytes_read,
)):
bytes_read += len(chunk)
if bytes_read > self._MAX_FILE_SIZE_BYTES:
return self._file_too_large(bytes_read)
digest.update(chunk)
if digest.hexdigest() == previous_hash:
return f"[File unchanged since last read: {path}]"
# Re-detect the file after rewinding: it may have changed
# type while the previous receipt was being checked.
stream.seek(0)
check_previous = False
except PermissionError as e:
return ToolResult.error(f"Error: {e}")
except Exception as e:
return ToolResult.error(f"Error reading file: {e}")
def _file_too_large(self, size: int) -> str:
size_mib = size / (1024 * 1024)
max_mib = self._MAX_FILE_SIZE_BYTES // (1024 * 1024)
return ToolResult.error(
f"Error: File too large to read ({size_mib:.1f} MiB). Maximum is {max_mib} MiB."
)
def _read_text(
self, stream: BinaryIO, first: bytes, fp: Path, path: str, mime: str | None,
offset: int, limit: int | None,
) -> str:
from nanobot.utils.document import _is_text_extension
bom_length = 0
if first.startswith(codecs.BOM_UTF8):
encoding, bom_length = "utf-8", len(codecs.BOM_UTF8)
elif first.startswith(codecs.BOM_UTF32_LE):
encoding, bom_length = "utf-32-le", len(codecs.BOM_UTF32_LE)
elif first.startswith(codecs.BOM_UTF32_BE):
encoding, bom_length = "utf-32-be", len(codecs.BOM_UTF32_BE)
elif first.startswith(codecs.BOM_UTF16_LE):
encoding, bom_length = "utf-16-le", len(codecs.BOM_UTF16_LE)
elif first.startswith(codecs.BOM_UTF16_BE):
encoding, bom_length = "utf-16-be", len(codecs.BOM_UTF16_BE)
else:
encoding = "utf-8"
selected_offset = max(1, offset)
selected_limit = limit or self._DEFAULT_LIMIT
text = _TextRange(selected_offset, selected_limit, self._MAX_CHARS)
# ASCII is identical in UTF-8 and Latin-1. Fork the accumulated range
# only when a non-ASCII byte makes the two interpretations differ.
allow_latin = not bom_length and _is_text_extension(fp.suffix.lower())
latin: _TextRange | None = None
decoder = codecs.getincrementaldecoder(encoding)(errors="strict")
digest = hashlib.sha256()
bytes_read = 0
decoded_bytes = 0
decode_error: str | None = None
chunk = first
while chunk:
bytes_read += len(chunk)
if bytes_read > self._MAX_FILE_SIZE_BYTES:
return self._file_too_large(bytes_read)
digest.update(chunk)
payload = chunk[bom_length:] if bytes_read == len(chunk) else chunk
if allow_latin:
if latin is None and not payload.isascii():
latin = deepcopy(text)
if latin is not None:
latin.feed(payload.decode("latin-1"))
if decode_error is None:
buffered = len(decoder.getstate()[0])
try:
text.feed(decoder.decode(payload, final=False))
except UnicodeDecodeError as e:
# utf-8-sig reports positions after the BOM; utf-16/32
# report them in the complete original byte sequence.
base = bom_length if encoding != "utf-8" else 0
decode_error = _decode_error_message(e, base + decoded_bytes - buffered)
decoded_bytes += len(payload)
chunk = stream.read(min(self._READ_CHUNK_SIZE, self._MAX_FILE_SIZE_BYTES + 1 - bytes_read))
if decode_error is None:
buffered = len(decoder.getstate()[0])
try:
text.feed(decoder.decode(b"", final=True))
except UnicodeDecodeError as e:
base = bom_length if encoding != "utf-8" else 0
decode_error = _decode_error_message(e, base + decoded_bytes - buffered)
content_hash = digest.hexdigest()
if decode_error is not None:
if bom_length:
return ToolResult.error(f"Error reading file: {decode_error}")
if latin is None:
return ToolResult.error(
f"Error: Cannot read binary file {path} (MIME: {mime or 'unknown'}). "
"Only supported text files and images can be read."
)
text = latin
text.finish()
total = text.total
if total == 0:
return f"(Empty file: {path})"
offset = selected_offset
if offset > total:
return ToolResult.error(f"Error: offset {offset} is beyond end of file ({total} lines)")
numbered = text.numbered
line_truncated = text.line_truncated
end = offset - 1 + len(numbered)
result = "\n".join(numbered)
if line_truncated:
result += (
f"\n\n(Line {offset} truncated; its remaining characters are not shown. "
"Use exec with a targeted command to inspect the omitted content.)"
)
if end < total:
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, content_hash=content_hash, result=result,
)
return result
def _read_pdf(self, fp: Path, pages: str | None) -> str:
from nanobot.utils.document import PdfPageRangeError, PdfSafetyError, extract_pdf_pages
+15 -21
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import asyncio
import json
from collections.abc import Mapping
from typing import Any
@@ -104,13 +103,10 @@ class SearchSessionsTool(_SessionTool):
query = query.strip()
if not query:
return ToolResult.error("Error: search query must not be empty")
matches = await asyncio.to_thread(
self._access.search,
query,
_SEARCH_LIMIT,
validated = await self._access.asearch(
query, _SEARCH_LIMIT, handles=self._handles,
exclude_session_key=current_request_session_key(),
)
handles = await self._handles.alist_all_by_key() if matches else {}
needle = query.casefold()
result = {
"notice": _UNTRUSTED_NOTICE,
@@ -119,10 +115,7 @@ class SearchSessionsTool(_SessionTool):
{
"session_key": match["session_key"],
"session_ref": _session_ref(match["session_key"]),
"handle": (
f"@{handles[match['session_key']].name}"
if match["session_key"] in handles else None
),
"handle": f"@{handle}" if handle is not None else None,
"title": match["title"],
"updated_at": match["updated_at"],
"excerpts": [
@@ -136,7 +129,7 @@ class SearchSessionsTool(_SessionTool):
for message in match["messages"]
],
}
for match in matches
for match, handle in validated
],
}
return json.dumps(result, ensure_ascii=False)
@@ -180,7 +173,7 @@ class ReadSessionTool(_SessionTool):
session_key = session_key.strip()
if not session_key:
return ToolResult.error("Error: session_key must not be empty")
session_handle: str | None = None
handle_name: str | None = None
if session_key.startswith("@"):
try:
handle_name = normalize_session_handle(session_key)
@@ -189,7 +182,6 @@ class ReadSessionTool(_SessionTool):
handle = await self._handles.aresolve(handle_name)
if handle is None:
return ToolResult.error(f"Error: session @{handle_name} was not found")
session_handle = f"@{handle_name}"
session_key = handle.session_key
query_text = query.strip() if query else ""
if query_text in _UNSUPPORTED_MATCH_ALL_QUERIES:
@@ -197,17 +189,19 @@ class ReadSessionTool(_SessionTool):
"Error: query matches literal substrings; '*' and '.*' do not mean match all. "
"Omit query to read the latest messages."
)
match = await asyncio.to_thread(
self._access.read,
match = await self._access.aread(
session_key,
query=query_text,
limit=_READ_LIMIT,
exclude_session_key=current_request_session_key(),
)
if match is None:
return ToolResult.error(
f"Error: session not found: {session_handle or session_key}"
)
validated = await self._access.avalidate(
[match], {session_key: handle_name} if handle_name is not None else {},
) if match is not None else []
if not validated or (handle_name is not None and validated[0][1] is None):
reference = f"@{handle_name}" if handle_name is not None else session_key
return ToolResult.error(f"Error: session not found: {reference}")
match = validated[0][0]
needle = query_text.casefold()
result: dict[str, Any] = {
"notice": _UNTRUSTED_NOTICE,
@@ -218,8 +212,8 @@ class ReadSessionTool(_SessionTool):
for message in match["messages"]
],
}
if session_handle is not None:
result["handle"] = session_handle
if handle_name is not None:
result["handle"] = f"@{handle_name}"
else:
result.update({
"session_key": match["session_key"],