refactor(session): centralize state ownership in SQLite (#5943)
* fix(session): move persistence off event loop * refactor(session): isolate async persistence boundary * refactor(session): keep a single session manager * refactor(session): use stateless async adapters * fix(session): serialize local persistence without file-lock contention * refactor(session): own async persistence and snapshot commits * refactor(session): narrow persistence changes to async adapters * refactor(session): remove redundant async forwarding helpers * fix(command): offload compact session persistence * fix(session): adapt idle compaction to current main * fix(webui): offload session metadata persistence * refactor(session): centralize state ownership in SQLite * fix(session): skip storage for non-recoverable followups * test(webui): honor the full gateway event deadline * perf(session): persist incremental changes and reuse owner snapshots * test(agent): allow durable worker shutdown in burst test * fix(gateway): drain session storage on Windows console shutdown * fix(session): enforce bounded ownership and lifecycle-safe persistence * fix: reject unresolved home paths and stabilize platform tests * fix(session): preserve request context compatibility and owner-backed tests * docs: focus configuration guide on user-facing behavior * fix(session): adapt goal admission to async ownership after rebase * fix(session): integrate current gateway and subagent contracts * fix(session): align rebased workspace admission and async tests * fix(session): support compatible SQLite schema evolution * test(agent): use session owner in workspace context regressions * test: stabilize Windows lifecycle and browser checks * refactor(session): remove premature JSONL file export * ci: bound Windows full-suite worker concurrency * chore: remove session state refactor notes * fix(session): queue writes and retain worker connections * perf(webui): read detached metadata for session and task lists * perf(agent): bound prompt preparation and local token counting * docs: remove internal session storage guide * perf(session): skip archived transcripts during idle scans * fix(session): coordinate turns and isolate legacy session data Bind WebUI input generations to the execution session and serialize idle and SDK compaction with turns. Keep turn drafts through preparation so the latest channel route persists. Move imported workspace JSONL and checkpoints to durable private backups before gateway admission, resuming cleanup after interruptions. Remove committed child sessions when task creation is cancelled. Validation: focused Python and frontend regressions, Ruff, BasedPyright, import boundaries, WebUI build, and isolated gateway/browser flows. * fix(agent): keep cancellation hooks independent of prompt preparation * fix(session): preserve admission, delivery, and migration contracts * fix(agent): preserve cancellation settlement after rebase * fix(session): preserve request attribution through async ownership
This commit is contained in:
1 parent
33ff520d12
commit
8f6a5594fb
144 files changed
+8293
-4912
No files matched your search
@@ -0,0 +1,290 @@
|
||||
"""One-time JSONL import, introduced in 0.3.6 and removed in 0.5.0.
|
||||
|
||||
0.4.x is the final migration release line. Older installations must pass through
|
||||
that line before upgrading to 0.5.0. Workspace sources move to private backups
|
||||
after the import commits; failed imports leave their source files unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import stat
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, TypedDict, cast
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.providers.base import ProviderConversationState
|
||||
from nanobot.session.location import SessionLocation
|
||||
from nanobot.session.manager import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.session.sqlite_store import SqliteSessionStore
|
||||
|
||||
INTRODUCED_VERSION = "0.3.6"
|
||||
LAST_SUPPORTED_RELEASE_LINE = "0.4.x"
|
||||
SUNSET_VERSION = "0.5.0"
|
||||
WORKSPACE_BACKUP_DIR = "jsonl-backup"
|
||||
_WORKSPACE_SOURCES_KEY = "jsonl_workspace_sources"
|
||||
|
||||
|
||||
class _WorkspaceSource(TypedDict):
|
||||
name: str
|
||||
digest: str
|
||||
|
||||
|
||||
def _file_identity(value: os.stat_result) -> tuple[int, int, int, int]:
|
||||
return value.st_dev, value.st_ino, value.st_size, value.st_mtime_ns
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _LegacyFile:
|
||||
path: Path
|
||||
content: bytes
|
||||
stat: os.stat_result
|
||||
|
||||
@property
|
||||
def digest(self) -> str:
|
||||
return hashlib.sha256(self.content).hexdigest()
|
||||
|
||||
|
||||
def _read_file(path: Path) -> _LegacyFile:
|
||||
if not stat.S_ISREG(path.lstat().st_mode):
|
||||
raise ValueError(f"JSONL migration requires a regular file: {path}")
|
||||
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
|
||||
with os.fdopen(os.open(path, flags), "rb") as handle:
|
||||
before = os.fstat(handle.fileno())
|
||||
if not stat.S_ISREG(before.st_mode):
|
||||
raise ValueError(f"JSONL migration requires a regular file: {path}")
|
||||
content = handle.read()
|
||||
after = os.fstat(handle.fileno())
|
||||
if _file_identity(before) != _file_identity(after):
|
||||
raise ValueError(f"JSONL migration source changed while reading: {path}")
|
||||
return _LegacyFile(path, content, after)
|
||||
|
||||
|
||||
def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
||||
value: dict[str, Any] = {}
|
||||
for key, item in pairs:
|
||||
if key in value:
|
||||
raise ValueError(f"duplicate JSON key: {key!r}")
|
||||
value[key] = item
|
||||
return value
|
||||
|
||||
|
||||
def _record(line: str) -> dict[str, Any]:
|
||||
value: object = json.loads(line, object_pairs_hook=_unique_object)
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("JSONL records must be objects")
|
||||
return cast(dict[str, Any], value)
|
||||
|
||||
|
||||
def read_jsonl(path: Path) -> tuple[Session, list[_LegacyFile]]:
|
||||
"""Read a complete legacy session, failing without modifying malformed input."""
|
||||
source = _read_file(path)
|
||||
files = [source]
|
||||
header: dict[str, Any] | None = None
|
||||
messages: list[dict[str, Any]] = []
|
||||
provider: ProviderConversationState | None = None
|
||||
provider_seen = False
|
||||
for line in source.content.decode("utf-8").splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
item = _record(line)
|
||||
if item.get("_type") == "metadata":
|
||||
if header is not None:
|
||||
raise ValueError(f"multiple session headers: {path}")
|
||||
header = item
|
||||
elif item.get("_type") == "provider_state":
|
||||
if provider_seen:
|
||||
raise ValueError(f"multiple provider state records: {path}")
|
||||
provider_seen = True
|
||||
provider = ProviderConversationState.from_private_record(item.get("state"))
|
||||
if provider is None:
|
||||
raise ValueError(f"invalid private provider state: {path}")
|
||||
else:
|
||||
if not isinstance(item.get("role"), str):
|
||||
raise ValueError(f"invalid session message: {path}")
|
||||
messages.append(item)
|
||||
if header is None:
|
||||
raise ValueError(f"missing session header: {path}")
|
||||
key = header.get("key") or SessionLocation.session_key_from_path(path)
|
||||
if not isinstance(key, str) or not key:
|
||||
raise ValueError(f"cannot determine session key: {path}")
|
||||
metadata: object = header.get("metadata")
|
||||
if metadata is None:
|
||||
metadata = {}
|
||||
if not isinstance(metadata, dict):
|
||||
raise ValueError(f"invalid session metadata: {path}")
|
||||
fallback = datetime.fromtimestamp(source.stat.st_mtime).isoformat()
|
||||
session = Session(
|
||||
key=key, messages=messages, metadata=cast(dict[str, Any], metadata),
|
||||
created_at=datetime.fromisoformat(header.get("created_at") or fallback),
|
||||
updated_at=datetime.fromisoformat(header.get("updated_at") or fallback),
|
||||
last_consolidated=header.get("last_archived", header.get("last_consolidated", 0)),
|
||||
provider_state=provider,
|
||||
)
|
||||
checkpoint_path = path.with_suffix(".checkpoint.json")
|
||||
if checkpoint_path.exists() or checkpoint_path.is_symlink():
|
||||
checkpoint_source = _read_file(checkpoint_path)
|
||||
files.append(checkpoint_source)
|
||||
checkpoint = _record(checkpoint_source.content.decode("utf-8"))
|
||||
if (
|
||||
checkpoint_source.stat.st_mtime_ns >= source.stat.st_mtime_ns
|
||||
and checkpoint.get("version") == 1
|
||||
and checkpoint.get("session_key") == key
|
||||
and checkpoint.get("base_updated_at") == session.updated_at.isoformat()
|
||||
and checkpoint.get("base_message_count") == len(messages)
|
||||
):
|
||||
if not isinstance(checkpoint.get("checkpoint"), dict):
|
||||
raise ValueError(f"invalid checkpoint: {checkpoint_path}")
|
||||
session.metadata["runtime_checkpoint"] = checkpoint["checkpoint"]
|
||||
raw_provider = checkpoint.get("provider_state")
|
||||
session.provider_state = ProviderConversationState.from_private_record(raw_provider)
|
||||
if raw_provider is not None and session.provider_state is None:
|
||||
raise ValueError(f"invalid checkpoint provider state: {checkpoint_path}")
|
||||
return session, files
|
||||
|
||||
|
||||
def migrate_jsonl(store: SqliteSessionStore, workspace: Path) -> int:
|
||||
"""Import atomically, then let the caller commit the durable completion marker.
|
||||
|
||||
A malformed or conflicting source aborts the whole import. The committed
|
||||
workspace-source manifest lets startup finish isolation after a crash.
|
||||
"""
|
||||
imported: dict[str, tuple[Path, tuple[str, ...]]] = {}
|
||||
workspace_sources: list[_WorkspaceSource] = []
|
||||
workspace_directory = workspace / "sessions"
|
||||
for directory in (store.path.parent, workspace_directory):
|
||||
if directory.is_symlink():
|
||||
raise ValueError(f"migration source must not be a symlink: {directory}")
|
||||
for path in sorted(directory.glob("*.jsonl")):
|
||||
try:
|
||||
session, files = read_jsonl(path)
|
||||
digests = tuple(source.digest for source in files)
|
||||
prior = imported.get(session.key)
|
||||
if prior is not None:
|
||||
prior_path, prior_digests = prior
|
||||
if prior_digests != digests or store.load(session.key) != session:
|
||||
raise ValueError(f"duplicate JSONL session key: {prior_path} and {path}")
|
||||
else:
|
||||
if store.load(session.key) is not None:
|
||||
raise ValueError(f"session already exists in SQLite: {session.key}")
|
||||
store.save(session)
|
||||
imported[session.key] = path, digests
|
||||
if directory == workspace_directory:
|
||||
workspace_sources.extend(
|
||||
{"name": source.path.name, "digest": source.digest} for source in files
|
||||
)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(
|
||||
f"JSONL migration failed for {path}; source files are unchanged. "
|
||||
"Resolve the invalid or conflicting file and restart."
|
||||
) from exc
|
||||
if workspace_sources:
|
||||
with store.transaction() as db:
|
||||
db.execute("INSERT INTO storage_meta (key, value) VALUES (?, ?)", (
|
||||
_WORKSPACE_SOURCES_KEY, json.dumps(workspace_sources),
|
||||
))
|
||||
if imported:
|
||||
logger.info("Imported {} JSONL sessions into {}", len(imported), store.path)
|
||||
return len(imported)
|
||||
|
||||
|
||||
def _workspace_sources(raw: str) -> list[_WorkspaceSource]:
|
||||
value: object = json.loads(raw)
|
||||
if not isinstance(value, list):
|
||||
raise ValueError("workspace migration manifest must be a list")
|
||||
sources: list[_WorkspaceSource] = []
|
||||
for item in cast(list[object], value):
|
||||
if not isinstance(item, dict):
|
||||
raise ValueError("workspace migration source must be an object")
|
||||
record = cast(dict[str, object], item)
|
||||
name, digest = record.get("name"), record.get("digest")
|
||||
if (
|
||||
not isinstance(name, str) or Path(name).name != name
|
||||
or not name.endswith((".jsonl", ".checkpoint.json"))
|
||||
or not isinstance(digest, str) or len(digest) != 64
|
||||
or any(char not in "0123456789abcdef" for char in digest)
|
||||
):
|
||||
raise ValueError("invalid workspace migration source")
|
||||
sources.append({"name": name, "digest": digest})
|
||||
return sources
|
||||
|
||||
|
||||
def _write_backup(path: Path, source: _LegacyFile) -> None:
|
||||
temporary = path.with_name(f".{path.name}.{secrets.token_hex(8)}.tmp")
|
||||
try:
|
||||
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
||||
with os.fdopen(os.open(temporary, flags, 0o600), "wb") as handle:
|
||||
handle.write(source.content)
|
||||
handle.flush()
|
||||
os.utime(temporary, ns=(source.stat.st_atime_ns, source.stat.st_mtime_ns))
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def finish_workspace_migration(store: SqliteSessionStore, workspace: Path) -> None:
|
||||
"""Durably back up every workspace source before removing any of them.
|
||||
|
||||
The import and its manifest commit together. Cleanup holds the startup write
|
||||
lock and clears the manifest only after both backup and removal are durable.
|
||||
"""
|
||||
source_directory = workspace / "sessions"
|
||||
backup_directory = store.path.parent / WORKSPACE_BACKUP_DIR
|
||||
with store.transaction() as db:
|
||||
pending = db.execute(
|
||||
"SELECT value FROM storage_meta WHERE key=?", (_WORKSPACE_SOURCES_KEY,),
|
||||
).fetchone()
|
||||
if pending is None:
|
||||
return
|
||||
try:
|
||||
sources = _workspace_sources(pending[0])
|
||||
if source_directory.is_symlink() or backup_directory.is_symlink():
|
||||
raise ValueError("workspace migration directories must not be symlinks")
|
||||
backup_directory.mkdir(mode=0o700, exist_ok=True)
|
||||
SessionLocation.fsync_directory(backup_directory.parent)
|
||||
prepared: list[tuple[Path, os.stat_result]] = []
|
||||
for record in sources:
|
||||
source_path = source_directory / record["name"]
|
||||
backup_path = backup_directory / record["name"]
|
||||
source: _LegacyFile | None = None
|
||||
try:
|
||||
source = _read_file(source_path)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
if source is not None:
|
||||
if source.digest != record["digest"]:
|
||||
raise ValueError(f"workspace migration source changed: {source_path}")
|
||||
prepared.append((source_path, source.stat))
|
||||
try:
|
||||
backup = _read_file(backup_path)
|
||||
except FileNotFoundError:
|
||||
if source is None:
|
||||
raise ValueError(f"workspace migration source and backup are missing: {source_path}") from None
|
||||
_write_backup(backup_path, source)
|
||||
else:
|
||||
if backup.digest != record["digest"]:
|
||||
raise ValueError(f"workspace migration backup differs from its source: {backup_path}")
|
||||
SessionLocation.fsync_directory(backup_directory)
|
||||
for path, expected in prepared:
|
||||
actual = path.lstat()
|
||||
if not stat.S_ISREG(actual.st_mode) or _file_identity(actual) != _file_identity(expected):
|
||||
raise ValueError(f"workspace migration source changed: {path}")
|
||||
for path, _expected in prepared:
|
||||
path.unlink()
|
||||
if source_directory.exists():
|
||||
SessionLocation.fsync_directory(source_directory)
|
||||
db.execute("DELETE FROM storage_meta WHERE key=?", (_WORKSPACE_SOURCES_KEY,))
|
||||
except Exception as exc:
|
||||
raise RuntimeError(
|
||||
f"Could not move legacy sessions out of {source_directory}; "
|
||||
f"backups are in {backup_directory}. Resolve the file error and restart."
|
||||
) from exc
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Stable workspace identity and private session storage locations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import errno
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
|
||||
from filelock import FileLock
|
||||
|
||||
from nanobot.config.paths import get_runtime_subdir
|
||||
from nanobot.utils.helpers import (
|
||||
ensure_dir,
|
||||
safe_filename,
|
||||
)
|
||||
|
||||
_WORKSPACE_STATE_DIR = ".nanobot"
|
||||
_WORKSPACE_ID_FILE = "workspace-id"
|
||||
_WORKSPACE_ID_RE = re.compile(r"^[0-9a-f]{32}$")
|
||||
_SESSION_MIGRATION_LOCK_TIMEOUT_SECONDS = 30
|
||||
|
||||
|
||||
class SessionLocation:
|
||||
def __init__(self, workspace: Path, *, sessions_root: Path | None = None):
|
||||
canonical_workspace = Path(workspace).expanduser().resolve(strict=False)
|
||||
ensure_dir(canonical_workspace)
|
||||
root = (
|
||||
Path(sessions_root).expanduser().resolve(strict=False)
|
||||
if sessions_root is not None
|
||||
else get_runtime_subdir("sessions").resolve(strict=False)
|
||||
)
|
||||
if root == canonical_workspace or root.is_relative_to(canonical_workspace):
|
||||
raise RuntimeError(
|
||||
"session storage must be outside the agent workspace; "
|
||||
"move --config outside --workspace or choose a nested workspace directory"
|
||||
)
|
||||
ensure_dir(root)
|
||||
with suppress(OSError):
|
||||
os.chmod(root, 0o700)
|
||||
self.workspace = canonical_workspace
|
||||
self._migration_lock = FileLock(
|
||||
str(root / ".workspace-migration.lock"),
|
||||
timeout=_SESSION_MIGRATION_LOCK_TIMEOUT_SECONDS,
|
||||
)
|
||||
with self._migration_lock:
|
||||
workspace_id = self._load_or_create_workspace_id(canonical_workspace, root)
|
||||
workspace_id = self._claim_workspace_namespace(
|
||||
root,
|
||||
canonical_workspace,
|
||||
workspace_id,
|
||||
)
|
||||
self.sessions_dir = ensure_dir(root / workspace_id)
|
||||
|
||||
@staticmethod
|
||||
def fsync_directory(path: Path) -> None:
|
||||
"""Persist storage directory entries where directory fsync is supported."""
|
||||
with suppress(PermissionError, NotImplementedError):
|
||||
fd = os.open(path, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
except OSError as exc:
|
||||
if exc.errno != errno.EINVAL:
|
||||
raise
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
@classmethod
|
||||
def _write_text_atomic(cls, path: Path, content: str, *, mode: int = 0o600) -> None:
|
||||
tmp = path.with_name(f".{path.name}.{secrets.token_hex(8)}.tmp")
|
||||
try:
|
||||
with open(tmp, "x", encoding="utf-8") as handle:
|
||||
os.chmod(tmp, mode)
|
||||
handle.write(content)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(tmp, path)
|
||||
cls.fsync_directory(path.parent)
|
||||
finally:
|
||||
tmp.unlink(missing_ok=True)
|
||||
|
||||
@classmethod
|
||||
def _read_workspace_id(cls, marker: Path) -> str:
|
||||
if marker.is_symlink():
|
||||
raise RuntimeError(f"workspace identity marker must not be a symlink: {marker}")
|
||||
value = marker.read_text(encoding="utf-8").strip()
|
||||
if not _WORKSPACE_ID_RE.fullmatch(value):
|
||||
raise RuntimeError(
|
||||
f"workspace identity marker is invalid: {marker}; "
|
||||
"restore its original 32-character identifier before starting nanobot"
|
||||
)
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _workspace_id_path(workspace: Path) -> Path:
|
||||
state_dir = workspace / _WORKSPACE_STATE_DIR
|
||||
if state_dir.is_symlink():
|
||||
raise RuntimeError(f"workspace state directory must not be a symlink: {state_dir}")
|
||||
ensure_dir(state_dir)
|
||||
return state_dir / _WORKSPACE_ID_FILE
|
||||
|
||||
@classmethod
|
||||
def _find_workspace_namespace(cls, workspace: Path, root: Path) -> str | None:
|
||||
"""Recover an identity marker removed by cleanup at the same workspace path."""
|
||||
matches: list[str] = []
|
||||
for sessions_dir in root.iterdir():
|
||||
if (
|
||||
not _WORKSPACE_ID_RE.fullmatch(sessions_dir.name)
|
||||
or sessions_dir.is_symlink()
|
||||
or not sessions_dir.is_dir()
|
||||
):
|
||||
continue
|
||||
marker = sessions_dir / ".workspace"
|
||||
if marker.is_symlink() or not marker.is_file():
|
||||
continue
|
||||
try:
|
||||
recorded = Path(marker.read_text(encoding="utf-8").strip()).expanduser()
|
||||
recorded = recorded.resolve(strict=False)
|
||||
same_workspace = recorded == workspace or (
|
||||
recorded.exists() and recorded.samefile(workspace)
|
||||
)
|
||||
except (OSError, UnicodeError, ValueError):
|
||||
continue
|
||||
if same_workspace:
|
||||
matches.append(sessions_dir.name)
|
||||
if len(matches) > 1:
|
||||
raise RuntimeError(
|
||||
f"multiple session namespaces claim workspace {workspace}; "
|
||||
"remove the stale namespace marker before starting nanobot"
|
||||
)
|
||||
return matches[0] if matches else None
|
||||
|
||||
@classmethod
|
||||
def _load_or_create_workspace_id(cls, workspace: Path, root: Path) -> str:
|
||||
marker = cls._workspace_id_path(workspace)
|
||||
if marker.exists() or marker.is_symlink():
|
||||
return cls._read_workspace_id(marker)
|
||||
|
||||
recovered = cls._find_workspace_namespace(workspace, root)
|
||||
if recovered is not None:
|
||||
cls._write_text_atomic(marker, f"{recovered}\n")
|
||||
return recovered
|
||||
|
||||
workspace_id = secrets.token_hex(16)
|
||||
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
||||
flags |= getattr(os, "O_NOFOLLOW", 0)
|
||||
try:
|
||||
fd = os.open(marker, flags, 0o600)
|
||||
except FileExistsError:
|
||||
return cls._read_workspace_id(marker)
|
||||
try:
|
||||
payload = f"{workspace_id}\n".encode("ascii")
|
||||
view = memoryview(payload)
|
||||
while view:
|
||||
written = os.write(fd, view)
|
||||
view = view[written:]
|
||||
os.fsync(fd)
|
||||
except BaseException:
|
||||
with suppress(OSError):
|
||||
marker.unlink()
|
||||
raise
|
||||
finally:
|
||||
os.close(fd)
|
||||
cls.fsync_directory(marker.parent)
|
||||
return workspace_id
|
||||
|
||||
@classmethod
|
||||
def _replace_workspace_id(cls, workspace: Path, workspace_id: str) -> None:
|
||||
cls._write_text_atomic(cls._workspace_id_path(workspace), f"{workspace_id}\n")
|
||||
|
||||
@classmethod
|
||||
def _write_workspace_marker(cls, sessions_dir: Path, workspace: Path) -> None:
|
||||
cls._write_text_atomic(sessions_dir / ".workspace", f"{workspace}\n")
|
||||
|
||||
@classmethod
|
||||
def _claim_workspace_namespace(
|
||||
cls,
|
||||
root: Path,
|
||||
workspace: Path,
|
||||
workspace_id: str,
|
||||
) -> str:
|
||||
"""Bind a stable workspace ID, rotating copied live workspaces apart."""
|
||||
for _attempt in range(3):
|
||||
sessions_dir = root / workspace_id
|
||||
marker = sessions_dir / ".workspace"
|
||||
if sessions_dir.is_symlink():
|
||||
raise RuntimeError(f"session namespace must not be a symlink: {sessions_dir}")
|
||||
if not sessions_dir.exists():
|
||||
ensure_dir(sessions_dir)
|
||||
cls._write_workspace_marker(sessions_dir, workspace)
|
||||
return workspace_id
|
||||
if marker.is_symlink():
|
||||
raise RuntimeError(f"session workspace marker must not be a symlink: {marker}")
|
||||
if not marker.exists():
|
||||
if any(sessions_dir.iterdir()):
|
||||
raise RuntimeError(
|
||||
f"session namespace has data but no workspace marker: {sessions_dir}"
|
||||
)
|
||||
cls._write_workspace_marker(sessions_dir, workspace)
|
||||
return workspace_id
|
||||
|
||||
recorded_text = marker.read_text(encoding="utf-8").strip()
|
||||
if not recorded_text:
|
||||
raise RuntimeError(f"session workspace marker is empty: {marker}")
|
||||
recorded = Path(recorded_text).expanduser().resolve(strict=False)
|
||||
if recorded == workspace:
|
||||
return workspace_id
|
||||
try:
|
||||
same_workspace = recorded.exists() and recorded.samefile(workspace)
|
||||
except OSError:
|
||||
same_workspace = False
|
||||
if same_workspace:
|
||||
cls._write_workspace_marker(sessions_dir, workspace)
|
||||
return workspace_id
|
||||
if not recorded.exists():
|
||||
# The identity marker travelled with a renamed or moved workspace.
|
||||
cls._write_workspace_marker(sessions_dir, workspace)
|
||||
return workspace_id
|
||||
|
||||
# Both paths exist and are different: this is a copy, not a move.
|
||||
workspace_id = secrets.token_hex(16)
|
||||
cls._replace_workspace_id(workspace, workspace_id)
|
||||
|
||||
raise RuntimeError(f"could not allocate an isolated session namespace for {workspace}")
|
||||
|
||||
@staticmethod
|
||||
def safe_key(key: str) -> str:
|
||||
return safe_filename(key.replace(":", "_"))
|
||||
|
||||
@staticmethod
|
||||
def storage_key(key: str) -> str:
|
||||
return base64.urlsafe_b64encode(key.encode()).decode().rstrip("=")
|
||||
|
||||
@staticmethod
|
||||
def decode_storage_key(stem: str) -> str | None:
|
||||
try:
|
||||
padding = 4 - len(stem) % 4
|
||||
if padding != 4:
|
||||
stem += "=" * padding
|
||||
return base64.urlsafe_b64decode(stem).decode("utf-8")
|
||||
except (ValueError, TypeError, AttributeError, KeyError):
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def session_key_from_path(cls, path: Path) -> str | None:
|
||||
key = cls.decode_storage_key(path.stem)
|
||||
if key is None or cls.storage_key(key) != path.stem:
|
||||
return None
|
||||
return key
|
||||
+180
-1431
File diff suppressed because it is too large.
Load diff
@@ -10,6 +10,7 @@ from dataclasses import dataclass
|
||||
from typing import Any, TypedDict, cast
|
||||
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.types import SessionTypes
|
||||
|
||||
SESSION_HANDLE_METADATA_KEY = "session_handle"
|
||||
|
||||
@@ -128,7 +129,7 @@ def _candidate_indexes(syllable_count: int):
|
||||
yield (start + offset * step) % size
|
||||
|
||||
|
||||
def _allocate_name(used: set[str]) -> str:
|
||||
def allocate_session_handle_name(used: set[str]) -> str:
|
||||
for syllable_count in _SYLLABLE_COUNTS:
|
||||
for index in _candidate_indexes(syllable_count):
|
||||
parts = _name_parts_at(syllable_count, index)
|
||||
@@ -143,6 +144,51 @@ def _allocate_name(used: set[str]) -> str:
|
||||
return name
|
||||
|
||||
|
||||
# Backward-compatible alias for callers that used the original private helper.
|
||||
_allocate_name = allocate_session_handle_name
|
||||
|
||||
|
||||
def allocate_session_handles(
|
||||
rows: list[dict[str, Any]], types: SessionTypes,
|
||||
) -> tuple[dict[str, str], dict[str, str]]:
|
||||
"""Return valid existing names and metadata updates for missing handles."""
|
||||
used: set[str] = set()
|
||||
names: dict[str, str] = {}
|
||||
pending: list[str] = []
|
||||
for row in sorted(
|
||||
rows,
|
||||
key=lambda item: (
|
||||
str(item.get("created_at", "")),
|
||||
str(item.get("key", "")),
|
||||
),
|
||||
):
|
||||
raw_key = row.get("key")
|
||||
if not isinstance(raw_key, str):
|
||||
continue
|
||||
raw_metadata = row.get("metadata")
|
||||
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
|
||||
if not types.needs_handle(metadata):
|
||||
continue
|
||||
raw_name = metadata.get(SESSION_HANDLE_METADATA_KEY)
|
||||
try:
|
||||
name = normalize_session_handle(raw_name) if isinstance(raw_name, str) else ""
|
||||
except ValueError:
|
||||
name = ""
|
||||
if not name or name in used:
|
||||
pending.append(raw_key)
|
||||
continue
|
||||
names[raw_key] = name
|
||||
used.add(name)
|
||||
|
||||
updates: dict[str, str] = {}
|
||||
for key in pending:
|
||||
name = allocate_session_handle_name(used)
|
||||
names[key] = name
|
||||
updates[key] = name
|
||||
used.add(name)
|
||||
return names, updates
|
||||
|
||||
|
||||
class SessionHandleResolver:
|
||||
"""Allocate and resolve handles stored in canonical session metadata."""
|
||||
|
||||
@@ -150,71 +196,65 @@ class SessionHandleResolver:
|
||||
self._sessions = sessions
|
||||
|
||||
def _ensure_all(self) -> dict[str, SessionHandle]:
|
||||
with self._sessions.locked_session_files():
|
||||
rows = sorted(
|
||||
self._sessions.list_sessions(),
|
||||
key=lambda row: (
|
||||
str(row.get("created_at", "")),
|
||||
str(row.get("key", "")),
|
||||
),
|
||||
)
|
||||
used: set[str] = set()
|
||||
names: dict[str, str] = {}
|
||||
pending: list[str] = []
|
||||
for row in rows:
|
||||
raw_key: Any = row.get("key")
|
||||
if not isinstance(raw_key, str):
|
||||
continue
|
||||
payload = self._sessions.read_session_metadata(raw_key)
|
||||
raw_metadata = payload.get("metadata") if payload is not None else None
|
||||
metadata = (
|
||||
cast(dict[str, Any], raw_metadata)
|
||||
if isinstance(raw_metadata, dict)
|
||||
else {}
|
||||
)
|
||||
if not self._sessions.types.needs_handle(metadata):
|
||||
continue
|
||||
raw_name = metadata.get(SESSION_HANDLE_METADATA_KEY)
|
||||
try:
|
||||
name = normalize_session_handle(raw_name) if isinstance(raw_name, str) else ""
|
||||
except ValueError:
|
||||
name = ""
|
||||
if not name or name in used:
|
||||
pending.append(raw_key)
|
||||
continue
|
||||
names[raw_key] = name
|
||||
used.add(name)
|
||||
names = self._sessions.ensure_session_handles_offline()
|
||||
return {
|
||||
key: session_handle_for_name(key, name)
|
||||
for key, name in names.items()
|
||||
}
|
||||
|
||||
for key in pending:
|
||||
name = _allocate_name(used)
|
||||
if not self._sessions.update_session_metadata(
|
||||
key,
|
||||
{SESSION_HANDLE_METADATA_KEY: name},
|
||||
fsync=True,
|
||||
):
|
||||
continue
|
||||
names[key] = name
|
||||
used.add(name)
|
||||
async def _ensure_all_async(self) -> dict[str, SessionHandle]:
|
||||
names = await self._sessions.state.ensure_session_handles()
|
||||
return {
|
||||
key: session_handle_for_name(key, name)
|
||||
for key, name in names.items()
|
||||
}
|
||||
|
||||
return {
|
||||
key: session_handle_for_name(key, name)
|
||||
for key, name in names.items()
|
||||
}
|
||||
def handles_from_metadata(
|
||||
self, rows: list[dict[str, Any]],
|
||||
) -> dict[str, SessionHandle] | None:
|
||||
"""Resolve a detached snapshot, or request allocation through the owner."""
|
||||
names, updates = allocate_session_handles(rows, self._sessions.types)
|
||||
if updates:
|
||||
return None
|
||||
return {
|
||||
key: session_handle_for_name(key, name)
|
||||
for key, name in names.items()
|
||||
}
|
||||
|
||||
def handle_for_session(self, session_key: str) -> SessionHandle | None:
|
||||
"""Offline compatibility API; runtime callers must use ahandle_for_session()."""
|
||||
try:
|
||||
key = _clean_session_key(session_key)
|
||||
except ValueError:
|
||||
return None
|
||||
return self._ensure_all().get(key)
|
||||
|
||||
async def ahandle_for_session(self, session_key: str) -> SessionHandle | None:
|
||||
try:
|
||||
key = _clean_session_key(session_key)
|
||||
except ValueError:
|
||||
return None
|
||||
return (await self._ensure_all_async()).get(key)
|
||||
|
||||
def list_all(self) -> list[SessionHandle]:
|
||||
"""Offline compatibility API; runtime callers must use alist_all()."""
|
||||
return sorted(self._ensure_all().values(), key=lambda handle: handle.name)
|
||||
|
||||
async def alist_all(self) -> list[SessionHandle]:
|
||||
return sorted(
|
||||
(await self._ensure_all_async()).values(),
|
||||
key=lambda handle: handle.name,
|
||||
)
|
||||
|
||||
def list_all_by_key(self) -> dict[str, SessionHandle]:
|
||||
"""Offline compatibility API; runtime callers must use alist_all_by_key()."""
|
||||
return self._ensure_all()
|
||||
|
||||
async def alist_all_by_key(self) -> dict[str, SessionHandle]:
|
||||
return await self._ensure_all_async()
|
||||
|
||||
def resolve(self, name: str) -> SessionHandle | None:
|
||||
"""Offline compatibility API; runtime callers must use aresolve()."""
|
||||
try:
|
||||
normalized = normalize_session_handle(name)
|
||||
except ValueError:
|
||||
@@ -227,3 +267,17 @@ class SessionHandleResolver:
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
async def aresolve(self, name: str) -> SessionHandle | None:
|
||||
try:
|
||||
normalized = normalize_session_handle(name)
|
||||
except ValueError:
|
||||
return None
|
||||
return next(
|
||||
(
|
||||
handle
|
||||
for handle in (await self._ensure_all_async()).values()
|
||||
if handle.name == normalized
|
||||
),
|
||||
None,
|
||||
)
|
||||
@@ -0,0 +1,441 @@
|
||||
"""Transactional SQLite storage for private conversation state."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
from collections.abc import Callable, Generator
|
||||
from contextlib import contextmanager, suppress
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, TypeVar, cast
|
||||
|
||||
from nanobot.providers.base import ProviderConversationState
|
||||
from nanobot.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.session.manager import (
|
||||
Session,
|
||||
SessionInfo,
|
||||
SessionMetadataPayload,
|
||||
SessionPayload,
|
||||
message_preview_text,
|
||||
metadata_title,
|
||||
)
|
||||
from nanobot.session.summary import is_summary_checkpoint
|
||||
from nanobot.session.types import PARENT_SESSION_KEY
|
||||
|
||||
_CHECKPOINT = "runtime_checkpoint"
|
||||
_INPUTS = ("pending_user_followups",)
|
||||
_T = TypeVar("_T")
|
||||
|
||||
|
||||
def _encode(value: object) -> str:
|
||||
return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
|
||||
|
||||
|
||||
def _object(value: str) -> dict[str, Any]:
|
||||
parsed: object = json.loads(value)
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("stored session record must be an object")
|
||||
return cast(dict[str, Any], parsed)
|
||||
|
||||
|
||||
def _create_schema_v1(db: sqlite3.Connection) -> None:
|
||||
for statement in (
|
||||
"CREATE TABLE IF NOT EXISTS storage_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)",
|
||||
"""CREATE TABLE IF NOT EXISTS sessions (
|
||||
key TEXT PRIMARY KEY, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
|
||||
metadata TEXT NOT NULL, provider_state TEXT, last_archived INTEGER NOT NULL,
|
||||
revision INTEGER NOT NULL, generation TEXT NOT NULL,
|
||||
title TEXT NOT NULL, preview TEXT NOT NULL, visible_updated_at TEXT
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS messages (
|
||||
session_key TEXT NOT NULL REFERENCES sessions(key) ON DELETE CASCADE,
|
||||
position INTEGER NOT NULL, record TEXT NOT NULL,
|
||||
PRIMARY KEY (session_key, position)
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS checkpoints (
|
||||
session_key TEXT PRIMARY KEY REFERENCES sessions(key) ON DELETE CASCADE,
|
||||
record TEXT NOT NULL
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS pending_inputs (
|
||||
session_key TEXT NOT NULL REFERENCES sessions(key) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL, position INTEGER NOT NULL, record TEXT NOT NULL,
|
||||
PRIMARY KEY (session_key, kind, position)
|
||||
)""",
|
||||
"CREATE INDEX IF NOT EXISTS sessions_updated ON sessions(updated_at DESC)",
|
||||
):
|
||||
db.execute(statement)
|
||||
|
||||
|
||||
# Entries upgrade version N to N+1. Preserve released entries and append upgrades.
|
||||
_SCHEMA_MIGRATIONS: tuple[Callable[[sqlite3.Connection], None], ...] = (_create_schema_v1,)
|
||||
|
||||
|
||||
def _schema_version(db: sqlite3.Connection) -> int:
|
||||
version = int(db.execute("PRAGMA user_version").fetchone()[0])
|
||||
if not 0 <= version <= len(_SCHEMA_MIGRATIONS):
|
||||
raise RuntimeError(f"unsupported session database schema: {version}")
|
||||
return version
|
||||
|
||||
|
||||
class SessionConflictError(RuntimeError):
|
||||
"""A command refers to a replaced session or obsolete history."""
|
||||
|
||||
|
||||
class SqliteSessionStore:
|
||||
"""Synchronous repository; runtime callers use the session state's worker.
|
||||
|
||||
Nested repository operations share a transaction. Runtime worker threads
|
||||
retain their own connections until their state owner drains and closes;
|
||||
administrative calls close each connection after their transaction.
|
||||
"""
|
||||
|
||||
def __init__(self, sessions_dir: Path) -> None:
|
||||
self.path = sessions_dir / "sessions.sqlite3"
|
||||
self._local = threading.local()
|
||||
|
||||
def run_write(self, operation: Callable[[], _T]) -> _T:
|
||||
"""Run one repository command inside a write transaction."""
|
||||
with self.transaction():
|
||||
return operation()
|
||||
|
||||
def run_read(self, operation: Callable[[], _T]) -> _T:
|
||||
"""Run one repository command against a consistent read snapshot."""
|
||||
with self.transaction(write=False):
|
||||
return operation()
|
||||
|
||||
def _open_connection(self, *, worker: bool = False) -> sqlite3.Connection:
|
||||
if self.path.is_symlink():
|
||||
raise RuntimeError("session database must not be a symlink")
|
||||
connection = sqlite3.connect(
|
||||
self.path, timeout=5, isolation_level=None, check_same_thread=not worker,
|
||||
)
|
||||
connection.row_factory = sqlite3.Row
|
||||
try:
|
||||
connection.execute("PRAGMA foreign_keys = ON")
|
||||
connection.execute("PRAGMA synchronous = FULL")
|
||||
except BaseException:
|
||||
connection.close()
|
||||
raise
|
||||
return connection
|
||||
|
||||
def worker_connection(self) -> sqlite3.Connection:
|
||||
"""Retain this worker's connection; its owner closes it after the worker exits."""
|
||||
connection: sqlite3.Connection | None = getattr(self._local, "worker_connection", None)
|
||||
if connection is None:
|
||||
connection = self._open_connection(worker=True)
|
||||
self._local.worker_connection = connection
|
||||
return connection
|
||||
|
||||
@contextmanager
|
||||
def transaction(self, *, write: bool = True) -> Generator[sqlite3.Connection, None, None]:
|
||||
current: sqlite3.Connection | None = getattr(self._local, "connection", None)
|
||||
if current is not None:
|
||||
yield current
|
||||
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)
|
||||
owned = connection is None
|
||||
if connection is None:
|
||||
connection = self._open_connection()
|
||||
self._local.connection = connection
|
||||
try:
|
||||
connection.execute("BEGIN IMMEDIATE" if write else "BEGIN")
|
||||
yield connection
|
||||
connection.commit()
|
||||
except BaseException:
|
||||
connection.rollback()
|
||||
raise
|
||||
finally:
|
||||
self._local.connection = None
|
||||
if owned:
|
||||
connection.close()
|
||||
|
||||
def initialize(self, workspace: Path) -> None:
|
||||
"""Upgrade the schema and import legacy sessions in one atomic transaction."""
|
||||
workspace = workspace.expanduser().resolve(strict=False)
|
||||
# WAL is persistent and must be enabled outside a transaction.
|
||||
if self.path.is_symlink():
|
||||
raise RuntimeError("session database must not be a symlink")
|
||||
connection = sqlite3.connect(self.path, timeout=30, isolation_level=None)
|
||||
try:
|
||||
# Reject newer databases before changing their persistent settings.
|
||||
_schema_version(connection)
|
||||
try:
|
||||
connection.execute("SELECT json_extract('{}', '$'), json_type('{}')")
|
||||
except sqlite3.OperationalError as exc:
|
||||
raise RuntimeError(
|
||||
"session storage requires SQLite JSON support; use a Python build "
|
||||
"linked to SQLite with JSON enabled"
|
||||
) from exc
|
||||
connection.execute("PRAGMA journal_mode = WAL")
|
||||
finally:
|
||||
connection.close()
|
||||
with suppress(OSError):
|
||||
os.chmod(self.path, 0o600)
|
||||
with self.transaction() as db:
|
||||
# Recheck under the write lock in case another startup upgraded first.
|
||||
version = _schema_version(db)
|
||||
for target, migrate in enumerate(_SCHEMA_MIGRATIONS[version:], start=version + 1):
|
||||
migrate(db)
|
||||
db.execute(f"PRAGMA user_version = {target}")
|
||||
marker = db.execute(
|
||||
"SELECT value FROM storage_meta WHERE key='jsonl_import'"
|
||||
).fetchone()
|
||||
if marker is None:
|
||||
from nanobot.session.jsonl_migration import migrate_jsonl
|
||||
|
||||
migrate_jsonl(self, workspace)
|
||||
db.execute("INSERT INTO storage_meta (key, value) VALUES ('jsonl_import', 'complete')")
|
||||
elif marker[0] != "complete":
|
||||
raise RuntimeError(
|
||||
f"invalid JSONL migration marker in {self.path}: {marker[0]!r}; "
|
||||
"restore a valid database backup or repair the marker explicitly"
|
||||
)
|
||||
from nanobot.session.jsonl_migration import finish_workspace_migration
|
||||
|
||||
finish_workspace_migration(self, workspace)
|
||||
|
||||
def _metadata(self, db: sqlite3.Connection, key: str, raw: str) -> dict[str, Any]:
|
||||
metadata = _object(raw)
|
||||
row = db.execute("SELECT record FROM checkpoints WHERE session_key=?", (key,)).fetchone()
|
||||
if row is not None:
|
||||
metadata[_CHECKPOINT] = _object(row[0])
|
||||
for kind in _INPUTS:
|
||||
values = [
|
||||
_object(row[0]) for row in db.execute(
|
||||
"SELECT record FROM pending_inputs WHERE session_key=? AND kind=? ORDER BY position",
|
||||
(key, kind),
|
||||
)
|
||||
]
|
||||
if values:
|
||||
metadata[kind] = values
|
||||
return metadata
|
||||
|
||||
def load(self, key: str, *, history: bool = True) -> Session | None:
|
||||
with self.transaction(write=False) as db:
|
||||
row = db.execute("SELECT * FROM sessions WHERE key=?", (key,)).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
session = Session(
|
||||
key=key,
|
||||
messages=[_object(item[0]) for item in db.execute(
|
||||
"SELECT record FROM messages WHERE session_key=? ORDER BY position", (key,),
|
||||
)] if history else [],
|
||||
created_at=datetime.fromisoformat(row["created_at"]),
|
||||
updated_at=datetime.fromisoformat(row["updated_at"]),
|
||||
metadata=self._metadata(db, key, row["metadata"]),
|
||||
last_consolidated=row["last_archived"],
|
||||
provider_state=ProviderConversationState.from_private_record(
|
||||
_object(row["provider_state"])
|
||||
) if row["provider_state"] is not None else None,
|
||||
revision=row["revision"], generation=row["generation"], persisted=True,
|
||||
)
|
||||
if not history:
|
||||
# A header carries the real offset even though history was not requested.
|
||||
session.last_archived = row["last_archived"]
|
||||
return session
|
||||
|
||||
def has_unarchived_messages(self, key: str) -> bool:
|
||||
"""Check the indexed suffix without loading the archived transcript."""
|
||||
with self.transaction(write=False) as db:
|
||||
for row in db.execute(
|
||||
"""SELECT record FROM messages
|
||||
WHERE session_key=? AND position >= (
|
||||
SELECT last_archived FROM sessions WHERE key=?
|
||||
) ORDER BY position""",
|
||||
(key, key),
|
||||
):
|
||||
message = _object(row[0])
|
||||
if not message.get("_command") and not is_summary_checkpoint(message):
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _write_metadata(db: sqlite3.Connection, key: str, values: dict[str, Any], *, bump_revision: bool = True) -> None:
|
||||
metadata = dict(values)
|
||||
checkpoint = metadata.pop(_CHECKPOINT, None)
|
||||
if checkpoint is None:
|
||||
db.execute("DELETE FROM checkpoints WHERE session_key=?", (key,))
|
||||
else:
|
||||
db.execute(
|
||||
"INSERT INTO checkpoints (session_key, record) VALUES (?, ?) ON CONFLICT(session_key) DO UPDATE SET record=excluded.record",
|
||||
(key, _encode(checkpoint)),
|
||||
)
|
||||
for kind in _INPUTS:
|
||||
inputs = metadata.pop(kind, [])
|
||||
if not isinstance(inputs, list):
|
||||
raise ValueError(f"{kind} must be a list")
|
||||
db.execute("DELETE FROM pending_inputs WHERE session_key=? AND kind=?", (key, kind))
|
||||
db.executemany("INSERT INTO pending_inputs (session_key, kind, position, record) VALUES (?, ?, ?, ?)", [
|
||||
(key, kind, position, _encode(record))
|
||||
for position, record in enumerate(cast(list[object], inputs))
|
||||
])
|
||||
db.execute("UPDATE sessions SET metadata=?, title=?, revision=revision+? WHERE key=?", (
|
||||
_encode(metadata), metadata_title(metadata), int(bump_revision), key,
|
||||
))
|
||||
|
||||
def save(self, session: Session, *, message_start: int = 0) -> None:
|
||||
"""Commit history, optionally skipping a prefix verified at this revision."""
|
||||
if not 0 <= message_start <= len(session.messages):
|
||||
raise ValueError("invalid message suffix boundary")
|
||||
records = [_encode(message) for message in session.messages[message_start:]]
|
||||
provider = _encode(session.provider_state.to_private_record()) if session.provider_state else None
|
||||
preview = ""
|
||||
fallback = ""
|
||||
scanned_chars = 0
|
||||
for message in session.messages[:200]:
|
||||
scanned_chars += len(_encode(message)) + 1
|
||||
if scanned_chars > 1_000_000:
|
||||
break
|
||||
if is_hidden_history_message(message):
|
||||
continue
|
||||
text = message_preview_text(message)
|
||||
if message.get("role") == "user" and text:
|
||||
preview = text
|
||||
break
|
||||
if message.get("role") == "assistant" and not fallback:
|
||||
fallback = text
|
||||
preview = preview or fallback
|
||||
last_visible = next((m["timestamp"] for m in reversed(session.messages)
|
||||
if m.get("timestamp") and not is_hidden_history_message(m)
|
||||
and m.get("role") in {"user", "assistant"}), None)
|
||||
with self.transaction() as db:
|
||||
row = db.execute("SELECT revision, generation FROM sessions WHERE key=?", (session.key,)).fetchone()
|
||||
if row is None:
|
||||
if session.persisted:
|
||||
raise SessionConflictError("session was deleted")
|
||||
if message_start:
|
||||
raise ValueError("a new session must include its full history")
|
||||
db.execute("""INSERT INTO sessions (
|
||||
key, created_at, updated_at, metadata, provider_state, last_archived,
|
||||
revision, generation, title, preview, visible_updated_at
|
||||
) VALUES (?, ?, ?, '{}', NULL, 0, 0, ?, '', '', NULL)""", (
|
||||
session.key, session.created_at.isoformat(), session.updated_at.isoformat(), session.generation,
|
||||
))
|
||||
elif row[0] != session.revision or row[1] != session.generation:
|
||||
raise SessionConflictError("session history changed")
|
||||
db.execute("UPDATE sessions SET updated_at=?, provider_state=?, last_archived=?, revision=revision+1, preview=?, visible_updated_at=? WHERE key=?", (
|
||||
session.updated_at.isoformat(), provider, session.last_archived,
|
||||
preview, last_visible, session.key,
|
||||
))
|
||||
# Unchanged message rows do not generate writes. Appends only write the suffix.
|
||||
db.executemany("""INSERT INTO messages (session_key, position, record) VALUES (?, ?, ?)
|
||||
ON CONFLICT(session_key, position) DO UPDATE SET record=excluded.record
|
||||
WHERE messages.record != excluded.record""", [
|
||||
(session.key, position, record)
|
||||
for position, record in enumerate(records, message_start)
|
||||
])
|
||||
db.execute("DELETE FROM messages WHERE session_key=? AND position>=?", (session.key, len(session.messages)))
|
||||
self._write_metadata(db, session.key, session.metadata, bump_revision=False)
|
||||
session.revision += 1
|
||||
session.persisted = True
|
||||
|
||||
def save_runtime_checkpoint(self, session: Session) -> None:
|
||||
with self.transaction() as db:
|
||||
row = db.execute("SELECT generation FROM sessions WHERE key=?", (session.key,)).fetchone()
|
||||
if row is None or row[0] != session.generation:
|
||||
raise SessionConflictError("checkpoint belongs to a replaced session")
|
||||
metadata = self.read_metadata(session.key)
|
||||
assert metadata is not None
|
||||
values = metadata["metadata"]
|
||||
if _CHECKPOINT in session.metadata:
|
||||
values[_CHECKPOINT] = session.metadata[_CHECKPOINT]
|
||||
else:
|
||||
values.pop(_CHECKPOINT, None)
|
||||
self._write_metadata(db, session.key, values)
|
||||
session.revision += 1
|
||||
db.execute("UPDATE sessions SET provider_state=? WHERE key=?", (
|
||||
_encode(session.provider_state.to_private_record()) if session.provider_state else None,
|
||||
session.key,
|
||||
))
|
||||
|
||||
def update_metadata(self, key: str, updates: dict[str, Any]) -> bool:
|
||||
with self.transaction() as db:
|
||||
payload = self.read_metadata(key)
|
||||
if payload is None:
|
||||
return False
|
||||
self._write_metadata(db, key, {**payload["metadata"], **updates})
|
||||
return True
|
||||
|
||||
def replace_metadata(
|
||||
self, key: str, metadata: dict[str, Any], *, updated_at: datetime | None = None,
|
||||
) -> None:
|
||||
with self.transaction() as db:
|
||||
self._write_metadata(db, key, metadata)
|
||||
if updated_at is not None:
|
||||
db.execute("UPDATE sessions SET updated_at=? WHERE key=?", (updated_at.isoformat(), key))
|
||||
|
||||
def read_metadata(self, key: str) -> SessionMetadataPayload | None:
|
||||
with self.transaction(write=False) as db:
|
||||
row = db.execute("SELECT created_at, updated_at, metadata FROM sessions WHERE key=?", (key,)).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return {"key": key, "created_at": row[0], "updated_at": row[1],
|
||||
"metadata": self._metadata(db, key, row[2])}
|
||||
|
||||
def read(self, key: str) -> SessionPayload | None:
|
||||
session = self.load(key)
|
||||
if session is None:
|
||||
return None
|
||||
return {"key": key, "created_at": session.created_at.isoformat(),
|
||||
"updated_at": session.updated_at.isoformat(),
|
||||
"metadata": session.metadata, "messages": session.messages}
|
||||
|
||||
def delete(self, key: str) -> bool:
|
||||
with self.transaction() as db:
|
||||
return db.execute("DELETE FROM sessions WHERE key=?", (key,)).rowcount > 0
|
||||
|
||||
def list_sessions(self) -> list[SessionInfo]:
|
||||
with self.transaction(write=False) as db:
|
||||
return [SessionInfo(key=row[0], created_at=row[1], updated_at=row[2],
|
||||
title=row[3], preview=row[4], path=str(self.path))
|
||||
for row in db.execute("SELECT key, created_at, updated_at, title, preview FROM sessions ORDER BY updated_at DESC")]
|
||||
|
||||
def child_session_keys(self, parent_key: str) -> list[str]:
|
||||
"""Find all persisted child kinds without decoding unrelated metadata."""
|
||||
with self.transaction(write=False) as db:
|
||||
return [row[0] for row in db.execute(
|
||||
f"""SELECT key FROM sessions
|
||||
WHERE json_extract(metadata, '$.{PARENT_SESSION_KEY}')=?
|
||||
AND json_type(metadata, '$.{PARENT_SESSION_KEY}')='text'
|
||||
ORDER BY updated_at DESC""",
|
||||
(parent_key,),
|
||||
)]
|
||||
|
||||
def list_child_session_metadata(self, parent_key: str) -> list[SessionMetadataPayload]:
|
||||
"""Read child headers from one snapshot, excluding checkpoints and pending inputs."""
|
||||
with self.transaction(write=False) as db:
|
||||
return [{"key": row[0], "created_at": row[1], "updated_at": row[2],
|
||||
"metadata": _object(row[3])}
|
||||
for row in db.execute(
|
||||
f"""SELECT key, created_at, updated_at, metadata FROM sessions
|
||||
WHERE json_extract(metadata, '$.{PARENT_SESSION_KEY}')=?
|
||||
AND json_type(metadata, '$.{PARENT_SESSION_KEY}')='text'
|
||||
ORDER BY updated_at DESC""",
|
||||
(parent_key,),
|
||||
)]
|
||||
|
||||
def list_metadata(self) -> list[dict[str, Any]]:
|
||||
with self.transaction(write=False) as db:
|
||||
# Fetch one value so a large list does not cross the Python/SQLite
|
||||
# iterator boundary for every session while other workers are busy.
|
||||
encoded = db.execute("""
|
||||
SELECT json_group_array(json_object(
|
||||
'key', key, 'created_at', created_at, 'updated_at', updated_at,
|
||||
'title', title, 'preview', preview, 'visible_updated_at', visible_updated_at,
|
||||
'metadata', metadata
|
||||
)) FROM (
|
||||
SELECT key, created_at, updated_at, title, preview, visible_updated_at, metadata
|
||||
FROM sessions ORDER BY updated_at DESC
|
||||
)
|
||||
""").fetchone()[0]
|
||||
# The SQL projection constructs this list and its dictionary fields.
|
||||
rows = cast(list[dict[str, Any]], json.loads(encoded))
|
||||
for row in rows:
|
||||
row["path"] = str(self.path)
|
||||
row["metadata"] = _object(row["metadata"])
|
||||
return rows
|
||||
File diff suppressed because it is too large.
Load diff
@@ -114,14 +114,16 @@ def should_finalize_on_max_iterations(
|
||||
)
|
||||
|
||||
|
||||
async def maybe_continue_turn(ctx: TurnContext) -> bool:
|
||||
async def maybe_continue_turn(
|
||||
ctx: TurnContext, *, session_metadata: Mapping[str, Any],
|
||||
) -> bool:
|
||||
"""Queue an internal continuation for *ctx* when policy allows it."""
|
||||
if ctx.session is None or ctx.pending_queue is None:
|
||||
return False
|
||||
if not _continuation_available(
|
||||
stop_reason=ctx.stop_reason,
|
||||
pending_queue_available=True,
|
||||
session_metadata=ctx.session.metadata,
|
||||
session_metadata=session_metadata,
|
||||
message_metadata=ctx.msg.metadata,
|
||||
):
|
||||
return False
|
||||
@@ -136,7 +138,7 @@ async def maybe_continue_turn(ctx: TurnContext) -> bool:
|
||||
"message_id": request.message_id,
|
||||
"turn_id": request.turn_id,
|
||||
}
|
||||
content = _goal_continuation_prompt(ctx.session.metadata)
|
||||
content = _goal_continuation_prompt(session_metadata)
|
||||
messages = _strip_terminal_assistant(ctx.all_messages, ctx.final_content)
|
||||
_increment_goal_continuation_round(ctx.session.metadata)
|
||||
|
||||
|
||||
@@ -49,6 +49,7 @@ from nanobot.session.session_messages import (
|
||||
SessionMessageEnvelope,
|
||||
session_message_envelope,
|
||||
)
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
from nanobot.utils.helpers import strip_think, truncate_text
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
from nanobot.webui.metadata import (
|
||||
@@ -210,12 +211,14 @@ async def maybe_generate_webui_title(
|
||||
so pass ``target_session_key`` to project the title onto that per-chat
|
||||
session instead of storing it on the shared one.
|
||||
"""
|
||||
routed_session = sessions.get_or_create(session_key)
|
||||
routed_session = await sessions.state.read(session_key)
|
||||
if routed_session is None:
|
||||
return False
|
||||
target_is_routed = target_session_key is None or target_session_key == session_key
|
||||
if target_is_routed or target_session_key is None:
|
||||
target_session = routed_session
|
||||
else:
|
||||
target_session = sessions.get_or_create(target_session_key)
|
||||
target_session = await sessions.state.get(target_session_key)
|
||||
if (
|
||||
routed_session.metadata.get(WEBUI_SESSION_METADATA_KEY) is not True
|
||||
and target_session.metadata.get(WEBUI_SESSION_METADATA_KEY) is not True
|
||||
@@ -228,8 +231,13 @@ async def maybe_generate_webui_title(
|
||||
cleaned_current_title = clean_generated_title(current_title)
|
||||
if cleaned_current_title:
|
||||
if cleaned_current_title != current_title:
|
||||
target_session.metadata[WEBUI_TITLE_METADATA_KEY] = cleaned_current_title
|
||||
sessions.save(target_session)
|
||||
def clean_title(metadata: dict[str, Any]) -> None:
|
||||
if (metadata.get(WEBUI_TITLE_METADATA_KEY) == current_title
|
||||
and metadata.get(WEBUI_TITLE_USER_EDITED_METADATA_KEY) is not True):
|
||||
metadata[WEBUI_TITLE_METADATA_KEY] = cleaned_current_title
|
||||
await sessions.state.mutate_metadata(
|
||||
target_session.key, clean_title, expected_generation=target_session.generation,
|
||||
)
|
||||
return False
|
||||
target_session.metadata.pop(WEBUI_TITLE_METADATA_KEY, None)
|
||||
|
||||
@@ -292,9 +300,20 @@ async def maybe_generate_webui_title(
|
||||
response.finish_reason,
|
||||
)
|
||||
return False
|
||||
target_session.metadata[WEBUI_TITLE_METADATA_KEY] = title
|
||||
sessions.save(target_session)
|
||||
return True
|
||||
def set_title(metadata: dict[str, Any]) -> bool:
|
||||
if metadata.get(WEBUI_TITLE_USER_EDITED_METADATA_KEY) is True:
|
||||
return False
|
||||
if metadata.get(WEBUI_TITLE_METADATA_KEY) != current_title:
|
||||
return False
|
||||
metadata[WEBUI_TITLE_METADATA_KEY] = title
|
||||
return True
|
||||
try:
|
||||
changed, _ = await sessions.state.mutate_metadata(
|
||||
target_session.key, set_title, expected_generation=target_session.generation,
|
||||
)
|
||||
except SessionConflictError:
|
||||
return False
|
||||
return changed
|
||||
|
||||
|
||||
async def maybe_generate_webui_title_after_turn(
|
||||
@@ -473,8 +492,8 @@ class WebuiTurnRoutePolicy:
|
||||
)
|
||||
and route.channel == "websocket"
|
||||
):
|
||||
session = self.sessions.get_or_create(session_key)
|
||||
if session.metadata.get(WEBUI_SESSION_METADATA_KEY) is True:
|
||||
metadata_snapshot = self.sessions.state.peek_metadata(session_key)
|
||||
if metadata_snapshot is not None and metadata_snapshot.get(WEBUI_SESSION_METADATA_KEY) is True:
|
||||
metadata = dict(route.metadata)
|
||||
turn_prefix = "session-input" if internal_user_input else "subagent"
|
||||
metadata.update({
|
||||
@@ -552,6 +571,7 @@ class WebuiTurnCoordinator:
|
||||
sessions: SessionManager
|
||||
schedule_background: Callable[[Awaitable[None]], None]
|
||||
recovery: RecoveryCoordinator | None = None
|
||||
|
||||
def subscribe(self) -> Callable[[], None]:
|
||||
"""Subscribe this coordinator to runtime events."""
|
||||
unsubscribe = [
|
||||
@@ -626,7 +646,7 @@ class WebuiTurnCoordinator:
|
||||
or not is_webui_session_key(session_key)
|
||||
):
|
||||
return
|
||||
persisted = self.sessions.read_session_metadata(session_key)
|
||||
persisted = await self.sessions.state.read_metadata(session_key)
|
||||
metadata_value: object = persisted.get("metadata") if persisted is not None else None
|
||||
metadata = (
|
||||
cast(dict[str, Any], metadata_value)
|
||||
@@ -658,11 +678,15 @@ class WebuiTurnCoordinator:
|
||||
),
|
||||
))
|
||||
|
||||
def _handle_session_turn_started(self, event: SessionTurnStarted) -> None:
|
||||
if not self._is_websocket_event(event.context):
|
||||
return
|
||||
session = self.sessions.get_or_create(event.context.session_key)
|
||||
mark_webui_session(session, event.context.metadata)
|
||||
async def _handle_session_turn_started(self, event: SessionTurnStarted) -> None:
|
||||
if (self._is_websocket_event(event.context)
|
||||
and event.context.metadata.get(WEBUI_SESSION_METADATA_KEY) is True):
|
||||
await self.sessions.state.update_metadata(
|
||||
event.context.session_key,
|
||||
{WEBUI_SESSION_METADATA_KEY: True},
|
||||
expected_generation=event.context.session_generation,
|
||||
create_if_missing=False,
|
||||
)
|
||||
|
||||
async def _handle_run_status_changed(self, event: TurnRunStatusChanged) -> None:
|
||||
if not self._is_websocket_event(event.context):
|
||||
@@ -771,7 +795,7 @@ class WebuiTurnCoordinator:
|
||||
if msg.channel != "websocket":
|
||||
return
|
||||
|
||||
session = self.sessions.get_or_create(session_key)
|
||||
session = await self.sessions.state.get(session_key)
|
||||
await self.bus.publish_outbound(
|
||||
outbound_message_for_event(
|
||||
channel=msg.channel,
|
||||
|
||||
Reference in new issue
Block a user