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

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

No files matched your search

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