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

+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: