refactor: remove legacy history and proxy migrations (#6518)

This commit is contained in:
chengyongru authored and GitHub committed 2026-10-29 18:28:44 +08:00
1 parent 1c28b20c7e
commit cb3ba45317
47 files changed
+207 -1925

No files matched your search

-1
View File
@@ -653,7 +653,6 @@ class WebSocketChannel(BaseChannel):
)
async def start(self) -> None:
await self._outbound.initialize()
self.gateway.http.remote_instances.resume()
from nanobot.utils.logging_bridge import redirect_lib_logging
-3
View File
@@ -12,7 +12,6 @@ if TYPE_CHECKING:
get_cli_history_path,
get_cron_dir,
get_data_dir,
get_legacy_sessions_dir,
get_logs_dir,
get_media_dir,
get_runtime_subdir,
@@ -38,7 +37,6 @@ _EXPORTS = {
"get_workspace_path": "nanobot.config.paths",
"is_default_workspace": "nanobot.config.paths",
"get_cli_history_path": "nanobot.config.paths",
"get_legacy_sessions_dir": "nanobot.config.paths",
}
@@ -70,5 +68,4 @@ __all__ = [
"get_workspace_path",
"is_default_workspace",
"get_cli_history_path",
"get_legacy_sessions_dir",
]
-58
View File
@@ -2,11 +2,9 @@
import os
import re
from typing import Any, cast
from urllib.parse import quote, urlsplit
from pydantic import Field, field_validator
from pydantic_core import PydanticCustomError
from nanobot.config_base import Base
@@ -70,59 +68,3 @@ class NetworkConfig(Base):
if not proxy:
raise ValueError("Configure the shared proxy in Advanced before enabling it")
return proxy
def _config_object(value: object) -> dict[str, Any] | None:
return cast(dict[str, Any], value) if isinstance(value, dict) else None
def migrate_legacy_proxy_config(value: Any) -> Any:
"""Consolidate legacy addresses after settings sources have been merged."""
if not isinstance(value, dict):
return value
data = cast(dict[str, Any], value)
sections: list[dict[str, Any]] = []
providers = _config_object(data.get("providers")) or {}
sections.extend(section for value in providers.values() if (section := _config_object(value)) is not None)
tools = _config_object(data.get("tools")) or {}
if (web := _config_object(tools.get("web"))) is not None:
sections.append(web)
channels = _config_object(data.get("channels")) or {}
sections.extend(section for name in ("telegram", "discord", "slack", "matrix", "whatsapp") if (section := _config_object(channels.get(name))) is not None)
network = data.get("network")
explicit_proxy = isinstance(network, NetworkConfig) or isinstance(network, dict) and "proxy" in network
addresses: set[str] = set()
migrated: list[dict[str, Any]] = []
for section in sections:
raw = section.get("proxy")
if isinstance(raw, str) and raw.strip():
if not explicit_proxy:
proxy = NetworkConfig.normalize_proxy(raw)
assert proxy is not None
username = section.get("proxyUsername", section.get("proxy_username"))
password = section.get("proxyPassword", section.get("proxy_password"))
if isinstance(username, str) and username and isinstance(password, str) and password:
if _ENV_REF_PATTERN.fullmatch(proxy):
raise PydanticCustomError("proxy_credential_migration", "Combine the Discord proxy URL and credentials into one full URL environment variable, or set network.proxy before upgrading.")
scheme, host = proxy.split("://", 1)
host = host.rsplit("@", 1)[-1]
credentials = f"{quote(username, safe='${}')}:{quote(password, safe='${}')}"
proxy = f"{scheme}://{credentials}@{host}"
addresses.add(proxy)
migrated.append(section)
if addresses:
if len(addresses) > 1:
raise PydanticCustomError("proxy_address_migration", "Multiple legacy proxy addresses are no longer supported. Set network.proxy to one address before upgrading.")
if not isinstance(network, dict):
network = {}
data["network"] = network
network["proxy"] = next(iter(addresses))
for section in sections:
for key in ("proxy", "proxyUsername", "proxy_username", "proxyPassword", "proxy_password"):
section.pop(key, None)
for section in migrated:
if "useProxy" not in section and "use_proxy" not in section:
section["useProxy"] = True
return data
+1 -6
View File
@@ -45,7 +45,7 @@ def get_logs_dir() -> Path:
def get_webui_dir() -> Path:
"""Return WebUI state and legacy display-history import/backup storage."""
"""Return the WebUI state directory."""
return get_runtime_subdir("webui")
@@ -65,8 +65,3 @@ def is_default_workspace(workspace: str | Path | None) -> bool:
def get_cli_history_path() -> Path:
"""Return the selected home's CLI history file path."""
return get_home_path() / "history" / "cli_history"
def get_legacy_sessions_dir() -> Path:
"""Return the selected home's legacy session directory for migration fallback."""
return get_home_path() / "sessions"
+1 -6
View File
@@ -21,7 +21,7 @@ from nanobot.agent.tools.web_config import (
)
from nanobot.agent.tools.web_config import WebToolsConfig
from nanobot.config.home import get_default_workspace
from nanobot.config.network import NetworkConfig, migrate_legacy_proxy_config
from nanobot.config.network import NetworkConfig
from nanobot.config.provider_api_migration import migrate_legacy_provider_api
from nanobot.config.timezone import detect_system_timezone
from nanobot.config_base import Base
@@ -517,11 +517,6 @@ class Config(BaseSettings):
serialization_alias="modelPresets",
)
@model_validator(mode="before")
@classmethod
def _migrate_proxy_config(cls, value: Any) -> Any:
return migrate_legacy_proxy_config(value)
@classmethod
def settings_customise_sources(
cls,
-8
View File
@@ -59,14 +59,6 @@ class HistoryFact:
)
@dataclass(frozen=True)
class HistoryImport:
key: str
facts: list[HistoryFact]
created_at_ms: int = 0
updated_at_ms: int = 0
@dataclass(frozen=True)
class HistoryTurn:
ordinal: int
-291
View File
@@ -1,291 +0,0 @@
"""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
# Unicode line separators are valid inside legacy JSON strings.
for line in source.content.decode("utf-8").split("\n"):
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
+1 -30
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import base64
import errno
import os
import re
@@ -13,10 +12,7 @@ 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,
)
from nanobot.utils.helpers import ensure_dir
_WORKSPACE_STATE_DIR = ".nanobot"
_WORKSPACE_ID_FILE = "workspace-id"
@@ -225,28 +221,3 @@ class SessionLocation:
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
+1 -21
View File
@@ -433,7 +433,7 @@ class SessionManager:
self.location = SessionLocation(workspace, sessions_root=sessions_root)
self.sessions_dir = self.location.sessions_dir
self._store = SqliteSessionStore(self.sessions_dir)
self._store.initialize(workspace)
self._store.initialize()
self._delete_observer: Callable[[str], None] | None = None
self.types = SessionTypes()
self._state: SessionState | None = None
@@ -462,26 +462,6 @@ class SessionManager:
"""Observe explicit session deletion for process-local state cleanup."""
self._delete_observer = observer
@staticmethod
def safe_key(key: str) -> str:
"""Public helper used by HTTP handlers to map an arbitrary key to a stable filename stem."""
return SessionLocation.safe_key(key)
@staticmethod
def _storage_key(key: str) -> str:
"""Collision-resistant encoding for internal session storage filenames."""
return SessionLocation.storage_key(key)
@staticmethod
def _decode_storage_key(stem: str) -> str | None:
"""Reverse _storage_key(): decode a base64url (no-padding) stem back to the original key."""
return SessionLocation.decode_storage_key(stem)
@staticmethod
def decode_storage_key(stem: str) -> str | None:
"""Public decoder for components that inspect canonical session filenames."""
return SessionManager._decode_storage_key(stem)
def _require_offline_mutation(self) -> None:
if self._state is not None and self._state.is_bound:
raise RuntimeError(
+3 -50
View File
@@ -13,7 +13,7 @@ from pathlib import Path
from typing import Any, TypeVar, cast
from nanobot.providers.base import ProviderConversationState
from nanobot.session.display_history import HistoryFact, HistoryImport, HistoryKind, HistoryReader
from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import (
Session,
@@ -183,9 +183,8 @@ class SqliteSessionStore:
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)
def initialize(self) -> None:
"""Initialize or upgrade the SQLite schema."""
# WAL is persistent and must be enabled outside a transaction.
if self.path.is_symlink():
raise RuntimeError("session database must not be a symlink")
@@ -211,22 +210,6 @@ class SqliteSessionStore:
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)
@@ -420,36 +403,6 @@ class SqliteSessionStore:
"updated_at": session.updated_at.isoformat(),
"metadata": session.metadata, "messages": session.messages}
def migrate_history(
self, name: str, collect: Callable[[list[SessionInfo]], list[HistoryImport]],
) -> None:
"""Commit a channel-owned legacy import and its once-only marker together."""
with self.transaction() as db:
marker = db.execute("SELECT value FROM storage_meta WHERE key=?", (name,)).fetchone()
if marker is not None:
if marker[0] != "complete":
raise RuntimeError(f"invalid history import marker: {name}")
return
for item in collect(self.list_sessions()):
session = self.load(item.key, history=False)
if session is None:
session = Session(key=item.key)
if item.created_at_ms:
session.created_at = datetime.fromtimestamp(item.created_at_ms / 1000)
if item.updated_at_ms:
session.updated_at = datetime.fromtimestamp(item.updated_at_ms / 1000)
self.save(session)
revision = self.project_history(item.key, lambda reader: reader.revision)
if revision is not None and revision[1] >= 0:
raise SessionConflictError(f"history already exists before import: {item.key}")
self.append_history(item.key, item.facts, expected_generation=session.generation)
db.execute("UPDATE history_heads SET updated_at_ms=max(updated_at_ms, ?) WHERE session_key=?",
(item.updated_at_ms, item.key))
# Import ownership survives deletion: another namespace must not
# mistake this instance-wide backup for a new orphan later.
db.execute("INSERT INTO storage_meta (key, value) VALUES (?, 'complete')", (f"{name}:{item.key}",))
db.execute("INSERT INTO storage_meta (key, value) VALUES (?, 'complete')", (name,))
def project_history(self, key: str, project: Callable[[HistoryReader], _T]) -> _T:
"""Project durable display facts and canonical messages from one snapshot."""
with self.transaction(write=False) as db:
+1 -9
View File
@@ -14,12 +14,11 @@ from datetime import datetime
from typing import Any, TypeVar, cast
from nanobot.bus.events import InboundMessage
from nanobot.session.display_history import HistoryFact, HistoryImport, HistoryKind, HistoryReader
from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader
from nanobot.session.keys import is_dream_session
from nanobot.session.manager import (
Session,
SessionIdentity,
SessionInfo,
SessionPolicy,
fork_session,
)
@@ -702,13 +701,6 @@ class SessionState:
metadata = {**baseline.metadata, _CHECKPOINT_KEY: committed.metadata[_CHECKPOINT_KEY]}
draft._baseline = replace(baseline, metadata=metadata, provider_state=committed.provider_state) # pyright: ignore[reportPrivateUsage]
async def migrate_history(
self, name: str, collect: Callable[[list[SessionInfo]], list[HistoryImport]],
) -> None:
await self._execute(
None, lambda: self._store.migrate_history(name, collect), operation_name="migrate_history",
)
async def project_history(
self, key: str, project: Callable[[HistoryReader], _T],
) -> _T:
+6 -129
View File
@@ -1,23 +1,14 @@
"""WebUI projection of durable session facts and strict legacy transcript import."""
"""WebUI projection of durable session facts."""
from __future__ import annotations
import json
import re
import sqlite3
from collections.abc import Mapping, Sequence
from contextlib import closing
from pathlib import Path
from typing import Any, cast
from collections.abc import Mapping
from typing import Any
from nanobot.bus.events import INBOUND_META_LOCAL_MEDIA
from nanobot.config.paths import get_webui_dir
from nanobot.session.display_history import HistoryFact, HistoryImport, HistoryKind, HistoryReader
from nanobot.session.manager import SessionInfo, SessionManager
from nanobot.webui.session_identity import is_valid_webui_chat_id, webui_chat_id, webui_session_key
from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader
from nanobot.webui.session_identity import webui_chat_id
HISTORY_IMPORT_MARKER = "webui_history_import_v1"
_SEGMENT_NAME = re.compile(r"^\d{6}\.jsonl$")
_EVENTS = {
"user": HistoryKind.INPUT,
"message": HistoryKind.ANSWER,
@@ -47,11 +38,8 @@ _CONTENT_FIELDS = frozenset({
def fact_from_record(record: Mapping[str, Any]) -> HistoryFact:
"""Parse the channel boundary once; core storage never sees event/chat_id keys."""
event = record.get("event")
if event is None and record.get("role") in {"user", "assistant"}:
event = "user" if record["role"] == "user" else "message"
record = {**record, "text": record.get("text", record.get("content", ""))}
if event not in _EVENTS:
raise ValueError(f"unsupported legacy history event: {event!r}")
raise ValueError(f"unsupported history event: {event!r}")
kind = _EVENTS[event]
if event == "message":
message_kind = record.get("kind")
@@ -101,114 +89,3 @@ def turn_records(
return [{**record_from_fact(fact, history.key),
"_webui_replay_identity": f"turn:{ordinal}:record:{position}"}
for position, fact in history.read_entries(ordinal, max_records=max_records, max_bytes=max_bytes)]
def _read_legacy_file(path: Path) -> list[dict[str, Any]]:
if path.is_symlink() or not path.is_file():
raise ValueError(f"legacy history must be a regular, non-symlink file: {path}")
before = path.stat()
records: list[dict[str, Any]] = []
with path.open(encoding="utf-8") as handle:
for line_number, line in enumerate(handle, 1):
if not line.strip():
continue
try:
value: object = json.loads(line)
if not isinstance(value, dict):
raise ValueError("record is not an object")
record = cast(dict[str, Any], value)
fact_from_record(record).encode()
except (ValueError, TypeError) as exc:
raise ValueError(f"cannot import history {path}:{line_number}: {exc}") from exc
records.append(record)
after = path.stat()
if (before.st_ino, before.st_size, before.st_mtime_ns) != (after.st_ino, after.st_size, after.st_mtime_ns):
raise ValueError(f"legacy history changed during import: {path}")
return records
def collect_legacy_history(
sessions: Sequence[SessionInfo], *, directory: Path | None = None,
namespace: Path | None = None,
) -> list[HistoryImport]:
"""Resolve recorded identities; a lossy filename alone cannot identify an orphan."""
from nanobot.webui.transcript import compact_legacy_records
directory = directory if directory is not None else get_webui_dir()
if directory.is_symlink():
raise ValueError(f"legacy history directory must not be a symlink: {directory}")
if not directory.exists():
return []
groups: dict[str, list[Path]] = {}
for path in sorted(directory.iterdir()):
if path.name.endswith(".segments"):
if path.is_symlink() or not path.is_dir():
raise ValueError(f"invalid legacy history segments directory: {path}")
groups.setdefault(path.name[:-len(".segments")], []).extend(
item for item in sorted(path.iterdir()) if _SEGMENT_NAME.fullmatch(item.name)
)
elif path.suffix == ".jsonl":
groups.setdefault(path.stem, [])
for stem, paths in groups.items():
active = directory / f"{stem}.jsonl"
if active.exists() or active.is_symlink():
paths.append(active)
keys_by_stem: dict[str, set[str]] = {}
for session in sessions:
keys_by_stem.setdefault(SessionManager.safe_key(session["key"]), set()).add(session["key"])
foreign_owners: dict[str, list[Path]] = {}
if namespace is not None and groups:
for database in namespace.parent.glob("*/sessions.sqlite3"):
if database.parent == namespace:
continue
if database.is_symlink() or database.parent.is_symlink():
raise ValueError(f"invalid session namespace for history migration: {database}")
with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as db:
owned = {str(row[0]) for row in db.execute("SELECT key FROM sessions")}
prefix = f"{HISTORY_IMPORT_MARKER}:"
owned.update(str(row[0])[len(prefix):] for row in db.execute(
"SELECT key FROM storage_meta WHERE key LIKE ? AND value='complete'",
(prefix + "%",),
))
for key in owned:
foreign_owners.setdefault(key, []).append(database)
imports: list[HistoryImport] = []
for stem, paths in groups.items():
records = [record for path in paths for record in _read_legacy_file(path)]
if not records:
continue
recorded_keys: set[str] = set()
for record in records:
chat_id = record.get("chat_id")
if chat_id is not None:
if not is_valid_webui_chat_id(chat_id):
raise ValueError(f"invalid recorded chat identity in legacy history: {stem}")
recorded_keys.add(webui_session_key(chat_id))
candidates = recorded_keys or keys_by_stem.get(stem, set())
if len(candidates) != 1:
raise ValueError(f"ambiguous legacy history identity: {stem}; expected one recorded chat or canonical session")
key = next(iter(candidates))
if SessionManager.safe_key(key) != stem:
raise ValueError(f"legacy history filename conflicts with its recorded identity: {stem}")
if key in foreign_owners:
if key not in keys_by_stem.get(stem, set()) and len(foreign_owners[key]) == 1:
# This instance-wide backup belongs to another workspace. Its
# owner will import it when that namespace starts.
continue
raise ValueError(
f"cannot select a SQLite owner for legacy history {key}: also present in "
f"{foreign_owners[key]}; resolve the duplicate explicitly before restarting"
)
facts = [fact_from_record(record) for record in compact_legacy_records(records)]
times = [fact.created_at_ms for fact in facts if fact.created_at_ms]
file_times = [int(path.stat().st_mtime * 1000) for path in paths]
imports.append(HistoryImport(key, facts, min(times or file_times), max(times or file_times)))
return imports
async def initialize_history(sessions: SessionManager) -> None:
"""Finish the once-only import before recovery or transport admission."""
await sessions.state.migrate_history(
HISTORY_IMPORT_MARKER,
lambda rows: collect_legacy_history(rows, namespace=sessions.sessions_dir),
)
-3
View File
@@ -102,9 +102,6 @@ class WebUIOutboundDelivery:
self._stream_text_buffers: dict[tuple[str, str], list[str]] = {}
self._reasoning_text_buffers: dict[tuple[str, str], list[str]] = {}
async def initialize(self) -> None:
await self._transcripts.initialize()
def bind_pairing(self, bus: MessageBus, *, channel: str) -> Callable[[], None]:
async def queue_changed(event: PairingChanged) -> None:
await bus.publish_event(event, channel=channel, chat_id="*")
+1 -4
View File
@@ -86,9 +86,6 @@ class RecoveryCoordinator:
async def scan(self) -> None:
"""Recover every interrupted WebUI session once at gateway startup."""
from nanobot.webui.history import initialize_history
await initialize_history(self.sessions)
for key in await self._recovery_candidates():
metadata_payload = await self.sessions.state.read_metadata(key)
raw_metadata = metadata_payload.get("metadata") if metadata_payload else None
@@ -118,7 +115,7 @@ class RecoveryCoordinator:
await self._publish(route[1], failed)
async def _recovery_candidates(self) -> list[str]:
"""Legacy display-only sessions have canonical headers after import."""
"""Display-only sessions also have canonical headers in SQLite."""
return [item["key"] for item in await self.sessions.state.list_sessions()]
@staticmethod
-25
View File
@@ -36,7 +36,6 @@ from nanobot.session.sqlite_store import SessionConflictError
from nanobot.session.state import SessionOperationQueueFullError
from nanobot.webui.history import (
fact_from_record,
initialize_history,
record_from_fact,
turn_records,
)
@@ -318,25 +317,6 @@ def _compact_completed_stream_deltas(
], len(dropped_indexes)
def _compact_completed_turns(
turns: list[list[dict[str, Any]]],
) -> tuple[list[list[dict[str, Any]]], int]:
compacted: list[list[dict[str, Any]]] = []
dropped = 0
for turn in turns:
next_turn, turn_dropped = _compact_completed_stream_deltas(turn)
compacted.append(next_turn)
dropped += turn_dropped
return compacted, dropped
def compact_legacy_records(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
turns, _ = _compact_completed_turns(_split_transcript_turns(records))
return [record for turn in turns for record in turn]
def _records_with_replay_identity(
records: list[dict[str, Any]],
*,
@@ -531,11 +511,6 @@ class WebUITranscriptRecorder:
self._log = log
self._turn_sequences: dict[tuple[str, str], int] = {}
async def initialize(self) -> None:
sessions = self.sessions
if sessions is not None:
await initialize_history(sessions)
def client_turn_metadata(self, value: Any) -> dict[str, str]:
return {WEBUI_TURN_METADATA_KEY: normalize_webui_turn_id(value)}