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
@@ -20,5 +20,4 @@ CREATE TABLE pending_inputs (
PRIMARY KEY (session_key, kind, position)
);
CREATE INDEX sessions_updated ON sessions(updated_at DESC);
INSERT INTO storage_meta (key, value) VALUES ('jsonl_import', 'complete');
PRAGMA user_version = 1;
@@ -1,9 +1,6 @@
"""Reset a corrupt last_consolidated offset instead of hiding history (#4066)."""
import json
from pathlib import Path
from nanobot.session.manager import Session, SessionManager
from nanobot.session.manager import Session
def _session(count: int, last_consolidated: object) -> Session:
@@ -21,39 +18,6 @@ def test_non_integer_offset_is_reset():
assert _session(3, offset).last_consolidated == 0
def test_loaded_corrupt_offset_keeps_messages(tmp_path: Path):
offsets = {
"string": "999",
"null": None,
"float": 0.5,
"bool": True,
}
for name, offset in offsets.items():
workspace = tmp_path / name
path = workspace / "sessions" / "old.jsonl"
path.parent.mkdir(parents=True, exist_ok=True)
message = {"role": "user", "content": f"survived {name}"}
path.write_text(
"\n".join([
json.dumps({
"_type": "metadata",
"key": "chan:chat",
"metadata": {},
"last_consolidated": offset,
}),
json.dumps(message),
]) + "\n",
encoding="utf-8",
)
session = SessionManager(workspace).get_or_create("chan:chat")
assert session.messages == [message]
assert session.last_consolidated == 0
assert session.get_history(max_messages=10) == [message]
def test_valid_offset_is_preserved():
session = _session(10, 4)
assert session.last_consolidated == 4
@@ -63,59 +27,6 @@ def test_valid_offset_is_preserved():
]
def test_last_archived_field_migrates_with_legacy_alias(tmp_path: Path):
path = tmp_path / "sessions" / "old.jsonl"
path.parent.mkdir(parents=True, exist_ok=True)
messages = [
{"role": "user", "content": "first"},
{"role": "assistant", "content": "second"},
]
path.write_text(
"\n".join([
json.dumps({
"_type": "metadata",
"key": "chan:chat",
"metadata": {},
"last_archived": 1,
}),
*(json.dumps(message) for message in messages),
]) + "\n",
encoding="utf-8",
)
manager = SessionManager(tmp_path)
session = manager.get_or_create("chan:chat")
assert session.last_archived == 1
assert session.last_consolidated == 1
manager.save(session)
assert manager.read_session_snapshot("chan:chat").last_archived == 1
def test_loaded_null_metadata_becomes_empty_dict(tmp_path: Path):
"""Session jsonl metadata:null must load as {} so agent .pop/.get work."""
path = tmp_path / "sessions" / "old.jsonl"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps({
"_type": "metadata",
"key": "chan:chat",
"created_at": "2026-01-01T00:00:00",
"updated_at": "2026-01-01T00:00:00",
"metadata": None,
"last_consolidated": 0,
}) + "\n",
encoding="utf-8",
)
manager = SessionManager(tmp_path)
session = manager.get_or_create("chan:chat")
assert session.metadata == {}
session.metadata["title"] = "ok"
assert session.metadata["title"] == "ok"
session.metadata.pop("title", None)
assert session.metadata == {}
def test_session_post_init_coerces_null_metadata():
session = Session(key="chan:chat", metadata=None) # type: ignore[arg-type]
assert session.metadata == {}
-123
View File
@@ -13,7 +13,6 @@ from nanobot.session.display_history import HistoryFact, HistoryKind
from nanobot.session.manager import SessionManager
from nanobot.session.sqlite_store import SessionConflictError
from nanobot.webui.forking import create_webui_chat_fork
from nanobot.webui.history import HISTORY_IMPORT_MARKER, collect_legacy_history
from nanobot.webui.transcript import WebUITranscriptRecorder, build_webui_thread_response
@@ -21,13 +20,6 @@ def _manager(tmp_path: Path) -> SessionManager:
return SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
def _legacy(directory: Path, key: str, records: list[dict]) -> Path:
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"{SessionManager.safe_key(key)}.jsonl"
path.write_text("".join(json.dumps(record, ensure_ascii=False) + "\n" for record in records), encoding="utf-8")
return path
async def test_display_facts_survive_reopen_without_entering_model_history(tmp_path):
sessions = _manager(tmp_path)
session = await sessions.state.get("websocket:durable")
@@ -121,73 +113,6 @@ async def test_fork_rolls_back_both_histories_if_display_copy_fails(tmp_path, mo
await sessions.state.aclose()
async def test_legacy_import_is_atomic_repeatable_and_deletion_cannot_resurrect_backup(tmp_path):
sessions = _manager(tmp_path)
directory = tmp_path / "legacy"
path = _legacy(directory, "websocket:imported", [
{"event": "user", "chat_id": "imported", "text": "hello", "created_at_ms": 1000},
{"event": "delta", "chat_id": "imported", "text": "an"},
{"event": "delta", "chat_id": "imported", "text": "swer"},
{"event": "stream_end", "chat_id": "imported"},
{"event": "turn_end", "chat_id": "imported"},
])
before = path.read_bytes()
def collect(rows):
return collect_legacy_history(rows, directory=directory)
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, collect)
facts = await sessions.state.project_history("websocket:imported", lambda history: history.all_facts())
assert [fact.kind for fact in facts] == [HistoryKind.INPUT, HistoryKind.ANSWER_SEGMENT, HistoryKind.COMPLETION]
assert facts[1].content["text"] == "answer"
assert path.read_bytes() == before
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, collect)
assert await sessions.state.project_history("websocket:imported", lambda history: history.all_facts()) == facts
assert await sessions.state.delete("websocket:imported")
await sessions.state.aclose()
reopened = _manager(tmp_path)
await reopened.state.migrate_history(HISTORY_IMPORT_MARKER, collect)
assert await reopened.state.read_metadata("websocket:imported") is None
await reopened.state.aclose()
async def test_corrupt_legacy_input_rolls_back_import_marker_and_all_records(tmp_path):
sessions = _manager(tmp_path)
directory = tmp_path / "legacy"
_legacy(directory, "websocket:first", [{"event": "user", "chat_id": "first", "text": "safe"}])
corrupt = _legacy(directory, "websocket:second", [{"event": "user", "chat_id": "second", "text": "also safe"}])
with corrupt.open("a", encoding="utf-8") as handle:
handle.write('{"event":\n')
with pytest.raises(ValueError, match="cannot import history"):
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(rows, directory=directory))
assert await sessions.state.list_sessions() == []
with closing(sqlite3.connect(sessions.sessions_dir / "sessions.sqlite3")) as db:
assert db.execute("SELECT value FROM storage_meta WHERE key=?", (HISTORY_IMPORT_MARKER,)).fetchone() is None
_legacy(directory, "websocket:second", [{"event": "user", "chat_id": "second", "text": "fixed"}])
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(rows, directory=directory))
assert {row["key"] for row in await sessions.state.list_sessions()} == {"websocket:first", "websocket:second"}
await sessions.state.aclose()
async def test_segments_import_in_order_without_trusting_damaged_manifest(tmp_path):
sessions = _manager(tmp_path)
directory = tmp_path / "legacy"
segments = directory / "websocket_order.segments"
segments.mkdir(parents=True)
for number in (2, 1):
(segments / f"{number:06}.jsonl").write_text(json.dumps({"event": "message", "chat_id": "order", "text": str(number)}) + "\n", encoding="utf-8")
(segments / "manifest.json").write_text("broken cached manifest", encoding="utf-8")
_legacy(directory, "websocket:order", [{"event": "message", "chat_id": "order", "text": "3"}])
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(rows, directory=directory))
assert await sessions.state.project_history("websocket:order", lambda history: [fact.content["text"] for fact in history.all_facts()]) == ["1", "2", "3"]
await sessions.state.aclose()
def test_orphan_lossy_filename_requires_recorded_identity(tmp_path):
directory = tmp_path / "legacy"
_legacy(directory, "websocket:a_b", [{"event": "message", "text": "unknown whether a_b or a:b"}])
with pytest.raises(ValueError, match="ambiguous legacy history identity"):
collect_legacy_history([], directory=directory)
async def test_recorder_keeps_completed_segments_not_every_transport_delta(tmp_path):
sessions = _manager(tmp_path)
key = "websocket:stream"
@@ -249,31 +174,6 @@ asyncio.run(run())
assert reopened.read_session_file(source.key)["messages"] == source.messages
@pytest.mark.asyncio
async def test_legacy_import_owner_survives_delete_and_new_workspace(tmp_path):
from nanobot.webui.history import collect_legacy_history
root = tmp_path / "sessions"
legacy = tmp_path / "webui"
legacy.mkdir()
key = "websocket:owned"
(legacy / f"{SessionManager.safe_key(key)}.jsonl").write_text(
'{"event":"user","chat_id":"owned","text":"keep ownership"}\n', encoding="utf-8",
)
first = SessionManager(tmp_path / "first", sessions_root=root)
await first.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(
rows, directory=legacy, namespace=first.sessions_dir,
))
await first.state.delete(key)
await first.state.aclose()
second = SessionManager(tmp_path / "second", sessions_root=root)
await second.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(
rows, directory=legacy, namespace=second.sessions_dir,
))
assert await second.state.read(key) is None
await second.state.aclose()
async def test_large_display_fact_serialization_and_copy_stay_off_runtime_loop(tmp_path, monkeypatch):
import threading
@@ -317,29 +217,6 @@ def test_message_projection_adapter_preserves_reply_and_agent_activity():
assert record_from_fact(fact, "websocket:activity") == record
async def test_legacy_activity_without_record_timestamps_preserves_file_time(tmp_path):
import os
from nanobot.webui.session_list_index import list_webui_sessions
sessions = _manager(tmp_path)
session = await sessions.state.get_header("websocket:old-activity")
directory = tmp_path / "legacy"
path = _legacy(directory, session.key, [{
"event": "message", "chat_id": "old-activity", "text": "historical display activity",
}])
os.utime(path, (1760000000, 1760000000))
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(
rows, directory=directory,
))
rows = list_webui_sessions(sessions, await sessions.state.list_metadata())
from datetime import datetime
assert datetime.fromisoformat(rows[0]["updated_at"]).timestamp() == 1760000000
assert rows[0]["preview"] == "historical display activity"
await sessions.state.aclose()
@pytest.mark.parametrize("stored_display", [False, True])
async def test_new_fork_activity_uses_creation_time_not_inherited_history(tmp_path, stored_display):
from datetime import datetime
-1
View File
@@ -35,7 +35,6 @@ def _input(text, turn_id):
@pytest.mark.parametrize("count", [1, 2])
@pytest.mark.parametrize("leave_unconsumed", [False, True])
async def test_late_consumption_commits_history_and_only_its_ids(tmp_path, monkeypatch, count, leave_unconsumed):
monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: tmp_path / "webui")
sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
state = sessions.state
try:
+10 -25
View File
@@ -23,15 +23,6 @@ from nanobot.webui import history as history_module
from nanobot.webui.recovery import RecoveryActionError, RecoveryCoordinator
@pytest.fixture(autouse=True)
def _isolate_webui_transcripts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Recovery scans must discover only test-owned transcripts, not active user chats."""
webui_dir = tmp_path / "isolated-webui"
webui_dir.mkdir()
monkeypatch.setattr(history_module, "get_webui_dir", lambda: webui_dir)
monkeypatch.setattr(history_module, "get_webui_dir", lambda: webui_dir)
def _persist(manager: SessionManager, session: Session) -> None:
session.metadata["webui"] = True
manager.save(session)
@@ -128,25 +119,19 @@ async def test_materialized_interruption_can_continue_from_saved_context(
@pytest.mark.asyncio
async def test_transcript_only_interruption_is_discovered_without_materializing_completed_history(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
webui_dir = tmp_path / "webui"
webui_dir.mkdir()
monkeypatch.setattr(history_module, "get_webui_dir", lambda: webui_dir)
monkeypatch.setattr(history_module, "get_webui_dir", lambda: webui_dir)
unfinished_key = "websocket:unfinished"
completed_key = "websocket:completed"
(webui_dir / f"{SessionManager.safe_key(unfinished_key)}.jsonl").write_text(
'{"event":"user","chat_id":"unfinished","text":"keep going"}\n'
'{"event":"message","chat_id":"unfinished","kind":"progress","text":"Working"}\n',
encoding="utf-8",
)
(webui_dir / f"{SessionManager.safe_key(completed_key)}.jsonl").write_text(
'{"event":"user","chat_id":"completed","text":"done"}\n'
'{"event":"message","chat_id":"completed","text":"finished"}\n'
'{"event":"turn_end","chat_id":"completed"}\n',
encoding="utf-8",
)
stored = SessionManager(tmp_path / "workspace")
stored.append_history(unfinished_key, [history_module.fact_from_record(record) for record in (
{"event": "user", "text": "keep going"},
{"event": "message", "kind": "progress", "text": "Working"},
)])
stored.append_history(completed_key, [history_module.fact_from_record(record) for record in (
{"event": "user", "text": "done"},
{"event": "message", "text": "finished"},
{"event": "turn_end"},
)])
coordinator, bus, sessions = _coordinator(tmp_path / "workspace")
await coordinator.scan()
@@ -1,11 +0,0 @@
"""Completed migration makes legacy JSONL files inert."""
from nanobot.session.manager import SessionManager
def test_list_and_reads_ignore_files_created_after_migration(tmp_path):
manager = SessionManager(tmp_path)
(manager.sessions_dir / "cli_test.jsonl").write_text("invalid JSON")
assert manager.list_sessions() == []
assert manager.read_session_metadata("cli:test") is None
assert manager.read_session_file("cli:test") is None
-74
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import json
import os
import shutil
import subprocess
@@ -12,40 +11,9 @@ from pathlib import Path
import pytest
from nanobot.config.loader import load_config
from nanobot.session.jsonl_migration import WORKSPACE_BACKUP_DIR
from nanobot.session.location import SessionLocation
from nanobot.session.manager import SessionManager
def _write_legacy_session(
old_dir: Path,
key: str,
content: str,
*,
updated_at: str = "2026-01-01T00:00:00",
) -> Path:
"""Write a valid session file in the legacy in-workspace location."""
old_dir.mkdir(parents=True, exist_ok=True)
path = old_dir / f"{SessionLocation.storage_key(key)}.jsonl"
path.write_text(
json.dumps(
{
"_type": "metadata",
"key": key,
"created_at": "2026-01-01T00:00:00",
"updated_at": updated_at,
"metadata": {},
"last_consolidated": 0,
}
)
+ "\n"
+ json.dumps({"role": "user", "content": content})
+ "\n",
encoding="utf-8",
)
return path
def test_sessions_are_stored_outside_workspace(tmp_path: Path) -> None:
workspace = tmp_path / "workspace"
manager = SessionManager(workspace=workspace)
@@ -219,45 +187,3 @@ def test_equivalent_workspace_paths_share_one_store(tmp_path: Path) -> None:
via_link = SessionManager(workspace=link_workspace).get_or_create("telegram:1")
assert via_link.messages[-1]["content"] == "via-real"
def test_migration_rejects_symlinked_session_file(tmp_path, create_symlink):
workspace = tmp_path / "workspace"
path = _write_legacy_session(workspace / "sessions", "cli:test", "original")
target = tmp_path / "outside.jsonl"
path.rename(target)
create_symlink(path, target)
with pytest.raises(RuntimeError, match="migration failed"):
SessionManager(workspace)
assert "original" in target.read_text()
def test_migration_rejects_symlinked_source_directory(tmp_path, create_symlink):
workspace = tmp_path / "workspace"
workspace.mkdir()
outside = tmp_path / "outside"
outside.mkdir()
create_symlink(workspace / "sessions", outside, target_is_directory=True)
with pytest.raises(ValueError, match="symlink"):
SessionManager(workspace)
def test_workspace_migration_rejects_symlinked_backup_directory(tmp_path, create_symlink):
workspace = tmp_path / "workspace"
root = tmp_path / "root"
source = _write_legacy_session(workspace / "sessions", "cli:test", "original")
original = source.read_bytes()
location = SessionLocation(workspace, sessions_root=root)
outside = tmp_path / "outside"
outside.mkdir()
backup = location.sessions_dir / WORKSPACE_BACKUP_DIR
create_symlink(backup, outside, target_is_directory=True)
with pytest.raises(RuntimeError, match="Could not move legacy sessions"):
SessionManager(workspace, sessions_root=root)
assert source.read_bytes() == original
assert list(outside.iterdir()) == []
backup.unlink()
manager = SessionManager(workspace, sessions_root=root)
assert not source.exists()
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / source.name).read_bytes() == original
+13 -45
View File
@@ -1,6 +1,5 @@
"""Session schema upgrades preserve records and fail atomically."""
import json
import sqlite3
from contextlib import closing
from pathlib import Path
@@ -38,22 +37,6 @@ def _session() -> Session:
)
def _write_legacy(workspace: Path, session: Session) -> Path:
directory = workspace / "sessions"
directory.mkdir(parents=True)
path = directory / "session.jsonl"
assert session.provider_state is not None
records = [
{"_type": "metadata", "key": session.key, "metadata": session.metadata,
"created_at": session.created_at.isoformat(), "updated_at": session.updated_at.isoformat(),
"last_archived": session.last_archived},
{"_type": "provider_state", "state": session.provider_state.to_private_record()},
*session.messages,
]
path.write_text("\n".join(json.dumps(record) for record in records) + "\n", encoding="utf-8")
return path
def _database_snapshot(path: Path) -> tuple[int, str, str]:
with closing(sqlite3.connect(path)) as db:
return (
@@ -63,10 +46,8 @@ def _database_snapshot(path: Path) -> tuple[int, str, str]:
)
def test_ordered_upgrades_preserve_records_and_do_not_repeat_import(tmp_path, monkeypatch):
workspace = tmp_path / "workspace"
def test_ordered_upgrades_preserve_records(tmp_path, monkeypatch):
original = _session()
source = _write_legacy(workspace, original)
store = SqliteSessionStore(tmp_path)
with closing(sqlite3.connect(store.path)) as db:
schema = Path(__file__).with_name("fixtures") / "sqlite_v1.sql"
@@ -83,9 +64,8 @@ def test_ordered_upgrades_preserve_records_and_do_not_repeat_import(tmp_path, mo
monkeypatch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", (
*sqlite_store._SCHEMA_MIGRATIONS, add_archived, index_archived,
))
source.write_text("stale malformed source must not be imported again", encoding="utf-8")
upgraded = SqliteSessionStore(tmp_path)
upgraded.initialize(workspace)
upgraded.initialize()
assert _database_snapshot(store.path)[0] == len(sqlite_store._SCHEMA_MIGRATIONS)
loaded = upgraded.load(original.key)
assert loaded is not None
@@ -95,7 +75,7 @@ def test_ordered_upgrades_preserve_records_and_do_not_repeat_import(tmp_path, mo
upgraded.save(loaded)
reopened = SqliteSessionStore(tmp_path)
reopened.initialize(workspace)
reopened.initialize()
roundtrip = reopened.load(original.key)
assert roundtrip is not None
assert roundtrip.messages == original.messages
@@ -104,13 +84,11 @@ def test_ordered_upgrades_preserve_records_and_do_not_repeat_import(tmp_path, mo
with closing(sqlite3.connect(store.path)) as db:
assert db.execute("SELECT archived FROM sessions").fetchall() == [(0,)]
assert db.execute("SELECT name FROM sqlite_master WHERE name='sessions_archived'").fetchone()
assert db.execute("SELECT value FROM storage_meta WHERE key='jsonl_import'").fetchone() == ("complete",)
def test_failed_upgrade_rolls_back_schema_version_and_records_then_can_retry(tmp_path, monkeypatch):
workspace = tmp_path / "workspace"
store = SqliteSessionStore(tmp_path)
store.initialize(workspace)
store.initialize()
original = _session()
store.save(original)
before = _database_snapshot(store.path)
@@ -128,7 +106,7 @@ def test_failed_upgrade_rolls_back_schema_version_and_records_then_can_retry(tmp
*migrations, add_archived, fail_upgrade,
))
with pytest.raises(RuntimeError, match="migration interrupted"):
store.initialize(workspace)
store.initialize()
assert _database_snapshot(store.path) == before
def complete_upgrade(db: sqlite3.Connection) -> None:
@@ -137,7 +115,7 @@ def test_failed_upgrade_rolls_back_schema_version_and_records_then_can_retry(tmp
monkeypatch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", (
*migrations, add_archived, complete_upgrade,
))
store.initialize(workspace)
store.initialize()
assert _database_snapshot(store.path)[0] == len(sqlite_store._SCHEMA_MIGRATIONS)
loaded = store.load(original.key)
assert loaded is not None
@@ -146,7 +124,7 @@ def test_failed_upgrade_rolls_back_schema_version_and_records_then_can_retry(tmp
assert loaded.provider_state == original.provider_state
def test_added_columns_allow_import_and_all_session_write_paths(tmp_path, monkeypatch):
def test_added_columns_allow_all_session_write_paths(tmp_path, monkeypatch):
def add_optional_columns(db: sqlite3.Connection) -> None:
for table in ("storage_meta", "sessions", "messages", "checkpoints", "pending_inputs"):
db.execute(f"ALTER TABLE {table} ADD COLUMN extension TEXT")
@@ -155,16 +133,8 @@ def test_added_columns_allow_import_and_all_session_write_paths(tmp_path, monkey
monkeypatch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", (
*sqlite_store._SCHEMA_MIGRATIONS, add_optional_columns,
))
workspace = tmp_path / "workspace"
imported = _session()
_write_legacy(workspace, imported)
store = SqliteSessionStore(tmp_path)
store.initialize(workspace)
loaded = store.load(imported.key)
assert loaded is not None
assert loaded.messages == imported.messages
assert loaded.metadata == imported.metadata
assert loaded.provider_state == imported.provider_state
store.initialize()
created = _session()
created.key = "chat:new"
@@ -183,15 +153,14 @@ def test_added_columns_allow_import_and_all_session_write_paths(tmp_path, monkey
assert roundtrip.metadata == current.metadata
assert roundtrip.provider_state == current.provider_state
with closing(sqlite3.connect(store.path)) as db:
for table in ("storage_meta", "sessions", "messages", "checkpoints", "pending_inputs"):
for table in ("sessions", "messages", "checkpoints", "pending_inputs"):
rows = db.execute(f"SELECT extension, format_version FROM {table}").fetchall()
assert rows and all(row == (None, 1) for row in rows)
def test_future_schema_is_rejected_without_modifying_database(tmp_path):
workspace = tmp_path / "workspace"
store = SqliteSessionStore(tmp_path)
store.initialize(workspace)
store.initialize()
store.save(_session())
future_version = len(sqlite_store._SCHEMA_MIGRATIONS) + 1
with closing(sqlite3.connect(store.path)) as db:
@@ -202,16 +171,15 @@ def test_future_schema_is_rejected_without_modifying_database(tmp_path):
before_files = {path.name for path in tmp_path.iterdir()}
with pytest.raises(RuntimeError, match=f"unsupported session database schema: {future_version}"):
store.initialize(workspace)
store.initialize()
assert _database_snapshot(store.path) == before
assert store.path.read_bytes() == before_bytes
assert {path.name for path in tmp_path.iterdir()} == before_files
def test_missing_sqlite_json_support_is_rejected_before_database_changes(tmp_path, monkeypatch):
workspace = tmp_path / "workspace"
store = SqliteSessionStore(tmp_path)
store.initialize(workspace)
store.initialize()
store.save(_session())
with closing(sqlite3.connect(store.path)) as db:
db.execute("PRAGMA journal_mode = DELETE")
@@ -231,6 +199,6 @@ def test_missing_sqlite_json_support_is_rejected_before_database_changes(tmp_pat
with monkeypatch.context() as patch:
patch.setattr(sqlite3, "connect", connect)
with pytest.raises(RuntimeError, match="requires SQLite JSON support"):
store.initialize(workspace)
store.initialize()
assert _database_snapshot(store.path) == before
assert store.path.read_bytes() == before_bytes
+1 -357
View File
@@ -1,245 +1,18 @@
"""SQLite durability, migration, and asynchronous state ownership contracts."""
"""SQLite durability and asynchronous state ownership contracts."""
import asyncio
import json
import shutil
import sqlite3
import subprocess
import sys
import threading
import time
import tomllib
from pathlib import Path
import pytest
from packaging.version import Version
import nanobot.session.jsonl_migration as jsonl_migration
from nanobot.session.jsonl_migration import SUNSET_VERSION, WORKSPACE_BACKUP_DIR
from nanobot.session.location import SessionLocation
from nanobot.session.manager import Session, SessionManager
from nanobot.session.sqlite_store import SessionConflictError
def legacy(workspace: Path, key: str = "websocket:old", *, content: str = "hello") -> Path:
directory = workspace / "sessions"
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"{SessionLocation.storage_key(key)}.jsonl"
path.write_text(json.dumps({"_type": "metadata", "key": key, "metadata": {"title": "old"},
"last_archived": 0, "created_at": "2026-01-01T00:00:00",
"updated_at": "2026-01-01T00:00:00"}) + "\n" +
json.dumps({"role": "user", "content": content}) + "\n")
return path
def test_migration_must_be_removed_at_declared_sunset():
version = tomllib.loads((Path(__file__).parents[2] / "pyproject.toml").read_text())["project"]["version"]
assert SUNSET_VERSION == "0.5.0"
assert Version(Version(version).base_version) < Version(SUNSET_VERSION), (
"Remove jsonl_migration, its initialization hook, and migration-only tests before 0.5.0"
)
def test_import_is_once_and_private_sources_are_unchanged(tmp_path):
workspace = tmp_path / "workspace"
path = legacy(workspace)
location = SessionLocation(workspace)
path = path.replace(location.sessions_dir / path.name)
original = path.read_bytes()
manager = SessionManager(workspace)
assert manager.read_session_snapshot("websocket:old").messages[0]["content"] == "hello"
assert path.read_bytes() == original
manager.delete_session("websocket:old")
# Reopening must not resurrect deleted conversations, even if the source changes.
path.write_text("broken legacy file")
assert SessionManager(workspace).read_session_snapshot("websocket:old") is None
@pytest.mark.parametrize(("newline", "trailing_newline"), [
("\n", True), ("\r\n", True), ("\n", False), ("\r\n", False),
], ids=["lf", "crlf", "lf-no-final-newline", "crlf-no-final-newline"])
def test_migration_preserves_unicode_separators(tmp_path, newline, trailing_newline):
workspace = tmp_path / "workspace"
path = legacy(workspace, content="中文🙂\u0085NEL\u2028LS\u2029PS\nLF\rCR")
records = [json.loads(line) for line in path.read_text(encoding="utf-8").split("\n")
if line.strip()]
records.append({"role": "assistant", "content": "reply\u2029\u2028\u0085"})
lines = [json.dumps(record, ensure_ascii=False) for record in records]
lines[1:1] = ["", " \t"]
original = (newline.join(lines) + (newline if trailing_newline else "")).encode("utf-8")
path.write_bytes(original)
manager = SessionManager(workspace)
expected = records[1:]
assert manager.read_session_snapshot("websocket:old").messages == expected
assert not path.exists()
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
reopened = SessionManager(workspace)
assert reopened.read_session_snapshot("websocket:old").messages == expected
def test_invalid_source_rolls_back_entire_migration(tmp_path):
workspace = tmp_path / "workspace"
path = legacy(workspace)
original = path.read_bytes()
bad = path.parent / "zz-invalid.jsonl"
bad.write_text("not json")
with pytest.raises(RuntimeError, match="migration failed"):
SessionManager(workspace)
assert path.read_bytes() == original
bad.unlink()
manager = SessionManager(workspace)
assert len(manager.list_sessions()) == 1
assert not path.exists()
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
def test_migration_preserves_checkpoint_and_pending_inputs(tmp_path):
workspace = tmp_path / "workspace"
path = legacy(workspace)
checkpoint = {"version": 1, "session_key": "websocket:old", "base_message_count": 1,
"base_updated_at": "2026-01-01T00:00:00", "checkpoint": {"messages": [{"role": "assistant", "content": "partial"}]},
"provider_state": None}
checkpoint_path = path.with_suffix(".checkpoint.json")
checkpoint_path.write_text(json.dumps(checkpoint))
original, original_checkpoint = path.read_bytes(), checkpoint_path.read_bytes()
original_mtime, checkpoint_mtime = path.stat().st_mtime_ns, checkpoint_path.stat().st_mtime_ns
manager = SessionManager(workspace)
assert manager.get_or_create("websocket:old").metadata["runtime_checkpoint"] == checkpoint["checkpoint"]
backup = manager.sessions_dir / WORKSPACE_BACKUP_DIR
assert (backup / path.name).read_bytes() == original
assert (backup / checkpoint_path.name).read_bytes() == original_checkpoint
assert (backup / path.name).stat().st_mtime_ns == original_mtime
assert (backup / checkpoint_path.name).stat().st_mtime_ns == checkpoint_mtime
assert not path.exists() and not checkpoint_path.exists()
async def test_workspace_migration_isolates_raw_private_records(tmp_path):
from nanobot.agent.tools.filesystem import ReadFileTool
from nanobot.agent.tools.sessions import ReadSessionTool
from nanobot.providers.base import ProviderConversationState
workspace = tmp_path / "workspace"
path = legacy(workspace)
provider = ProviderConversationState(
kind="openai_responses", provider="openai", model="gpt-test", version=1,
payload={"items": [{"encrypted_content": "private-provider-state"}]},
)
with path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps({"_type": "provider_state", "state": provider.to_private_record()}) + "\n")
handle.write(json.dumps({"role": "tool", "tool_call_id": "call", "content": "private-tool-output"}) + "\n")
original = path.read_bytes()
manager = SessionManager(workspace)
backup = manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name
assert not path.exists()
assert backup.read_bytes() == original
if sys.platform != "win32":
assert backup.stat().st_mode & 0o777 == 0o600
assert backup.parent.stat().st_mode & 0o777 == 0o700
public = await ReadSessionTool(manager).execute(session_key="websocket:old")
assert "private-provider-state" not in public and "private-tool-output" not in public
tool = ReadFileTool(workspace=workspace, allowed_dir=workspace, restrict_to_workspace=True)
assert (await tool.execute(path=str(path))).is_error
blocked = await tool.execute(path=str(backup))
assert blocked.is_error and "outside allowed directory" in blocked
manager.delete_session("websocket:old")
assert SessionManager(workspace).read_session_snapshot("websocket:old") is None
assert backup.read_bytes() == original
def test_restart_finishes_workspace_isolation_after_import_commit(tmp_path, monkeypatch):
workspace = tmp_path / "workspace"
root = tmp_path / "root"
path = legacy(workspace)
original = path.read_bytes()
location = SessionLocation(workspace, sessions_root=root)
def interrupted(*_args):
raise RuntimeError("interrupted after import commit")
with monkeypatch.context() as patch:
patch.setattr(jsonl_migration, "finish_workspace_migration", interrupted)
with pytest.raises(RuntimeError, match="interrupted after import commit"):
SessionManager(workspace, sessions_root=root)
assert path.read_bytes() == original
with sqlite3.connect(location.sessions_dir / "sessions.sqlite3") as db:
assert db.execute("SELECT count(*) FROM sessions").fetchone()[0] == 1
assert db.execute("SELECT value FROM storage_meta WHERE key='jsonl_import'").fetchone()[0] == "complete"
manager = SessionManager(workspace, sessions_root=root)
assert len(manager.list_sessions()) == 1
assert not path.exists()
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
def test_workspace_backup_failure_retains_sources_and_retries(tmp_path, monkeypatch):
workspace = tmp_path / "workspace"
path = legacy(workspace)
original = path.read_bytes()
def failed_backup(*_args):
raise OSError("backup storage unavailable")
with monkeypatch.context() as patch:
patch.setattr(jsonl_migration, "_write_backup", failed_backup)
with pytest.raises(RuntimeError, match="Could not move legacy sessions"):
SessionManager(workspace)
assert path.read_bytes() == original
manager = SessionManager(workspace)
assert not path.exists()
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
def test_restart_finishes_partial_workspace_source_removal(tmp_path, monkeypatch):
workspace = tmp_path / "workspace"
path = legacy(workspace)
checkpoint_path = path.with_suffix(".checkpoint.json")
checkpoint_path.write_text(json.dumps({"version": 1}))
original, original_checkpoint = path.read_bytes(), checkpoint_path.read_bytes()
original_unlink = Path.unlink
def interrupted_unlink(target, *args, **kwargs):
if target == checkpoint_path:
raise OSError("interrupted checkpoint removal")
return original_unlink(target, *args, **kwargs)
with monkeypatch.context() as patch:
patch.setattr(Path, "unlink", interrupted_unlink)
with pytest.raises(RuntimeError, match="Could not move legacy sessions"):
SessionManager(workspace)
assert not path.exists()
assert checkpoint_path.read_bytes() == original_checkpoint
manager = SessionManager(workspace)
assert len(manager.list_sessions()) == 1
assert not checkpoint_path.exists()
backup = manager.sessions_dir / WORKSPACE_BACKUP_DIR
assert (backup / path.name).read_bytes() == original
assert (backup / checkpoint_path.name).read_bytes() == original_checkpoint
def test_restart_requires_durable_workspace_source_removal(tmp_path, monkeypatch):
workspace = tmp_path / "workspace"
path = legacy(workspace)
original = path.read_bytes()
original_sync = SessionLocation.fsync_directory
def unavailable_directory_sync(directory):
if directory == path.parent:
raise OSError("source directory flush unavailable")
original_sync(directory)
with monkeypatch.context() as patch:
patch.setattr(SessionLocation, "fsync_directory", staticmethod(unavailable_directory_sync))
for _ in range(2):
with pytest.raises(RuntimeError, match="Could not move legacy sessions"):
SessionManager(workspace)
assert not path.exists()
manager = SessionManager(workspace)
assert len(manager.list_sessions()) == 1
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
def test_stale_administrative_save_is_rejected(tmp_path):
manager = SessionManager(tmp_path)
session = Session(key="chat:a")
@@ -504,135 +277,6 @@ async def test_large_draft_copy_and_publication_run_on_owner_worker(tmp_path, mo
await state.aclose()
def test_duplicate_json_keys_abort_entire_migration(tmp_path):
workspace = tmp_path / "workspace"
path = legacy(workspace)
path.write_text(
'{"_type":"metadata","key":"chat:a","key":"chat:b",'
'"metadata":{},"created_at":"2026-01-01T00:00:00",'
'"updated_at":"2026-01-01T00:00:00"}\n',
encoding="utf-8",
)
with pytest.raises(RuntimeError, match="migration failed"):
SessionManager(workspace, sessions_root=tmp_path / "root")
database = next((tmp_path / "root").glob("*/sessions.sqlite3"))
with sqlite3.connect(database) as db:
tables = {
row[0]
for row in db.execute(
"SELECT name FROM sqlite_master WHERE type='table'"
)
}
assert "sessions" not in tables
assert "storage_meta" not in tables
def test_nested_duplicate_json_keys_abort_migration(tmp_path):
workspace = tmp_path / "workspace"
path = legacy(workspace)
path.write_text(
'{"_type":"metadata","key":"chat:a","metadata":{"title":"a","title":"b"},'
'"created_at":"2026-01-01T00:00:00",'
'"updated_at":"2026-01-01T00:00:00"}\n',
encoding="utf-8",
)
with pytest.raises(RuntimeError, match="migration failed"):
SessionManager(workspace, sessions_root=tmp_path / "root")
def test_second_provider_state_aborts_migration(tmp_path):
workspace = tmp_path / "workspace"
path = legacy(workspace)
state = {
"kind": "responses",
"provider": "openai",
"model": "gpt-test",
"version": 1,
"payload": {"secret": "opaque"},
"pending_messages": [],
}
with path.open("a", encoding="utf-8") as handle:
record = json.dumps({"_type": "provider_state", "state": state})
handle.write(record + "\n" + record + "\n")
with pytest.raises(RuntimeError, match="migration failed"):
SessionManager(workspace, sessions_root=tmp_path / "root")
@pytest.mark.parametrize("with_checkpoint", [False, True])
def test_identical_migration_copies_are_imported_once_and_cleaned_up(tmp_path, with_checkpoint):
workspace = tmp_path / "workspace"
root = tmp_path / "root"
source = legacy(workspace, key="chat:a")
sources = [source]
if with_checkpoint:
checkpoint = source.with_suffix(".checkpoint.json")
checkpoint.write_text(json.dumps({
"version": 1, "session_key": "chat:a", "base_message_count": 1,
"base_updated_at": "2026-01-01T00:00:00",
"checkpoint": {"messages": [{"role": "assistant", "content": "partial"}]},
}))
sources.append(checkpoint)
location = SessionLocation(workspace, sessions_root=root)
originals = {path.name: path.read_bytes() for path in sources}
for path in sources:
shutil.copy2(path, location.sessions_dir / path.name)
for _ in range(2):
manager = SessionManager(workspace, sessions_root=root)
assert len(manager.list_sessions()) == 1
session = manager.read_session_snapshot("chat:a")
assert [message["content"] for message in session.messages] == ["hello"]
if with_checkpoint:
assert session.metadata["runtime_checkpoint"]["messages"][0]["content"] == "partial"
for path in sources:
assert not path.exists()
assert (location.sessions_dir / path.name).read_bytes() == originals[path.name]
assert (location.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == originals[path.name]
def test_duplicate_sources_with_different_timestamps_abort_migration(tmp_path):
workspace = tmp_path / "workspace"
root = tmp_path / "root"
source = legacy(workspace, key="chat:a")
location = SessionLocation(workspace, sessions_root=root)
duplicate = location.sessions_dir / source.name
duplicate.write_text(
source.read_text(encoding="utf-8").replace(
'"updated_at": "2026-01-01T00:00:00"',
'"updated_at": "2026-01-02T00:00:00"',
),
encoding="utf-8",
)
with pytest.raises(RuntimeError, match="migration failed"):
SessionManager(workspace, sessions_root=root)
duplicate.unlink()
manager = SessionManager(workspace, sessions_root=root)
assert manager.read_session_snapshot("chat:a") is not None
def test_invalid_migration_marker_fails_closed(tmp_path):
workspace = tmp_path / "workspace"
root = tmp_path / "root"
manager = SessionManager(workspace, sessions_root=root)
with sqlite3.connect(manager._store.path) as db:
db.execute(
"UPDATE storage_meta SET value='corrupt' WHERE key='jsonl_import'"
)
legacy(workspace, key="chat:must-not-import")
with pytest.raises(RuntimeError, match="invalid JSONL migration marker"):
SessionManager(workspace, sessions_root=root)
with sqlite3.connect(manager._store.path) as db:
assert db.execute(
"SELECT count(*) FROM sessions WHERE key='chat:must-not-import'"
).fetchone()[0] == 0
async def test_missing_update_commands_do_not_create_sessions(tmp_path):
manager = SessionManager(tmp_path)
state = manager.state