Skip to content

Your lightweight open-source personal agent.

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

chengyongru1a89a25abd68
diff --git a/nanobot/agent/tools/file_state.py b/nanobot/agent/tools/file_state.py
index 45fdede6c..12acbaf5d 100644
--- a/nanobot/agent/tools/file_state.py
+++ b/nanobot/agent/tools/file_state.py
@@ -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."""
diff --git a/nanobot/agent/tools/filesystem.py b/nanobot/agent/tools/filesystem.py
index 42c475e42..62396660c 100644
--- a/nanobot/agent/tools/filesystem.py
+++ b/nanobot/agent/tools/filesystem.py
@@ -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})"
-
- 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})")
-
- 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
-
- 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
+ # 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)
+
+ 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))
+
+ 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})")
+
+ 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
diff --git a/nanobot/agent/tools/sessions.py b/nanobot/agent/tools/sessions.py
index 9fc2a9950..a288a54b8 100644
--- a/nanobot/agent/tools/sessions.py
+++ b/nanobot/agent/tools/sessions.py
@@ -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"],
diff --git a/nanobot/providers/openai_compat_provider.py b/nanobot/providers/openai_compat_provider.py
index e5d917435..3a9983748 100644
--- a/nanobot/providers/openai_compat_provider.py
+++ b/nanobot/providers/openai_compat_provider.py
@@ -12,9 +12,10 @@ import string
import time
import uuid
from collections import deque
-from collections.abc import AsyncIterator, Awaitable, Callable, Iterable
+from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Iterable
+from contextlib import asynccontextmanager
from ipaddress import ip_address
-from typing import TYPE_CHECKING, Any, cast
+from typing import TYPE_CHECKING, Any, TypeVar, cast
from urllib.parse import urlparse
from loguru import logger
@@ -110,6 +111,47 @@ _MIMO_THINKING_MODELS: frozenset[str] = frozenset({
})
_OPENAI_COMPAT_REQUEST_TIMEOUT_S = 120.0
+
+class _ChatStreamCloseError(Exception):
+ """A stream finished without a primary error, but its cleanup failed."""
+
+
+class _ChatStreamCallbackError(Exception):
+ def __init__(self, error: Exception) -> None:
+ super().__init__(str(error))
+ self.error = error
+
+
+_Delta = TypeVar("_Delta")
+
+
+async def _emit_chat_delta(callback: Callable[[_Delta], Awaitable[None]], delta: _Delta) -> None:
+ try:
+ await callback(delta)
+ except Exception as error:
+ raise _ChatStreamCallbackError(error) from error
+
+
+@asynccontextmanager
+async def _managed_chat_stream(chat_stream: Any) -> AsyncGenerator[Any, None]:
+ try:
+ yield chat_stream
+ except BaseException as primary_error:
+ try:
+ await chat_stream.close()
+ except Exception as close_error:
+ logger.warning(
+ "OpenAI chat stream cleanup failed after {}: {}",
+ type(primary_error).__name__, close_error,
+ )
+ raise
+ else:
+ try:
+ await chat_stream.close()
+ except Exception as close_error:
+ raise _ChatStreamCloseError(str(close_error)) from close_error
+
+
# Maps ProviderSpec.thinking_style → extra_body builder.
# Each builder takes a bool (thinking_enabled) and returns the dict to
# merge into extra_body, keeping the style→wire-format mapping in one place.
@@ -1422,128 +1464,11 @@ class OpenAICompatProvider(LLMProvider):
)
@classmethod
- def _parse_chunks(cls, chunks: list[Any]) -> LLMResponse:
- content_parts: list[str] = []
- reasoning_parts: list[str] = []
- tc_bufs: dict[int, dict[str, Any]] = {}
- finish_reason = "stop"
- usage: LLMUsage | None = None
-
- def _accum_tc(tc: Any, idx_hint: int) -> None:
- tc_index: int = _get(tc, "index") if _get(tc, "index") is not None else idx_hint
- buf = tc_bufs.setdefault(tc_index, {
- "id": "", "name": "", "arguments": "",
- "extra_content": None, "prov": None, "fn_prov": None,
- })
- tc_id = _get(tc, "id")
- if tc_id:
- buf["id"] = str(tc_id)
- fn = _get(tc, "function")
- if fn is not None:
- fn_name = _get(fn, "name")
- if fn_name:
- buf["name"] = str(fn_name)
- fn_args = _get(fn, "arguments")
- if fn_args:
- buf["arguments"] += str(fn_args)
- ec, prov, fn_prov = _extract_tc_extras(tc)
- if ec:
- buf["extra_content"] = ec
- if prov:
- buf["prov"] = prov
- if fn_prov:
- buf["fn_prov"] = fn_prov
-
- def _accum_legacy_function_call(function_call: Any) -> None:
- if not function_call:
- return
- buf = tc_bufs.setdefault(0, {
- "id": "", "name": "", "arguments": "",
- "extra_content": None, "prov": None, "fn_prov": None,
- })
- fn_name = _get(function_call, "name")
- if fn_name:
- buf["name"] = str(fn_name)
- fn_args = _get(function_call, "arguments")
- if fn_args:
- buf["arguments"] += str(fn_args)
-
+ def _parse_chunks(cls, chunks: Iterable[Any]) -> LLMResponse:
+ accumulator = cls._ChatStreamAccumulator(cls)
for chunk in chunks:
- if isinstance(chunk, str):
- content_parts.append(chunk)
- continue
-
- chunk_map = cls._maybe_mapping(chunk)
- if chunk_map is None:
- raise TypeError(f"Unsupported chat chunk type: {type(chunk).__name__}")
- choices = cast(
- list[object],
- chunk_map.get("choices") or [],
- )
- if not choices:
- usage = cls._extract_usage(chunk_map) or usage
- text = cls._extract_text_content(
- chunk_map.get("content") or chunk_map.get("output_text")
- )
- if text:
- content_parts.append(text)
- continue
- choice = cls._maybe_mapping(choices[0]) or {}
- if choice.get("finish_reason"):
- finish_reason = str(choice["finish_reason"])
- delta = cls._maybe_mapping(choice.get("delta")) or {}
- raw_delta_content = delta.get("content")
- text = cls._extract_text_content(raw_delta_content)
- if text:
- content_parts.append(text)
- text = cls._extract_text_content(delta.get("reasoning_content"))
- if not text:
- text = cls._extract_text_content(delta.get("reasoning"))
- if not text:
- # Mistral streams thinking inside the content array as
- # {"type":"thinking", thinking:[{"type":"text", ...}]}.
- text = cls._extract_thinking_content(raw_delta_content)
- if text:
- reasoning_parts.append(text)
- for idx, tc in enumerate(
- cast(
- Iterable[object],
- delta.get("tool_calls") or [],
- )
- ):
- _accum_tc(tc, idx)
- _accum_legacy_function_call(delta.get("function_call"))
- usage = cls._extract_usage(chunk_map) or usage
-
- # Some providers (e.g. Zhipu/GLM) reuse the same tool_call id for
- # parallel tool calls in streaming mode. Deduplicate before building
- # the response so downstream tool messages don't collide.
- _seen_tc_ids: set[str] = set()
- for b in tc_bufs.values():
- if not b["id"] or b["id"] in _seen_tc_ids:
- b["id"] = _short_tool_id()
- _seen_tc_ids.add(b["id"])
-
- content = "".join(content_parts) or None
- tool_calls = [
- ToolCallRequest(
- id=b["id"] or _short_tool_id(),
- name=b["name"],
- arguments=parse_tool_arguments(b["arguments"]),
- extra_content=b.get("extra_content"),
- provider_specific_fields=b.get("prov"),
- function_provider_specific_fields=b.get("fn_prov"),
- )
- for b in tc_bufs.values()
- ]
-
- return LLMResponse(
- content=content,
- tool_calls=tool_calls,
- finish_reason=finish_reason,
- usage=usage,
- reasoning_content="".join(reasoning_parts) or None,
- )
+ accumulator.add(chunk)
+ return accumulator.finish()
@classmethod
def _extract_error_metadata(cls, e: Exception) -> dict[str, Any]:
@@ -1757,66 +1682,89 @@ class OpenAICompatProvider(LLMProvider):
Any,
await client.chat.completions.create(**kwargs),
)
- chunks: list[Any] = []
- completed = False
- stream_iter: AsyncIterator[Any] = chat_stream.__aiter__()
- while True:
- try:
- chunk: Any = await asyncio.wait_for(
- stream_iter.__anext__(),
- timeout=idle_timeout_s,
- )
- except StopAsyncIteration:
- break
- chunks.append(chunk)
- if chunk.choices:
- completed |= bool(chunk.choices[0].finish_reason)
- delta_obj = chunk.choices[0].delta
- raw_delta_content = getattr(delta_obj, "content", None)
- if on_content_delta:
- # Mistral streams content as a list of {"type":"thinking",
- # ...} + {"type":"text",...} blocks. Extract just the
- # text portion before invoking the callback so callers
- # never see non-string content.
- text = self._extract_text_content(raw_delta_content)
- if text:
- await on_content_delta(text)
- if on_thinking_delta:
- reasoning = getattr(delta_obj, "reasoning_content", None) or getattr(
- delta_obj, "reasoning", None,
+ async with _managed_chat_stream(chat_stream) as stream:
+ accumulator = self._ChatStreamAccumulator(type(self))
+ parse_error: Exception | None = None
+ completed = False
+ stream_iter: AsyncIterator[Any] = stream.__aiter__()
+ while True:
+ try:
+ chunk: Any = await asyncio.wait_for(
+ stream_iter.__anext__(),
+ timeout=idle_timeout_s,
)
- r_text = self._extract_text_content(reasoning)
- if not r_text:
- # Mistral keeps the thinking trace inside the
- # content array rather than a separate field.
- r_text = self._extract_thinking_content(raw_delta_content)
- if r_text:
- await on_thinking_delta(r_text)
- if on_tool_call_delta:
- for idx, tool_delta in enumerate(
- getattr(delta_obj, "tool_calls", None) or []
- ):
- fn = _get(tool_delta, "function")
- tool_index = _get(tool_delta, "index")
- await on_tool_call_delta({
- "index": tool_index if tool_index is not None else idx,
- "call_id": str(_get(tool_delta, "id") or ""),
- "name": str(_get(fn, "name") or "") if fn is not None else "",
- "arguments_delta": (
- str(_get(fn, "arguments") or "") if fn is not None else ""
- ),
- })
- function_call = getattr(delta_obj, "function_call", None)
- if function_call:
- await on_tool_call_delta({
- "index": 0,
- "call_id": "",
- "name": str(_get(function_call, "name") or ""),
- "arguments_delta": str(_get(function_call, "arguments") or ""),
- })
- if not completed:
- raise ConnectionError("Model stream ended before a finish reason was received")
- return self._parse_chunks(chunks)
+ except StopAsyncIteration:
+ break
+ if chunk.choices:
+ completed |= bool(chunk.choices[0].finish_reason)
+ delta_obj = chunk.choices[0].delta
+ raw_delta_content = getattr(delta_obj, "content", None)
+ if on_content_delta:
+ # Mistral streams content as a list of {"type":"thinking",
+ # ...} + {"type":"text",...} blocks. Extract just the
+ # text portion before invoking the callback so callers
+ # never see non-string content.
+ text = self._extract_text_content(raw_delta_content)
+ if text:
+ await _emit_chat_delta(on_content_delta, text)
+ if on_thinking_delta:
+ reasoning = getattr(delta_obj, "reasoning_content", None) or getattr(
+ delta_obj, "reasoning", None,
+ )
+ r_text = self._extract_text_content(reasoning)
+ if not r_text:
+ # Mistral keeps the thinking trace inside the
+ # content array rather than a separate field.
+ r_text = self._extract_thinking_content(raw_delta_content)
+ if r_text:
+ await _emit_chat_delta(on_thinking_delta, r_text)
+ if on_tool_call_delta:
+ for idx, tool_delta in enumerate(
+ getattr(delta_obj, "tool_calls", None) or []
+ ):
+ fn = _get(tool_delta, "function")
+ tool_index = _get(tool_delta, "index")
+ await _emit_chat_delta(on_tool_call_delta, {
+ "index": tool_index if tool_index is not None else idx,
+ "call_id": str(_get(tool_delta, "id") or ""),
+ "name": str(_get(fn, "name") or "") if fn is not None else "",
+ "arguments_delta": (
+ str(_get(fn, "arguments") or "") if fn is not None else ""
+ ),
+ })
+ function_call = getattr(delta_obj, "function_call", None)
+ if function_call:
+ await _emit_chat_delta(on_tool_call_delta, {
+ "index": 0,
+ "call_id": "",
+ "name": str(_get(function_call, "name") or ""),
+ "arguments_delta": str(_get(function_call, "arguments") or ""),
+ })
+ if parse_error is None:
+ try:
+ accumulator.add(chunk)
+ except Exception as e:
+ # The old parser ran after streaming: keep its first error,
+ # but let later callbacks and stream failures take priority.
+ # A traceback would retain the failed SDK chunk until EOF.
+ parse_error = e.with_traceback(None)
+ if not completed:
+ raise ConnectionError("Model stream ended before a finish reason was received")
+ if parse_error is not None:
+ raise parse_error
+ return accumulator.finish()
+ except _ChatStreamCallbackError as e:
+ response = self._handle_error(e.error, spec=self._spec, api_base=self.api_base)
+ response.error_kind = "callback"
+ response.error_should_retry = False
+ return response
+ except _ChatStreamCloseError as e:
+ return LLMResponse(
+ content=f"Error closing LLM stream: {e}",
+ finish_reason="error",
+ error_kind="cleanup",
+ error_should_retry=False,
+ )
except asyncio.TimeoutError:
return LLMResponse(
content=(
@@ -1829,5 +1777,132 @@ class OpenAICompatProvider(LLMProvider):
except Exception as e:
return self._handle_error(e, spec=self._spec, api_base=self.api_base)
+ async def _retry_without_images(
+ self,
+ call: Callable[..., Awaitable[LLMResponse]],
+ kw: dict[str, Any],
+ original_messages: list[dict[str, Any]],
+ response: LLMResponse,
+ ) -> LLMResponse:
+ # Neither a callback nor a cleanup failure indicates image incompatibility.
+ if response.error_kind in {"callback", "cleanup"}:
+ return response
+ return await super()._retry_without_images(call, kw, original_messages, response)
+
def get_default_model(self) -> str:
return self.default_model
+
+
+ class _ChatStreamAccumulator:
+ """Build one response without retaining the SDK's completed chunks."""
+
+ def __init__(self, parser: type[OpenAICompatProvider]) -> None:
+ self._parser = parser
+ self._content_parts: list[str] = []
+ self._reasoning_parts: list[str] = []
+ self._tool_calls: dict[int, dict[str, Any]] = {}
+ self._finish_reason = "stop"
+ self._usage: LLMUsage | None = None
+
+ def _tool_call(self, index: int) -> dict[str, Any]:
+ return self._tool_calls.setdefault(index, {
+ "id": "", "name": "", "arguments": "",
+ "extra_content": None, "prov": None, "fn_prov": None,
+ })
+
+ def _accum_tc(self, tc: Any, idx_hint: int) -> None:
+ tc_index: int = _get(tc, "index") if _get(tc, "index") is not None else idx_hint
+ buf = self._tool_call(tc_index)
+ tc_id = _get(tc, "id")
+ if tc_id:
+ buf["id"] = str(tc_id)
+ fn = _get(tc, "function")
+ if fn is not None:
+ fn_name = _get(fn, "name")
+ if fn_name:
+ buf["name"] = str(fn_name)
+ fn_args = _get(fn, "arguments")
+ if fn_args:
+ buf["arguments"] += str(fn_args)
+ ec, prov, fn_prov = _extract_tc_extras(tc)
+ if ec:
+ buf["extra_content"] = ec
+ if prov:
+ buf["prov"] = prov
+ if fn_prov:
+ buf["fn_prov"] = fn_prov
+
+ def _accum_legacy_function_call(self, function_call: Any) -> None:
+ if not function_call:
+ return
+ buf = self._tool_call(0)
+ fn_name = _get(function_call, "name")
+ if fn_name:
+ buf["name"] = str(fn_name)
+ fn_args = _get(function_call, "arguments")
+ if fn_args:
+ buf["arguments"] += str(fn_args)
+
+ def add(self, chunk: Any) -> None:
+ if isinstance(chunk, str):
+ self._content_parts.append(chunk)
+ return
+
+ cls = self._parser
+ chunk_map = cls._maybe_mapping(chunk)
+ if chunk_map is None:
+ raise TypeError(f"Unsupported chat chunk type: {type(chunk).__name__}")
+ choices = cast(list[object], chunk_map.get("choices") or [])
+ if not choices:
+ self._usage = cls._extract_usage(chunk_map) or self._usage
+ text = cls._extract_text_content(
+ chunk_map.get("content") or chunk_map.get("output_text")
+ )
+ if text:
+ self._content_parts.append(text)
+ return
+ choice = cls._maybe_mapping(choices[0]) or {}
+ if choice.get("finish_reason"):
+ self._finish_reason = str(choice["finish_reason"])
+ delta = cls._maybe_mapping(choice.get("delta")) or {}
+ raw_delta_content = delta.get("content")
+ text = cls._extract_text_content(raw_delta_content)
+ if text:
+ self._content_parts.append(text)
+ text = cls._extract_text_content(delta.get("reasoning_content"))
+ if not text:
+ text = cls._extract_text_content(delta.get("reasoning"))
+ if not text:
+ text = cls._extract_thinking_content(raw_delta_content)
+ if text:
+ self._reasoning_parts.append(text)
+ for idx, tc in enumerate(cast(Iterable[object], delta.get("tool_calls") or [])):
+ self._accum_tc(tc, idx)
+ self._accum_legacy_function_call(delta.get("function_call"))
+ self._usage = cls._extract_usage(chunk_map) or self._usage
+
+ def finish(self) -> LLMResponse:
+ # Some providers reuse the same ID for parallel calls.
+ seen_ids: set[str] = set()
+ for buf in self._tool_calls.values():
+ if not buf["id"] or buf["id"] in seen_ids:
+ buf["id"] = _short_tool_id()
+ seen_ids.add(buf["id"])
+ tool_calls = [
+ ToolCallRequest(
+ id=buf["id"] or _short_tool_id(),
+ name=buf["name"],
+ arguments=parse_tool_arguments(buf["arguments"]),
+ extra_content=buf.get("extra_content"),
+ provider_specific_fields=buf.get("prov"),
+ function_provider_specific_fields=buf.get("fn_prov"),
+ )
+ for buf in self._tool_calls.values()
+ ]
+ return LLMResponse(
+ content="".join(self._content_parts) or None,
+ tool_calls=tool_calls,
+ finish_reason=self._finish_reason,
+ usage=self._usage,
+ reasoning_content="".join(self._reasoning_parts) or None,
+ )
diff --git a/nanobot/providers/openai_responses/state.py b/nanobot/providers/openai_responses/state.py
index 523dc0568..a60fe39bf 100644
--- a/nanobot/providers/openai_responses/state.py
+++ b/nanobot/providers/openai_responses/state.py
@@ -55,21 +55,22 @@ def prepare_responses_input(
When no compatible state exists, it is converted normally as a safe
fallback.
"""
- instructions, fallback_items = convert_messages(
- messages,
- preserve_reasoning=preserve_reasoning,
+ prior_items = (
+ _state_items(state)
+ if state is not None and responses_state_matches(state, provider=provider, model=model)
+ else None
)
- if state is None or not responses_state_matches(
- state,
- provider=provider,
- model=model,
- ):
- return instructions, fallback_items, False
-
- prior_items = _state_items(state)
if prior_items is None:
- return instructions, fallback_items, False
-
+ instructions, items = convert_messages(messages, preserve_reasoning=preserve_reasoning)
+ return instructions, items, False
+
+ instructions = ""
+ for message in reversed(messages):
+ if message.get("role") == "system":
+ content = message.get("content")
+ instructions = content if isinstance(content, str) else ""
+ break
+ assert state is not None
_, delta_items = convert_messages(
state.pending_messages,
preserve_reasoning=preserve_reasoning,
diff --git a/nanobot/session/history.py b/nanobot/session/history.py
index 2d0d720d1..4cea520a6 100644
--- a/nanobot/session/history.py
+++ b/nanobot/session/history.py
@@ -1,11 +1,21 @@
from __future__ import annotations
-from collections.abc import Mapping
-from typing import Any, TypedDict, cast
+import asyncio
+import threading
+from collections.abc import Callable, Iterator, Mapping
+from concurrent.futures import CancelledError
+from typing import Any, TypedDict, TypeVar, cast
from nanobot.runtime_context import public_history_message
from nanobot.session.history_visibility import is_hidden_history_message
-from nanobot.session.manager import SessionManager
+from nanobot.session.manager import SessionHistoryPayload, SessionManager, metadata_title
+from nanobot.session.session_handles import (
+ SESSION_HANDLE_METADATA_KEY,
+ SessionHandleResolver,
+ normalize_session_handle,
+)
+
+_T = TypeVar("_T")
class SessionMessage(TypedDict):
@@ -17,16 +27,85 @@ class SessionMessage(TypedDict):
class SessionMatch(TypedDict):
session_key: str
+ generation: str
title: str
updated_at: str | None
messages: list[SessionMessage]
+def _check_cancelled(cancelled: threading.Event | None) -> None:
+ if cancelled is not None and cancelled.is_set():
+ raise CancelledError()
+
+
+async def _run_cancellable(operation: Callable[[threading.Event], _T]) -> _T:
+ """Cancel queued work immediately; drain a started transaction before returning."""
+ cancelled = threading.Event()
+ start_lock = threading.Lock()
+ started = False
+
+ def run() -> _T:
+ nonlocal started
+ # Cancellation and entry into the operation have one atomic ownership
+ # handoff. A dequeued worker may not touch the database after cancellation.
+ with start_lock:
+ if cancelled.is_set():
+ raise CancelledError()
+ started = True
+ return operation(cancelled)
+
+ worker = asyncio.create_task(asyncio.to_thread(run))
+ try:
+ return await asyncio.shield(worker)
+ except asyncio.CancelledError as cancellation:
+ with start_lock:
+ cancelled.set()
+ drain = started
+ if not drain:
+ worker.cancel()
+ raise
+ while not worker.done():
+ try:
+ await asyncio.shield(worker)
+ except asyncio.CancelledError:
+ # Repeated caller cancellation must not orphan an active reader.
+ continue
+ except BaseException:
+ break
+ try:
+ worker.result()
+ except (CancelledError, asyncio.CancelledError):
+ pass
+ except BaseException as exc:
+ # Preserve unexpected worker failures while cancellation still wins.
+ raise cancellation from exc
+ raise
+
+
def _text(value: object) -> str:
return value.strip()[:160] if isinstance(value, str) else ""
-def _message_text(message: Mapping[str, Any]) -> str:
+def _title_rank(title: str, needle: str) -> int | None:
+ folded = title.casefold()
+ return (
+ 0 if folded == needle
+ else 1 if folded.startswith(needle)
+ else 2 if needle in folded
+ else None
+ )
+
+
+def _handle_name(raw: object) -> str | None:
+ if not isinstance(raw, str):
+ return None
+ try:
+ return normalize_session_handle(raw)
+ except ValueError:
+ return None
+
+
+def _message_text(message: Mapping[str, Any], cancelled: threading.Event | None) -> str:
content = message.get("content")
if isinstance(content, str):
return content.strip()
@@ -34,6 +113,7 @@ def _message_text(message: Mapping[str, Any]) -> str:
return ""
parts: list[str] = []
for raw_block in cast(list[object], content):
+ _check_cancelled(cancelled)
if not isinstance(raw_block, dict):
continue
block = cast(dict[object, object], raw_block)
@@ -43,21 +123,18 @@ def _message_text(message: Mapping[str, Any]) -> str:
return "\n".join(parts).strip()
-def _matching_messages(raw_messages: object, *, needle: str, limit: int) -> list[SessionMessage]:
- if not isinstance(raw_messages, list):
- return []
- messages = cast(list[object], raw_messages)
+def _matching_messages(
+ messages: Iterator[tuple[int, dict[str, Any]]], *, needle: str, limit: int,
+ cancelled: threading.Event | None,
+) -> list[SessionMessage]:
matches: list[SessionMessage] = []
- for index in range(len(messages) - 1, -1, -1):
- raw_message = messages[index]
- if not isinstance(raw_message, dict):
- continue
- message = cast(dict[str, Any], raw_message)
+ for index, message in messages:
+ _check_cancelled(cancelled)
role = message.get("role")
if role not in {"user", "assistant"} or message.get("_command") or is_hidden_history_message(message):
continue
public = public_history_message(message)
- text = _message_text(public)
+ text = _message_text(public, cancelled)
if not text or (needle and needle not in text.casefold()):
continue
timestamp = public.get("timestamp")
@@ -73,61 +150,129 @@ def _matching_messages(raw_messages: object, *, needle: str, limit: int) -> list
return matches
+_SearchCandidate = tuple[int, int, str | SessionMatch]
+_SearchMatch = tuple[int, int, SessionMatch]
+
+
class SessionHistoryReader:
"""Search full persisted history, including messages before summary checkpoints."""
def __init__(self, sessions: SessionManager) -> None:
self._sessions = sessions
- def search(
- self,
- query: str,
- limit: int,
- *,
+ async def asearch(
+ self, query: str, limit: int, *, handles: SessionHandleResolver,
exclude_session_key: str | None = None,
+ ) -> list[tuple[SessionMatch, str | None]]:
+ candidates, matches = await _run_cancellable(lambda cancelled: self._start_search(
+ query, limit, exclude_session_key, cancelled,
+ ))
+ if not matches:
+ return []
+ resolved = await handles.alist_all_by_key()
+ names = {key: handle.name for key, handle in resolved.items()}
+ return await _run_cancellable(lambda cancelled: self._sessions.read_batch(
+ lambda: self._complete_search(query, candidates, matches, names, limit, cancelled),
+ ))
+
+ def search(
+ self, query: str, limit: int, *, exclude_session_key: str | None = None,
+ cancelled: threading.Event | None = None,
) -> list[SessionMatch]:
+ _, matches = self._start_search(query, limit, exclude_session_key, cancelled)
+ return [match for _, _, match in matches]
+
+ def _start_search(
+ self, query: str, limit: int, exclude_session_key: str | None,
+ cancelled: threading.Event | None,
+ ) -> tuple[list[_SearchCandidate], list[_SearchMatch]]:
+ candidates: list[_SearchCandidate] = []
needle = query.casefold()
- ranked: list[tuple[int, SessionMatch]] = []
- remaining: list[dict[str, Any]] = []
- for row in self._sessions.list_sessions():
- key = row.get("key")
- if not isinstance(key, str) or key == exclude_session_key:
- continue
- payload = self._sessions.read_session_metadata(key)
- if payload is None:
- continue
- raw_metadata = cast(object, payload.get("metadata"))
- metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
- if not self._sessions.types.public_history(metadata):
- continue
- title = _text(row.get("title"))
- folded = title.casefold()
- rank = (
- 0 if folded == needle
- else 1 if folded.startswith(needle)
- else 2 if needle in folded
- else None
+
+ def headers() -> None:
+ # Capture ranking and visibility together, then release the snapshot
+ # before scanning any history. The last candidate is the next to visit.
+ for position, row in enumerate(self._sessions.list_sessions()):
+ _check_cancelled(cancelled)
+ key = row.get("key")
+ if not isinstance(key, str) or key == exclude_session_key:
+ continue
+ payload = self._sessions.read_history_header(key)
+ if payload is None or not self._sessions.types.public_history(payload["metadata"]):
+ continue
+ title = _text(row.get("title"))
+ rank = _title_rank(title, needle)
+ if rank is None:
+ candidates.append((3, position, key))
+ continue
+ updated = row.get("updated_at")
+ candidates.append((rank, position, {
+ "session_key": key,
+ "generation": payload["generation"],
+ "title": title,
+ "updated_at": updated if isinstance(updated, str) else None,
+ "messages": [],
+ }))
+
+ def start() -> list[_SearchMatch]:
+ self._sessions.read_consistently(headers, cancelled=cancelled)
+ candidates.sort(key=lambda item: (item[0], item[1]), reverse=True)
+ return self._take_matches(query, candidates, limit, cancelled)
+
+ matches = self._sessions.read_batch(start)
+ return candidates, matches
+
+ def _take_matches(
+ self, query: str, candidates: list[_SearchCandidate], limit: int,
+ cancelled: threading.Event | None,
+ ) -> list[_SearchMatch]:
+ matches: list[_SearchMatch] = []
+ needle = query.casefold()
+ while candidates and len(matches) < limit:
+ _check_cancelled(cancelled)
+ rank, position, candidate = candidates.pop()
+ if isinstance(candidate, str):
+ # A body match needs a fresh header and history from one snapshot.
+ match = self.read(candidate, query=query, limit=2, cancelled=cancelled, _for_search=True)
+ if match is None:
+ continue
+ title_rank = _title_rank(match["title"], needle)
+ if title_rank is not None:
+ rank = title_rank
+ match["messages"] = []
+ elif match["messages"]:
+ match["title"] = match["title"] or _text(match["messages"][0]["content"])
+ else:
+ continue
+ else:
+ match = candidate
+ matches.append((rank, position, match))
+ return sorted(matches, key=lambda item: (item[0], item[1]))
+
+ def _complete_search(
+ self, query: str, candidates: list[_SearchCandidate], matches: list[_SearchMatch],
+ handles: Mapping[str, str], limit: int, cancelled: threading.Event,
+ ) -> list[tuple[SessionMatch, str | None]]:
+ while True:
+ _check_cancelled(cancelled)
+ valid = self._validate(
+ [match for _, _, match in matches], handles, cancelled,
+ conflict_minimum=limit if candidates else 0,
)
- if rank is None:
- remaining.append(row)
- continue
- updated = row.get("updated_at")
- ranked.append((rank, {
- "session_key": key,
- "title": title,
- "updated_at": updated if isinstance(updated, str) else None,
- "messages": [],
- }))
+ if len(valid) >= limit or not candidates:
+ return valid
+ keys = {match["session_key"] for match, _ in valid}
+ matches = [item for item in matches if item[2]["session_key"] in keys]
+ matches.extend(self._take_matches(query, candidates, limit - len(matches), cancelled))
+ matches.sort(key=lambda item: (item[0], item[1]))
- ranked.sort(key=lambda item: item[0])
- for row in remaining:
- if len(ranked) >= limit:
- break
- match = self.read(cast(str, row["key"]), query=query, limit=2)
- if match is not None and match["messages"]:
- match["title"] = _text(row.get("title")) or _text(match["messages"][0]["content"])
- ranked.append((3, match))
- return [item[1] for item in ranked[:limit]]
+ async def aread(
+ self, session_key: str, *, query: str, limit: int,
+ exclude_session_key: str | None = None,
+ ) -> SessionMatch | None:
+ return await _run_cancellable(lambda cancelled: self.read(
+ session_key, query=query, limit=limit, exclude_session_key=exclude_session_key, cancelled=cancelled,
+ ))
def read(
self,
@@ -136,20 +281,88 @@ class SessionHistoryReader:
query: str,
limit: int,
exclude_session_key: str | None = None,
+ cancelled: threading.Event | None = None,
+ _for_search: bool = False,
) -> SessionMatch | None:
if session_key == exclude_session_key:
return None
- payload = self._sessions.read_session_file(session_key)
- if payload is None:
- return None
- raw_metadata = cast(object, payload.get("metadata"))
- metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
- if not self._sessions.types.public_history(metadata):
- return None
- updated = payload.get("updated_at")
- return {
- "session_key": session_key,
- "title": _text(metadata.get("title")),
- "updated_at": updated if isinstance(updated, str) else None,
- "messages": _matching_messages(payload.get("messages"), needle=query.casefold(), limit=limit),
- }
+
+ def project(
+ payload: SessionHistoryPayload, messages: Iterator[tuple[int, dict[str, Any]]],
+ ) -> SessionMatch | None:
+ _check_cancelled(cancelled)
+ metadata = payload["metadata"]
+ if not self._sessions.types.public_history(metadata):
+ return None
+ updated = payload.get("updated_at")
+ return {
+ "session_key": session_key,
+ "generation": payload["generation"],
+ "title": _text(metadata_title(metadata) if _for_search else metadata.get("title")),
+ "updated_at": updated if isinstance(updated, str) else None,
+ "messages": _matching_messages(
+ messages, needle=query.casefold(), limit=limit, cancelled=cancelled,
+ ),
+ }
+
+ return self._sessions.read_consistently(
+ lambda: self._sessions.project_session_messages(session_key, project), cancelled=cancelled,
+ )
+
+ async def avalidate(
+ self, matches: list[SessionMatch], handles: Mapping[str, str],
+ ) -> list[tuple[SessionMatch, str | None]]:
+ return await _run_cancellable(lambda cancelled: self._validate(matches, handles, cancelled))
+
+ def _validate(
+ self, matches: list[SessionMatch], handles: Mapping[str, str], cancelled: threading.Event,
+ *, conflict_minimum: int = 0,
+ ) -> list[tuple[SessionMatch, str | None]]:
+ def validate() -> list[tuple[SessionMatch, str | None]]:
+ valid: list[tuple[SessionMatch, str | None]] = []
+ for match in matches:
+ _check_cancelled(cancelled)
+ key = match["session_key"]
+ payload = self._sessions.read_history_header(key)
+ if payload is None or payload["generation"] != match["generation"]:
+ continue
+ metadata = payload["metadata"]
+ if not self._sessions.types.public_history(metadata):
+ continue
+ handle = handles.get(key)
+ if (
+ not self._sessions.types.needs_handle(metadata)
+ or _handle_name(metadata.get(SESSION_HANDLE_METADATA_KEY)) != handle
+ ):
+ handle = None
+ valid.append((match, handle))
+
+ if len(valid) < conflict_minimum:
+ return valid
+ names = {handle for _, handle in valid if handle is not None}
+ if not names:
+ return valid
+
+ def conflicts(rows: Iterator[tuple[str, object]]) -> set[str]:
+ seen: set[str] = set()
+ ambiguous: set[str] = set()
+ for key, raw_name in rows:
+ _check_cancelled(cancelled)
+ name = _handle_name(raw_name)
+ if name not in names:
+ continue
+ payload = self._sessions.read_history_header(key)
+ if payload is None or not self._sessions.types.needs_handle(payload["metadata"]):
+ continue
+ if name in seen:
+ ambiguous.add(name)
+ else:
+ seen.add(name)
+ return ambiguous
+
+ # Another process may have imported a duplicate name after the
+ # resolver snapshot. Do not return a handle that could route away.
+ ambiguous = self._sessions.project_session_handle_names(conflicts)
+ return [(match, None if handle in ambiguous else handle) for match, handle in valid]
+
+ return self._sessions.read_consistently(validate, cancelled=cancelled)
diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py
index d23e3eeca..75099fb6e 100644
--- a/nanobot/session/manager.py
+++ b/nanobot/session/manager.py
@@ -2,6 +2,8 @@ from __future__ import annotations
import asyncio
import re
+import threading
+from collections.abc import Iterator
from copy import deepcopy
from dataclasses import dataclass, field
from datetime import datetime
@@ -363,6 +365,10 @@ class SessionMetadataPayload(TypedDict):
metadata: dict[str, Any]
+class SessionHistoryPayload(SessionMetadataPayload):
+ generation: str
+
+
class SessionInfo(TypedDict):
key: str
created_at: str
@@ -610,6 +616,37 @@ class SessionManager:
self._store.append_history(key, facts, expected_generation=session.generation)
self._store.run_write(append)
+ def read_consistently(
+ self, operation: Callable[[], _T], *, cancelled: threading.Event | None = None,
+ ) -> _T:
+ """Run nested repository reads against one committed snapshot."""
+ return self._store.run_read(operation, cancelled=cancelled)
+
+ def read_batch(self, operation: Callable[[], _T]) -> _T:
+ """Reuse a connection without extending nested read snapshots."""
+ return self._store.run_read_batch(operation)
+
+ def read_history_header(self, key: str) -> SessionHistoryPayload | None:
+ """Read the metadata and generation needed by persisted history tools."""
+ return self._store.read_history_header(key)
+
+ def project_session_messages(
+ self,
+ key: str,
+ project: Callable[[SessionHistoryPayload, Iterator[tuple[int, dict[str, Any]]]], _T],
+ ) -> _T | None:
+ """Project a session header and reverse message stream within one snapshot.
+
+ The stream is valid only during the callback.
+ """
+ return self._store.project_session_messages(key, project)
+
+ def project_session_handle_names(
+ self, project: Callable[[Iterator[tuple[str, object]]], _T],
+ ) -> _T:
+ """Project stored handle names within the caller's read snapshot."""
+ return self._store.project_session_handle_names(project)
+
def read_session_file(self, key: str) -> dict[str, Any] | None:
"""Read a session without populating the cache."""
return cast(dict[str, Any] | None, self._store.read(key))
diff --git a/nanobot/session/sqlite_store.py b/nanobot/session/sqlite_store.py
index c9fb5918b..b96af1fa0 100644
--- a/nanobot/session/sqlite_store.py
+++ b/nanobot/session/sqlite_store.py
@@ -4,7 +4,8 @@ import json
import os
import sqlite3
import threading
-from collections.abc import Callable, Generator
+from collections.abc import Callable, Generator, Iterator
+from concurrent.futures import CancelledError
from contextlib import contextmanager, suppress
from datetime import datetime
from pathlib import Path
@@ -16,6 +17,7 @@ from nanobot.session.history_graph import history_record_size
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import (
Session,
+ SessionHistoryPayload,
SessionInfo,
SessionMetadataPayload,
SessionPayload,
@@ -149,10 +151,41 @@ class SqliteSessionStore:
with self.transaction():
return operation()
- def run_read(self, operation: Callable[[], _T]) -> _T:
+ def run_read(
+ self, operation: Callable[[], _T], *, cancelled: threading.Event | None = None,
+ ) -> _T:
"""Run one repository command against a consistent read snapshot."""
- with self.transaction(write=False):
+ with self.transaction(write=False) as db:
+ if cancelled is None:
+ return operation()
+ if cancelled.is_set():
+ raise CancelledError()
+ # Interrupt long SQLite work as well as the Python-level row scans.
+ db.set_progress_handler(cancelled.is_set, 1000)
+ try:
+ return operation()
+ except sqlite3.OperationalError:
+ if cancelled.is_set():
+ raise CancelledError() from None
+ raise
+ finally:
+ db.set_progress_handler(None, 0)
+
+ def run_read_batch(self, operation: Callable[[], _T]) -> _T:
+ """Reuse one connection across independent short read transactions."""
+ if getattr(self._local, "connection", None) is not None or getattr(self._local, "read_batch", None) is not None:
+ return operation()
+ connection: sqlite3.Connection | None = getattr(self._local, "worker_connection", None)
+ owned = connection is None
+ if connection is None:
+ connection = self._open_connection()
+ self._local.read_batch = connection
+ try:
return operation()
+ finally:
+ self._local.read_batch = None
+ if owned:
+ connection.close()
def _open_connection(self, *, worker: bool = False) -> sqlite3.Connection:
if self.path.is_symlink():
@@ -185,7 +218,9 @@ class SqliteSessionStore:
return
if self.path.is_symlink():
raise RuntimeError("session database must not be a symlink")
- connection: sqlite3.Connection | None = getattr(self._local, "worker_connection", None)
+ connection: sqlite3.Connection | None = getattr(self._local, "read_batch", None)
+ if connection is None:
+ connection = getattr(self._local, "worker_connection", None)
owned = connection is None
if connection is None:
connection = self._open_connection()
@@ -432,6 +467,53 @@ class SqliteSessionStore:
return {"key": key, "created_at": row[0], "updated_at": row[1],
"metadata": self._metadata(db, key, row[2])}
+ def read_history_header(self, key: str) -> SessionHistoryPayload | None:
+ """Read search identity and metadata without runtime checkpoints or inputs."""
+ with self.transaction(write=False) as db:
+ row = db.execute(
+ "SELECT created_at, updated_at, metadata, generation FROM sessions WHERE key=?", (key,),
+ ).fetchone()
+ if row is None:
+ return None
+ return {"key": key, "created_at": datetime.fromisoformat(row[0]).isoformat(),
+ "updated_at": datetime.fromisoformat(row[1]).isoformat(),
+ "metadata": _object(row[2]), "generation": row[3]}
+
+ def project_session_messages(
+ self,
+ key: str,
+ project: Callable[[SessionHistoryPayload, Iterator[tuple[int, dict[str, Any]]]], _T],
+ ) -> _T | None:
+ """Project the header and canonical messages without materializing history."""
+ with self.transaction(write=False) as db:
+ header = self.read_history_header(key)
+ if header is None:
+ return None
+ # Indices refer to the ordered message list, not SQLite positions.
+ # Count first so sparse positions retain the same observable indices.
+ count = db.execute(
+ "SELECT COUNT(*) FROM messages WHERE session_key=?", (key,),
+ ).fetchone()[0]
+ rows = db.execute(
+ "SELECT record FROM messages WHERE session_key=? ORDER BY position DESC", (key,),
+ )
+ messages = ((count - 1 - index, _object(row[0])) for index, row in enumerate(rows))
+ try:
+ return project(header, messages)
+ finally:
+ rows.close()
+
+ def project_session_handle_names(
+ self, project: Callable[[Iterator[tuple[str, object]]], _T],
+ ) -> _T:
+ """Stream stored names for handle ambiguity checks in the caller's snapshot."""
+ with self.transaction(write=False) as db:
+ rows = db.execute("SELECT key, json_extract(metadata, '$.session_handle') FROM sessions")
+ try:
+ return project((str(row[0]), cast(object, row[1])) for row in rows)
+ finally:
+ rows.close()
+
def read(self, key: str) -> SessionPayload | None:
session = self.load(key)
if session is None:
diff --git a/tests/agent/test_unified_session.py b/tests/agent/test_unified_session.py
index f0841fbf6..80e8e79f5 100644
--- a/tests/agent/test_unified_session.py
+++ b/tests/agent/test_unified_session.py
@@ -9,6 +9,7 @@ import pytest
from agent.session_helpers import mock_session_manager, run_session
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.file_state import FileStateStore
+from nanobot.agent.tools.filesystem import ReadFileTool
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.command.application import register_builtin_commands
@@ -199,7 +200,10 @@ class TestCmdNewUnifiedSession:
previous_file_state = file_state_store.for_session("unified:default")
tracked_file = tmp_path / "tracked.txt"
tracked_file.write_text("tracked", encoding="utf-8")
- previous_file_state.record_read(tracked_file)
+ await ReadFileTool(workspace=tmp_path, file_states=previous_file_state).execute(
+ path=str(tracked_file),
+ )
+ assert previous_file_state.get(tracked_file) is not None
loop = SimpleNamespace(
sessions=sessions,
consolidator=SimpleNamespace(archive_session=AsyncMock(return_value=True)),
@@ -230,7 +234,7 @@ class TestCmdNewUnifiedSession:
assert reloaded.messages == []
reset_file_state = file_state_store.for_session("unified:default")
assert reset_file_state is not previous_file_state
- assert reset_file_state.is_unchanged(tracked_file) is False
+ assert reset_file_state.get(tracked_file) is None
archived = loop.consolidator.archive_session.call_args.args[0]
assert archived.key == "unified:default"
assert archived.messages == expected_snapshot
diff --git a/tests/agent/tools/test_session_history.py b/tests/agent/tools/test_session_history.py
index 2e927b7da..041b574db 100644
--- a/tests/agent/tools/test_session_history.py
+++ b/tests/agent/tools/test_session_history.py
@@ -1,12 +1,25 @@
from __future__ import annotations
+import asyncio
+import gc
import json
+import sqlite3
+import threading
+import time
+import tracemalloc
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import suppress
+from datetime import datetime
import pytest
from nanobot.agent.tools.context import RequestContext, request_context
from nanobot.agent.tools.sessions import ReadSessionTool, SearchSessionsTool
+from nanobot.runtime_context import RuntimeContextBlock, append_runtime_context
+from nanobot.session.automation_spec import AUTOMATION_HISTORY_META
+from nanobot.session.history import SessionHistoryReader
from nanobot.session.manager import SessionManager
+from nanobot.session.types import SessionType
@pytest.mark.asyncio
@@ -98,3 +111,561 @@ async def test_session_tools_use_canonical_records_after_restart(history, tmp_pa
assert [item["content"] for item in json.loads(read)["messages"]] == ["canonical needle"]
assert display_search["results"] == []
assert durable_files() == original
+
+
+async def test_session_tools_stream_visible_archived_history_with_casefold_and_original_indices(tmp_path):
+ manager = SessionManager(tmp_path)
+ key = "sdk:archived"
+ session = manager.get_or_create(key)
+ session.updated_at = datetime(2025, 1, 2, 3, 4, 5)
+ session.messages = [
+ {"role": "user", "content": "Straße 0"},
+ {"role": "assistant", "content": "STRASSE 1"},
+ {"role": "tool", "content": "Straße tool"},
+ {"role": "user", "content": "Straße hidden", "_hidden_history": True},
+ {"role": "user", "content": "Straße command", "_command": True},
+ {"role": "assistant", "content": [
+ {"type": "text", "text": "Straße 2"},
+ {"type": "image", "url": "unused"},
+ {"type": "text", "text": "second line"},
+ ], "timestamp": 7},
+ ]
+ session.messages.extend({"role": "user", "content": f"Straße {i}"} for i in range(3, 12))
+ session.commit_summary_checkpoint("Archived earlier context")
+ content, marker = append_runtime_context(
+ [{"type": "text", "text": "Straße public"}],
+ [RuntimeContextBlock(source="private", content="private-context-secret")],
+ )
+ session.messages.append({"role": "user", "content": content, "_runtime_context": marker})
+ session.messages.extend(
+ {"role": "assistant", "content": "Straße hidden tail", "_hidden_history": True}
+ for _ in range(12)
+ )
+ session.messages.append({
+ "role": "user", "content": "Straße automation-secret", AUTOMATION_HISTORY_META: {"kind": "trigger"},
+ })
+ manager.save(session)
+ manager._store.set_archived_keys([key])
+
+ with request_context(RequestContext(channel="sdk", chat_id="current", session_key="sdk:current")):
+ read = json.loads(await ReadSessionTool(manager).execute(session_key=key, query="STRASSE"))
+ blocks = json.loads(await ReadSessionTool(manager).execute(session_key=key, query="SECOND LINE"))
+ search = json.loads(await SearchSessionsTool(manager).execute(query="STRASSE"))
+ secret = json.loads(await SearchSessionsTool(manager).execute(query="private-context-secret"))
+ automation = json.loads(await SearchSessionsTool(manager).execute(query="automation-secret"))
+ empty = json.loads(await ReadSessionTool(manager).execute(session_key=key, query="not-present"))
+ assert [item["message_index"] for item in read["messages"]] == [8, 9, 10, 11, 12, 13, 14, 16]
+ assert read["messages"][-1]["content"] == "Straße public"
+ assert read["updated_at"] == "2025-01-02T03:04:05"
+ assert [(m["message_index"], m["content"], m["timestamp"]) for m in blocks["messages"]] == [
+ (5, "Straße 2 second line", 7),
+ ]
+ assert [row["session_key"] for row in search["results"]] == [key]
+ assert search["results"][0]["title"] == "Straße 11"
+ assert [item["message_index"] for item in search["results"][0]["excerpts"]] == [14, 16]
+ assert secret["results"] == []
+ assert automation["results"] == []
+ assert empty["messages"] == []
+ reader = SessionHistoryReader(manager)
+ assert reader.read(key, query="", limit=8, exclude_session_key=key) is None
+ await manager.state.aclose()
+
+
+def test_session_search_ranking_and_visibility_remain_snapshot_based(tmp_path):
+ manager = SessionManager(tmp_path)
+ manager.types.register(SessionType("custom-public", needs_handle=False, public_history=True))
+ manager.types.register(SessionType("custom-private", needs_handle=False, public_history=False))
+ examples = [
+ ("sdk:body", "notes", "custom-public", "Straße in body", 2025),
+ ("sdk:substring", "x Straße", "conversation", "unused", 2023),
+ ("sdk:prefix", "Straße plan", "conversation", "unused", 2022),
+ ("sdk:exact-old", "Straße", "conversation", "unused", 2020),
+ ("sdk:exact-new", "STRASSE", "conversation", "unused", 2021),
+ ("sdk:private", "Straße", "custom-private", "Straße", 2026),
+ ("sdk:unknown", "Straße", "unregistered", "Straße", 2026),
+ ]
+ for key, title, kind, content, year in examples:
+ session = manager.get_or_create(key)
+ session.metadata.update({"title": title, "title_user_edited": True, "session_type": kind})
+ session.messages = [{"role": "user", "content": content}]
+ session.updated_at = datetime(year, 1, 1)
+ manager.save(session)
+
+ reader = SessionHistoryReader(manager)
+ assert [match["session_key"] for match in reader.search("STRASSE", limit=3)] == [
+ "sdk:exact-new", "sdk:exact-old", "sdk:prefix",
+ ]
+ matches = reader.search("STRASSE", limit=5, exclude_session_key="sdk:exact-old")
+ assert [match["session_key"] for match in matches] == [
+ "sdk:exact-new", "sdk:prefix", "sdk:substring", "sdk:body",
+ ]
+ assert [match["title"] for match in matches] == ["STRASSE", "Straße plan", "x Straße", "notes"]
+ assert matches[-1]["messages"][0]["content"] == "Straße in body"
+ assert matches[-1]["updated_at"] == "2025-01-01T00:00:00"
+ assert reader.read("sdk:private", query="", limit=8) is None
+ assert reader.read("sdk:unknown", query="", limit=8) is None
+ assert len(reader.search("", limit=2)) == 2
+ assert reader.search("unmatched", limit=5) == []
+
+
+def test_search_keeps_visibility_title_and_messages_consistent(tmp_path, monkeypatch):
+ manager = SessionManager(tmp_path)
+ session = manager.get_or_create("sdk:history")
+ session.metadata["title"] = "Notes"
+ session.updated_at = datetime(2024, 1, 1)
+ session.messages = [{"role": "user", "content": "old needle"}]
+ manager.save(session)
+ writer = SessionManager(tmp_path)
+ replacement = writer.get_or_create(session.key)
+ replacement.metadata.update({"title": "new title", "session_type": "private"})
+ replacement.updated_at = datetime(2026, 1, 1)
+ replacement.messages = [{"role": "user", "content": "new needle"}]
+ original_list = manager.list_sessions
+
+ def list_then_commit():
+ rows = original_list()
+ writer.save(replacement)
+ return rows
+
+ monkeypatch.setattr(manager, "list_sessions", list_then_commit)
+ reader = SessionHistoryReader(manager)
+ matches = reader.search("needle", limit=5)
+ # A search may omit the now-private session rather than pinning one global
+ # snapshot; if it returns a match, it must not combine the two versions.
+ assert [(match["title"], match["updated_at"], match["messages"][0]["content"]) for match in matches] in (
+ [], [("Notes", "2024-01-01T00:00:00", "old needle")],
+ )
+ assert reader.read(session.key, query="", limit=8) is None
+
+
+def test_read_uses_one_snapshot_for_header_and_messages(tmp_path, monkeypatch):
+ manager = SessionManager(tmp_path)
+ session = manager.get_or_create("sdk:history")
+ session.metadata["title"] = "old title"
+ session.messages = [{"role": "user", "content": "old message"}]
+ manager.save(session)
+ writer = SessionManager(tmp_path)
+ replacement = writer.get_or_create(session.key)
+ replacement.metadata["title"] = "new title"
+ replacement.messages = [{"role": "user", "content": "new message"}]
+ original_public_history = manager.types.public_history
+
+ def commit_after_header(metadata):
+ writer.save(replacement)
+ return original_public_history(metadata)
+
+ monkeypatch.setattr(manager.types, "public_history", commit_after_header)
+ match = SessionHistoryReader(manager).read(session.key, query="", limit=8)
+ assert match["title"] == "old title"
+ assert [message["content"] for message in match["messages"]] == ["old message"]
+
+
+def test_session_read_decodes_only_as_far_as_needed(tmp_path, monkeypatch):
+ from nanobot.session import sqlite_store
+
+ manager = SessionManager(tmp_path)
+ session = manager.get_or_create("sdk:history")
+ session.messages = [
+ {"role": "user", "content": f"message {i}", "_marker": "history-row"}
+ for i in range(100)
+ ]
+ session.messages.append({
+ "role": "user", "content": "hidden", "_marker": "history-row", "_hidden_history": True,
+ })
+ manager.save(session)
+ original_object = sqlite_store._object
+ decoded_rows = []
+
+ def count_rows(raw):
+ result = original_object(raw)
+ if result.get("_marker") == "history-row":
+ decoded_rows.append(result)
+ return result
+
+ monkeypatch.setattr(sqlite_store, "_object", count_rows)
+ reader = SessionHistoryReader(manager)
+ result = reader.read(session.key, query="", limit=8)
+ assert [message["message_index"] for message in result["messages"]] == list(range(92, 100))
+ assert len(decoded_rows) == 9
+
+ decoded_rows.clear()
+ result = reader.read(session.key, query="not-present", limit=8)
+ assert result["messages"] == []
+ assert len(decoded_rows) == 101
+
+
+async def test_session_tool_memory_is_bounded_for_long_persisted_history(tmp_path):
+ manager = SessionManager(tmp_path)
+ session = manager.get_or_create("sdk:history")
+ session.metadata["title"] = "notes"
+ session.messages = [
+ {"role": "user", "content": f"message {i} " + "x" * 2048}
+ for i in range(3000)
+ ]
+ manager.save(session)
+ del session
+ gc.collect()
+
+ for tool, kwargs in (
+ (ReadSessionTool(manager), {"session_key": "sdk:history"}),
+ (SearchSessionsTool(manager), {"query": "not-present"}),
+ ):
+ was_tracing = tracemalloc.is_tracing()
+ if not was_tracing:
+ tracemalloc.start()
+ before, _ = tracemalloc.get_traced_memory()
+ tracemalloc.reset_peak()
+ try:
+ result = json.loads(await tool.execute(**kwargs))
+ _, peak = tracemalloc.get_traced_memory()
+ finally:
+ if not was_tracing:
+ tracemalloc.stop()
+ assert peak - before < 2 * 1024 * 1024
+ if "messages" in result:
+ assert [item["message_index"] for item in result["messages"]] == list(range(2992, 3000))
+ else:
+ assert result["results"] == []
+ if manager._state is not None:
+ await manager.state.aclose()
+
+
[email protected]("tool_name", ["read", "search"])
+async def test_queued_history_tool_cancels_without_starting_a_transaction(tmp_path, monkeypatch, tool_name):
+ manager = SessionManager(tmp_path)
+ session = manager.get_or_create("sdk:history")
+ session.messages = [{"role": "user", "content": "needle"}]
+ manager.save(session)
+ entered, release, queued, transaction = (threading.Event() for _ in range(4))
+
+ class SignallingExecutor(ThreadPoolExecutor):
+ def __init__(self):
+ super().__init__(max_workers=1)
+ self.submissions = 0
+
+ def submit(self, fn, /, *args, **kwargs):
+ future = super().submit(fn, *args, **kwargs)
+ self.submissions += 1
+ if self.submissions == 2:
+ queued.set()
+ return future
+
+ def block_executor():
+ entered.set()
+ assert release.wait(5)
+
+ for method in ("read_batch", "read_consistently"):
+ original = getattr(manager, method)
+
+ def tracked(*args, _original=original, **kwargs):
+ transaction.set()
+ return _original(*args, **kwargs)
+
+ monkeypatch.setattr(manager, method, tracked)
+
+ loop = asyncio.get_running_loop()
+ previous_executor = loop._default_executor
+ executor = SignallingExecutor()
+ loop.set_default_executor(executor)
+ blocker = loop.run_in_executor(None, block_executor)
+ tool = ReadSessionTool(manager) if tool_name == "read" else SearchSessionsTool(manager)
+ kwargs = {"session_key": session.key, "query": "needle"} if tool_name == "read" else {"query": "needle"}
+
+ async def wait_for_event(event):
+ while not event.is_set():
+ await asyncio.sleep(0.001)
+
+ task = None
+ try:
+ await asyncio.wait_for(wait_for_event(entered), timeout=5)
+ task = asyncio.create_task(tool.execute(**kwargs))
+ await asyncio.wait_for(wait_for_event(queued), timeout=5)
+ task.cancel()
+ completed, _ = await asyncio.wait({task}, timeout=0.5)
+ assert task in completed, "a queued history worker blocked cancellation"
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert not transaction.is_set()
+ finally:
+ release.set()
+ await blocker
+ # A fence ensures any previously queued worker has actually been dequeued.
+ await loop.run_in_executor(None, lambda: None)
+ if task is not None:
+ with suppress(asyncio.CancelledError):
+ await task
+ loop._default_executor = previous_executor
+ executor.shutdown(wait=True)
+ if manager._state is not None:
+ await manager.state.aclose()
+ assert not transaction.is_set(), "cancelled queued work entered the database after return"
+
+
[email protected]("tool_name", ["read", "search", "search-refill"])
+async def test_cancelled_history_scan_exits_and_releases_wal_snapshot(tmp_path, monkeypatch, tool_name):
+ from nanobot.session import sqlite_store
+
+ manager = SessionManager(tmp_path)
+ key = "sdk:long-history"
+ session = manager.get_or_create(key)
+ session.messages = [
+ {"role": "user", "content": f"ordinary {i}", "_marker": "long-history"}
+ for i in range(3000)
+ ]
+ manager.save(session)
+ if tool_name == "search-refill":
+ for i in range(5):
+ candidate = manager.get_or_create(f"sdk:candidate-{i}")
+ candidate.metadata.update({"title": "not-present", "title_user_edited": True})
+ manager.save(candidate)
+ db = sqlite3.connect(manager._store.path, isolation_level=None, timeout=0.2)
+ db.execute("PRAGMA wal_autocheckpoint=0")
+ db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
+ entered, release, done = threading.Event(), threading.Event(), threading.Event()
+ original_object = sqlite_store._object
+
+ def slow_rows(raw):
+ result = original_object(raw)
+ if result.get("_marker") == "long-history":
+ if not entered.is_set():
+ entered.set()
+ assert release.wait(5)
+ time.sleep(0.0005)
+ return result
+
+ monkeypatch.setattr(sqlite_store, "_object", slow_rows)
+ tool = ReadSessionTool(manager) if tool_name == "read" else SearchSessionsTool(manager)
+ if tool_name == "search-refill":
+ lookup = tool._handles.alist_all_by_key
+
+ async def reset_before_lookup():
+ for i in range(5):
+ candidate_key = f"sdk:candidate-{i}"
+ await manager.state.reset(candidate_key)
+ await manager.state.update_metadata(candidate_key, {"title": "other"})
+ return await lookup()
+
+ monkeypatch.setattr(tool._handles, "alist_all_by_key", reset_before_lookup)
+ method = {"read": "read", "search": "_start_search", "search-refill": "_complete_search"}[tool_name]
+ original = getattr(tool._access, method)
+
+ def tracked(*args, **kwargs):
+ try:
+ return original(*args, **kwargs)
+ finally:
+ done.set()
+
+ monkeypatch.setattr(tool._access, method, tracked)
+ kwargs = {"session_key": key, "query": "not-present"} if tool_name == "read" else {"query": "not-present"}
+ task = asyncio.create_task(tool.execute(**kwargs))
+ try:
+ assert await asyncio.to_thread(entered.wait, 5)
+ db.execute("UPDATE sessions SET title='while scanning' WHERE key=?", (key,))
+ _, frames, checkpointed = db.execute("PRAGMA wal_checkpoint(PASSIVE)").fetchone()
+ assert frames > checkpointed # The paused reader really holds the older snapshot.
+ task.cancel()
+ await asyncio.sleep(0)
+ assert not task.done(), "cancellation returned while the reader still held a snapshot"
+ task.cancel() # A second stop must not detach the already-started reader.
+ await asyncio.sleep(0)
+ assert not task.done()
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert await asyncio.to_thread(done.wait, 0.5), "cancelled worker continued scanning"
+ db.execute("UPDATE sessions SET title='after cancellation' WHERE key=?", (key,))
+ assert db.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchone() == (0, 0, 0)
+ finally:
+ release.set()
+ await asyncio.to_thread(done.wait, 5)
+ db.close()
+ if manager._state is not None:
+ await manager.state.aclose()
+
+
+async def test_cancelled_running_reader_preserves_unexpected_worker_failure(tmp_path, monkeypatch):
+ from nanobot.session import sqlite_store
+
+ manager = SessionManager(tmp_path)
+ session = manager.get_or_create("sdk:history")
+ session.messages = [{"role": "user", "content": "needle", "_marker": "failing-row"}]
+ manager.save(session)
+ entered, release = threading.Event(), threading.Event()
+ original = sqlite_store._object
+
+ def fail_row(raw):
+ record = original(raw)
+ if record.get("_marker") == "failing-row":
+ entered.set()
+ assert release.wait(5)
+ raise ValueError("failed to decode history")
+ return record
+
+ monkeypatch.setattr(sqlite_store, "_object", fail_row)
+ task = asyncio.create_task(ReadSessionTool(manager).execute(session_key=session.key))
+ try:
+ assert await asyncio.to_thread(entered.wait, 5)
+ task.cancel()
+ await asyncio.sleep(0)
+ assert not task.done()
+ release.set()
+ with pytest.raises(asyncio.CancelledError) as cancelled:
+ await task
+ assert isinstance(cancelled.value.__cause__, ValueError)
+ assert str(cancelled.value.__cause__) == "failed to decode history"
+ finally:
+ release.set()
+ if not task.done():
+ with suppress(asyncio.CancelledError):
+ await task
+ if manager._state is not None:
+ await manager.state.aclose()
+
+
[email protected]("change", ["reset", "recreate"])
+async def test_search_during_replacement_never_mixes_header_and_body(tmp_path, monkeypatch, change):
+ manager = SessionManager(tmp_path)
+ writer = SessionManager(tmp_path)
+ key = "sdk:history"
+ session = manager.get_or_create(key)
+ session.metadata["title"] = "old title"
+ session.messages = [{"role": "user", "content": "needle old content"}]
+ manager.save(session)
+ captured, release = threading.Event(), threading.Event()
+ original_list = manager.list_sessions
+
+ def pause_after_list():
+ rows = original_list()
+ captured.set()
+ assert release.wait(5)
+ return rows
+
+ monkeypatch.setattr(manager, "list_sessions", pause_after_list)
+ task = asyncio.create_task(SearchSessionsTool(manager).execute(query="needle"))
+ try:
+ assert await asyncio.to_thread(captured.wait, 5)
+ if change == "reset":
+ await writer.state.reset(key)
+ else:
+ assert await writer.state.delete(key)
+ await writer.state.import_messages(
+ key, [{"role": "user", "content": "needle new content"}], metadata={"title": "new title"},
+ )
+ release.set()
+ results = json.loads(await task)["results"]
+ if results:
+ assert len(results) == 1
+ assert results[0]["title"] == "new title"
+ assert results[0]["excerpts"][0]["content"] == "needle new content"
+ assert results[0]["handle"] is not None
+ finally:
+ release.set()
+ await writer.state.aclose()
+ if manager._state is not None:
+ await manager.state.aclose()
+
+
[email protected]("by_handle", [False, True])
+async def test_read_during_reset_does_not_return_old_history(tmp_path, monkeypatch, by_handle):
+ manager = SessionManager(tmp_path)
+ writer = SessionManager(tmp_path)
+ key = "sdk:history"
+ session = manager.get_or_create(key)
+ session.messages = [{"role": "user", "content": "old content"}]
+ manager.save(session)
+ tool = ReadSessionTool(manager)
+ handle = await tool._handles.ahandle_for_session(key)
+ captured, release = threading.Event(), threading.Event()
+ public_history = manager.types.public_history
+
+ def pause_after_header(metadata):
+ if not captured.is_set():
+ captured.set()
+ assert release.wait(5)
+ return public_history(metadata)
+
+ monkeypatch.setattr(manager.types, "public_history", pause_after_header)
+ reference = f"@{handle.name}" if by_handle else key
+ task = asyncio.create_task(tool.execute(session_key=reference))
+ try:
+ assert await asyncio.to_thread(captured.wait, 5)
+ await writer.state.reset(key)
+ await writer.state.import_messages(key, [{"role": "user", "content": "new content"}])
+ release.set()
+ result = await task
+ assert result.is_error and "session not found" in str(result)
+ finally:
+ release.set()
+ await writer.state.aclose()
+ await manager.state.aclose()
+
+
+async def test_search_does_not_hold_a_global_snapshot_between_histories(tmp_path, monkeypatch):
+ manager = SessionManager(tmp_path)
+ for i in range(2):
+ session = manager.get_or_create(f"sdk:{i}")
+ session.messages = [{"role": "user", "content": "ordinary"}]
+ session.updated_at = datetime(2025, 1, i + 1)
+ manager.save(session)
+ db = sqlite3.connect(manager._store.path, isolation_level=None, timeout=0.2)
+ db.execute("PRAGMA wal_autocheckpoint=0")
+ db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
+ entered, release = threading.Event(), threading.Event()
+ tool = SearchSessionsTool(manager)
+ original_read = tool._access.read
+
+ def pause_before_second(key, **kwargs):
+ if key == "sdk:0":
+ entered.set()
+ assert release.wait(5)
+ return original_read(key, **kwargs)
+
+ monkeypatch.setattr(tool._access, "read", pause_before_second)
+ task = asyncio.create_task(tool.execute(query="not-present"))
+ try:
+ assert await asyncio.to_thread(entered.wait, 5)
+ db.execute("UPDATE sessions SET title='changed' WHERE key='sdk:1'")
+ assert db.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchone() == (0, 0, 0)
+ release.set()
+ assert json.loads(await task)["results"] == []
+ finally:
+ release.set()
+ db.close()
+ if manager._state is not None:
+ await manager.state.aclose()
+
+
+def test_search_preserves_recency_order_when_a_title_changes_during_scan(tmp_path, monkeypatch):
+ manager = SessionManager(tmp_path)
+ newer = manager.get_or_create("sdk:newer")
+ newer.metadata["title"] = "notes"
+ newer.messages = [{"role": "user", "content": "needle in body"}]
+ newer.updated_at = datetime(2025, 1, 1)
+ manager.save(newer)
+ older = manager.get_or_create("sdk:older")
+ older.metadata["title"] = "needle old"
+ older.updated_at = datetime(2020, 1, 1)
+ manager.save(older)
+ writer = SessionManager(tmp_path)
+ changed = writer.get_or_create(newer.key)
+ changed.metadata["title"] = "needle new"
+ reader = SessionHistoryReader(manager)
+ original_read = reader.read
+
+ def change_before_read(key, **kwargs):
+ if key == newer.key:
+ writer.save(changed)
+ return original_read(key, **kwargs)
+
+ monkeypatch.setattr(reader, "read", change_before_read)
+ assert [match["session_key"] for match in reader.search("needle", limit=5)] == [
+ newer.key, older.key,
+ ]
diff --git a/tests/agent/tools/test_sessions.py b/tests/agent/tools/test_sessions.py
index ad9fcd318..9a429db5e 100644
--- a/tests/agent/tools/test_sessions.py
+++ b/tests/agent/tools/test_sessions.py
@@ -1,8 +1,11 @@
from __future__ import annotations
+import asyncio
import json
+import threading
from contextlib import AbstractContextManager
from datetime import datetime
+from types import SimpleNamespace
import pytest
@@ -13,6 +16,7 @@ from nanobot.agent.tools.session_messages import SendSessionMessageTool
from nanobot.agent.tools.sessions import ReadSessionTool, SearchSessionsTool
from nanobot.bus.queue import MessageBus
from nanobot.runtime_context import RuntimeContextBlock, append_runtime_context
+from nanobot.sdk.clients import SessionClient
from nanobot.session.manager import SessionManager
from nanobot.session.session_handles import SessionHandleResolver
@@ -152,22 +156,60 @@ async def test_search_sessions_ranks_titles_before_message_matches(manager):
@pytest.mark.asyncio
-async def test_search_keeps_match_if_session_is_deleted_before_handle_lookup(manager, monkeypatch):
[email protected]("change,match_title", [
+ ("reset", False), ("recreate", True), ("delete", True), ("private", False),
+])
+async def test_search_drops_stale_or_private_matches_before_handle_lookup(manager, monkeypatch, change, match_title):
key = "slack:history"
- _save_session(manager, key, title="Database notes", messages=[])
+ _save_session(manager, key, title="needle title" if match_title else "notes", messages=[
+ {"role": "user", "content": "needle old content"},
+ ])
+ old_generation = manager.read_session_version(key)[0]
tool = SearchSessionsTool(manager)
lookup = tool._handles.alist_all_by_key
- async def delete_before_lookup():
- assert await manager.state.delete(key)
+ async def change_before_lookup():
+ if change == "reset":
+ await manager.state.reset(key)
+ await manager.state.import_messages(
+ key, [{"role": "user", "content": "new content"}], metadata={"title": "new title"},
+ )
+ elif change in {"recreate", "delete"}:
+ assert await manager.state.delete(key)
+ if change == "recreate":
+ await manager.state.import_messages(key, [{"role": "user", "content": "new content"}])
+ else:
+ await manager.state.update_metadata(key, {"session_type": "private"})
+ if change in {"reset", "recreate"}:
+ assert manager.read_session_version(key)[0] != old_generation
+ monkeypatch.setattr(tool._handles, "alist_all_by_key", lookup)
return await lookup()
- monkeypatch.setattr(tool._handles, "alist_all_by_key", delete_before_lookup)
+ monkeypatch.setattr(tool._handles, "alist_all_by_key", change_before_lookup)
with _webui_request():
- result = _decode(await tool.execute(query="Database"))
+ result = _decode(await tool.execute(query="needle"))
- assert [row["session_key"] for row in result["results"]] == [key]
- assert result["results"][0]["handle"] is None
+ assert result["results"] == []
+
+
+async def test_read_by_handle_does_not_read_a_reassigned_handle(manager, monkeypatch):
+ key = "slack:history"
+ _save_session(manager, key, title="Notes", messages=[{"role": "user", "content": "old content"}])
+ tool = ReadSessionTool(manager)
+ original = await tool._handles.ahandle_for_session(key)
+ resolve = tool._handles.aresolve
+
+ async def replace_after_resolve(name):
+ handle = await resolve(name)
+ await manager.state.delete(key)
+ await manager.state.import_messages(key, [{"role": "user", "content": "new content"}],
+ metadata={"session_handle": "luna"})
+ return handle
+
+ monkeypatch.setattr(tool._handles, "aresolve", replace_after_resolve)
+ result = await tool.execute(session_key=f"@{original.name}")
+ assert result.is_error and "session not found" in str(result)
@pytest.mark.asyncio
@@ -371,3 +413,240 @@ async def test_session_tools_work_without_request_context(manager):
assert [row["session_key"] for row in result["results"]] == ["custom:history"]
assert read["session_key"] == "custom:history"
+
+
+async def test_search_retains_valid_matches_when_a_candidate_is_reset(manager, monkeypatch):
+ for i in range(6):
+ _save_session(manager, f"sdk:{i}", title=f"needle {i}", messages=[],
+ updated_at=datetime(2025, 1, i + 1))
+ tool = SearchSessionsTool(manager)
+ lookup = tool._handles.alist_all_by_key
+
+ async def reset_once():
+ monkeypatch.setattr(tool._handles, "alist_all_by_key", lookup)
+ await manager.state.reset("sdk:5")
+ await manager.state.update_metadata("sdk:5", {"title": "other"})
+ return await lookup()
+
+ monkeypatch.setattr(tool._handles, "alist_all_by_key", reset_once)
+ result = _decode(await tool.execute(query="needle"))
+ assert [row["session_key"] for row in result["results"]] == [f"sdk:{i}" for i in (4, 3, 2, 1, 0)]
+
+
[email protected]("first_matches_title,sixth_matches_title", [
+ (True, True), (True, False), (False, False),
+])
[email protected]("reset_count", [5, 11])
+async def test_search_fills_from_remaining_candidates_after_resets(
+ manager, monkeypatch, first_matches_title, sixth_matches_title, reset_count,
+):
+ for i in range(reset_count + 1):
+ _save_session(
+ manager, f"sdk:{i}",
+ title="Straße plan" if (first_matches_title if i else sixth_matches_title) else "notes",
+ messages=[
+ {"role": "tool", "content": "Straße hidden"},
+ {"role": "user", "content": f"Straße stable {i}"},
+ ],
+ updated_at=datetime(2025, 1, i + 1),
+ )
+ tool = SearchSessionsTool(manager)
+ lookup = tool._handles.alist_all_by_key
+ list_sessions = manager.list_sessions
+ calls = scans = 0
+
+ def count_header_scans():
+ nonlocal scans
+ scans += 1
+ return list_sessions()
+
+ async def reset_before_lookup():
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ for i in range(reset_count, 0, -1):
+ await manager.state.reset(f"sdk:{i}")
+ await manager.state.update_metadata(f"sdk:{i}", {"title": "other"})
+ return await lookup()
+
+ monkeypatch.setattr(manager, "list_sessions", count_header_scans)
+ monkeypatch.setattr(tool._handles, "alist_all_by_key", reset_before_lookup)
+ first = _decode(await tool.execute(query="STRASSE"))
+ second = _decode(await tool.execute(query="STRASSE"))
+ for result in (first, second):
+ assert [row["session_key"] for row in result["results"]] == ["sdk:0"]
+ row = result["results"][0]
+ assert row["handle"] is not None
+ if not sixth_matches_title:
+ assert [(item["message_index"], item["content"]) for item in row["excerpts"]] == [
+ (1, "Straße stable 0"),
+ ]
+ assert calls == scans == 2 # One handle lookup and one header scan per execution.
+
+
[email protected]("matches_title", [True, False])
+async def test_search_stops_reading_bodies_after_five_matches(manager, monkeypatch, matches_title):
+ for i in range(9):
+ _save_session(
+ manager, f"sdk:{i}", title="needle title" if matches_title else "notes",
+ messages=[{"role": "user", "content": "needle body"}],
+ updated_at=datetime(2025, 1, i + 1),
+ )
+ tool = SearchSessionsTool(manager)
+ original = tool._access.read
+ scanned = []
+
+ def track_read(key, **kwargs):
+ scanned.append(key)
+ return original(key, **kwargs)
+
+ monkeypatch.setattr(tool._access, "read", track_read)
+ result = _decode(await tool.execute(query="needle"))
+ assert [row["session_key"] for row in result["results"]] == [f"sdk:{i}" for i in range(8, 3, -1)]
+ assert scanned == ([] if matches_title else [f"sdk:{i}" for i in range(8, 3, -1)])
+
+
+async def test_refill_revalidates_retained_and_new_candidates(manager, monkeypatch):
+ for i in range(12):
+ _save_session(manager, f"sdk:{i}", title="needle", messages=[],
+ updated_at=datetime(2025, 1, i + 1))
+ tool = SearchSessionsTool(manager)
+ lookup = tool._handles.alist_all_by_key
+ validate = tool._access._validate
+ project_names = manager.project_session_handle_names
+ validated, release = threading.Event(), threading.Event()
+ validation_calls = ambiguity_scans = 0
+
+ async def reset_before_lookup():
+ await manager.state.reset("sdk:11")
+ await manager.state.update_metadata("sdk:11", {"title": "other"})
+ return await lookup()
+
+ def pause_after_first_validation(*args, **kwargs):
+ nonlocal validation_calls
+ result = validate(*args, **kwargs)
+ validation_calls += 1
+ if validation_calls == 1:
+ validated.set()
+ assert release.wait(5)
+ return result
+
+ def count_ambiguity_scans(project):
+ nonlocal ambiguity_scans
+ ambiguity_scans += 1
+ return project_names(project)
+
+ monkeypatch.setattr(tool._handles, "alist_all_by_key", reset_before_lookup)
+ monkeypatch.setattr(tool._access, "_validate", pause_after_first_validation)
+ monkeypatch.setattr(manager, "project_session_handle_names", count_ambiguity_scans)
+ task = asyncio.create_task(tool.execute(query="needle"))
+ try:
+ assert await asyncio.to_thread(validated.wait, 5)
+ # One retained match and the next cached candidate both become stale.
+ for key in ("sdk:10", "sdk:6"):
+ await manager.state.reset(key)
+ await manager.state.update_metadata(key, {"title": "other"})
+ release.set()
+ result = _decode(await task)
+ assert [row["session_key"] for row in result["results"]] == [
+ "sdk:9", "sdk:8", "sdk:7", "sdk:5", "sdk:4",
+ ]
+ assert validation_calls == 3
+ assert ambiguity_scans == 1
+ finally:
+ release.set()
+ if not task.done():
+ await task
+
+
+async def test_refill_reranks_a_candidate_whose_title_changed(manager, monkeypatch):
+ for i in range(5):
+ _save_session(manager, f"sdk:{i}", title="needle plan", messages=[],
+ updated_at=datetime(2025, 1, i + 1))
+ _save_session(manager, "sdk:newest", title="notes", messages=[], updated_at=datetime(2026, 1, 1))
+ tool = SearchSessionsTool(manager)
+ lookup = tool._handles.alist_all_by_key
+
+ async def change_before_lookup():
+ await manager.state.reset("sdk:4")
+ await manager.state.update_metadata("sdk:4", {"title": "other"})
+ await manager.state.update_metadata("sdk:newest", {"title": "needle"})
+ return await lookup()
+
+ monkeypatch.setattr(tool._handles, "alist_all_by_key", change_before_lookup)
+ result = _decode(await tool.execute(query="needle"))
+ assert [row["session_key"] for row in result["results"]] == [
+ "sdk:newest", "sdk:3", "sdk:2", "sdk:1", "sdk:0",
+ ]
+
+
+async def test_refilled_match_does_not_expose_sdk_duplicate_handle(manager, monkeypatch):
+ for i in range(6):
+ _save_session(manager, f"sdk:{i}", title="needle", messages=[],
+ updated_at=datetime(2025, 1, i + 1))
+ _save_session(manager, "sdk:older", title="notes", messages=[], updated_at=datetime(2020, 1, 1))
+ tool = SearchSessionsTool(manager)
+ lookup = tool._handles.alist_all_by_key
+ original = await lookup()
+ client = SessionClient(SimpleNamespace(sessions=manager))
+
+ async def reset_and_import_duplicate():
+ for i in range(5, 0, -1):
+ await manager.state.reset(f"sdk:{i}")
+ await manager.state.update_metadata(f"sdk:{i}", {"title": "other"})
+ handles = await lookup()
+ await client.ingest("sdk:older", [], metadata={"session_handle": original["sdk:0"].name})
+ return handles
+
+ monkeypatch.setattr(tool._handles, "alist_all_by_key", reset_and_import_duplicate)
+ result = _decode(await tool.execute(query="needle"))
+ assert [row["session_key"] for row in result["results"]] == ["sdk:0"]
+ assert result["results"][0]["handle"] is None
+
+
+async def test_handle_is_not_exposed_if_another_session_acquires_the_same_name(manager, monkeypatch):
+ _save_session(manager, "sdk:older", title="older", messages=[])
+ _save_session(manager, "sdk:target", title="target", messages=[{"role": "user", "content": "needle"}])
+ search = SearchSessionsTool(manager)
+ initial = await search._handles.alist_all_by_key()
+ target_name = initial["sdk:target"].name
+ client = SessionClient(SimpleNamespace(sessions=manager))
+ snapshot = await client.export("sdk:target")
+ assert snapshot is not None and snapshot.metadata["session_handle"] == target_name
+ lookup = search._handles.alist_all_by_key
+
+ async def restore_after_lookup():
+ handles = await lookup()
+ # SDK restore carries the exported handle into an existing empty session.
+ await client.restore(snapshot, session_key="sdk:older")
+ return handles
+
+ monkeypatch.setattr(search._handles, "alist_all_by_key", restore_after_lookup)
+ result = _decode(await search.execute(query="needle"))
+ assert result["results"][0]["session_key"] == "sdk:target"
+ assert result["results"][0]["handle"] is None
+ reassigned = await search._handles.aresolve(target_name)
+ assert reassigned is not None and reassigned.session_key == "sdk:older"
+
+ read = ReadSessionTool(manager)
+ current = await read._handles.ahandle_for_session("sdk:target")
+ assert current is not None
+ resolve = read._handles.aresolve
+
+ async def ingest_after_resolve(name):
+ handle = await resolve(name)
+ await client.ingest("sdk:older", [], metadata={"session_handle": current.name})
+ return handle
+
+ monkeypatch.setattr(read._handles, "aresolve", ingest_after_resolve)
+ result = await read.execute(session_key=f"@{current.name}")
+ assert result.is_error and "session not found" in str(result)
+ reassigned = await resolve(current.name)
+ assert reassigned is not None and reassigned.session_key == "sdk:older"
diff --git a/tests/providers/test_internal_streaming.py b/tests/providers/test_internal_streaming.py
index fc26743fd..a38ae5c26 100644
--- a/tests/providers/test_internal_streaming.py
+++ b/tests/providers/test_internal_streaming.py
@@ -1,10 +1,18 @@
import asyncio
+import importlib.util
import json
+import os
+import subprocess
+import sys
+import textwrap
+import weakref
from collections.abc import AsyncIterator, Awaitable, Callable
import httpx
+import openai
import pytest
from agent.runner_helpers import failed_test_consolidator
+from loguru import logger
from openai import AsyncOpenAI
from nanobot.agent.hook import AgentHook
@@ -259,3 +267,646 @@ async def test_chat_only_provider_still_has_a_timeout(monkeypatch, finalize):
assert result.stop_reason == ("max_iterations" if finalize else "error")
if finalize:
assert result.final_content == "Tool budget exhausted."
+
+
+def _chat_event(delta=None, *, finish=None, usage=None):
+ event = {
+ "id": "synthetic", "object": "chat.completion.chunk", "created": 0,
+ "model": "synthetic", "choices": [],
+ }
+ if delta is not None:
+ event["choices"] = [{"index": 0, "delta": delta, "finish_reason": finish}]
+ if usage is not None:
+ event["usage"] = usage
+ return event
+
+
+def _bad_chat_event(kind):
+ if kind == "usage":
+ return _chat_event(usage={"prompt_tokens": "invalid", "completion_tokens": 1, "total_tokens": 2})
+ return _chat_event({"tool_calls": [{
+ "index": [0], "id": "bad", "type": "function",
+ "function": {"name": "bad_tool", "arguments": "{}"},
+ }]})
+
+
+class _ControlledChatStream(_EventStream):
+ def __init__(self, events, *, disconnect=False, pause_at=None, close_error=None):
+ super().__init__(events)
+ self.disconnect = disconnect
+ self.pause_at = pause_at
+ self.close_error = close_error
+ self.reached_pause = asyncio.Event()
+ self.release = asyncio.Event()
+ self.sent = 0
+ self.close_calls = 0
+
+ async def aclose(self):
+ self.close_calls += 1
+ self.closed = True
+ if self.close_error is not None:
+ raise self.close_error
+
+ async def __aiter__(self):
+ for index, event in enumerate(self.events):
+ if index == self.pause_at:
+ self.reached_pause.set()
+ await self.release.wait()
+ self.sent += 1
+ yield f"data: {json.dumps(event)}\n\n".encode()
+ if self.disconnect:
+ raise ConnectionError("synthetic connection lost")
+ yield b"data: [DONE]\n\n"
+
+
+async def chat_sdk():
+ clients = []
+
+ def make(streams):
+ requests = []
+
+ def handler(request):
+ requests.append(request)
+ assert json.loads(request.content)["stream"] is True
+ return httpx.Response(
+ 200, headers={"content-type": "text/event-stream"},
+ stream=streams[len(requests) - 1],
+ )
+
+ client = AsyncOpenAI(
+ api_key="synthetic", base_url="https://synthetic.invalid/v1", max_retries=0,
+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
+ )
+ clients.append(client)
+ provider = OpenAICompatProvider(
+ api_key="synthetic", default_model="synthetic",
+ model_api=ModelAPICapabilities(("chat_completions",), "chat_completions"),
+ )
+ provider._client = client
+ provider._CHAT_RETRY_DELAYS = (0,)
+ return provider, requests
+
+ yield make
+ for client in clients:
+ await client.close()
+
+
[email protected]("first_bad", ["usage", "index"])
+async def test_chat_parse_failure_waits_for_all_live_deltas(chat_sdk, first_bad):
+ other_bad = "index" if first_bad == "usage" else "usage"
+ stream = _ControlledChatStream([
+ _bad_chat_event(first_bad), _bad_chat_event(other_bad),
+ _chat_event({
+ "content": "later", "reasoning_content": "thought",
+ "tool_calls": [{"index": 1, "id": "good", "type": "function",
+ "function": {"name": "tool", "arguments": "{}"}}],
+ }),
+ _chat_event({}, finish="stop"),
+ ], pause_at=3)
+ provider, _ = chat_sdk([stream])
+ callbacks = []
+
+ async def content(value):
+ callbacks.append(("content", value))
+
+ async def thinking(value):
+ callbacks.append(("thinking", value))
+
+ async def tool(value):
+ callbacks.append(("tool", value))
+
+ task = asyncio.create_task(provider.chat_stream(
+ [{"role": "user", "content": "work"}], on_content_delta=content,
+ on_thinking_delta=thinking, on_tool_call_delta=tool,
+ ))
+ try:
+ await asyncio.wait_for(stream.reached_pause.wait(), timeout=1)
+ assert not task.done()
+ assert callbacks == [
+ ("tool", {"index": [0], "call_id": "bad", "name": "bad_tool", "arguments_delta": "{}"}),
+ ("content", "later"), ("thinking", "thought"),
+ ("tool", {"index": 1, "call_id": "good", "name": "tool", "arguments_delta": "{}"}),
+ ]
+ stream.release.set()
+ result = await task
+ finally:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+
+ assert result.finish_reason == "error"
+ assert ("invalid literal" if first_bad == "usage" else "unhashable type") in result.content
+ assert stream.closed
+
+
[email protected]("bad", ["usage", "index"])
[email protected]("interruption", ["disconnect", "eof", "disconnect-after-finish"])
+async def test_chat_interruption_precedes_parse_failure_and_retries(chat_sdk, bad, interruption):
+ events = [_bad_chat_event(bad), _chat_event({"reasoning_content": "before retry"})]
+ if interruption == "disconnect-after-finish":
+ events.append(_chat_event({}, finish="stop"))
+ first = _ControlledChatStream(events, disconnect=interruption != "eof")
+ second = _ControlledChatStream([
+ _chat_event({"content": "recovered"}), _chat_event({}, finish="stop"),
+ _chat_event(usage={"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}),
+ ])
+ provider, requests = chat_sdk([first, second])
+ thinking, content = [], []
+
+ async def on_thinking(value):
+ thinking.append(value)
+
+ async def on_content(value):
+ content.append(value)
+
+ result = await provider.chat_stream_with_retry(
+ [{"role": "user", "content": "work"}],
+ on_thinking_delta=on_thinking, on_content_delta=on_content,
+ )
+ assert len(requests) == 2
+ assert thinking == ["before retry"]
+ assert content == ["recovered"]
+ assert result.finish_reason == "stop" and result.content == "recovered"
+ assert result.usage is not None and result.usage.total_tokens == 15
+ assert first.closed and second.closed
+
+
+async def test_chat_content_after_parse_failure_preserves_retry_guard(chat_sdk):
+ first = _ControlledChatStream([
+ _bad_chat_event("usage"), _chat_event({"content": "already shown"}),
+ ], disconnect=True)
+ provider, requests = chat_sdk([first])
+ content = []
+
+ async def on_content(value):
+ content.append(value)
+
+ result = await provider.chat_stream_with_retry(
+ [{"role": "user", "content": "work"}], on_content_delta=on_content,
+ )
+ assert len(requests) == 1 and content == ["already shown"]
+ assert result.error_kind == "connection" and "synthetic connection lost" in result.content
+ assert first.closed
+
+
[email protected]("parse_first", [False, True])
+async def test_chat_callback_error_closes_stream(chat_sdk, parse_first):
+ prefix = [_bad_chat_event("usage")] if parse_first else []
+ stream = _ControlledChatStream(prefix + [
+ _chat_event({"content": "fail callback"}), _chat_event({}, finish="stop"),
+ ])
+ provider, _ = chat_sdk([stream])
+
+ async def on_content(value):
+ raise RuntimeError("callback failed")
+
+ result = await provider.chat_stream(
+ [{"role": "user", "content": "work"}], on_content_delta=on_content,
+ )
+ assert result.finish_reason == "error" and "callback failed" in result.content
+ assert stream.sent == len(prefix) + 1 and stream.closed
+
+
[email protected]("parse_first", [False, True])
[email protected]("blocked", ["read", "callback"])
+async def test_chat_cancel_closes_stream(chat_sdk, blocked, parse_first):
+ prefix = [_bad_chat_event("usage")] if parse_first else []
+ stream = _ControlledChatStream(prefix + [
+ _chat_event({"content": "wait"}), _chat_event({}, finish="stop"),
+ ], pause_at=len(prefix) if blocked == "read" else None)
+ provider, _ = chat_sdk([stream])
+ callback_started = asyncio.Event()
+
+ async def on_content(value):
+ callback_started.set()
+ await asyncio.Event().wait()
+
+ task = asyncio.create_task(provider.chat_stream(
+ [{"role": "user", "content": "work"}], on_content_delta=on_content,
+ ))
+ try:
+ started = stream.reached_pause if blocked == "read" else callback_started
+ await asyncio.wait_for(started.wait(), timeout=1)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert stream.closed
+ finally:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+
+
+async def test_chat_timeout_after_parse_failure_wins_and_closes(chat_sdk, monkeypatch):
+ monkeypatch.setenv("NANOBOT_STREAM_IDLE_TIMEOUT_S", "0.05")
+ stream = _ControlledChatStream([
+ _bad_chat_event("usage"), _chat_event({}, finish="stop"),
+ ], pause_at=1)
+ provider, _ = chat_sdk([stream])
+ result = await provider.chat_stream([{"role": "user", "content": "work"}])
+ assert result.error_kind == "timeout"
+ assert stream.closed
+
+
+async def test_chat_sdk_error_after_parse_failure_wins_and_closes(chat_sdk):
+ stream = _ControlledChatStream([
+ _bad_chat_event("usage"), {"error": {"message": "provider stream error", "code": "bad_stream"}},
+ _chat_event({}, finish="stop"),
+ ])
+ provider, _ = chat_sdk([stream])
+ result = await provider.chat_stream([{"role": "user", "content": "work"}])
+ assert result.finish_reason == "error" and "provider stream error" in result.content
+ assert result.error_code == "bad_stream"
+ assert stream.sent == 2 and stream.closed
+
+
[email protected]("bad", [False, True])
+async def test_chat_sdk_chunks_are_not_retained_during_stream(chat_sdk, monkeypatch, bad):
+ stream = _ControlledChatStream([
+ _chat_event({"content": "first"}),
+ _bad_chat_event("usage") if bad else _chat_event({"content": "second"}),
+ _chat_event({"content": "third"}), _chat_event({"content": "fourth"}),
+ _chat_event({}, finish="stop", usage={
+ "prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
+ }),
+ ])
+ provider, _ = chat_sdk([stream])
+ references = []
+ released = []
+ deltas = []
+ original_add = OpenAICompatProvider._ChatStreamAccumulator.add
+
+ def track_add(accumulator, chunk):
+ references.append(weakref.ref(chunk))
+ original_add(accumulator, chunk)
+
+ monkeypatch.setattr(OpenAICompatProvider._ChatStreamAccumulator, "add", track_add)
+
+ async def on_content(value):
+ deltas.append(value)
+ if value == "fourth":
+ released.extend(ref() is None for ref in references[:2])
+
+ result = await provider.chat_stream(
+ [{"role": "user", "content": "work"}], on_content_delta=on_content,
+ )
+ assert released == [True, True]
+ assert deltas == (["first", "third", "fourth"] if bad else ["first", "second", "third", "fourth"])
+ assert result.finish_reason == ("error" if bad else "stop")
+ if not bad:
+ assert result.content == "".join(deltas)
+ assert result.usage is not None and result.usage.total_tokens == 15
+ assert stream.closed
+
+
+async def test_chat_sdk_normal_deltas_usage_and_tool_metadata(chat_sdk):
+ stream = _ControlledChatStream([
+ _chat_event({
+ "content": "hello ", "reasoning_content": "think ",
+ "tool_calls": [{
+ "index": 0, "id": "call_1", "type": "function",
+ "function": {"name": "write_file", "arguments": '{"path":', "vendor_fn": "f"},
+ "extra_content": {"google": {"thought_signature": "signed"}},
+ "vendor_call": "c",
+ }],
+ }),
+ _chat_event({
+ "content": "world", "reasoning": "more",
+ "tool_calls": [{"index": 0, "function": {"arguments": '"a.txt"}'}}],
+ }),
+ _chat_event({"tool_calls": [{
+ "index": 1, "id": "call_1", "type": "function",
+ "function": {"name": "read_file", "arguments": '{"path":"b.txt"}'},
+ }]}),
+ _chat_event({}, finish="tool_calls"),
+ _chat_event(usage={
+ "prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 16,
+ "prompt_tokens_details": {"cached_tokens": 3},
+ }),
+ ])
+ provider, requests = chat_sdk([stream])
+ callbacks = []
+
+ async def content(value):
+ callbacks.append(("content", value))
+
+ async def thinking(value):
+ callbacks.append(("thinking", value))
+
+ async def tool(value):
+ callbacks.append(("tool", value))
+
+ result = await provider.chat_stream(
+ [{"role": "user", "content": "work"}], on_content_delta=content,
+ on_thinking_delta=thinking, on_tool_call_delta=tool,
+ )
+ assert callbacks == [
+ ("content", "hello "), ("thinking", "think "),
+ ("tool", {"index": 0, "call_id": "call_1", "name": "write_file", "arguments_delta": '{"path":'}),
+ ("content", "world"), ("thinking", "more"),
+ ("tool", {"index": 0, "call_id": "", "name": "", "arguments_delta": '"a.txt"}'}),
+ ("tool", {"index": 1, "call_id": "call_1", "name": "read_file", "arguments_delta": '{"path":"b.txt"}'}),
+ ]
+ assert len(requests) == 1 and stream.closed
+ assert result.finish_reason == "tool_calls"
+ assert result.content == "hello world" and result.reasoning_content == "think more"
+ assert result.usage is not None
+ assert (result.usage.input_tokens, result.usage.output_tokens, result.usage.total_tokens) == (10, 5, 16)
+ assert result.usage.cache_read_tokens == 3
+ first, second = result.tool_calls
+ assert (first.id, first.name, first.arguments) == ("call_1", "write_file", {"path": "a.txt"})
+ assert first.extra_content == {"google": {"thought_signature": "signed"}}
+ assert first.provider_specific_fields == {"vendor_call": "c"}
+ assert first.function_provider_specific_fields == {"vendor_fn": "f"}
+ assert second.id and second.id != first.id
+ assert (second.name, second.arguments) == ("read_file", {"path": "b.txt"})
+
+
+async def test_chat_sdk_mistral_thinking_and_legacy_function_call(chat_sdk):
+ stream = _ControlledChatStream([
+ _chat_event({
+ "content": [
+ {"type": "thinking", "thinking": [{"type": "text", "text": "ponder"}]},
+ {"type": "text", "text": "hello"},
+ ],
+ "function_call": {"name": "old_tool", "arguments": '{"n":'},
+ }),
+ _chat_event({"function_call": {"arguments": "1}"}}, finish="function_call"),
+ _chat_event(usage={"prompt_tokens": 4, "completion_tokens": 2, "total_tokens": 6}),
+ ])
+ provider, _ = chat_sdk([stream])
+ callbacks = []
+
+ async def content(value):
+ callbacks.append(("content", value))
+
+ async def thinking(value):
+ callbacks.append(("thinking", value))
+
+ async def tool(value):
+ callbacks.append(("tool", value))
+
+ result = await provider.chat_stream(
+ [{"role": "user", "content": "work"}], on_content_delta=content,
+ on_thinking_delta=thinking, on_tool_call_delta=tool,
+ )
+ assert callbacks == [
+ ("content", "hello"), ("thinking", "ponder"),
+ ("tool", {"index": 0, "call_id": "", "name": "old_tool", "arguments_delta": '{"n":'}),
+ ("tool", {"index": 0, "call_id": "", "name": "", "arguments_delta": "1}"}),
+ ]
+ assert result.finish_reason == "function_call" and result.content == "hello"
+ assert result.reasoning_content == "ponder"
+ assert len(result.tool_calls) == 1
+ assert result.tool_calls[0].name == "old_tool" and result.tool_calls[0].arguments == {"n": 1}
+ assert result.usage is not None and result.usage.total_tokens == 6
+ assert stream.closed
+
+
+def cleanup_warnings():
+ messages = []
+ sink = logger.add(messages.append, format="{message}", level="WARNING")
+ try:
+ yield messages
+ finally:
+ logger.remove(sink)
+
+
+def _require_minimum_sdk_for_iterator_close_failure():
+ # SDK 2.24 closes inside its iterator and masks these errors before the
+ # provider's cleanup runs. That pre-existing SDK behavior is outside this fix.
+ if openai.__version__ != "2.8.0":
+ pytest.skip("this regression targets the 2.8.0 SDK's caller-owned close")
+
+
[email protected]("blocked", ["read", "callback"])
+async def test_chat_cancel_wins_over_close_error_without_retry(chat_sdk, cleanup_warnings, blocked):
+ if blocked == "read":
+ _require_minimum_sdk_for_iterator_close_failure()
+ stream = _ControlledChatStream([
+ _chat_event({"content": "waiting"}), _chat_event({}, finish="stop"),
+ ], pause_at=0 if blocked == "read" else None, close_error=httpx.CloseError("connection reset"))
+ retry = _ControlledChatStream([_chat_event({"content": "unexpected"}, finish="stop")])
+ provider, requests = chat_sdk([stream, retry])
+ callback_started = asyncio.Event()
+
+ async def on_content(value):
+ if value == "waiting":
+ callback_started.set()
+ await asyncio.Event().wait()
+
+ task = asyncio.create_task(provider.chat_stream_with_retry(
+ [{"role": "user", "content": "work"}], on_content_delta=on_content,
+ ))
+ try:
+ started = stream.reached_pause if blocked == "read" else callback_started
+ await asyncio.wait_for(started.wait(), timeout=5)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ finally:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+
+ assert len(requests) == 1 and stream.closed and stream.close_calls == 1
+ assert any("connection reset" in message for message in cleanup_warnings)
+
+
[email protected]("parse_first", [False, True])
+async def test_chat_provider_error_wins_over_close_error_without_retry(
+ chat_sdk, cleanup_warnings, parse_first,
+):
+ _require_minimum_sdk_for_iterator_close_failure()
+ prefix = [_bad_chat_event("usage")] if parse_first else []
+ stream = _ControlledChatStream(prefix + [{"error": {
+ "message": "quota exhausted", "type": "insufficient_quota", "code": "insufficient_quota",
+ }}], close_error=httpx.CloseError("connection reset"))
+ retry = _ControlledChatStream([_chat_event({"content": "unexpected"}, finish="stop")])
+ provider, requests = chat_sdk([stream, retry])
+
+ result = await provider.chat_stream_with_retry([{"role": "user", "content": "work"}])
+
+ assert result.finish_reason == "error"
+ assert result.error_type == result.error_code == "insufficient_quota"
+ assert "quota exhausted" in result.content
+ assert len(requests) == 1 and stream.closed and stream.close_calls == 1
+ assert any("connection reset" in message for message in cleanup_warnings)
+
+
+async def test_chat_disconnect_wins_over_close_error_and_still_retries(chat_sdk, cleanup_warnings):
+ _require_minimum_sdk_for_iterator_close_failure()
+ first = _ControlledChatStream([
+ _bad_chat_event("usage"), _chat_event({"reasoning_content": "thinking"}),
+ ], disconnect=True, close_error=httpx.CloseError("connection reset"))
+ second = _ControlledChatStream([_chat_event({"content": "recovered"}, finish="stop")])
+ provider, requests = chat_sdk([first, second])
+
+ result = await provider.chat_stream_with_retry([{"role": "user", "content": "work"}])
+
+ assert result.finish_reason == "stop" and result.content == "recovered"
+ assert len(requests) == 2 and first.closed and second.closed
+ assert any("after ConnectionError: connection reset" in message for message in cleanup_warnings)
+
+
+async def test_chat_timeout_wins_over_close_error(chat_sdk, cleanup_warnings, monkeypatch):
+ _require_minimum_sdk_for_iterator_close_failure()
+ monkeypatch.setenv("NANOBOT_STREAM_IDLE_TIMEOUT_S", "0.05")
+ stream = _ControlledChatStream([
+ _bad_chat_event("usage"), _chat_event({}, finish="stop"),
+ ], pause_at=1, close_error=httpx.CloseError("connection reset"))
+ provider, requests = chat_sdk([stream])
+
+ result = await provider.chat_stream([{"role": "user", "content": "work"}])
+
+ assert result.error_kind == "timeout" and len(requests) == 1 and stream.closed
+ assert any("connection reset" in message for message in cleanup_warnings)
+
+
+async def test_chat_callback_error_wins_over_close_error(chat_sdk, cleanup_warnings):
+ stream = _ControlledChatStream([
+ _bad_chat_event("usage"), _chat_event({"content": "fail"}),
+ ], close_error=httpx.CloseError("connection reset"))
+ provider, requests = chat_sdk([stream])
+
+ async def on_content(value):
+ raise RuntimeError("callback failed")
+
+ result = await provider.chat_stream(
+ [{"role": "user", "content": "work"}], on_content_delta=on_content,
+ )
+ assert result.finish_reason == "error" and "callback failed" in result.content
+ assert len(requests) == 1 and stream.closed and stream.close_calls == 1
+ assert any("connection reset" in message for message in cleanup_warnings)
+
+
[email protected]("close_fails", [False, True])
[email protected]("error_type", [RuntimeError, ConnectionError])
+async def test_chat_callback_error_does_not_retry_without_images(chat_sdk, close_fails, error_type):
+ stream = _ControlledChatStream(
+ [_chat_event({"reasoning_content": "thinking"})],
+ close_error=httpx.CloseError("connection reset") if close_fails else None,
+ )
+ retry = _ControlledChatStream([_chat_event({"content": "unexpected"}, finish="stop")])
+ provider, requests = chat_sdk([stream, retry])
+ messages = [{"role": "user", "content": [
+ {"type": "text", "text": "work"},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}},
+ ]}]
+ original = json.loads(json.dumps(messages))
+
+ async def on_thinking(_value):
+ raise error_type("callback failed")
+
+ result = await provider.chat_stream_with_retry(messages, on_thinking_delta=on_thinking)
+
+ assert result.finish_reason == "error" and "callback failed" in result.content
+ assert len(requests) == 1
+ assert messages == original
+ assert stream.closed
+
+
[email protected]("mode", ["success", "quota", "cancel"])
+def test_langfuse_async_openai_chat_stream(mode):
+ if importlib.util.find_spec("langfuse") is None:
+ pytest.skip("optional Langfuse dependency is not installed")
+ if mode == "quota":
+ _require_minimum_sdk_for_iterator_close_failure()
+
+ # Langfuse instruments OpenAI globally; isolate those hooks in a child.
+ script = textwrap.dedent("""
+ import asyncio
+ import runpy
+ import sys
+ from pathlib import Path
+
+ import httpx
+ import langfuse.openai as langfuse_openai
+ from nanobot.providers.openai_compat_provider import OpenAICompatProvider
+ from nanobot.providers.registry import ModelAPICapabilities
+
+ test_file = Path(sys.argv[2]).resolve()
+ sys.path.insert(0, str(test_file.parent.parent))
+ helpers = runpy.run_path(str(test_file))
+ event, stream_type = helpers["_chat_event"], helpers["_ControlledChatStream"]
+ mode = sys.argv[1]
+ starts, ends = [], []
+
+ class Generation:
+ def update(self, **kwargs):
+ return self
+ def end(self):
+ ends.append(True)
+ class Tracer:
+ def start_observation(self, **kwargs):
+ starts.append(True)
+ return Generation()
+ langfuse_openai.get_client = lambda **kwargs: Tracer()
+
+ events = ([{"error": {"message": "quota exhausted", "type": "insufficient_quota",
+ "code": "insufficient_quota"}}] if mode == "quota" else
+ [event({"content": "complete"}, finish="stop")])
+ stream = stream_type(events, close_error=(
+ httpx.CloseError("connection reset") if mode != "success" else None))
+ requests = []
+ def handler(request):
+ requests.append(request)
+ reply = stream if len(requests) == 1 else stream_type([
+ event({"content": "unexpected retry"}, finish="stop")])
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=reply)
+
+ async def main():
+ client = langfuse_openai.AsyncOpenAI(
+ api_key="synthetic", base_url="https://synthetic.invalid/v1", max_retries=0,
+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler), trust_env=False))
+ provider = OpenAICompatProvider(
+ api_key="synthetic", default_model="synthetic",
+ model_api=ModelAPICapabilities(("chat_completions",), "chat_completions"))
+ provider._client = client
+ provider._CHAT_RETRY_DELAYS = (0,)
+ try:
+ if mode == "cancel":
+ started = asyncio.Event()
+ async def on_content(value):
+ started.set()
+ await asyncio.Event().wait()
+ task = asyncio.create_task(provider.chat_stream_with_retry(
+ [{"role": "user", "content": "work"}], on_content_delta=on_content))
+ await asyncio.wait_for(started.wait(), timeout=5)
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ else:
+ raise AssertionError("caller cancellation was lost")
+ else:
+ result = await provider.chat_stream_with_retry(
+ [{"role": "user", "content": "work"}])
+ if mode == "success":
+ assert result.finish_reason == "stop" and result.content == "complete"
+ else:
+ assert result.finish_reason == "error"
+ assert result.error_type == result.error_code == "insufficient_quota"
+ assert len(requests) == 1 and stream.closed and stream.close_calls == 1
+ assert len(starts) == len(ends) == 1
+ finally:
+ await client.close()
+ asyncio.run(main())
+ """)
+ env = {
+ key: os.environ[key]
+ for key in (
+ "PATH", "SYSTEMROOT", "WINDIR", "TEMP", "TMP", "HOME", "USERPROFILE", "APPDATA",
+ "LOCALAPPDATA", "PYTHONPATH", "PYTHONDONTWRITEBYTECODE", "LD_LIBRARY_PATH",
+ )
+ if key in os.environ
+ }
+ result = subprocess.run(
+ [sys.executable, "-B", "-c", script, mode, __file__], env=env,
+ capture_output=True, text=True, timeout=30, check=False,
+ creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
diff --git a/tests/providers/test_openai_compat_spec.py b/tests/providers/test_openai_compat_spec.py
index b8600348c..35cde223b 100644
--- a/tests/providers/test_openai_compat_spec.py
+++ b/tests/providers/test_openai_compat_spec.py
@@ -4,6 +4,7 @@ import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
+import httpx
import pytest
from openai.types.chat import ChatCompletion, ChatCompletionChunk
@@ -121,6 +122,20 @@ def _chat_chunk(delta, finish=None, usage=None) -> ChatCompletionChunk:
})
+class _FakeChatStream:
+ def __init__(self, iterator):
+ self.iterator = iterator
+ self.close_error = None
+
+ def __aiter__(self):
+ return self.iterator.__aiter__()
+
+ async def close(self):
+ await self.iterator.aclose()
+ if self.close_error is not None:
+ raise self.close_error
+
+
def _fake_chat_stream(text: str = "ok"):
async def _stream():
yield _chat_chunk({"content": text})
@@ -128,7 +143,7 @@ def _fake_chat_stream(text: str = "ok"):
"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
})
- return _stream()
+ return _FakeChatStream(_stream())
def _fake_chat_stream_reasoning_chunks():
@@ -142,7 +157,7 @@ def _fake_chat_stream_reasoning_chunks():
"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
})
- return _stream()
+ return _FakeChatStream(_stream())
def _fake_chat_stream_tool_call_chunks():
@@ -163,7 +178,7 @@ def _fake_chat_stream_tool_call_chunks():
"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
})
- return _stream()
+ return _FakeChatStream(_stream())
def _fake_chat_stream_legacy_function_call_chunks():
@@ -178,7 +193,34 @@ def _fake_chat_stream_legacy_function_call_chunks():
"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
})
- return _stream()
+ return _FakeChatStream(_stream())
+
+
[email protected]("close_error", [
+ httpx.CloseError("connection reset"), TimeoutError("cleanup deadline"),
+], ids=["close-error", "close-timeout"])
[email protected]("with_image", [False, True], ids=["text", "image"])
+async def test_stream_close_only_error_is_visible_without_retry(close_error, with_image):
+ stream = _fake_chat_stream("complete")
+ stream.close_error = close_error
+ content = [{"type": "text", "text": "work"}]
+ if with_image:
+ content.append({"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}})
+ messages = [{"role": "user", "content": content}]
+ with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI") as mock_openai:
+ create = AsyncMock(return_value=stream)
+ mock_openai.return_value.chat.completions.create = create
+ provider = OpenAICompatProvider(
+ api_key="synthetic", default_model="synthetic",
+ model_api=ModelAPICapabilities(("chat_completions",), "chat_completions"),
+ )
+ provider._CHAT_RETRY_DELAYS = (0,)
+ result = await provider.chat_stream_with_retry(messages)
+
+ assert result.finish_reason == "error" and str(close_error) in result.content
+ assert result.error_kind == "cleanup" and result.error_should_retry is False
+ assert create.await_count == 1
+ assert messages[0]["content"] == content
@pytest.mark.asyncio
@@ -390,6 +432,9 @@ class _FakeResponsesError(Exception):
class _StalledStream:
+ async def close(self):
+ pass
+
def __aiter__(self):
return self
diff --git a/tests/providers/test_openai_responses.py b/tests/providers/test_openai_responses.py
index 49437d3c9..ff770b44c 100644
--- a/tests/providers/test_openai_responses.py
+++ b/tests/providers/test_openai_responses.py
@@ -954,6 +954,37 @@ class TestResponsesConversationState:
}
assert "lossy public transcript" not in str(items)
+ @pytest.mark.parametrize("last_system, expected", [
+ ("latest instructions", "latest instructions"),
+ ([{"type": "text", "text": "not a string"}], ""),
+ ])
+ def test_replay_uses_the_latest_system_message(self, last_system, expected):
+ state = build_responses_state(
+ provider="openai:test", model="test-model",
+ input_items=[{"role": "user", "content": "accepted"}], output_items=[],
+ ).with_pending_messages([{"role": "user", "content": "new"}])
+ messages = [
+ {"role": "system", "content": "old instructions"},
+ {"role": "user", "content": "historical"},
+ {"role": "system", "content": last_system},
+ ]
+
+ instructions, items, replayed = prepare_responses_input(
+ messages, state=state, provider="openai:test", model="test-model",
+ )
+ assert replayed is True
+ assert instructions == expected
+ assert items == [
+ {"role": "user", "content": "accepted"},
+ {"role": "user", "content": [{"type": "input_text", "text": "new"}]},
+ ]
+
+ fallback_instructions, fallback_items, replayed = prepare_responses_input(
+ messages, state=state, provider="openai:other", model="test-model",
+ )
+ assert replayed is False
+ assert (fallback_instructions, fallback_items) == convert_messages(messages)
+
def test_replayed_and_delta_reasoning_items_keep_array_content(self):
# Regression for PR #5214: token consolidation clears
# ``provider_state``, so the next turn converts the full history
diff --git a/tests/providers/test_stream_idle_timeout_config.py b/tests/providers/test_stream_idle_timeout_config.py
index 6aaca7a3f..a1ffd08d9 100644
--- a/tests/providers/test_stream_idle_timeout_config.py
+++ b/tests/providers/test_stream_idle_timeout_config.py
@@ -23,6 +23,7 @@ class _AsyncStream:
def __init__(self, chunks: list[Any]) -> None:
self._chunks = chunks
self._idx = 0
+ self.close = AsyncMock()
def __aiter__(self) -> _AsyncStream:
return self
@@ -82,15 +83,17 @@ async def test_openai_compat_stream_ignores_invalid_idle_timeout_env(monkeypatch
"model": "test-model",
"choices": [{"index": 0, "delta": {"content": "ok"}, "finish_reason": "stop"}],
})
+ stream = _AsyncStream([chunk])
provider._client = SimpleNamespace(
chat=SimpleNamespace(completions=SimpleNamespace(
- create=AsyncMock(return_value=_AsyncStream([chunk])),
+ create=AsyncMock(return_value=stream),
)),
)
result = await provider.chat_stream(messages=[{"role": "user", "content": "hi"}])
assert result.content == "ok"
+ stream.close.assert_awaited_once()
@pytest.mark.asyncio
diff --git a/tests/tools/test_read_enhancements.py b/tests/tools/test_read_enhancements.py
index 571075999..6ba218033 100644
--- a/tests/tools/test_read_enhancements.py
+++ b/tests/tools/test_read_enhancements.py
@@ -1,6 +1,9 @@
import base64
+import codecs
+import hashlib
import os
import sys
+import tracemalloc
from unittest.mock import patch
import pytest
@@ -14,6 +17,20 @@ from nanobot.utils.document import (
)
+class _ReadStreamWrapper:
+ def __init__(self, stream):
+ self.stream = stream
+
+ def __getattr__(self, name):
+ return getattr(self.stream, name)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return self.stream.__exit__(*args)
+
+
def _document_source(text: str) -> DocumentLineSource:
lines = (
LocatedDocumentLine(line, line_no, "")
@@ -51,6 +68,60 @@ class TestReadDedup:
assert "unchanged" in second.lower()
assert "line 0" not in second
+ @pytest.mark.asyncio
+ async def test_visible_unchanged_receipt_skips_text_parsing(self, tool, tmp_path, monkeypatch):
+ f = tmp_path / "data.txt"
+ f.write_text("one\ntwo\n", encoding="utf-8")
+ with file_state.file_read_context("read-1", lambda: {}):
+ first = await tool.execute(path=str(f), limit=1)
+
+ def fail_parse(*_args):
+ raise AssertionError("unchanged content must not be parsed again")
+
+ monkeypatch.setattr(tool, "_read_text", fail_parse)
+ with file_state.file_read_context("read-2", lambda: {"read-1": first}):
+ second = await tool.execute(path=str(f), limit=1)
+ assert second == f"[File unchanged since last read: {f}]"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("case", ["fresh", "force", "not_visible", "different_range"])
+ async def test_read_without_a_usable_receipt_makes_one_pass(
+ self, tool, tmp_path, monkeypatch, case,
+ ):
+ f = tmp_path / "data.txt"
+ raw = b"first\n" + b"x" * 80 + b"\nlast\n"
+ f.write_bytes(raw)
+ if case != "fresh":
+ with file_state.file_read_context("read-1", lambda: {}):
+ first = await tool.execute(path=str(f), limit=1)
+ else:
+ first = ""
+ real_fdopen = os.fdopen
+ counts = {"bytes": 0, "seeks": 0}
+
+ class CountingStream(_ReadStreamWrapper):
+ def read(self, size):
+ chunk = self.stream.read(size)
+ counts["bytes"] += len(chunk)
+ return chunk
+
+ def seek(self, *args):
+ counts["seeks"] += 1
+ return self.stream.seek(*args)
+
+ monkeypatch.setattr(
+ "nanobot.agent.tools.filesystem.os.fdopen",
+ lambda *args, **kwargs: CountingStream(real_fdopen(*args, **kwargs)),
+ )
+ visible = {} if case == "not_visible" else {"read-1": first}
+ offset = 2 if case == "different_range" else 1
+ with file_state.file_read_context("read-2", lambda: visible):
+ result = await tool.execute(path=str(f), offset=offset, limit=1, force=case == "force")
+
+ assert result.startswith(f"{offset}| ")
+ assert counts == {"bytes": len(raw), "seeks": 0}
+ assert tool._file_states.get(f).content_hash == hashlib.sha256(raw).hexdigest()
+
@pytest.mark.asyncio
async def test_read_after_external_modification_returns_full(self, tool, tmp_path):
f = tmp_path / "data.txt"
@@ -588,3 +659,425 @@ class TestReadFileDescription:
tool = ReadFileTool()
desc = tool.description.lower()
assert "document" in desc or "docx" in desc or "xlsx" in desc or "pptx" in desc
+
+
+class TestBoundedTextReads:
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("chunk_size", [16, 17])
+ @pytest.mark.parametrize(
+ ("encoding", "bom"),
+ [
+ ("utf-8", b""),
+ ("utf-8", codecs.BOM_UTF8),
+ ("utf-16-le", codecs.BOM_UTF16_LE),
+ ("utf-16-be", codecs.BOM_UTF16_BE),
+ ("utf-32-le", codecs.BOM_UTF32_LE),
+ ("utf-32-be", codecs.BOM_UTF32_BE),
+ ],
+ )
+ async def test_chunked_text_matches_splitlines_and_normalization(
+ self, tmp_path, monkeypatch, encoding, bom, chunk_size,
+ ):
+ content = (
+ "a" * 15 + "\r\n" + "prefix\r\r\nnext\rsolo\n"
+ + "\v\f\x1c\x1d\x1e\x85\u2028\u2029界😀end"
+ )
+ f = tmp_path / "mixed.txt"
+ f.write_bytes(bom + content.encode(encoding))
+ tool = ReadFileTool(workspace=tmp_path)
+ monkeypatch.setattr(tool, "_READ_CHUNK_SIZE", chunk_size)
+ lines = content.replace("\r\n", "\n").splitlines()
+
+ for offset, limit in [(1, 3), (4, 4), (len(lines), 1)]:
+ end = min(offset - 1 + limit, len(lines))
+ expected = "\n".join(
+ f"{number}| {line}"
+ for number, line in enumerate(lines[offset - 1:end], offset)
+ )
+ if end < len(lines):
+ expected += (
+ f"\n\n(Showing lines {offset}-{end} of {len(lines)}. "
+ f"Use offset={end + 1} to continue.)"
+ )
+ else:
+ expected += f"\n\n(End of file — {len(lines)} lines total)"
+ assert await tool.execute(path=str(f), offset=offset, limit=limit, force=True) == expected
+ result = await tool.execute(path=str(f), offset=len(lines) + 1, force=True)
+ assert result == f"Error: offset {len(lines) + 1} is beyond end of file ({len(lines)} lines)"
+
+ @pytest.mark.asyncio
+ async def test_late_utf8_error_uses_latin1_for_the_entire_known_text_file(
+ self, tmp_path, monkeypatch,
+ ):
+ raw = b"caf\xc3\xa9\n" + b"x" * 50 + b"\x85last\xff"
+ tool = ReadFileTool(workspace=tmp_path)
+ monkeypatch.setattr(tool, "_READ_CHUNK_SIZE", 16)
+ text_file = tmp_path / "legacy.txt"
+ text_file.write_bytes(raw)
+
+ result = await tool.execute(path=str(text_file), limit=1)
+
+ assert result == "1| café\n\n(Showing lines 1-1 of 3. Use offset=2 to continue.)"
+ assert tool._file_states.get(text_file).content_hash == hashlib.sha256(raw).hexdigest()
+
+ binary = tmp_path / "data.bin"
+ binary.write_bytes(raw)
+ result = await tool.execute(path=str(binary), limit=1)
+ assert result.is_error
+ assert str(result).startswith(f"Error: Cannot read binary file {binary} (MIME:")
+ assert tool._file_states.get(binary) is None
+
+ @pytest.mark.asyncio
+ async def test_latin1_fallback_preserves_prior_ascii_and_split_line_boundary(self, tmp_path, monkeypatch):
+ f = tmp_path / "legacy.txt"
+ raw = b"first\n" + b"a" * 9 + b"\r" + b"\xc3\xa9\xff\nlast\n"
+ f.write_bytes(raw)
+ tool = ReadFileTool(workspace=tmp_path)
+ monkeypatch.setattr(tool, "_READ_CHUNK_SIZE", 16)
+
+ result = await tool.execute(path=str(f), limit=4)
+
+ assert result == "1| first\n2| aaaaaaaaa\n3| éÿ\n4| last\n\n(End of file — 4 lines total)"
+ assert tool._file_states.get(f).content_hash == hashlib.sha256(raw).hexdigest()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("raw", "encoding"),
+ [
+ (codecs.BOM_UTF8 + b"a" * 40 + b"\xc3", "utf-8-sig"),
+ (codecs.BOM_UTF8 + b"a" * 40 + b"\xfflater", "utf-8-sig"),
+ (codecs.BOM_UTF16_LE + b"a\x00" * 20 + b"\x00", "utf-16"),
+ (codecs.BOM_UTF32_BE + b"\x00\x00\x00a" * 10 + b"\x00\x11\x00\x00", "utf-32"),
+ ],
+ )
+ async def test_malformed_bom_keeps_original_decode_error(
+ self, tmp_path, monkeypatch, raw, encoding,
+ ):
+ f = tmp_path / "broken.txt"
+ f.write_bytes(raw)
+ tool = ReadFileTool(workspace=tmp_path)
+ monkeypatch.setattr(tool, "_READ_CHUNK_SIZE", 17)
+ with pytest.raises(UnicodeDecodeError) as exc:
+ raw.decode(encoding)
+
+ result = await tool.execute(path=str(f), limit=1)
+
+ assert result.is_error
+ assert result == f"Error reading file: {exc.value}"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("filename", "raw", "mime"),
+ [
+ ("image.dat", b"\x89PNG\r\n\x1a\ncontents", "image/png"),
+ ("image.png", b"plain text with image extension", "image/png"),
+ ],
+ )
+ async def test_magic_and_extension_image_reads_are_unchanged(self, tmp_path, filename, raw, mime):
+ f = tmp_path / filename
+ f.write_bytes(raw)
+ tool = ReadFileTool(workspace=tmp_path)
+
+ result = await tool.execute(path=str(f), limit=1)
+
+ assert result[0]["image_url"]["url"] == f"data:{mime};base64,{base64.b64encode(raw).decode()}"
+ assert result[1] == {"type": "text", "text": f"(Image file: {f})"}
+
+ @pytest.mark.asyncio
+ async def test_image_growth_during_read_respects_size_limit(self, tmp_path, monkeypatch):
+ f = tmp_path / "growing.png"
+ f.write_bytes(b"\x89PNG\r\n\x1a\n" + b"x" * 16)
+ tool = ReadFileTool(workspace=tmp_path)
+ monkeypatch.setattr(tool, "_READ_CHUNK_SIZE", 16)
+ monkeypatch.setattr(tool, "_MAX_FILE_SIZE_BYTES", 64)
+ real_fdopen = os.fdopen
+
+ class GrowingStream(_ReadStreamWrapper):
+ def __init__(self, stream):
+ super().__init__(stream)
+ self.grown = False
+
+ def read(self, size):
+ chunk = self.stream.read(size)
+ if not self.grown:
+ self.grown = True
+ with f.open("ab") as out:
+ out.write(b"y" * 64)
+ return chunk
+
+ monkeypatch.setattr(
+ "nanobot.agent.tools.filesystem.os.fdopen",
+ lambda *args, **kwargs: GrowingStream(real_fdopen(*args, **kwargs)),
+ )
+ result = await tool.execute(path=str(f))
+
+ assert result.is_error
+ assert "File too large to read" in result
+
+ @pytest.mark.asyncio
+ async def test_small_image_does_not_allocate_the_file_size_limit(self, tmp_path):
+ if tracemalloc.is_tracing():
+ pytest.skip("requires isolated tracemalloc accounting")
+ f = tmp_path / "small.png"
+ f.write_bytes(b"\x89PNG\r\n\x1a\ncontents")
+ tool = ReadFileTool(workspace=tmp_path)
+ await tool.execute(path=str(f))
+
+ tracemalloc.start()
+ try:
+ result = await tool.execute(path=str(f))
+ peak = tracemalloc.get_traced_memory()[1]
+ finally:
+ tracemalloc.stop()
+
+ assert result[0]["type"] == "image_url"
+ assert peak < 2 * 1024 * 1024
+
+ @pytest.mark.asyncio
+ async def test_hash_and_dedup_cover_changes_outside_selected_range(self, tmp_path, monkeypatch):
+ f = tmp_path / "data.txt"
+ raw = b"first\n" + b"x" * 100 + b"\nend-A\n"
+ f.write_bytes(raw)
+ tool = ReadFileTool(workspace=tmp_path)
+ monkeypatch.setattr(tool, "_READ_CHUNK_SIZE", 16)
+ with file_state.file_read_context("read-1", lambda: {}):
+ first = await tool.execute(path=str(f), limit=1)
+ assert tool._file_states.get(f).content_hash == hashlib.sha256(raw).hexdigest()
+ with file_state.file_read_context("read-2", lambda: {"read-1": first}):
+ assert "File unchanged" in await tool.execute(path=str(f), limit=1)
+
+ mtime = f.stat().st_mtime_ns
+ changed = raw.replace(b"end-A", b"end-B")
+ f.write_bytes(changed)
+ os.utime(f, ns=(mtime, mtime))
+ with file_state.file_read_context("read-3", lambda: {"read-1": first}):
+ reread = await tool.execute(path=str(f), limit=1)
+ assert reread == first
+ assert tool._file_states.get(f).content_hash == hashlib.sha256(changed).hexdigest()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("new_type", ["utf16", "image"])
+ async def test_changed_file_is_redetected_and_hashed_after_precheck(
+ self, tmp_path, monkeypatch, new_type,
+ ):
+ f = tmp_path / "data.txt"
+ f.write_bytes(b"original\n")
+ tool = ReadFileTool(workspace=tmp_path)
+ with file_state.file_read_context("read-1", lambda: {}):
+ first = await tool.execute(path=str(f))
+ f.write_bytes(b"intermediate bytes\n")
+ final = (
+ "new text\n".encode("utf-16") if new_type == "utf16"
+ else b"\x89PNG\r\n\x1a\nimage data"
+ )
+ real_fdopen = os.fdopen
+
+ class ChangeAfterPrecheck(_ReadStreamWrapper):
+ def __init__(self, stream):
+ super().__init__(stream)
+ self.changed = False
+
+ def read(self, size):
+ chunk = self.stream.read(size)
+ if not chunk and not self.changed:
+ self.changed = True
+ f.write_bytes(final)
+ return chunk
+
+ monkeypatch.setattr(
+ "nanobot.agent.tools.filesystem.os.fdopen",
+ lambda *args, **kwargs: ChangeAfterPrecheck(real_fdopen(*args, **kwargs)),
+ )
+ with file_state.file_read_context("read-2", lambda: {"read-1": first}):
+ second = await tool.execute(path=str(f))
+
+ if new_type == "image":
+ assert second[0]["image_url"]["url"] == (
+ f"data:image/png;base64,{base64.b64encode(final).decode()}"
+ )
+ assert tool._file_states.get(f).content_hash == hashlib.sha256(b"original\n").hexdigest()
+ else:
+ assert second == "1| new text\n\n(End of file — 1 lines total)"
+ assert tool._file_states.get(f).content_hash == hashlib.sha256(final).hexdigest()
+ with file_state.file_read_context("read-3", lambda: {"read-2": second}):
+ repeat = await tool.execute(path=str(f))
+ assert repeat == f"[File unchanged since last read: {f}]"
+
+ @pytest.mark.asyncio
+ async def test_shrunk_image_after_receipt_check_does_not_allocate_old_file_size(self, tmp_path, monkeypatch):
+ if tracemalloc.is_tracing():
+ pytest.skip("requires isolated tracemalloc accounting")
+ f = tmp_path / "data.txt"
+ f.write_bytes(b"x" * (8 * 1024 * 1024))
+ tool = ReadFileTool(workspace=tmp_path)
+ with file_state.file_read_context("read-1", lambda: {}):
+ first = await tool.execute(path=str(f), limit=1)
+ with f.open("r+b") as out:
+ out.seek(-1, os.SEEK_END)
+ out.write(b"y")
+ image = b"\x89PNG\r\n\x1a\nsmall"
+ real_fdopen = os.fdopen
+
+ class ChangeAfterPrecheck(_ReadStreamWrapper):
+ def __init__(self, stream):
+ super().__init__(stream)
+ self.changed = False
+
+ def read(self, size):
+ chunk = self.stream.read(size)
+ if not chunk and not self.changed:
+ self.changed = True
+ f.write_bytes(image)
+ return chunk
+
+ monkeypatch.setattr(
+ "nanobot.agent.tools.filesystem.os.fdopen",
+ lambda *args, **kwargs: ChangeAfterPrecheck(real_fdopen(*args, **kwargs)),
+ )
+ tracemalloc.start()
+ try:
+ with file_state.file_read_context("read-2", lambda: {"read-1": first}):
+ result = await tool.execute(path=str(f), limit=1)
+ peak = tracemalloc.get_traced_memory()[1]
+ finally:
+ tracemalloc.stop()
+
+ assert result[0]["image_url"]["url"] == f"data:image/png;base64,{base64.b64encode(image).decode()}"
+ assert peak < 3 * 1024 * 1024
+
+ @pytest.mark.asyncio
+ async def test_growth_during_hash_precheck_respects_size_limit(self, tmp_path, monkeypatch):
+ f = tmp_path / "data.txt"
+ raw = b"first\n" + b"x" * 20
+ f.write_bytes(raw)
+ tool = ReadFileTool(workspace=tmp_path)
+ monkeypatch.setattr(tool, "_READ_CHUNK_SIZE", 16)
+ monkeypatch.setattr(tool, "_MAX_FILE_SIZE_BYTES", 64)
+ with file_state.file_read_context("read-1", lambda: {}):
+ first = await tool.execute(path=str(f))
+ real_fdopen = os.fdopen
+
+ class GrowingStream(_ReadStreamWrapper):
+ def __init__(self, stream):
+ super().__init__(stream)
+ self.grown = False
+
+ def read(self, size):
+ chunk = self.stream.read(size)
+ if not self.grown:
+ self.grown = True
+ with f.open("ab") as out:
+ out.write(b"y" * 64)
+ return chunk
+
+ monkeypatch.setattr(
+ "nanobot.agent.tools.filesystem.os.fdopen",
+ lambda *args, **kwargs: GrowingStream(real_fdopen(*args, **kwargs)),
+ )
+ with file_state.file_read_context("read-2", lambda: {"read-1": first}):
+ result = await tool.execute(path=str(f))
+
+ assert result.is_error
+ assert "File too large to read" in result
+ assert tool._file_states.get(f).content_hash == hashlib.sha256(raw).hexdigest()
+
+ @pytest.mark.asyncio
+ async def test_file_at_size_limit_is_readable(self, tmp_path, monkeypatch):
+ f = tmp_path / "exact.txt"
+ raw = b"x" * 99 + b"\n"
+ f.write_bytes(raw)
+ tool = ReadFileTool(workspace=tmp_path)
+ monkeypatch.setattr(tool, "_MAX_FILE_SIZE_BYTES", len(raw))
+ monkeypatch.setattr(tool, "_READ_CHUNK_SIZE", 16)
+
+ result = await tool.execute(path=str(f), limit=1)
+
+ assert result == "1| " + "x" * 99 + "\n\n(End of file — 1 lines total)"
+ assert tool._file_states.get(f).content_hash == hashlib.sha256(raw).hexdigest()
+
+ @pytest.mark.asyncio
+ async def test_opened_nonregular_file_is_not_read(self, tmp_path, monkeypatch):
+ f = tmp_path / "replaced.txt"
+ f.write_text("regular", encoding="utf-8")
+ target = f.resolve()
+ read_fd, write_fd = os.pipe()
+ os.close(write_fd)
+ real_open = os.open
+
+ def open_replacement(path, flags, *args, **kwargs):
+ if os.fspath(path) == os.fspath(target):
+ return read_fd
+ return real_open(path, flags, *args, **kwargs)
+
+ tool = ReadFileTool()
+ try:
+ with monkeypatch.context() as scoped:
+ scoped.setattr("nanobot.agent.tools.filesystem.os.open", open_replacement)
+ result = await tool.execute(path=str(f))
+ finally:
+ try:
+ os.close(read_fd)
+ except OSError:
+ pass
+
+ assert result.is_error
+ assert result == f"Error: Not a file: {f}"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("exceeds_limit", [False, True])
+ async def test_growth_after_open_is_read_once_and_respects_size_limit(
+ self, tmp_path, monkeypatch, exceeds_limit,
+ ):
+ f = tmp_path / "growing.txt"
+ original = b"first\n" + b"x" * 40 + b"\nlast\n"
+ addition = b"extra\n" * (12 if exceeds_limit else 1)
+ f.write_bytes(original)
+ tool = ReadFileTool(workspace=tmp_path)
+ monkeypatch.setattr(tool, "_READ_CHUNK_SIZE", 16)
+ monkeypatch.setattr(tool, "_MAX_FILE_SIZE_BYTES", 100)
+ read_text = tool._read_text
+
+ def append_before_reading_rest(stream, first, *args):
+ with f.open("ab") as out:
+ out.write(addition)
+ return read_text(stream, first, *args)
+
+ monkeypatch.setattr(tool, "_read_text", append_before_reading_rest)
+ result = await tool.execute(path=str(f), limit=1)
+
+ if exceeds_limit:
+ assert result.is_error
+ assert "File too large to read" in result
+ assert tool._file_states.get(f) is None
+ else:
+ assert result == "1| first\n\n(Showing lines 1-1 of 4. Use offset=2 to continue.)"
+ assert tool._file_states.get(f).content_hash == hashlib.sha256(original + addition).hexdigest()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("offset", [1, 2])
+ async def test_large_unbroken_line_has_bounded_python_allocations(self, tmp_path, offset):
+ if tracemalloc.is_tracing():
+ pytest.skip("requires isolated tracemalloc accounting")
+ f = tmp_path / "large.txt"
+ with f.open("wb") as out:
+ out.write(b"first\n")
+ for _ in range(128):
+ out.write(b"x" * 65536)
+ out.write(b"\nlast\n")
+ tool = ReadFileTool(workspace=tmp_path)
+ warmup = tmp_path / "warmup.txt"
+ warmup.write_text("warmup", encoding="utf-8")
+ await tool.execute(path=str(warmup))
+
+ tracemalloc.start()
+ try:
+ result = await tool.execute(path=str(f), offset=offset, limit=1)
+ peak = tracemalloc.get_traced_memory()[1]
+ finally:
+ tracemalloc.stop()
+
+ assert "of 3. Use offset=" in result
+ if offset == 2:
+ assert "Line 2 truncated" in result
+ assert peak < 3 * 1024 * 1024