refactor(session): centralize state ownership in SQLite (#5943)
* fix(session): move persistence off event loop * refactor(session): isolate async persistence boundary * refactor(session): keep a single session manager * refactor(session): use stateless async adapters * fix(session): serialize local persistence without file-lock contention * refactor(session): own async persistence and snapshot commits * refactor(session): narrow persistence changes to async adapters * refactor(session): remove redundant async forwarding helpers * fix(command): offload compact session persistence * fix(session): adapt idle compaction to current main * fix(webui): offload session metadata persistence * refactor(session): centralize state ownership in SQLite * fix(session): skip storage for non-recoverable followups * test(webui): honor the full gateway event deadline * perf(session): persist incremental changes and reuse owner snapshots * test(agent): allow durable worker shutdown in burst test * fix(gateway): drain session storage on Windows console shutdown * fix(session): enforce bounded ownership and lifecycle-safe persistence * fix: reject unresolved home paths and stabilize platform tests * fix(session): preserve request context compatibility and owner-backed tests * docs: focus configuration guide on user-facing behavior * fix(session): adapt goal admission to async ownership after rebase * fix(session): integrate current gateway and subagent contracts * fix(session): align rebased workspace admission and async tests * fix(session): support compatible SQLite schema evolution * test(agent): use session owner in workspace context regressions * test: stabilize Windows lifecycle and browser checks * refactor(session): remove premature JSONL file export * ci: bound Windows full-suite worker concurrency * chore: remove session state refactor notes * fix(session): queue writes and retain worker connections * perf(webui): read detached metadata for session and task lists * perf(agent): bound prompt preparation and local token counting * docs: remove internal session storage guide * perf(session): skip archived transcripts during idle scans * fix(session): coordinate turns and isolate legacy session data Bind WebUI input generations to the execution session and serialize idle and SDK compaction with turns. Keep turn drafts through preparation so the latest channel route persists. Move imported workspace JSONL and checkpoints to durable private backups before gateway admission, resuming cleanup after interruptions. Remove committed child sessions when task creation is cancelled. Validation: focused Python and frontend regressions, Ruff, BasedPyright, import boundaries, WebUI build, and isolated gateway/browser flows. * fix(agent): keep cancellation hooks independent of prompt preparation * fix(session): preserve admission, delivery, and migration contracts * fix(agent): preserve cancellation settlement after rebase * fix(session): preserve request attribution through async ownership
This commit is contained in:
1 parent
33ff520d12
commit
8f6a5594fb
144 files changed
+8293
-4912
No files matched your search
@@ -0,0 +1,24 @@
|
||||
CREATE TABLE storage_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
CREATE TABLE sessions (
|
||||
key TEXT PRIMARY KEY, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
|
||||
metadata TEXT NOT NULL, provider_state TEXT, last_archived INTEGER NOT NULL,
|
||||
revision INTEGER NOT NULL, generation TEXT NOT NULL,
|
||||
title TEXT NOT NULL, preview TEXT NOT NULL, visible_updated_at TEXT
|
||||
);
|
||||
CREATE TABLE messages (
|
||||
session_key TEXT NOT NULL REFERENCES sessions(key) ON DELETE CASCADE,
|
||||
position INTEGER NOT NULL, record TEXT NOT NULL,
|
||||
PRIMARY KEY (session_key, position)
|
||||
);
|
||||
CREATE TABLE checkpoints (
|
||||
session_key TEXT PRIMARY KEY REFERENCES sessions(key) ON DELETE CASCADE,
|
||||
record TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE pending_inputs (
|
||||
session_key TEXT NOT NULL REFERENCES sessions(key) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL, position INTEGER NOT NULL, record TEXT NOT NULL,
|
||||
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;
|
||||
@@ -30,8 +30,8 @@ def test_loaded_corrupt_offset_keeps_messages(tmp_path: Path):
|
||||
}
|
||||
|
||||
for name, offset in offsets.items():
|
||||
manager = SessionManager(tmp_path / name)
|
||||
path = manager._get_session_path("chan:chat")
|
||||
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(
|
||||
@@ -47,7 +47,7 @@ def test_loaded_corrupt_offset_keeps_messages(tmp_path: Path):
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
session = manager.get_or_create("chan:chat")
|
||||
session = SessionManager(workspace).get_or_create("chan:chat")
|
||||
|
||||
assert session.messages == [message]
|
||||
assert session.last_consolidated == 0
|
||||
@@ -64,8 +64,7 @@ def test_valid_offset_is_preserved():
|
||||
|
||||
|
||||
def test_last_archived_field_migrates_with_legacy_alias(tmp_path: Path):
|
||||
manager = SessionManager(tmp_path)
|
||||
path = manager._get_session_path("chan:chat")
|
||||
path = tmp_path / "sessions" / "old.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
messages = [
|
||||
{"role": "user", "content": "first"},
|
||||
@@ -84,20 +83,18 @@ def test_last_archived_field_migrates_with_legacy_alias(tmp_path: Path):
|
||||
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)
|
||||
metadata = json.loads(path.read_text(encoding="utf-8").splitlines()[0])
|
||||
assert metadata["last_archived"] == 1
|
||||
assert metadata["last_consolidated"] == 1
|
||||
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."""
|
||||
manager = SessionManager(tmp_path)
|
||||
path = manager._get_session_path("chan:chat")
|
||||
path = tmp_path / "sessions" / "old.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
json.dumps({
|
||||
@@ -110,6 +107,7 @@ def test_loaded_null_metadata_becomes_empty_dict(tmp_path: Path):
|
||||
}) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("chan:chat")
|
||||
assert session.metadata == {}
|
||||
session.metadata["title"] = "ok"
|
||||
|
||||
@@ -177,13 +177,13 @@ async def test_scan_loads_only_sessions_that_need_webui_recovery(
|
||||
|
||||
coordinator, _, restarted = _coordinator(tmp_path)
|
||||
loaded: list[str] = []
|
||||
get_or_create = restarted.get_or_create
|
||||
get_or_create = restarted.state.get
|
||||
|
||||
def tracked_get_or_create(key: str) -> Session:
|
||||
async def tracked_get_or_create(key: str) -> Session:
|
||||
loaded.append(key)
|
||||
return get_or_create(key)
|
||||
return await get_or_create(key)
|
||||
|
||||
monkeypatch.setattr(restarted, "get_or_create", tracked_get_or_create)
|
||||
monkeypatch.setattr(restarted.state, "get", tracked_get_or_create)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.transcript.has_unfinished_transcript_tail",
|
||||
lambda _key: False,
|
||||
|
||||
@@ -0,0 +1,443 @@
|
||||
"""Admission, ordering, and shutdown at the asynchronous session boundary."""
|
||||
|
||||
import asyncio
|
||||
import sqlite3
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.state import SessionOperationQueueFullError, SessionState
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", ["cli", "telegram", "system"])
|
||||
async def test_non_websocket_followup_does_not_access_storage(tmp_path, monkeypatch, channel):
|
||||
manager = SessionManager(tmp_path)
|
||||
|
||||
def unexpected_transaction(*args, **kwargs):
|
||||
pytest.fail("a non-recoverable follow-up must not access session storage")
|
||||
|
||||
monkeypatch.setattr(manager._store, "transaction", unexpected_transaction)
|
||||
state = manager.state
|
||||
try:
|
||||
assert await state.queue_followup(
|
||||
f"{channel}:chat",
|
||||
InboundMessage(channel=channel, sender_id="u", chat_id="chat", content="follow-up"),
|
||||
) is None
|
||||
finally:
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_writes_run_in_submission_order(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
await state.get("chat:a")
|
||||
await asyncio.gather(*(state.update_metadata("chat:a", {"title": str(i)}) for i in range(50)))
|
||||
assert (await state.get("chat:a")).metadata["title"] == "49"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_close_drains_accepted_operations(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("chat:a")
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = manager._store.replace_metadata
|
||||
|
||||
def blocked(key, metadata, **kwargs):
|
||||
started.set()
|
||||
release.wait(5)
|
||||
return original(key, metadata, **kwargs)
|
||||
|
||||
monkeypatch.setattr(manager._store, "replace_metadata", blocked)
|
||||
task = asyncio.create_task(state.update_metadata("chat:a", {"title": "committed"}))
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
close = asyncio.create_task(state.aclose())
|
||||
await asyncio.sleep(0)
|
||||
assert not close.done()
|
||||
release.set()
|
||||
await asyncio.gather(task, close)
|
||||
assert manager.get_or_create("chat:a").metadata["title"] == "committed"
|
||||
with pytest.raises(RuntimeError, match="closed"):
|
||||
await state.update_metadata("chat:a", {"title": "late"})
|
||||
|
||||
|
||||
async def test_full_owner_rejects_without_creating_waiters(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = SessionState(manager._store, capacity=1, workers=1)
|
||||
await state.get("chat:a")
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = manager._store.replace_metadata
|
||||
|
||||
def blocked(key, metadata, **kwargs):
|
||||
started.set()
|
||||
release.wait(5)
|
||||
return original(key, metadata, **kwargs)
|
||||
|
||||
monkeypatch.setattr(manager._store, "replace_metadata", blocked)
|
||||
accepted = asyncio.create_task(state.update_metadata("chat:a", {"title": "accepted"}))
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
|
||||
with pytest.raises(SessionOperationQueueFullError, match="queue is full"):
|
||||
await state.update_metadata("chat:b", {"title": "rejected"})
|
||||
|
||||
release.set()
|
||||
await accepted
|
||||
assert await state.read("chat:b") is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_slow_session_does_not_block_unrelated_session(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = SessionState(manager._store, capacity=4, workers=2)
|
||||
await state.get("chat:a")
|
||||
await state.get("chat:b")
|
||||
await state.update_metadata("chat:b", {"title": "ready"})
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = manager._store.replace_metadata
|
||||
|
||||
def blocked(key, metadata, **kwargs):
|
||||
if key == "chat:a":
|
||||
started.set()
|
||||
release.wait(5)
|
||||
return original(key, metadata, **kwargs)
|
||||
|
||||
monkeypatch.setattr(manager._store, "replace_metadata", blocked)
|
||||
slow = asyncio.create_task(state.update_metadata("chat:a", {"title": "slow"}))
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
other = await asyncio.wait_for(state.read("chat:b"), timeout=0.25)
|
||||
assert other is not None and other.metadata["title"] == "ready"
|
||||
release.set()
|
||||
await slow
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_close_timeout_does_not_cancel_internal_drain(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("chat:a")
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = manager._store.replace_metadata
|
||||
|
||||
def blocked(key, metadata, **kwargs):
|
||||
started.set()
|
||||
release.wait(5)
|
||||
return original(key, metadata, **kwargs)
|
||||
|
||||
monkeypatch.setattr(manager._store, "replace_metadata", blocked)
|
||||
accepted = asyncio.create_task(state.update_metadata("chat:a", {"title": "committed"}))
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
with pytest.raises(TimeoutError):
|
||||
await asyncio.wait_for(state.aclose(), timeout=0.05)
|
||||
with pytest.raises(RuntimeError, match="closed"):
|
||||
await state.update_metadata("chat:b", {"title": "late"})
|
||||
release.set()
|
||||
await accepted
|
||||
await state.aclose()
|
||||
assert manager.get_or_create("chat:a").metadata["title"] == "committed"
|
||||
|
||||
|
||||
async def test_global_barrier_orders_both_sides_of_admission(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
started, release = threading.Event(), threading.Event()
|
||||
order = []
|
||||
|
||||
def first():
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
order.append("first")
|
||||
|
||||
first_task = asyncio.create_task(state._execute("chat:a", first))
|
||||
tasks = [first_task]
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
tasks.append(asyncio.create_task(state._execute(None, lambda: order.append("barrier"))))
|
||||
await asyncio.sleep(0)
|
||||
tasks.append(asyncio.create_task(state._execute("chat:b", lambda: order.append("later"))))
|
||||
await asyncio.sleep(0)
|
||||
assert state._admitted == 3
|
||||
assert order == []
|
||||
release.set()
|
||||
await asyncio.gather(*tasks)
|
||||
assert order == ["first", "barrier", "later"]
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_fork_waits_for_target_and_blocks_later_target_read(tmp_path, monkeypatch):
|
||||
state = SessionManager(tmp_path).state
|
||||
await state.import_messages("chat:source", [{"role": "user", "content": "kept"}])
|
||||
target_started, target_release = threading.Event(), threading.Event()
|
||||
fork_started, fork_release = threading.Event(), threading.Event()
|
||||
original_load = state._load
|
||||
|
||||
def paused_source(key, *, history=True):
|
||||
if key == "chat:source":
|
||||
fork_started.set()
|
||||
assert fork_release.wait(5)
|
||||
return original_load(key, history=history)
|
||||
|
||||
def target_operation():
|
||||
target_started.set()
|
||||
assert target_release.wait(5)
|
||||
|
||||
monkeypatch.setattr(state, "_load", paused_source)
|
||||
tasks = [asyncio.create_task(state._execute("chat:target", target_operation))]
|
||||
try:
|
||||
assert await asyncio.to_thread(target_started.wait, 2)
|
||||
fork = asyncio.create_task(state.fork("chat:source", "chat:target", 1))
|
||||
tasks.append(fork)
|
||||
await asyncio.sleep(0)
|
||||
read = asyncio.create_task(state.read("chat:target"))
|
||||
tasks.append(read)
|
||||
await asyncio.sleep(0)
|
||||
assert state._admitted == 3
|
||||
assert not fork_started.is_set()
|
||||
target_release.set()
|
||||
assert await asyncio.to_thread(fork_started.wait, 2)
|
||||
assert not read.done()
|
||||
fork_release.set()
|
||||
result = await fork
|
||||
snapshot = await read
|
||||
assert result is not None and snapshot is not None
|
||||
assert result.generation == snapshot.generation
|
||||
assert snapshot.messages[0]["content"] == "kept"
|
||||
finally:
|
||||
target_release.set()
|
||||
fork_release.set()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_failed_predecessor_does_not_poison_key_or_global_barrier(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
order = []
|
||||
|
||||
def fail():
|
||||
raise ValueError("injected")
|
||||
|
||||
failed = asyncio.create_task(state._execute("chat:a", fail))
|
||||
same_key = asyncio.create_task(state._execute("chat:a", lambda: order.append("same")))
|
||||
barrier = asyncio.create_task(state._execute(None, lambda: order.append("barrier")))
|
||||
results = await asyncio.gather(failed, same_key, barrier, return_exceptions=True)
|
||||
assert isinstance(results[0], ValueError)
|
||||
assert results[1:] == [None, None]
|
||||
assert order == ["same", "barrier"]
|
||||
assert state._admitted == 0
|
||||
assert state._key_tails == {}
|
||||
assert state._global_tail is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_cancel_before_coroutine_starts_submits_no_command(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
task = asyncio.create_task(state.get("chat:unaccepted"))
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert state._admitted == 0
|
||||
assert await state.read("chat:unaccepted") is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_followup_can_initialize_first_turn_but_cannot_revive_deleted_session(tmp_path):
|
||||
from nanobot.session.recovery import pending_followups
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
state = SessionManager(tmp_path).state
|
||||
message = InboundMessage(channel="websocket", sender_id="u", chat_id="a", content="second")
|
||||
assert await state.queue_followup("websocket:a", message)
|
||||
session = await state.get("websocket:a")
|
||||
assert [item.content for item in pending_followups(session)] == ["second"]
|
||||
await state.delete(session.key)
|
||||
with pytest.raises(SessionConflictError, match="existing session"):
|
||||
await state.queue_followup(session.key, message)
|
||||
assert await state.read(session.key) is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_followup_rejects_discarded_or_replaced_generation(tmp_path):
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
state = SessionManager(tmp_path).state
|
||||
session = await state.register_transient("websocket:private")
|
||||
message = InboundMessage(
|
||||
channel="websocket", sender_id="u", chat_id="private", content="private",
|
||||
require_existing_session=True, session_generation=session.generation,
|
||||
)
|
||||
await state.discard(session.key)
|
||||
with pytest.raises(SessionConflictError, match="existing session"):
|
||||
await state.queue_followup(session.key, message)
|
||||
replacement = await state.register_transient(session.key)
|
||||
with pytest.raises(SessionConflictError, match="replaced session"):
|
||||
await state.queue_followup(session.key, message)
|
||||
assert (await state.get(replacement.key)).metadata == {}
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_display_metadata_reads_committed_snapshot_during_write(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("websocket:busy")
|
||||
await state.update_metadata("websocket:busy", {"title": "committed"})
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = manager._store.replace_metadata
|
||||
|
||||
def blocked(key, metadata, **kwargs):
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return original(key, metadata, **kwargs)
|
||||
|
||||
monkeypatch.setattr(manager._store, "replace_metadata", blocked)
|
||||
write = asyncio.create_task(state.update_metadata("websocket:busy", {"title": "next"}))
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
rows = await asyncio.wait_for(state.list_metadata(), timeout=0.5)
|
||||
assert rows[0]["metadata"]["title"] == "committed"
|
||||
rows[0]["metadata"]["title"] = "local edit"
|
||||
finally:
|
||||
release.set()
|
||||
await write
|
||||
assert (await state.list_metadata())[0]["metadata"]["title"] == "next"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_cached_header_preserves_policy_and_offsets_without_history(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
await state.import_messages("chat:header", [
|
||||
{"role": "user", "content": "input"}, {"role": "assistant", "content": "answer"},
|
||||
])
|
||||
draft = await state.get("chat:header")
|
||||
draft.last_archived = 1
|
||||
draft.metadata["nested"] = {"value": "committed"}
|
||||
await state.prepare_input(draft)
|
||||
header = state.peek_header("chat:header")
|
||||
assert header is not None
|
||||
assert header.messages == []
|
||||
assert header.last_archived == 1
|
||||
assert header.generation == draft.generation
|
||||
assert header.policy == draft.policy
|
||||
header.metadata["nested"]["value"] = "local edit"
|
||||
assert state.peek_metadata("chat:header")["nested"]["value"] == "committed"
|
||||
assert len(state.peek("chat:header").messages) == 2
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_missing_get_keeps_creation_before_a_later_delete(tmp_path, monkeypatch):
|
||||
state = SessionManager(tmp_path).state
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = state._load
|
||||
first = True
|
||||
|
||||
def paused_read(key, *, history=True):
|
||||
nonlocal first
|
||||
if first:
|
||||
first = False
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return original(key, history=history)
|
||||
|
||||
monkeypatch.setattr(state, "_load", paused_read)
|
||||
get = asyncio.create_task(state.get("chat:new"))
|
||||
tasks = [get]
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
deleted = asyncio.create_task(state.delete("chat:new"))
|
||||
tasks.append(deleted)
|
||||
await asyncio.sleep(0)
|
||||
assert not deleted.done()
|
||||
release.set()
|
||||
assert (await get).persisted
|
||||
assert await deleted
|
||||
assert await state.read("chat:new") is None
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_metadata_peek_and_header_do_not_expose_history_or_shared_metadata(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
try:
|
||||
assert state.peek_metadata("chat:missing") is None
|
||||
empty = await state.get_header("chat:empty")
|
||||
assert empty.messages == [] and empty.persisted
|
||||
assert state.peek_metadata(empty.key) == {}
|
||||
assert empty._baseline is None
|
||||
await state.import_messages("chat:history", [{"role": "user", "content": "retained"}])
|
||||
await state.update_metadata("chat:history", {"custom": {"values": ["saved"]}})
|
||||
await state.commit_summary(await state.get("chat:history"), "Saved context", archive_end=1)
|
||||
header = await state.get_header("chat:history")
|
||||
assert header.messages == [] and header._baseline is None
|
||||
assert header.last_archived > 0
|
||||
header.metadata["custom"]["values"].append("header edit")
|
||||
metadata = state.peek_metadata("chat:history")
|
||||
metadata["custom"]["values"].append("peek edit")
|
||||
loaded = await state.get("chat:history")
|
||||
assert loaded.generation == header.generation
|
||||
assert loaded.last_archived == header.last_archived
|
||||
assert loaded.messages[0]["content"] == "retained"
|
||||
assert loaded.metadata["custom"]["values"] == ["saved"]
|
||||
await state.register_transient("chat:private")
|
||||
assert state.peek_metadata("chat:private") == {}
|
||||
await state.update_metadata("chat:private", {"custom": {"values": ["private"]}})
|
||||
private = state.peek_metadata("chat:private")
|
||||
private["custom"]["values"].append("peek edit")
|
||||
assert state.peek_metadata("chat:private")["custom"]["values"] == ["private"]
|
||||
finally:
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_connection_open_failure_does_not_poison_the_owner(tmp_path, monkeypatch):
|
||||
state = SessionManager(tmp_path).state
|
||||
connect = sqlite3.connect
|
||||
first = True
|
||||
|
||||
def fail_first(*args, **kwargs):
|
||||
nonlocal first
|
||||
if first:
|
||||
first = False
|
||||
raise sqlite3.OperationalError("database is locked")
|
||||
return connect(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(sqlite3, "connect", fail_first)
|
||||
try:
|
||||
with pytest.raises(sqlite3.OperationalError, match="database is locked"):
|
||||
await state.get("chat:retry")
|
||||
assert state._admitted == 0
|
||||
draft = await state.get("chat:retry")
|
||||
draft.add_message("user", "accepted after lock was released")
|
||||
await state.prepare_input(draft)
|
||||
assert (await state.get(draft.key)).messages[-1]["content"] == "accepted after lock was released"
|
||||
finally:
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_history_peek_does_not_hold_the_metadata_control_lock(tmp_path, monkeypatch):
|
||||
import nanobot.session.state as owner
|
||||
from nanobot.session.manager import Session
|
||||
|
||||
state = SessionManager(tmp_path).state
|
||||
await state.import_messages("chat:child", [{"role": "user", "content": "history"}])
|
||||
await state.update_metadata("chat:child", {"title": "committed"})
|
||||
started, release = threading.Event(), threading.Event()
|
||||
deepcopy = owner.deepcopy
|
||||
|
||||
def paused_copy(value):
|
||||
if isinstance(value, Session):
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return deepcopy(value)
|
||||
|
||||
monkeypatch.setattr(owner, "deepcopy", paused_copy)
|
||||
history = asyncio.create_task(asyncio.to_thread(state.peek, "chat:child"))
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
assert state.peek_metadata("chat:child")["title"] == "committed"
|
||||
assert not history.done()
|
||||
finally:
|
||||
release.set()
|
||||
await history
|
||||
await state.aclose()
|
||||
@@ -1,89 +1,46 @@
|
||||
import gc
|
||||
import weakref
|
||||
"""Detached views and transient session lifetime."""
|
||||
|
||||
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, SessionManager
|
||||
import pytest
|
||||
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
|
||||
def _bounded_manager(tmp_path, limit: int) -> SessionManager:
|
||||
async def test_committed_view_cache_is_bounded(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
for i in range(140):
|
||||
await state.get(str(i))
|
||||
await state.update_metadata(str(i), {"title": str(i)})
|
||||
assert len(state._snapshots) <= 128
|
||||
assert state.peek("0") is None
|
||||
assert (await state.get("0")).metadata["title"] == "0"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_cached_views_are_detached(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
await state.get("chat:a")
|
||||
await state.update_metadata("chat:a", {"title": "saved"})
|
||||
cached = state.peek("chat:a")
|
||||
cached.metadata["title"] = "unsaved"
|
||||
assert state.peek("chat:a").metadata["title"] == "saved"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_transient_session_never_reaches_storage(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
manager._max_cached_sessions = limit
|
||||
return manager
|
||||
|
||||
|
||||
def test_default_session_cache_is_bounded(tmp_path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
|
||||
for index in range(SESSION_CACHE_MAX_SIZE + 1):
|
||||
manager.get_or_create(f"test:{index}")
|
||||
|
||||
assert len(manager._cache) == SESSION_CACHE_MAX_SIZE
|
||||
|
||||
|
||||
def test_session_cache_releases_inactive_lru_entries(tmp_path) -> None:
|
||||
manager = _bounded_manager(tmp_path, 1)
|
||||
first = manager.get_or_create("test:first")
|
||||
first.add_message("user", "persist me")
|
||||
manager.save(first)
|
||||
first_ref = weakref.ref(first)
|
||||
|
||||
second = manager.get_or_create("test:second")
|
||||
manager.save(second)
|
||||
del first
|
||||
gc.collect()
|
||||
|
||||
assert len(manager._cache) == 1
|
||||
assert first_ref() is None
|
||||
assert manager.get_or_create("test:first").messages[0]["content"] == "persist me"
|
||||
|
||||
|
||||
def test_session_cache_keeps_identity_for_evicted_active_sessions(tmp_path) -> None:
|
||||
manager = _bounded_manager(tmp_path, 1)
|
||||
active = manager.get_or_create("test:active")
|
||||
manager.save(active)
|
||||
|
||||
manager.save(manager.get_or_create("test:other"))
|
||||
|
||||
assert manager.get_or_create("test:active") is active
|
||||
|
||||
|
||||
def test_session_cache_refreshes_lru_order_on_access(tmp_path) -> None:
|
||||
manager = _bounded_manager(tmp_path, 2)
|
||||
manager.save(manager.get_or_create("test:first"))
|
||||
manager.save(manager.get_or_create("test:second"))
|
||||
|
||||
manager.get_or_create("test:first")
|
||||
manager.save(manager.get_or_create("test:third"))
|
||||
|
||||
assert list(manager._cache) == ["test:first", "test:third"]
|
||||
|
||||
|
||||
def test_flush_all_includes_live_sessions_outside_strong_cache(tmp_path, monkeypatch) -> None:
|
||||
manager = _bounded_manager(tmp_path, 1)
|
||||
active = manager.get_or_create("test:active")
|
||||
manager.save(active)
|
||||
manager.save(manager.get_or_create("test:other"))
|
||||
saved: list[tuple[str, bool]] = []
|
||||
original_save = manager.save
|
||||
|
||||
def recording_save(session, *, fsync=False):
|
||||
saved.append((session.key, fsync))
|
||||
original_save(session, fsync=fsync)
|
||||
|
||||
monkeypatch.setattr(manager, "save", recording_save)
|
||||
|
||||
assert manager.flush_all() == 2
|
||||
assert set(saved) == {("test:active", True), ("test:other", True)}
|
||||
|
||||
|
||||
def test_transient_session_never_reaches_storage(tmp_path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create_transient("websocket:temporary-test")
|
||||
session.add_message("user", "secret")
|
||||
|
||||
manager.save(session, fsync=True)
|
||||
|
||||
assert manager.get_cached(session.key) is session
|
||||
assert manager.read_session_file(session.key) is None
|
||||
assert list(manager.sessions_dir.glob("*.jsonl")) == []
|
||||
manager.invalidate(session.key)
|
||||
assert manager.get_cached(session.key) is None
|
||||
state = manager.state
|
||||
draft = await state.register_transient(
|
||||
"temporary:a", disabled_tools=frozenset({"create_goal"})
|
||||
)
|
||||
draft.add_message("user", "private")
|
||||
await state.prepare_input(draft)
|
||||
draft.add_message("assistant", "answer")
|
||||
await state.finish_turn(draft)
|
||||
assert len((await state.get(draft.key)).messages) == 2
|
||||
assert manager.read_session_snapshot(draft.key) is None
|
||||
assert manager.list_sessions() == []
|
||||
state.forget_transient(draft.key)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.finish_turn(draft)
|
||||
await state.aclose()
|
||||
@@ -1,198 +1,12 @@
|
||||
"""Tests for session fsync and flush_all on graceful shutdown."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import call, patch
|
||||
|
||||
import pytest
|
||||
"""Durability configuration is applied to every SQLite connection."""
|
||||
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
_IS_WINDOWS = sys.platform == "win32"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sessions_dir(tmp_path: Path) -> Path:
|
||||
d = tmp_path / "sessions"
|
||||
d.mkdir()
|
||||
return tmp_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manager(sessions_dir: Path) -> SessionManager:
|
||||
return SessionManager(workspace=sessions_dir)
|
||||
|
||||
|
||||
class TestSaveFsync:
|
||||
"""Verify that save(fsync=True) calls os.fsync."""
|
||||
|
||||
def test_save_without_fsync_does_not_call_fsync(self, manager: SessionManager):
|
||||
session = manager.get_or_create("test:no-fsync")
|
||||
session.add_message("user", "hello")
|
||||
|
||||
with patch("os.fsync") as mock_fsync:
|
||||
manager.save(session, fsync=False)
|
||||
mock_fsync.assert_not_called()
|
||||
|
||||
def test_save_with_fsync_calls_fsync(self, manager: SessionManager):
|
||||
session = manager.get_or_create("test:with-fsync")
|
||||
session.add_message("user", "hello")
|
||||
|
||||
with patch("os.fsync") as mock_fsync:
|
||||
manager.save(session, fsync=True)
|
||||
# File fsync always runs; directory fsync only on non-Windows.
|
||||
expected = 1 if _IS_WINDOWS else 2
|
||||
assert mock_fsync.call_count == expected
|
||||
|
||||
def test_save_default_no_fsync(self, manager: SessionManager):
|
||||
"""Default save() should not fsync (backward compat)."""
|
||||
session = manager.get_or_create("test:default")
|
||||
session.add_message("user", "hello")
|
||||
|
||||
with patch("os.fsync") as mock_fsync:
|
||||
manager.save(session)
|
||||
mock_fsync.assert_not_called()
|
||||
|
||||
def test_save_ignores_unsupported_directory_fsync(
|
||||
self, manager: SessionManager
|
||||
) -> None:
|
||||
"""Shared filesystems may open directories but reject directory fsync."""
|
||||
session = manager.get_or_create("test:unsupported-directory-fsync")
|
||||
session.add_message("user", "hello")
|
||||
directory_fd = 987654
|
||||
with (
|
||||
manager.locked_session_files(),
|
||||
patch("nanobot.utils.helpers.os.open", return_value=directory_fd) as open_dir,
|
||||
patch(
|
||||
"nanobot.utils.helpers.os.fsync",
|
||||
side_effect=[None, OSError(errno.EINVAL, "Invalid argument")],
|
||||
),
|
||||
patch("nanobot.utils.helpers.os.close") as close_dir,
|
||||
):
|
||||
manager.save(session, fsync=True)
|
||||
|
||||
assert manager._get_session_path(session.key).exists()
|
||||
open_dir.assert_called_once_with(str(manager.sessions_dir), os.O_RDONLY)
|
||||
assert close_dir.call_args_list.count(call(directory_fd)) == 1
|
||||
|
||||
def test_save_propagates_other_directory_fsync_errors(
|
||||
self, manager: SessionManager
|
||||
) -> None:
|
||||
"""Only EINVAL is an expected unsupported-directory-fsync result."""
|
||||
session = manager.get_or_create("test:directory-fsync-io-error")
|
||||
directory_fd = 987654
|
||||
with (
|
||||
manager.locked_session_files(),
|
||||
patch("nanobot.utils.helpers.os.open", return_value=directory_fd),
|
||||
patch(
|
||||
"nanobot.utils.helpers.os.fsync",
|
||||
side_effect=[None, OSError(errno.EIO, "I/O error")],
|
||||
),
|
||||
patch("nanobot.utils.helpers.os.close") as close_dir,
|
||||
pytest.raises(OSError, match="I/O error"),
|
||||
):
|
||||
manager.save(session, fsync=True)
|
||||
|
||||
assert close_dir.call_args_list.count(call(directory_fd)) == 1
|
||||
|
||||
|
||||
class TestFlushAll:
|
||||
"""Verify flush_all re-saves all cached sessions with fsync."""
|
||||
|
||||
def test_flush_all_empty_cache(self, manager: SessionManager):
|
||||
assert manager.flush_all() == 0
|
||||
|
||||
def test_flush_all_saves_cached_sessions(self, manager: SessionManager):
|
||||
s1 = manager.get_or_create("test:session-1")
|
||||
s1.add_message("user", "msg 1")
|
||||
manager.save(s1)
|
||||
|
||||
s2 = manager.get_or_create("test:session-2")
|
||||
s2.add_message("user", "msg 2")
|
||||
manager.save(s2)
|
||||
|
||||
flushed = manager.flush_all()
|
||||
assert flushed == 2
|
||||
|
||||
def test_flush_all_uses_fsync(self, manager: SessionManager):
|
||||
session = manager.get_or_create("test:fsync-check")
|
||||
session.add_message("user", "important")
|
||||
manager.save(session)
|
||||
|
||||
with patch("os.fsync") as mock_fsync:
|
||||
manager.flush_all()
|
||||
# file fsync always; directory fsync only on non-Windows
|
||||
expected = 1 if _IS_WINDOWS else 2
|
||||
assert mock_fsync.call_count == expected
|
||||
|
||||
def test_flush_all_continues_on_error(self, manager: SessionManager):
|
||||
"""One broken session should not prevent others from flushing."""
|
||||
s1 = manager.get_or_create("test:good")
|
||||
s1.add_message("user", "ok")
|
||||
manager.save(s1)
|
||||
|
||||
s2 = manager.get_or_create("test:bad")
|
||||
s2.add_message("user", "ok")
|
||||
manager.save(s2)
|
||||
|
||||
original_save = manager.save
|
||||
call_count = {"n": 0}
|
||||
|
||||
def patched_save(session, *, fsync=False):
|
||||
call_count["n"] += 1
|
||||
if session.key == "test:bad":
|
||||
raise OSError("disk on fire")
|
||||
original_save(session, fsync=fsync)
|
||||
|
||||
manager.save = patched_save
|
||||
flushed = manager.flush_all()
|
||||
|
||||
# One succeeded, one failed — flush_all returns successful count
|
||||
assert flushed == 1
|
||||
assert call_count["n"] == 2
|
||||
|
||||
def test_flush_all_data_survives_reload(self, sessions_dir: Path):
|
||||
"""Data flushed by flush_all should survive a fresh SessionManager load."""
|
||||
mgr1 = SessionManager(workspace=sessions_dir)
|
||||
session = mgr1.get_or_create("test:persist")
|
||||
session.add_message("user", "remember this")
|
||||
session.add_message("assistant", "noted")
|
||||
mgr1.save(session)
|
||||
mgr1.flush_all()
|
||||
|
||||
# Simulate process restart — new manager, cold cache
|
||||
mgr2 = SessionManager(workspace=sessions_dir)
|
||||
reloaded = mgr2.get_or_create("test:persist")
|
||||
history = reloaded.get_history(max_messages=100)
|
||||
|
||||
assert len(history) == 2
|
||||
assert history[0]["content"] == "remember this"
|
||||
assert history[1]["content"] == "noted"
|
||||
|
||||
|
||||
class TestLoadErrors:
|
||||
@pytest.mark.parametrize(
|
||||
"operation",
|
||||
("get_or_create", "read_session_file", "read_session_metadata", "list_sessions"),
|
||||
)
|
||||
def test_permission_error_is_not_treated_as_corrupt_data(
|
||||
self,
|
||||
sessions_dir: Path,
|
||||
operation: str,
|
||||
) -> None:
|
||||
writer = SessionManager(workspace=sessions_dir)
|
||||
session = writer.get_or_create("test:permission")
|
||||
session.add_message("user", "must not disappear")
|
||||
writer.save(session)
|
||||
|
||||
reader = SessionManager(workspace=sessions_dir)
|
||||
with patch("builtins.open", side_effect=PermissionError("access denied")):
|
||||
with pytest.raises(PermissionError, match="access denied"):
|
||||
if operation == "list_sessions":
|
||||
reader.list_sessions()
|
||||
else:
|
||||
getattr(reader, operation)("test:permission")
|
||||
def test_every_transaction_uses_full_synchronous_and_foreign_keys(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
for _ in range(2):
|
||||
with manager._store.transaction() as db:
|
||||
assert db.execute("PRAGMA synchronous").fetchone()[0] == 2
|
||||
assert db.execute("PRAGMA foreign_keys").fetchone()[0] == 1
|
||||
assert db.execute("PRAGMA journal_mode").fetchone()[0] == "wal"
|
||||
@@ -1,7 +1,9 @@
|
||||
import asyncio
|
||||
import sqlite3
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from concurrent.futures import TimeoutError as FutureTimeout
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from threading import Event, Thread
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -138,7 +140,7 @@ def test_session_snapshot_and_handle_sync_share_one_lock(
|
||||
resolver.list_all()
|
||||
snapshot_taken = Event()
|
||||
release_snapshot = Event()
|
||||
original_list = manager.list_sessions
|
||||
original_list = manager._store.list_metadata
|
||||
|
||||
def paused_list():
|
||||
rows = original_list()
|
||||
@@ -146,7 +148,7 @@ def test_session_snapshot_and_handle_sync_share_one_lock(
|
||||
assert release_snapshot.wait(timeout=2)
|
||||
return rows
|
||||
|
||||
monkeypatch.setattr(manager, "list_sessions", paused_list)
|
||||
monkeypatch.setattr(manager._store, "list_metadata", paused_list)
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
old_sync = pool.submit(resolver.list_all)
|
||||
assert snapshot_taken.wait(timeout=2)
|
||||
@@ -219,3 +221,27 @@ def test_private_type_cannot_be_resolved_through_an_existing_handle(tmp_path: Pa
|
||||
|
||||
reopened = SessionManager(tmp_path)
|
||||
assert SessionHandleResolver(reopened).list_all() == []
|
||||
|
||||
|
||||
async def test_runtime_existing_handles_do_not_wait_for_an_external_write_lock(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("websocket:existing")
|
||||
expected = await state.ensure_session_handles()
|
||||
ready, release = Event(), Event()
|
||||
|
||||
def hold():
|
||||
with sqlite3.connect(manager._store.path) as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
ready.set()
|
||||
assert release.wait(5)
|
||||
|
||||
thread = Thread(target=hold)
|
||||
thread.start()
|
||||
try:
|
||||
assert await asyncio.to_thread(ready.wait, 2)
|
||||
assert await asyncio.wait_for(state.ensure_session_handles(), timeout=2) == expected
|
||||
finally:
|
||||
release.set()
|
||||
thread.join()
|
||||
await state.aclose()
|
||||
@@ -0,0 +1,216 @@
|
||||
"""Incremental storage must preserve snapshot isolation and cross-process conflicts."""
|
||||
|
||||
import asyncio
|
||||
import sqlite3
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
|
||||
async def test_append_does_not_resubmit_committed_rows(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.import_messages("chat:a", [
|
||||
{"role": "user", "content": str(i)} for i in range(100)
|
||||
])
|
||||
with sqlite3.connect(manager._store.path) as db:
|
||||
db.execute("""CREATE TRIGGER reject_prefix BEFORE INSERT ON messages
|
||||
WHEN NEW.position < 100 BEGIN SELECT RAISE(ABORT, 'prefix'); END""")
|
||||
draft.add_message("user", "new input")
|
||||
await state.prepare_input(draft)
|
||||
draft.add_message("assistant", "new answer")
|
||||
await state.finish_turn(draft)
|
||||
stored = manager.read_session_snapshot(draft.key)
|
||||
assert [m["content"] for m in stored.messages] == [str(i) for i in range(100)] + ["new input", "new answer"]
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_metadata_checkpoint_and_followups_do_not_read_history(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.import_messages("websocket:a", [
|
||||
{"role": "user", "content": str(i)} for i in range(100)
|
||||
])
|
||||
|
||||
def deny_history(action, table, *_args):
|
||||
return sqlite3.SQLITE_DENY if action == sqlite3.SQLITE_READ and table == "messages" else sqlite3.SQLITE_OK
|
||||
|
||||
def protect():
|
||||
with manager._store.transaction() as db:
|
||||
db.set_authorizer(deny_history)
|
||||
|
||||
await state._execute(draft.key, protect)
|
||||
await state.update_metadata(draft.key, {"title": "new"})
|
||||
await state.checkpoint_view(draft, {"step": 1})
|
||||
before_followup = manager.read_session_snapshot(draft.key).updated_at
|
||||
identifier = await state.queue_followup(draft.key, InboundMessage(
|
||||
channel="websocket", sender_id="u", chat_id="a", content="follow-up",
|
||||
))
|
||||
assert identifier
|
||||
assert manager.read_session_snapshot(draft.key).updated_at > before_followup
|
||||
await state.acknowledge_followups(draft.key, [identifier])
|
||||
await state.aclose()
|
||||
stored = manager.read_session_snapshot(draft.key)
|
||||
assert len(stored.messages) == 100
|
||||
assert stored.metadata["title"] == "new"
|
||||
assert stored.metadata["runtime_checkpoint"] == {"step": 1}
|
||||
assert not stored.metadata.get("pending_user_followups")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("transient", [False, True])
|
||||
async def test_nested_draft_edits_and_failed_commits_remain_private(tmp_path, transient):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = (
|
||||
await state.register_transient("chat:a")
|
||||
if transient
|
||||
else await state.get("chat:a")
|
||||
)
|
||||
draft.messages.append({"role": "user", "content": [{"type": "text", "text": "original"}]})
|
||||
await state.prepare_input(draft)
|
||||
peer = await state.get(draft.key)
|
||||
draft.messages[0]["content"][0]["text"] = "edited"
|
||||
assert state.peek(draft.key).messages[0]["content"][0]["text"] == "original"
|
||||
await state.finish_turn(draft)
|
||||
# Previously issued drafts still represent their old revision.
|
||||
assert peer.messages[0]["content"][0]["text"] == "original"
|
||||
peer.add_message("assistant", "stale append")
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.finish_turn(peer)
|
||||
draft.messages[0]["content"][0]["text"] = "unsaved after commit"
|
||||
assert (await state.get(draft.key)).messages[0]["content"][0]["text"] == "edited"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_import_and_fork_returns_do_not_alias_committed_records(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
source = await state.import_messages("chat:a", [
|
||||
{"role": "user", "content": [{"type": "text", "text": "original"}]},
|
||||
{"role": "user", "content": "next"},
|
||||
])
|
||||
fork = await state.fork(source.key, "chat:b", 1)
|
||||
source.messages[0]["content"][0]["text"] = "import edit"
|
||||
fork.messages[0]["content"][0]["text"] = "fork edit"
|
||||
for key in (source.key, fork.key):
|
||||
assert (await state.get(key)).messages[0]["content"][0]["text"] == "original"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_external_append_merges_and_external_edit_conflicts(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.import_messages("chat:a", [{"role": "user", "content": "first"}])
|
||||
other = SessionManager(tmp_path)
|
||||
external = other.get_or_create(draft.key)
|
||||
external.add_message("assistant", "external")
|
||||
other.save(external)
|
||||
draft.add_message("assistant", "local")
|
||||
await state.finish_turn(draft)
|
||||
assert [m["content"] for m in draft.messages] == ["first", "external", "local"]
|
||||
external = other.get_or_create(draft.key)
|
||||
external.messages[0]["content"] = "replaced"
|
||||
other.save(external)
|
||||
# A metadata-only command must not revalidate stale cached history accidentally.
|
||||
await state.update_metadata(draft.key, {"title": "new"})
|
||||
draft.add_message("assistant", "stale")
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.finish_turn(draft)
|
||||
assert (await state.get(draft.key)).messages[0]["content"] == "replaced"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_rejected_write_does_not_change_cached_snapshot(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.import_messages("chat:a", [{"role": "user", "content": "first"}])
|
||||
with sqlite3.connect(manager._store.path) as db:
|
||||
db.execute("""CREATE TRIGGER reject_append BEFORE INSERT ON messages
|
||||
WHEN NEW.position > 0 BEGIN SELECT RAISE(ABORT, 'injected'); END""")
|
||||
draft.add_message("assistant", "rejected")
|
||||
draft.metadata["title"] = "rejected"
|
||||
with pytest.raises(sqlite3.IntegrityError, match="injected"):
|
||||
await state.finish_turn(draft)
|
||||
cached = state.peek(draft.key)
|
||||
assert len(cached.messages) == 1
|
||||
assert "title" not in cached.metadata
|
||||
assert manager.read_session_snapshot(draft.key).messages == cached.messages
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_truncation_and_summary_keep_storage_and_cache_in_sync(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.import_messages("chat:a", [
|
||||
{"role": "user", "content": str(i)} for i in range(5)
|
||||
])
|
||||
draft.messages = draft.messages[:3]
|
||||
await state.finish_turn(draft)
|
||||
await state.commit_summary(draft, "summary", archive_end=2)
|
||||
current = await state.get(draft.key)
|
||||
await state.update_metadata(draft.key, {"title": "after summary"})
|
||||
stored = manager.read_session_snapshot(draft.key)
|
||||
assert len(stored.messages) == 4
|
||||
assert stored.last_archived == current.last_archived == 2
|
||||
assert stored.messages == current.messages == state.peek(draft.key).messages
|
||||
await state.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("transient", [False, True])
|
||||
async def test_metadata_callback_result_is_detached(tmp_path, transient):
|
||||
state = SessionManager(tmp_path).state
|
||||
if transient:
|
||||
await state.register_transient("chat:a")
|
||||
else:
|
||||
await state.get("chat:a")
|
||||
shared = {"nested": ["saved"]}
|
||||
|
||||
def change(metadata):
|
||||
metadata["custom"] = shared
|
||||
return shared
|
||||
|
||||
result, metadata = await state.mutate_metadata("chat:a", change)
|
||||
result["nested"].append("result mutation")
|
||||
metadata["custom"]["nested"].append("metadata mutation")
|
||||
shared["nested"].append("callback mutation")
|
||||
assert state.peek("chat:a").metadata["custom"] == {"nested": ["saved"]}
|
||||
assert (await state.get("chat:a")).metadata["custom"] == {"nested": ["saved"]}
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_owner_reuses_worker_connections_and_closes_them_after_drain(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
connections = []
|
||||
closed = []
|
||||
original_connect = sqlite3.connect
|
||||
|
||||
class TrackedConnection(sqlite3.Connection):
|
||||
def execute(self, *args, **kwargs):
|
||||
assert threading.get_ident() == self.owner_thread
|
||||
return super().execute(*args, **kwargs)
|
||||
|
||||
def close(self):
|
||||
closed.append((id(self), threading.get_ident()))
|
||||
return super().close()
|
||||
|
||||
def connect(*args, **kwargs):
|
||||
connection = original_connect(*args, **kwargs, factory=TrackedConnection)
|
||||
connection.owner_thread = threading.get_ident()
|
||||
connections.append((id(connection), threading.get_ident()))
|
||||
return connection
|
||||
|
||||
monkeypatch.setattr(sqlite3, "connect", connect)
|
||||
state = manager.state
|
||||
await state.get("chat:a")
|
||||
await state.update_metadata("chat:a", {"title": "new"})
|
||||
await state.get("chat:a")
|
||||
assert len(connections) == 2
|
||||
assert all(thread_id != threading.get_ident() for _, thread_id in connections)
|
||||
assert closed == []
|
||||
await asyncio.gather(state.aclose(), state.aclose())
|
||||
assert {identifier for identifier, _ in closed} == {identifier for identifier, _ in connections}
|
||||
assert len(closed) == len(connections)
|
||||
assert all(thread_id != threading.get_ident() for _, thread_id in closed)
|
||||
@@ -1,66 +1,11 @@
|
||||
"""Tests for retired legacy session storage paths."""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
"""Completed migration makes legacy JSONL files inert."""
|
||||
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
|
||||
def test_list_sessions_ignores_legacy_stem(tmp_path: Path) -> None:
|
||||
manager = SessionManager(tmp_path / "workspace")
|
||||
|
||||
# A legacy lossy-path filename must not be treated as current session storage,
|
||||
# even when the file contains otherwise recoverable records.
|
||||
legacy_stem = "telegram_12345"
|
||||
corrupt_path = manager.sessions_dir / f"{legacy_stem}.jsonl"
|
||||
corrupt_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
metadata = json.dumps({
|
||||
"_type": "metadata",
|
||||
"key": "telegram:12345",
|
||||
"created_at": datetime(2025, 1, 1).isoformat(),
|
||||
"updated_at": datetime(2025, 1, 1).isoformat(),
|
||||
})
|
||||
corrupt_path.write_text(
|
||||
metadata + "\n{INVALID JSON LINE\n"
|
||||
+ json.dumps({"role": "user", "content": "recoverable message"}) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
sessions = manager.list_sessions()
|
||||
|
||||
assert sessions == []
|
||||
assert corrupt_path.exists()
|
||||
|
||||
|
||||
def test_read_session_methods_ignore_legacy_lossy_stem(
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(
|
||||
"nanobot.session.manager.get_legacy_sessions_dir",
|
||||
lambda: tmp_path / "legacy_sessions",
|
||||
)
|
||||
manager = SessionManager(tmp_path / "workspace")
|
||||
session_id = "123e4567-e89b-12d3-a456-426614174000"
|
||||
key = f"websocket:{session_id}"
|
||||
legacy_path = manager._get_legacy_lossy_path(key)
|
||||
assert legacy_path.name == f"websocket_{session_id}.jsonl"
|
||||
|
||||
metadata = {
|
||||
"_type": "metadata",
|
||||
"key": key,
|
||||
"created_at": datetime(2025, 1, 1).isoformat(),
|
||||
"updated_at": datetime(2025, 1, 1).isoformat(),
|
||||
"metadata": {
|
||||
"workspace_scope": "project",
|
||||
"project_path": "/tmp/example-project",
|
||||
},
|
||||
}
|
||||
legacy_path.write_text(json.dumps(metadata) + "\n", encoding="utf-8")
|
||||
|
||||
metadata_result = manager.read_session_metadata(key)
|
||||
file_result = manager.read_session_file(key)
|
||||
|
||||
assert metadata_result is None
|
||||
assert file_result is None
|
||||
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
|
||||
@@ -8,12 +8,13 @@ import shutil
|
||||
import subprocess
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.config.loader import load_config
|
||||
from nanobot.session.manager import JsonlSessionStore, SessionManager
|
||||
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(
|
||||
@@ -25,7 +26,7 @@ def _write_legacy_session(
|
||||
) -> Path:
|
||||
"""Write a valid session file in the legacy in-workspace location."""
|
||||
old_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = old_dir / f"{JsonlSessionStore.storage_key(key)}.jsonl"
|
||||
path = old_dir / f"{SessionLocation.storage_key(key)}.jsonl"
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
@@ -126,7 +127,7 @@ def test_sessions_follow_active_custom_config_data_root(
|
||||
manager.save(session)
|
||||
|
||||
assert manager.sessions_dir.parent == custom_instance / "sessions"
|
||||
assert manager._get_session_path(session.key).exists()
|
||||
assert (manager.sessions_dir / "sessions.sqlite3").exists()
|
||||
assert not (default_home / ".nanobot" / "sessions").exists()
|
||||
|
||||
|
||||
@@ -220,126 +221,43 @@ def test_equivalent_workspace_paths_share_one_store(tmp_path: Path) -> None:
|
||||
assert via_link.messages[-1]["content"] == "via-real"
|
||||
|
||||
|
||||
def test_legacy_in_workspace_sessions_are_migrated(tmp_path: Path) -> None:
|
||||
def test_migration_rejects_symlinked_session_file(tmp_path, create_symlink):
|
||||
workspace = tmp_path / "workspace"
|
||||
key = "telegram:1"
|
||||
old_file = _write_legacy_session(workspace / "sessions", key, "migrated-msg")
|
||||
|
||||
manager = SessionManager(workspace=workspace)
|
||||
|
||||
# The session is readable through the normal store.
|
||||
loaded = manager.get_or_create(key)
|
||||
assert loaded.messages[-1]["content"] == "migrated-msg"
|
||||
# The legacy in-workspace file has been moved away...
|
||||
assert not old_file.exists()
|
||||
# ...into the out-of-workspace store.
|
||||
assert (manager.sessions_dir / old_file.name).exists()
|
||||
|
||||
# Migration is idempotent: a second construction must not corrupt anything.
|
||||
again = SessionManager(workspace=workspace).get_or_create(key)
|
||||
assert again.messages[-1]["content"] == "migrated-msg"
|
||||
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_keeps_source_when_install_fails(tmp_path: Path) -> None:
|
||||
def test_migration_rejects_symlinked_source_directory(tmp_path, create_symlink):
|
||||
workspace = tmp_path / "workspace"
|
||||
key = "telegram:partial"
|
||||
old_file = _write_legacy_session(workspace / "sessions", key, "still-safe")
|
||||
|
||||
with patch.object(JsonlSessionStore, "_install_snapshot", side_effect=OSError("disk full")):
|
||||
manager = SessionManager(workspace=workspace)
|
||||
|
||||
assert old_file.exists()
|
||||
assert not (manager.sessions_dir / old_file.name).exists()
|
||||
|
||||
retried = SessionManager(workspace=workspace)
|
||||
assert retried.get_or_create(key).messages[-1]["content"] == "still-safe"
|
||||
assert not old_file.exists()
|
||||
|
||||
|
||||
def test_migration_preserves_newest_valid_conflict(tmp_path: Path) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
key = "telegram:conflict"
|
||||
old_file = _write_legacy_session(workspace / "sessions", key, "newer-workspace")
|
||||
manager = SessionManager(workspace=workspace)
|
||||
|
||||
# Recreate an older legacy source while a newer destination already exists.
|
||||
manager_session = manager.get_or_create(key)
|
||||
manager_session.add_message("assistant", "newer-destination")
|
||||
manager.save(manager_session)
|
||||
_write_legacy_session(
|
||||
workspace / "sessions",
|
||||
key,
|
||||
"older-workspace",
|
||||
updated_at="2025-01-01T00:00:00",
|
||||
)
|
||||
|
||||
retried = SessionManager(workspace=workspace)
|
||||
loaded = retried.get_or_create(key)
|
||||
|
||||
assert loaded.messages[-1]["content"] == "newer-destination"
|
||||
conflicts = list((retried.sessions_dir / ".migration-conflicts").glob("*.jsonl"))
|
||||
assert len(conflicts) == 1
|
||||
assert "older-workspace" in conflicts[0].read_text(encoding="utf-8")
|
||||
assert not old_file.exists()
|
||||
|
||||
|
||||
def test_explicit_rollback_restore_copies_sessions_back_without_deleting_new_store(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
manager = SessionManager(workspace=workspace)
|
||||
session = manager.get_or_create("telegram:rollback")
|
||||
session.add_message("user", "available-to-old-version")
|
||||
manager.save(session, fsync=True)
|
||||
|
||||
result = manager.restore_sessions_to_workspace()
|
||||
legacy_file = workspace / "sessions" / manager._get_session_path(session.key).name
|
||||
|
||||
assert result.restored == 1
|
||||
assert result.unchanged == 0
|
||||
assert result.conflicts == ()
|
||||
assert legacy_file.exists()
|
||||
assert manager._get_session_path(session.key).exists()
|
||||
assert "available-to-old-version" in legacy_file.read_text(encoding="utf-8")
|
||||
|
||||
repeated = manager.restore_sessions_to_workspace()
|
||||
assert repeated.restored == 0
|
||||
assert repeated.unchanged == 1
|
||||
assert repeated.conflicts == ()
|
||||
|
||||
|
||||
def test_legacy_migration_rejects_symlinked_session_file(tmp_path: Path) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
old_dir = workspace / "sessions"
|
||||
old_dir.mkdir(parents=True)
|
||||
key = "telegram:symlink"
|
||||
outside = _write_legacy_session(tmp_path / "outside", key, "outside-secret")
|
||||
source = old_dir / outside.name
|
||||
try:
|
||||
source.symlink_to(outside)
|
||||
except OSError as exc:
|
||||
pytest.skip(f"file symlink unavailable: {exc}")
|
||||
|
||||
manager = SessionManager(workspace=workspace)
|
||||
|
||||
assert source.is_symlink()
|
||||
assert not (manager.sessions_dir / source.name).exists()
|
||||
assert manager.get_or_create(key).messages == []
|
||||
|
||||
|
||||
def test_legacy_migration_rejects_symlinked_sessions_directory(tmp_path: Path) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
outside = tmp_path / "outside"
|
||||
key = "telegram:directory-symlink"
|
||||
outside_file = _write_legacy_session(outside, key, "outside-secret")
|
||||
workspace.mkdir()
|
||||
try:
|
||||
(workspace / "sessions").symlink_to(outside, target_is_directory=True)
|
||||
except OSError as exc:
|
||||
pytest.skip(f"directory symlink unavailable: {exc}")
|
||||
outside = tmp_path / "outside"
|
||||
outside.mkdir()
|
||||
create_symlink(workspace / "sessions", outside, target_is_directory=True)
|
||||
with pytest.raises(ValueError, match="symlink"):
|
||||
SessionManager(workspace)
|
||||
|
||||
manager = SessionManager(workspace=workspace)
|
||||
|
||||
assert outside_file.exists()
|
||||
assert not (manager.sessions_dir / outside_file.name).exists()
|
||||
assert manager.get_or_create(key).messages == []
|
||||
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
|
||||
@@ -1,210 +1,98 @@
|
||||
from unittest.mock import MagicMock
|
||||
"""Administrative SQLite repository operations."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from nanobot.providers.base import ProviderConversationState
|
||||
from nanobot.session import Session, SessionManager
|
||||
from nanobot.session.manager import SessionStore
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
|
||||
from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY
|
||||
|
||||
|
||||
def test_manager_delegates_persistence_to_store(tmp_path) -> None:
|
||||
stored = Session(key="cli:test")
|
||||
stored.add_message("user", "hello")
|
||||
payload = {
|
||||
"key": stored.key,
|
||||
"created_at": stored.created_at.isoformat(),
|
||||
"updated_at": stored.updated_at.isoformat(),
|
||||
"metadata": {},
|
||||
"messages": stored.messages,
|
||||
def test_manager_roundtrips_full_history_and_private_state(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
session = Session(key="cli:test", messages=[{"role": "user", "content": str(i)} for i in range(2001)])
|
||||
session.provider_state = ProviderConversationState(kind="openai_responses", provider="openai:test",
|
||||
model="test-model", version=1, payload={"response_id": "private"})
|
||||
manager.save(session)
|
||||
loaded = manager.read_session_snapshot(session.key)
|
||||
assert loaded is not session
|
||||
assert loaded.messages == session.messages
|
||||
assert loaded.provider_state == session.provider_state
|
||||
assert "provider_state" not in manager.read_session_file(session.key)
|
||||
assert manager.list_sessions()[0]["preview"] == "0"
|
||||
|
||||
|
||||
def test_rename_model_preset_is_atomic(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
for key in ("cli:one", "cli:two"):
|
||||
manager.save(Session(key=key, metadata={SESSION_MODEL_PRESET_METADATA_KEY: "old"}))
|
||||
original = manager._store.update_metadata
|
||||
def fail_second(key, values, **kwargs):
|
||||
if key == "cli:two":
|
||||
raise OSError("disk full")
|
||||
return original(key, values, **kwargs)
|
||||
import pytest
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(manager._store, "update_metadata", fail_second)
|
||||
with pytest.raises(OSError):
|
||||
manager.rename_model_preset("old", "new")
|
||||
assert all(manager.get_or_create(key).metadata[SESSION_MODEL_PRESET_METADATA_KEY] == "old"
|
||||
for key in ("cli:one", "cli:two"))
|
||||
assert manager.rename_model_preset("old", "new") == 2
|
||||
assert all(manager.get_or_create(key).metadata[SESSION_MODEL_PRESET_METADATA_KEY] == "new"
|
||||
for key in ("cli:one", "cli:two"))
|
||||
|
||||
|
||||
def test_metadata_updates_do_not_replace_messages(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
manager.save(Session(key="cli:test", messages=[{"role": "user", "content": "hello"}]))
|
||||
assert manager.update_session_metadata("cli:test", {"title": "new"})
|
||||
assert manager.read_session_file("cli:test")["messages"] == [{"role": "user", "content": "hello"}]
|
||||
assert manager.read_session_metadata("cli:test")["metadata"]["title"] == "new"
|
||||
assert not manager.update_session_metadata("cli:missing", {"title": "x"})
|
||||
assert manager.delete_session("cli:test")
|
||||
assert manager.read_session_file("cli:test") is None
|
||||
|
||||
|
||||
def test_child_headers_select_declared_children_and_preserve_descendant_deletion(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
parent = "chat:项目'\"\\root"
|
||||
manager.save(Session(key=parent))
|
||||
manager.save(Session(key="chat:unrelated", metadata={"title": "unrelated"}))
|
||||
for key, kind, parent_key, second in (
|
||||
("subagent:first", "subagent", parent, 1),
|
||||
("extension:child", "extension", parent, 2),
|
||||
("extension:grandchild", "extension", "extension:child", 3),
|
||||
):
|
||||
manager.save(Session(
|
||||
key=key, updated_at=datetime(2026, 1, 1, 0, 0, second),
|
||||
messages=[{"role": "user", "content": "private transcript"}],
|
||||
metadata={
|
||||
PARENT_SESSION_KEY: parent_key, SESSION_TYPE_KEY: kind,
|
||||
"nested": {"value": key}, "runtime_checkpoint": {"step": 1},
|
||||
"pending_user_followups": [{"id": "queued"}],
|
||||
},
|
||||
))
|
||||
|
||||
def prohibit_full_listing():
|
||||
raise AssertionError("child queries must not materialize unrelated session headers")
|
||||
|
||||
monkeypatch.setattr(manager._store, "list_metadata", prohibit_full_listing)
|
||||
assert manager.child_session_keys(parent) == ["extension:child", "subagent:first"]
|
||||
rows = manager.list_child_session_metadata(parent)
|
||||
assert [row["key"] for row in rows] == ["extension:child", "subagent:first"]
|
||||
assert rows[0]["updated_at"] == "2026-01-01T00:00:02"
|
||||
assert rows[0]["metadata"] == {
|
||||
PARENT_SESSION_KEY: parent, SESSION_TYPE_KEY: "extension",
|
||||
"nested": {"value": "extension:child"},
|
||||
}
|
||||
metadata = {
|
||||
"key": stored.key,
|
||||
"created_at": stored.created_at.isoformat(),
|
||||
"updated_at": stored.updated_at.isoformat(),
|
||||
"metadata": {},
|
||||
}
|
||||
listing = [
|
||||
{
|
||||
"key": stored.key,
|
||||
"created_at": stored.created_at.isoformat(),
|
||||
"updated_at": stored.updated_at.isoformat(),
|
||||
"title": "",
|
||||
"preview": "hello",
|
||||
"path": "session.db",
|
||||
}
|
||||
]
|
||||
store = MagicMock(spec=SessionStore)
|
||||
store.load.return_value = stored
|
||||
store.read.return_value = payload
|
||||
store.read_metadata.return_value = metadata
|
||||
store.list_sessions.return_value = listing
|
||||
store.delete.return_value = True
|
||||
manager = SessionManager(tmp_path, store=store)
|
||||
rows[0]["metadata"]["nested"]["value"] = "detached edit"
|
||||
assert manager.list_child_session_metadata(parent)[0]["metadata"]["nested"]["value"] == "extension:child"
|
||||
assert manager.read_session_metadata("extension:child")["metadata"]["runtime_checkpoint"] == {"step": 1}
|
||||
|
||||
assert manager.get_or_create(stored.key) is stored
|
||||
assert manager.get_or_create(stored.key) is stored
|
||||
store.load.assert_called_once_with(stored.key)
|
||||
|
||||
manager.save(stored, fsync=True)
|
||||
store.save.assert_called_once_with(stored, fsync=True)
|
||||
assert manager.read_session_file(stored.key) == payload
|
||||
assert manager.read_session_metadata(stored.key) == metadata
|
||||
assert manager.list_sessions() == listing
|
||||
|
||||
assert manager.delete_session(stored.key) is True
|
||||
store.delete.assert_called_once_with(stored.key)
|
||||
assert manager.get_cached(stored.key) is None
|
||||
|
||||
|
||||
def test_manager_renames_model_preset_in_live_and_persisted_sessions(tmp_path) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
sessions_root = tmp_path / "sessions"
|
||||
manager = SessionManager(workspace, sessions_root=sessions_root)
|
||||
selected = manager.get_or_create("websocket:selected")
|
||||
selected.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "openai"
|
||||
manager.save(selected)
|
||||
other = manager.get_or_create("websocket:other")
|
||||
other.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "backup"
|
||||
manager.save(other)
|
||||
transient = manager.get_or_create_transient("websocket:temporary")
|
||||
transient.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "openai"
|
||||
|
||||
assert manager.rename_model_preset("openai", "Codex") == 2
|
||||
assert selected.metadata[SESSION_MODEL_PRESET_METADATA_KEY] == "Codex"
|
||||
assert transient.metadata[SESSION_MODEL_PRESET_METADATA_KEY] == "Codex"
|
||||
|
||||
reloaded = SessionManager(workspace, sessions_root=sessions_root)
|
||||
assert (
|
||||
reloaded.get_or_create("websocket:selected").metadata[
|
||||
SESSION_MODEL_PRESET_METADATA_KEY
|
||||
]
|
||||
== "Codex"
|
||||
)
|
||||
assert (
|
||||
reloaded.get_or_create("websocket:other").metadata[
|
||||
SESSION_MODEL_PRESET_METADATA_KEY
|
||||
]
|
||||
== "backup"
|
||||
)
|
||||
|
||||
|
||||
def test_read_session_snapshot_does_not_populate_runtime_cache(tmp_path) -> None:
|
||||
stored = Session(key="websocket:context")
|
||||
store = MagicMock(spec=SessionStore)
|
||||
store.load.return_value = stored
|
||||
manager = SessionManager(tmp_path, store=store)
|
||||
|
||||
assert manager.read_session_snapshot(stored.key) is stored
|
||||
assert manager.get_cached(stored.key) is None
|
||||
store.load.assert_called_once_with(stored.key)
|
||||
|
||||
|
||||
def test_manager_preserves_full_session_before_store_save(tmp_path) -> None:
|
||||
store = MagicMock(spec=SessionStore)
|
||||
manager = SessionManager(tmp_path, store=store)
|
||||
session = Session(
|
||||
key="cli:large",
|
||||
messages=[
|
||||
{
|
||||
"role": "user" if index % 2 == 0 else "assistant",
|
||||
"content": str(index),
|
||||
}
|
||||
for index in range(2_001)
|
||||
],
|
||||
)
|
||||
|
||||
manager.save(session)
|
||||
|
||||
assert len(session.messages) == 2_001
|
||||
assert session.messages[0]["content"] == "0"
|
||||
assert session.messages[-1]["content"] == "2000"
|
||||
store.save.assert_called_once_with(session, fsync=False)
|
||||
|
||||
|
||||
def test_runtime_checkpoint_does_not_rewrite_long_session(tmp_path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:long")
|
||||
for index in range(256):
|
||||
session.add_message("user", f"{index}:" + "x" * 4096)
|
||||
manager.save(session)
|
||||
|
||||
main_path = manager._get_session_path(session.key)
|
||||
main_before = main_path.read_bytes()
|
||||
stat_before = main_path.stat()
|
||||
session.metadata["runtime_checkpoint"] = {
|
||||
"phase": "tools_completed",
|
||||
"assistant_message": {"role": "assistant", "content": "working"},
|
||||
"completed_tool_results": [],
|
||||
"pending_tool_calls": [],
|
||||
}
|
||||
session.provider_state = ProviderConversationState(
|
||||
kind="openai_responses",
|
||||
provider="openai:test",
|
||||
model="test-model",
|
||||
version=1,
|
||||
payload={"response_id": "private-response"},
|
||||
)
|
||||
|
||||
manager.save_runtime_checkpoint(session)
|
||||
|
||||
checkpoint_path = manager._get_runtime_checkpoint_path(session.key)
|
||||
assert main_path.read_bytes() == main_before
|
||||
assert main_path.stat().st_ino == stat_before.st_ino
|
||||
assert main_path.stat().st_mtime_ns == stat_before.st_mtime_ns
|
||||
assert checkpoint_path.stat().st_size < len(main_before) // 100
|
||||
|
||||
restored = SessionManager(tmp_path).get_or_create(session.key)
|
||||
assert restored.metadata["runtime_checkpoint"]["phase"] == "tools_completed"
|
||||
assert restored.provider_state is not None
|
||||
assert restored.provider_state.payload == {"response_id": "private-response"}
|
||||
|
||||
|
||||
def test_completed_session_supersedes_stale_checkpoint(tmp_path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:completed")
|
||||
session.add_message("user", "question")
|
||||
manager.save(session)
|
||||
session.metadata["runtime_checkpoint"] = {"phase": "awaiting_tools"}
|
||||
manager.save_runtime_checkpoint(session)
|
||||
checkpoint_path = manager._get_runtime_checkpoint_path(session.key)
|
||||
stale_checkpoint = checkpoint_path.read_bytes()
|
||||
|
||||
session.metadata.pop("runtime_checkpoint")
|
||||
session.add_message("assistant", "answer")
|
||||
manager.save(session)
|
||||
assert not checkpoint_path.exists()
|
||||
|
||||
# Emulate a process dying after the main record was committed but before an
|
||||
# obsolete sidecar could be removed. The base fingerprint keeps it stale.
|
||||
checkpoint_path.write_bytes(stale_checkpoint)
|
||||
restored = SessionManager(tmp_path).get_or_create(session.key)
|
||||
assert "runtime_checkpoint" not in restored.metadata
|
||||
assert restored.messages[-1]["content"] == "answer"
|
||||
assert not checkpoint_path.exists()
|
||||
|
||||
|
||||
def test_delete_session_removes_runtime_checkpoint(tmp_path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:delete")
|
||||
session.add_message("user", "question")
|
||||
manager.save(session)
|
||||
session.metadata["runtime_checkpoint"] = {"phase": "awaiting_tools"}
|
||||
manager.save_runtime_checkpoint(session)
|
||||
checkpoint_path = manager._get_runtime_checkpoint_path(session.key)
|
||||
assert checkpoint_path.exists()
|
||||
|
||||
assert manager.delete_session(session.key) is True
|
||||
assert not checkpoint_path.exists()
|
||||
|
||||
|
||||
def test_invalid_runtime_checkpoint_is_discarded(tmp_path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:invalid-checkpoint")
|
||||
session.add_message("user", "question")
|
||||
manager.save(session)
|
||||
checkpoint_path = manager._get_runtime_checkpoint_path(session.key)
|
||||
checkpoint_path.write_text("{truncated", encoding="utf-8")
|
||||
|
||||
restored = SessionManager(tmp_path).get_or_create(session.key)
|
||||
|
||||
assert "runtime_checkpoint" not in restored.metadata
|
||||
assert not checkpoint_path.exists()
|
||||
deleted = []
|
||||
manager.set_delete_observer(deleted.append)
|
||||
assert manager.delete_session(parent)
|
||||
assert set(deleted) == {parent, "subagent:first", "extension:child", "extension:grandchild"}
|
||||
assert [row["key"] for row in manager.list_sessions()] == ["chat:unrelated"]
|
||||
assert manager.list_child_session_metadata(parent) == []
|
||||
@@ -0,0 +1,236 @@
|
||||
"""Session schema upgrades preserve records and fail atomically."""
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
import nanobot.session.sqlite_store as sqlite_store
|
||||
from nanobot.providers.base import ProviderConversationState
|
||||
from nanobot.session.manager import Session
|
||||
from nanobot.session.sqlite_store import SqliteSessionStore
|
||||
|
||||
|
||||
def _session() -> Session:
|
||||
return Session(
|
||||
key="chat:extensions",
|
||||
messages=[{"role": "user", "content": "hello", "extension": {"source": "import"}}],
|
||||
metadata={
|
||||
"title": "Extended session",
|
||||
"extension": {"enabled": True},
|
||||
"runtime_checkpoint": {
|
||||
"phase": "final_response", "iteration": 1, "model": "gpt-test",
|
||||
"assistant_message": {"role": "assistant", "content": "checkpoint answer"},
|
||||
"completed_tool_results": [], "pending_tool_calls": [], "extension": {"step": 2},
|
||||
},
|
||||
"pending_user_followups": [{
|
||||
"id": "followup", "sender_id": "user", "chat_id": "extensions", "content": "next",
|
||||
"media": [], "metadata": {}, "extension": True,
|
||||
}],
|
||||
},
|
||||
provider_state=ProviderConversationState(
|
||||
kind="openai_responses", provider="openai", model="gpt-test", version=1,
|
||||
payload={"items": [], "extension": {"cursor": "opaque"}},
|
||||
pending_messages=[{"role": "assistant", "content": "pending", "extension": True}],
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
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 (
|
||||
db.execute("PRAGMA user_version").fetchone()[0],
|
||||
db.execute("PRAGMA journal_mode").fetchone()[0],
|
||||
"\n".join(db.iterdump()),
|
||||
)
|
||||
|
||||
|
||||
def test_ordered_upgrades_preserve_records_and_do_not_repeat_import(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
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"
|
||||
db.executescript(schema.read_text(encoding="utf-8"))
|
||||
store.save(original)
|
||||
assert _database_snapshot(store.path)[0] == 1
|
||||
|
||||
def add_archived(db: sqlite3.Connection) -> None:
|
||||
db.execute("ALTER TABLE sessions ADD COLUMN archived INTEGER NOT NULL DEFAULT 0")
|
||||
|
||||
def index_archived(db: sqlite3.Connection) -> None:
|
||||
db.execute("CREATE INDEX sessions_archived ON sessions(archived)")
|
||||
|
||||
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)
|
||||
assert _database_snapshot(store.path)[0] == 3
|
||||
loaded = upgraded.load(original.key)
|
||||
assert loaded is not None
|
||||
assert loaded.messages == original.messages
|
||||
assert loaded.metadata == original.metadata
|
||||
assert loaded.provider_state == original.provider_state
|
||||
upgraded.save(loaded)
|
||||
|
||||
reopened = SqliteSessionStore(tmp_path)
|
||||
reopened.initialize(workspace)
|
||||
roundtrip = reopened.load(original.key)
|
||||
assert roundtrip is not None
|
||||
assert roundtrip.messages == original.messages
|
||||
assert roundtrip.metadata == original.metadata
|
||||
assert roundtrip.provider_state == original.provider_state
|
||||
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)
|
||||
original = _session()
|
||||
store.save(original)
|
||||
before = _database_snapshot(store.path)
|
||||
migrations = sqlite_store._SCHEMA_MIGRATIONS
|
||||
|
||||
def add_archived(db: sqlite3.Connection) -> None:
|
||||
db.execute("ALTER TABLE sessions ADD COLUMN archived INTEGER NOT NULL DEFAULT 0")
|
||||
|
||||
def fail_upgrade(db: sqlite3.Connection) -> None:
|
||||
db.execute("UPDATE sessions SET title='partial migration'")
|
||||
db.execute("CREATE TABLE migration_partial (value TEXT)")
|
||||
raise RuntimeError("migration interrupted")
|
||||
|
||||
monkeypatch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", (
|
||||
*migrations, add_archived, fail_upgrade,
|
||||
))
|
||||
with pytest.raises(RuntimeError, match="migration interrupted"):
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path) == before
|
||||
|
||||
def complete_upgrade(db: sqlite3.Connection) -> None:
|
||||
db.execute("CREATE INDEX sessions_archived ON sessions(archived)")
|
||||
|
||||
monkeypatch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", (
|
||||
*migrations, add_archived, complete_upgrade,
|
||||
))
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path)[0] == 3
|
||||
loaded = store.load(original.key)
|
||||
assert loaded is not None
|
||||
assert loaded.messages == original.messages
|
||||
assert loaded.metadata == original.metadata
|
||||
assert loaded.provider_state == original.provider_state
|
||||
|
||||
|
||||
def test_added_columns_allow_import_and_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")
|
||||
db.execute(f"ALTER TABLE {table} ADD COLUMN format_version INTEGER NOT NULL DEFAULT 1")
|
||||
|
||||
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
|
||||
|
||||
created = _session()
|
||||
created.key = "chat:new"
|
||||
store.save(created)
|
||||
created.add_message("assistant", "answer", extension={"keep": True})
|
||||
store.save(created, message_start=1)
|
||||
assert store.update_metadata(created.key, {"title": "Changed title"})
|
||||
current = store.load(created.key)
|
||||
assert current is not None
|
||||
current.metadata["runtime_checkpoint"]["extension"] = {"step": 3}
|
||||
store.save_runtime_checkpoint(current)
|
||||
store.replace_metadata(current.key, current.metadata)
|
||||
roundtrip = store.load(current.key)
|
||||
assert roundtrip is not None
|
||||
assert roundtrip.messages == created.messages
|
||||
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"):
|
||||
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.save(_session())
|
||||
future_version = len(sqlite_store._SCHEMA_MIGRATIONS) + 1
|
||||
with closing(sqlite3.connect(store.path)) as db:
|
||||
db.execute("PRAGMA journal_mode = DELETE")
|
||||
db.execute(f"PRAGMA user_version = {future_version}")
|
||||
before = _database_snapshot(store.path)
|
||||
before_bytes = store.path.read_bytes()
|
||||
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)
|
||||
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.save(_session())
|
||||
with closing(sqlite3.connect(store.path)) as db:
|
||||
db.execute("PRAGMA journal_mode = DELETE")
|
||||
before = _database_snapshot(store.path)
|
||||
before_bytes = store.path.read_bytes()
|
||||
native_connect = sqlite3.connect
|
||||
|
||||
class WithoutJson(sqlite3.Connection):
|
||||
def execute(self, sql, parameters=()):
|
||||
if "json_extract(" in sql:
|
||||
raise sqlite3.OperationalError("no such function: json_extract")
|
||||
return super().execute(sql, parameters)
|
||||
|
||||
def connect(*args, **kwargs):
|
||||
return native_connect(*args, factory=WithoutJson, **kwargs)
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(sqlite3, "connect", connect)
|
||||
with pytest.raises(RuntimeError, match="requires SQLite JSON support"):
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path) == before
|
||||
assert store.path.read_bytes() == before_bytes
|
||||
@@ -0,0 +1,727 @@
|
||||
"""SQLite durability, migration, 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
|
||||
|
||||
|
||||
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")
|
||||
manager.save(session)
|
||||
old = manager.get_or_create(session.key)
|
||||
session.add_message("user", "new")
|
||||
manager.save(session)
|
||||
old.add_message("user", "stale")
|
||||
with pytest.raises(SessionConflictError):
|
||||
manager.save(old)
|
||||
assert manager.get_or_create(session.key).messages[-1]["content"] == "new"
|
||||
|
||||
|
||||
def test_transaction_rolls_back_all_rows(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
def write_then_fail() -> None:
|
||||
session = Session(key="chat:a", metadata={"runtime_checkpoint": {"step": 1}, "pending_user_followups": [{"id": "x"}]})
|
||||
session.add_message("user", "hello")
|
||||
manager.save(session)
|
||||
raise RuntimeError("injected failure")
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
manager._store.run_write(write_then_fail)
|
||||
assert manager.list_sessions() == []
|
||||
with sqlite3.connect(manager.sessions_dir / "sessions.sqlite3") as db:
|
||||
for table in ("sessions", "messages", "checkpoints", "pending_inputs"):
|
||||
assert db.execute(f"SELECT count(*) FROM {table}").fetchone()[0] == 0
|
||||
|
||||
|
||||
async def test_metadata_updates_preserve_running_turn(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.get("chat:a")
|
||||
draft.add_message("user", "hello")
|
||||
draft.metadata["pending_user_turn"] = True
|
||||
await state.prepare_input(draft)
|
||||
await state.update_metadata(draft.key, {"title": "new title"})
|
||||
draft.add_message("assistant", "answer")
|
||||
await state.finish_turn(draft)
|
||||
loaded = await state.get(draft.key)
|
||||
assert loaded.metadata["title"] == "new title"
|
||||
assert [row["content"] for row in loaded.messages] == ["hello", "answer"]
|
||||
assert "pending_user_turn" not in loaded.metadata
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_reset_rejects_late_result_and_checkpoint(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
draft = await state.get("chat:a")
|
||||
draft.add_message("user", "hello")
|
||||
await state.prepare_input(draft)
|
||||
await state.reset(draft.key)
|
||||
draft.add_message("assistant", "late")
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.finish_turn(draft)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.checkpoint_view(draft, {"step": 2})
|
||||
assert (await state.get(draft.key)).messages == []
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_detached_reads_do_not_publish_mutations(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
await state.import_messages("chat:a", [{"role": "user", "content": "hello"}])
|
||||
draft = await state.get("chat:a")
|
||||
draft.messages[0]["content"] = "edited"
|
||||
draft.metadata["title"] = "unsaved"
|
||||
loaded = await state.get("chat:a")
|
||||
assert loaded.messages[0]["content"] == "hello"
|
||||
assert "title" not in loaded.metadata
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_checkpoint_does_not_rewrite_messages(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.get("chat:a")
|
||||
draft.add_message("user", "hello")
|
||||
await state.prepare_input(draft)
|
||||
path = manager.sessions_dir / "sessions.sqlite3"
|
||||
with sqlite3.connect(path) as db:
|
||||
db.execute("CREATE TRIGGER prohibit_rewrite BEFORE UPDATE ON messages BEGIN SELECT RAISE(ABORT, 'rewritten'); END")
|
||||
await state.checkpoint_view(draft, {"step": 1})
|
||||
assert (await state.get(draft.key)).metadata["runtime_checkpoint"] == {"step": 1}
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_database_lock_does_not_block_event_loop(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("chat:a")
|
||||
await state.update_metadata("chat:a", {"title": "old"})
|
||||
ready = threading.Event()
|
||||
release = threading.Event()
|
||||
def hold():
|
||||
with sqlite3.connect(manager.sessions_dir / "sessions.sqlite3") as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
ready.set()
|
||||
release.wait(5)
|
||||
thread = threading.Thread(target=hold)
|
||||
thread.start()
|
||||
await asyncio.to_thread(ready.wait, 2)
|
||||
task = asyncio.create_task(state.update_metadata("chat:a", {"title": "new"}))
|
||||
try:
|
||||
start = time.monotonic()
|
||||
await asyncio.sleep(0.03)
|
||||
assert time.monotonic() - start < 0.3
|
||||
assert not task.done()
|
||||
finally:
|
||||
release.set()
|
||||
await task
|
||||
thread.join()
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_existing_reads_do_not_wait_for_another_sessions_write_lock(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("chat:write")
|
||||
await state.get("chat:read")
|
||||
await state.update_metadata("chat:read", {"title": "committed"})
|
||||
ready, release = threading.Event(), threading.Event()
|
||||
|
||||
def hold():
|
||||
with sqlite3.connect(manager._store.path) as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
ready.set()
|
||||
assert release.wait(5)
|
||||
|
||||
thread = threading.Thread(target=hold)
|
||||
thread.start()
|
||||
await asyncio.to_thread(ready.wait, 2)
|
||||
write = asyncio.create_task(state.update_metadata("chat:write", {"title": "waiting"}))
|
||||
try:
|
||||
await asyncio.sleep(0)
|
||||
metadata = await asyncio.wait_for(state.read_metadata("chat:read"), timeout=2)
|
||||
draft = await asyncio.wait_for(state.get("chat:read"), timeout=2)
|
||||
header = await asyncio.wait_for(state.get_header("chat:read"), timeout=2)
|
||||
assert metadata["metadata"]["title"] == draft.metadata["title"] == header.metadata["title"] == "committed"
|
||||
assert not write.done()
|
||||
finally:
|
||||
release.set()
|
||||
await write
|
||||
thread.join()
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_closing_one_owner_preserves_another_owners_connections(tmp_path):
|
||||
from nanobot.session.state import SessionState
|
||||
|
||||
manager = SessionManager(tmp_path)
|
||||
first = SessionState(manager._store)
|
||||
second = SessionState(manager._store)
|
||||
try:
|
||||
await first.get("chat:first")
|
||||
await second.get("chat:second")
|
||||
await first.aclose()
|
||||
await second.update_metadata("chat:second", {"title": "still open"})
|
||||
assert (await second.get("chat:second")).metadata["title"] == "still open"
|
||||
finally:
|
||||
await first.aclose()
|
||||
await second.aclose()
|
||||
|
||||
|
||||
async def test_cancellation_settles_accepted_write(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
ready = threading.Event()
|
||||
release = threading.Event()
|
||||
original = manager._store.save
|
||||
def blocked(session, **kwargs):
|
||||
ready.set()
|
||||
release.wait(5)
|
||||
return original(session, **kwargs)
|
||||
monkeypatch.setattr(manager._store, "save", blocked)
|
||||
task = asyncio.create_task(state.import_messages("chat:a", [{"role": "user", "content": "accepted"}]))
|
||||
await asyncio.to_thread(ready.wait, 2)
|
||||
task.cancel()
|
||||
await asyncio.sleep(0)
|
||||
assert not task.done()
|
||||
release.set()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert (await state.get("chat:a")).messages[0]["content"] == "accepted"
|
||||
await state.aclose()
|
||||
with pytest.raises(RuntimeError, match="closed"):
|
||||
await state.get("chat:a")
|
||||
|
||||
|
||||
def test_committed_checkpoint_survives_process_exit(tmp_path):
|
||||
workspace, root = tmp_path / "workspace", tmp_path / "storage"
|
||||
script = '''
|
||||
import asyncio, os, sys
|
||||
from pathlib import Path
|
||||
from nanobot.session.manager import SessionManager
|
||||
async def main():
|
||||
state = SessionManager(Path(sys.argv[1]), sessions_root=Path(sys.argv[2])).state
|
||||
draft = await state.get("chat:a")
|
||||
draft.add_message("user", "accepted")
|
||||
draft.metadata["pending_user_turn"] = True
|
||||
await state.prepare_input(draft)
|
||||
await state.checkpoint_view(draft, {"step": "tool-finished"})
|
||||
os._exit(0)
|
||||
asyncio.run(main())
|
||||
'''
|
||||
subprocess.run([sys.executable, "-c", script, str(workspace), str(root)], check=True, timeout=15)
|
||||
manager = SessionManager(workspace, sessions_root=root)
|
||||
session = manager.get_or_create("chat:a")
|
||||
assert session.messages[0]["content"] == "accepted"
|
||||
assert session.metadata["runtime_checkpoint"] == {"step": "tool-finished"}
|
||||
|
||||
|
||||
async def test_late_metadata_and_summary_cannot_resurrect_deleted_session(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
draft = await state.get("chat:deleted")
|
||||
await state.delete(draft.key)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.mutate_metadata(
|
||||
draft.key, lambda metadata: metadata.update(title="late title"),
|
||||
expected_generation=draft.generation,
|
||||
)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.commit_summary(draft, "late summary", archive_end=0)
|
||||
assert await state.read(draft.key) is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_large_draft_copy_and_publication_run_on_owner_worker(tmp_path, monkeypatch):
|
||||
import nanobot.session.state as owner
|
||||
|
||||
state = SessionManager(tmp_path).state
|
||||
draft = await state.get("chat:copy")
|
||||
draft.add_message("user", "large transcript" * 10000)
|
||||
loop_thread = threading.get_ident()
|
||||
original_copy = owner.deepcopy
|
||||
copied = threading.Event()
|
||||
|
||||
def checked_copy(value):
|
||||
if isinstance(value, Session) or (isinstance(value, dict) and "role" in value):
|
||||
assert threading.get_ident() != loop_thread
|
||||
copied.set()
|
||||
return original_copy(value)
|
||||
|
||||
monkeypatch.setattr(owner, "deepcopy", checked_copy)
|
||||
await state.prepare_input(draft)
|
||||
await state.checkpoint_view(draft, {"step": 1})
|
||||
await state.finish_turn(draft)
|
||||
assert copied.is_set()
|
||||
assert (await state.read(draft.key)).messages == draft.messages
|
||||
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
|
||||
with pytest.raises(SessionConflictError, match="does not exist"):
|
||||
await state.update_metadata("chat:missing", {"title": "late"})
|
||||
with pytest.raises(SessionConflictError, match="does not exist"):
|
||||
await state.record_delivery(
|
||||
"chat:missing", "late", {}, expected_generation="deleted-generation",
|
||||
)
|
||||
assert manager.read_session_snapshot("chat:missing") is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_delete_rejects_late_delivery_and_metadata(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
session = await state.get("chat:a")
|
||||
assert await state.delete(session.key, expected_generation=session.generation)
|
||||
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.record_delivery(
|
||||
session.key,
|
||||
"deleted-secret",
|
||||
{},
|
||||
expected_generation=session.generation,
|
||||
)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.update_metadata(
|
||||
session.key,
|
||||
{"secret": "deleted-secret"},
|
||||
expected_generation=session.generation,
|
||||
)
|
||||
assert manager.read_session_snapshot(session.key) is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_old_generation_cannot_write_into_recreated_key(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
old = await state.get("chat:a")
|
||||
assert await state.delete(old.key, expected_generation=old.generation)
|
||||
current = await state.get(old.key)
|
||||
assert current.generation != old.generation
|
||||
|
||||
with pytest.raises(SessionConflictError, match="replaced session"):
|
||||
await state.record_delivery(
|
||||
old.key,
|
||||
"old result",
|
||||
{},
|
||||
expected_generation=old.generation,
|
||||
)
|
||||
loaded = await state.read(old.key)
|
||||
assert loaded is not None and loaded.messages == []
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_discarded_transient_late_delivery_never_becomes_durable(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
transient = await state.register_transient("temporary:a")
|
||||
await state.discard(transient.key)
|
||||
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.record_delivery(
|
||||
transient.key,
|
||||
"private late result",
|
||||
{},
|
||||
expected_generation=transient.generation,
|
||||
)
|
||||
assert manager.read_session_snapshot(transient.key) is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_read_and_delete_are_serialized_without_cache_ghost(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("chat:a")
|
||||
loaded, release = threading.Event(), threading.Event()
|
||||
original = state._load
|
||||
first = True
|
||||
|
||||
def paused_load(key, *, history=True):
|
||||
nonlocal first
|
||||
session = original(key, history=history)
|
||||
if first and key == "chat:a":
|
||||
first = False
|
||||
loaded.set()
|
||||
release.wait(5)
|
||||
return session
|
||||
|
||||
monkeypatch.setattr(state, "_load", paused_load)
|
||||
read = asyncio.create_task(state.read("chat:a"))
|
||||
assert await asyncio.to_thread(loaded.wait, 2)
|
||||
deletion = asyncio.create_task(state.delete("chat:a"))
|
||||
await asyncio.sleep(0.05)
|
||||
assert not deletion.done()
|
||||
release.set()
|
||||
assert await read is not None
|
||||
assert await deletion
|
||||
assert state.peek("chat:a") is None
|
||||
assert manager.read_session_snapshot("chat:a") is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_synchronous_mutation_is_rejected_after_owner_binds(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("chat:a")
|
||||
with pytest.raises(RuntimeError, match="async owner"):
|
||||
manager.delete_session("chat:a")
|
||||
with pytest.raises(RuntimeError, match="async owner"):
|
||||
manager.update_session_metadata("chat:a", {"title": "bypass"})
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_delivery_requires_explicit_nonempty_generation(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
session = await state.get("chat:a")
|
||||
with pytest.raises(ValueError, match="requires a session generation"):
|
||||
await state.record_delivery(session.key, "unguarded", {}, expected_generation="")
|
||||
await state.record_delivery(
|
||||
session.key, "current", {}, expected_generation=session.generation,
|
||||
)
|
||||
assert [message["content"] for message in (await state.get(session.key)).messages] == [
|
||||
"current",
|
||||
]
|
||||
await state.aclose()
|
||||
@@ -73,7 +73,7 @@ async def test_maybe_continue_turn_queues_internal_message():
|
||||
visible_run_started_at=1234.5,
|
||||
)
|
||||
|
||||
assert await maybe_continue_turn(ctx) is True
|
||||
assert await maybe_continue_turn(ctx, session_metadata=ctx.session.metadata) is True
|
||||
|
||||
queued = pending.get_nowait()
|
||||
assert queued.sender_id == "system:continuation"
|
||||
@@ -126,7 +126,7 @@ async def test_internal_continuation_respects_round_limit():
|
||||
pending_queue_available=True,
|
||||
session_metadata=meta,
|
||||
)
|
||||
assert await maybe_continue_turn(ctx) is False
|
||||
assert await maybe_continue_turn(ctx, session_metadata=ctx.session.metadata) is False
|
||||
|
||||
|
||||
def test_internal_continuation_requires_budget_boundary_and_queue():
|
||||
|
||||
Reference in new issue
Block a user