refactor: remove legacy history and proxy migrations (#6518)
This commit is contained in:
1 parent
1c28b20c7e
commit
cb3ba45317
47 files changed
+207
-1925
No files matched your search
+6
-129
@@ -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),
|
||||
)
|
||||
@@ -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="*")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)}
|
||||
|
||||
|
||||
Reference in new issue
Block a user