refactor(session): unify model and display history storage (#6336)

* refactor(session): persist display history in SQLite

* fix(session): preserve new fork activity timestamps

* test(agent): use SQLite-owned model failure recovery fixture

* test(agent): isolate session slash routing from loop shutdown

Exercise the real inbound dispatcher and await its session worker. Keep response deadlines and behavioral assertions, while leaving full SQLite cleanup to the existing async fixture rather than an unrelated two-second shutdown deadline.

* fix(webui): admit direct deliveries to display history

* docs: clarify session history migration guidance
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-21 16:13:59 +08:00
1 parent d617b723aa
commit b32b1327ce
50 files changed
+2123 -3235

No files matched your search

+177
View File
@@ -0,0 +1,177 @@
"""Durable display facts, separate from provider/model messages and transports."""
from __future__ import annotations
import json
import sqlite3
from collections.abc import Iterator, Mapping
from dataclasses import dataclass, field
from enum import StrEnum
from pathlib import Path
from typing import Any, cast
MAX_HISTORY_FACT_BYTES = 8 * 1024 * 1024
HISTORY_GENERATION_METADATA_KEY = "_history_generation"
class HistoryKind(StrEnum):
INPUT = "input"
ANSWER = "answer"
ANSWER_SEGMENT = "answer_segment"
REASONING = "reasoning"
REASONING_SEGMENT = "reasoning_segment"
PROGRESS = "progress"
TOOL_ACTIVITY = "tool_activity"
FILE_ACTIVITY = "file_activity"
COMPLETION = "completion"
FORK_BOUNDARY = "fork_boundary"
COMPACTION = "compaction"
# Only old transcripts can contain unfinished transport fragments.
ANSWER_FRAGMENT = "answer_fragment"
REASONING_FRAGMENT = "reasoning_fragment"
@dataclass(frozen=True)
class HistoryFact:
kind: HistoryKind
content: Mapping[str, Any] = field(default_factory=lambda: cast(dict[str, Any], {}))
turn_id: str | None = None
phase: str | None = None
sequence: int | None = None
created_at_ms: int = 0
def encode(self) -> str:
record = json.dumps({
"kind": self.kind.value, "content": dict(self.content),
"turn_id": self.turn_id, "phase": self.phase,
"sequence": self.sequence, "created_at_ms": self.created_at_ms,
}, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
if len(record.encode("utf-8")) > MAX_HISTORY_FACT_BYTES:
raise ValueError("history fact exceeds the 8 MiB storage limit")
return record
@classmethod
def decode(cls, record: str) -> HistoryFact:
value = cast(dict[str, Any], json.loads(record))
return cls(
HistoryKind(value["kind"]), value["content"], value["turn_id"],
value["phase"], value["sequence"], value["created_at_ms"],
)
@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
record_count: int
byte_count: int
user_count: int
class HistoryReader:
"""A single-session view valid only inside its owner's read transaction."""
def __init__(self, db: sqlite3.Connection, key: str, storage_path: Path) -> None:
self._db = db
self.key = key
self.storage_path = storage_path
@property
def revision(self) -> tuple[str, int] | None:
row = self._db.execute(
"""SELECT sessions.generation, coalesce(history_heads.revision, -1) FROM sessions
LEFT JOIN history_heads ON history_heads.session_key=sessions.key WHERE sessions.key=?""",
(self.key,),
).fetchone()
return (str(row[0]), int(row[1])) if row is not None else None
@property
def turn_count(self) -> int:
return int(self._db.execute(
"SELECT coalesce(max(ordinal)+1, 0) FROM history_turns WHERE session_key=?",
(self.key,),
).fetchone()[0])
def turns(
self, *, before: int | None = None, after: int = 0, reverse: bool = False,
) -> Iterator[HistoryTurn]:
upper = self.turn_count if before is None else before
order = "DESC" if reverse else "ASC"
for row in self._db.execute(
f"""SELECT ordinal, record_count, byte_count, user_count FROM history_turns
WHERE session_key=? AND ordinal>=? AND ordinal<? ORDER BY ordinal {order}""",
(self.key, after, upper),
):
yield HistoryTurn(*row)
def read_turn(self, ordinal: int) -> list[HistoryFact]:
return [fact for _, fact in self.read_entries(ordinal)]
def read_entries(
self, ordinal: int, *, max_records: int | None = None, max_bytes: int | None = None,
) -> list[tuple[int, HistoryFact]]:
clause = "session_key=? AND turn_ordinal=?"
params = (self.key, ordinal)
selected: list[int] | None = None
if max_records is not None and max_bytes is not None:
# Inspect sizes/positions, not unbounded JSON bodies, before decoding
# a pathological single turn. Preserve the first input and useful tail.
priorities: list[tuple[int, int]] = []
for kinds, order in (((HistoryKind.INPUT,), "ASC"),
((HistoryKind.COMPLETION,), "DESC"),
((HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT, HistoryKind.ANSWER_FRAGMENT), "DESC")):
row = self._db.execute(
f"SELECT position, length(CAST(record AS BLOB)) FROM history_entries WHERE {clause} "
f"AND kind IN ({','.join('?' for _ in kinds)}) ORDER BY position {order} LIMIT 1",
(*params, *kinds),
).fetchone()
if row is not None:
priorities.append((row[0], row[1]))
candidates = self._db.execute(
f"SELECT position, length(CAST(record AS BLOB)) FROM history_entries WHERE {clause} ORDER BY position DESC LIMIT ?",
(*params, max_records),
)
positions: set[int] = set()
used = 0
for position, size in (*priorities, *candidates):
if position not in positions and len(positions) < max_records and used + size <= max_bytes:
positions.add(position)
used += size
selected = sorted(positions)
if not selected:
return []
clause += f" AND position IN ({','.join('?' for _ in selected)})"
return [(row[0], HistoryFact.decode(row[1])) for row in self._db.execute(
f"SELECT position, record FROM history_entries WHERE {clause} ORDER BY position",
(*params, *(selected or [])),
)]
def user_count_before(self, ordinal: int) -> int:
return int(self._db.execute(
"SELECT coalesce(sum(user_count), 0) FROM history_turns WHERE session_key=? AND ordinal<?",
(self.key, ordinal),
).fetchone()[0])
def navigation(self) -> Iterator[tuple[int, int, HistoryFact]]:
"""Read input/answer records only, never file diffs or tool result bodies."""
kinds = (HistoryKind.INPUT, HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT,
HistoryKind.ANSWER_FRAGMENT, HistoryKind.COMPLETION)
for row in self._db.execute(
"""SELECT turn_ordinal, position, record FROM history_entries
WHERE session_key=? AND kind IN (?, ?, ?, ?, ?) ORDER BY turn_ordinal, position""",
(self.key, *kinds),
):
yield int(row[0]), int(row[1]), HistoryFact.decode(row[2])
def all_facts(self) -> list[HistoryFact]:
return [HistoryFact.decode(row[0]) for row in self._db.execute(
"SELECT record FROM history_entries WHERE session_key=? ORDER BY turn_ordinal, position",
(self.key,),
)]
+20 -1
View File
@@ -8,7 +8,7 @@ from copy import deepcopy
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, TypedDict, cast
from typing import TYPE_CHECKING, Any, Callable, TypedDict, TypeVar, cast
from uuid import uuid4
from nanobot.providers.base import ProviderConversationState
@@ -16,6 +16,7 @@ from nanobot.runtime_context import (
RUNTIME_CONTEXT_HISTORY_META,
public_history_message,
)
from nanobot.session.display_history import HistoryFact, HistoryReader
from nanobot.session.history_visibility import HIDDEN_HISTORY_META, is_hidden_history_message
from nanobot.session.location import SessionLocation
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
@@ -33,6 +34,7 @@ from nanobot.utils.subagent_channel_display import scrub_subagent_announce_body
if TYPE_CHECKING:
from nanobot.session.state import SessionState
_T = TypeVar("_T")
SESSION_CACHE_MAX_SIZE = 128
_MESSAGE_TIME_PREFIX_RE = re.compile(r"^\[Message Time: [^\]]+\]\n?")
_LOCAL_IMAGE_BREADCRUMB_RE = re.compile(r"^\[image: (?:/|~)[^\]]+\]\s*$")
@@ -585,10 +587,27 @@ class SessionManager:
target = fork_session(source, target_key, before_user_index)
if target is not None:
self._store.save(target)
self._store.copy_history_prefix(source_key, target, before_user_index)
return target
return self._store.run_write(fork)
def project_history(self, key: str, project: Callable[[HistoryReader], _T]) -> _T:
"""Read an administrative display snapshot; runtime uses state.project_history."""
return self._store.project_history(key, project)
def append_history(self, key: str, facts: list[HistoryFact]) -> None:
"""Append offline fixture/import facts with the current admitted generation."""
self._require_offline_mutation()
def append() -> None:
session = self._store.load(key, history=False)
if session is None:
session = self.get_or_create(key)
self._store.save(session)
self._store.append_history(key, facts, expected_generation=session.generation)
self._store.run_write(append)
def read_session_file(self, key: str) -> dict[str, Any] | None:
"""Read a session without populating the cache."""
return cast(dict[str, Any] | None, self._store.read(key))
+140 -4
View File
@@ -13,6 +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.history_visibility import is_hidden_history_message
from nanobot.session.manager import (
Session,
@@ -69,8 +70,36 @@ def _create_schema_v1(db: sqlite3.Connection) -> None:
db.execute(statement)
def _create_schema_v2(db: sqlite3.Connection) -> None:
for statement in (
"""CREATE TABLE history_heads (
session_key TEXT PRIMARY KEY REFERENCES sessions(key) ON DELETE CASCADE,
revision INTEGER NOT NULL DEFAULT 0,
updated_at_ms INTEGER NOT NULL DEFAULT 0,
preview TEXT NOT NULL DEFAULT '', user_preview TEXT NOT NULL DEFAULT ''
)""",
"""CREATE TABLE history_turns (
session_key TEXT NOT NULL REFERENCES sessions(key) ON DELETE CASCADE,
ordinal INTEGER NOT NULL, record_count INTEGER NOT NULL,
byte_count INTEGER NOT NULL, user_count INTEGER NOT NULL,
completed INTEGER NOT NULL,
PRIMARY KEY (session_key, ordinal)
)""",
"""CREATE TABLE history_entries (
session_key TEXT NOT NULL, turn_ordinal INTEGER NOT NULL,
position INTEGER NOT NULL, kind TEXT NOT NULL, record TEXT NOT NULL,
PRIMARY KEY (session_key, turn_ordinal, position),
FOREIGN KEY (session_key, turn_ordinal)
REFERENCES history_turns(session_key, ordinal) ON DELETE CASCADE
)""",
):
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,)
_SCHEMA_MIGRATIONS: tuple[Callable[[sqlite3.Connection], None], ...] = (
_create_schema_v1, _create_schema_v2,
)
def _schema_version(db: sqlite3.Connection) -> int:
@@ -391,6 +420,110 @@ 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:
return project(HistoryReader(db, key, self.path))
def append_history(
self, key: str, facts: list[HistoryFact], *, expected_generation: str,
) -> None:
encoded = [(fact, fact.encode()) for fact in facts]
with self.transaction() as db:
row = db.execute("SELECT generation FROM sessions WHERE key=?", (key,)).fetchone()
if row is None or row[0] != expected_generation:
raise SessionConflictError("history belongs to a deleted or replaced session")
db.execute("INSERT OR IGNORE INTO history_heads (session_key) VALUES (?)", (key,))
tail = db.execute(
"SELECT ordinal, record_count, completed FROM history_turns WHERE session_key=? ORDER BY ordinal DESC LIMIT 1",
(key,),
).fetchone()
ordinal, position = (int(tail[0]), int(tail[1])) if tail is not None else (0, 0)
completed = tail is not None and bool(tail[2])
for fact, record in encoded:
if completed:
ordinal, position = ordinal + 1, 0
if position == 0:
db.execute(
"INSERT INTO history_turns VALUES (?, ?, 0, 0, 0, 0)", (key, ordinal),
)
db.execute("INSERT INTO history_entries VALUES (?, ?, ?, ?, ?)", (
key, ordinal, position, fact.kind.value, record,
))
completed = fact.kind is HistoryKind.COMPLETION
db.execute(
"""UPDATE history_turns SET record_count=record_count+1, byte_count=byte_count+?,
user_count=user_count+?, completed=? WHERE session_key=? AND ordinal=?""",
(len(record.encode("utf-8")), int(fact.kind is HistoryKind.INPUT),
int(completed), key, ordinal),
)
position += 1
if fact.kind in {HistoryKind.INPUT, HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT}:
preview = message_preview_text({"content": fact.content.get("text", "")})
if preview:
field = "user_preview" if fact.kind is HistoryKind.INPUT else "preview"
db.execute(f"UPDATE history_heads SET {field}=? WHERE session_key=? AND {field}=''", (preview, key))
db.execute("UPDATE history_heads SET updated_at_ms=max(updated_at_ms, ?) WHERE session_key=?",
(fact.created_at_ms, key))
if encoded:
db.execute("UPDATE history_heads SET revision=revision+1 WHERE session_key=?", (key,))
def copy_history_prefix(self, source_key: str, target: Session, before_input: int) -> bool:
"""Copy a display prefix alongside its canonical fork, in the caller's transaction."""
def select(reader: HistoryReader) -> list[HistoryFact] | None:
revision = reader.revision
if revision is None or revision[1] < 0:
return None
copied: list[HistoryFact] = []
inputs = 0
for fact in reader.all_facts():
if fact.kind is HistoryKind.FORK_BOUNDARY:
continue
if fact.kind is HistoryKind.INPUT:
if inputs == before_input:
return copied
inputs += 1
copied.append(fact)
return copied if inputs == before_input else None
facts = self.project_history(source_key, select)
if facts is None:
return False
facts.append(HistoryFact(HistoryKind.FORK_BOUNDARY, created_at_ms=int(target.created_at.timestamp() * 1000)))
self.append_history(target.key, facts, expected_generation=target.generation)
return True
def delete(self, key: str) -> bool:
with self.transaction() as db:
return db.execute("DELETE FROM sessions WHERE key=?", (key,)).rowcount > 0
@@ -433,10 +566,13 @@ class SqliteSessionStore:
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
'metadata', metadata, 'history_updated_at_ms', history_updated_at_ms,
'history_preview', history_preview
)) FROM (
SELECT key, created_at, updated_at, title, preview, visible_updated_at, metadata
FROM sessions ORDER BY updated_at DESC
SELECT sessions.*, coalesce(history_heads.updated_at_ms, 0) AS history_updated_at_ms,
coalesce(nullif(history_heads.user_preview, ''), history_heads.preview, '') AS history_preview
FROM sessions LEFT JOIN history_heads ON history_heads.session_key=sessions.key
ORDER BY sessions.updated_at DESC
)
""").fetchone()[0]
# The SQL projection constructs this list and its dictionary fields.
+39 -1
View File
@@ -14,8 +14,15 @@ 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.keys import is_dream_session
from nanobot.session.manager import Session, SessionIdentity, SessionPolicy, fork_session
from nanobot.session.manager import (
Session,
SessionIdentity,
SessionInfo,
SessionPolicy,
fork_session,
)
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
from nanobot.session.sqlite_store import SessionConflictError, SqliteSessionStore
from nanobot.session.types import PARENT_SESSION_KEY, SessionTypes
@@ -692,6 +699,31 @@ 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:
return await self._execute(
key, lambda: self._store.project_history(key, project),
operation_name="project_history", write=False,
)
async def append_history(
self, key: str, facts: Sequence[HistoryFact], *, expected_generation: str,
) -> None:
records = list(facts)
await self._execute(
key,
lambda: self._store.append_history(key, deepcopy(records), expected_generation=expected_generation),
operation_name="append_history",
)
async def record_delivery(
self,
key: str,
@@ -933,6 +965,7 @@ class SessionState:
async def fork(
self, source_key: str, target_key: str, before_user_index: int,
*, title: str | None = None,
history_projection: Callable[[Session], list[HistoryFact]] | None = None,
) -> Session | None:
def commit() -> Session | None:
def write() -> Session | None:
@@ -945,6 +978,11 @@ class SessionState:
if title:
target.metadata["title"] = title
self._commit(target)
copied = self._store.copy_history_prefix(source_key, target, before_user_index)
if not copied and history_projection is not None:
facts = history_projection(target)
facts.append(HistoryFact(HistoryKind.FORK_BOUNDARY, created_at_ms=int(target.created_at.timestamp() * 1000)))
self._store.append_history(target.key, facts, expected_generation=target.generation)
return target
target = self._store.run_write(write)
+25 -1
View File
@@ -41,6 +41,7 @@ from nanobot.llm_usage.context import llm_usage_source
from nanobot.providers.base import LLMProvider, LLMUsage
from nanobot.providers.fallback_provider import FallbackModelObserver, FallbackModelSelection
from nanobot.runtime_context import public_history_message
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
from nanobot.session.goal_state import goal_state_ws_blob
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import Session, SessionManager
@@ -531,6 +532,25 @@ class WebuiTurnRoutePolicy:
return routed
async def admit(self, route: TurnRoute, session_key: str, generation: str | None) -> TurnRoute:
"""Bind replies to the display destination's admitted lifetime."""
if route.channel != "websocket":
return route
target_key = webui_session_key(route.chat_id)
metadata = dict(route.metadata)
if target_key == session_key and generation is not None:
metadata.setdefault(HISTORY_GENERATION_METADATA_KEY, generation)
return replace(route, metadata=metadata)
revision = await self.sessions.state.project_history(target_key, lambda history: history.revision)
if revision is None:
raise SessionConflictError("display destination is no longer active")
admitted = metadata.get(HISTORY_GENERATION_METADATA_KEY)
# A distinct alias admitted by the WebSocket edge must still be current.
if admitted not in (None, generation, revision[0]):
raise SessionConflictError("display destination generation was replaced")
metadata[HISTORY_GENERATION_METADATA_KEY] = revision[0]
return replace(route, metadata=metadata)
def build_webui_fallback_model_observer(bus: MessageBus) -> FallbackModelObserver:
"""Translate provider fallback choices into chat-scoped WebUI events."""
@@ -630,6 +650,7 @@ class WebuiTurnCoordinator:
content="",
metadata=dict(ctx.metadata or {}),
session_key_override=ctx.session_key,
session_generation=ctx.session_generation,
)
@staticmethod
@@ -657,8 +678,11 @@ class WebuiTurnCoordinator:
return
public_metadata = _session_message_public_metadata(envelope)
try:
append_session_message_input(
assert event.context.session_generation is not None
await append_session_message_input(
session_key,
sessions=self.sessions,
expected_generation=event.context.session_generation,
content=event.content,
created_at_ms=envelope["created_at_ms"],
session_message=public_metadata,