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 -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