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:
chengyongru authored and GitHub committed 2026-10-16 17:28:47 +08:00
1 parent 33ff520d12
commit 8f6a5594fb
144 files changed
+8293 -4912

No files matched your search

+42 -39
View File
@@ -65,9 +65,9 @@ def _fake_provider(name: str, *, max_tokens: int = 8192) -> MagicMock:
async def _admit_fake_runtime(bot, session_key, callback, runtime=None) -> None:
admitted = runtime or bot._loop.runtime_for_session(
admitted = runtime or (await bot._loop.runtime_for_session(
bot._loop.sessions.get_or_create(session_key)
)
))
await callback(admitted)
@@ -308,7 +308,8 @@ async def test_run_custom_session_key(tmp_path):
)
def test_request_context_preserves_legacy_positional_arguments(tmp_path):
@pytest.mark.parametrize("generation_kwargs", [{}, {"session_generation": "generation-1"}])
def test_request_context_preserves_legacy_positional_arguments(tmp_path, generation_kwargs):
from nanobot.agent.tools.context import RequestContext
context = RequestContext(
@@ -322,13 +323,20 @@ def test_request_context_preserves_legacy_positional_arguments(tmp_path):
"alice",
"turn-1",
tmp_path,
{"source": "sdk"},
False,
**generation_kwargs,
)
assert context.original_user_text == "hello"
assert context.runtime is None
assert context.session_generation == generation_kwargs.get("session_generation")
assert context.metadata == {"trusted": True}
assert context.sender_id == "alice"
assert context.turn_id == "turn-1"
assert context.workspace == tmp_path
assert context.attributes == {}
assert context.attributes == {"source": "sdk"}
assert context.log_content is False
@pytest.mark.asyncio
@@ -365,7 +373,7 @@ async def test_run_exposes_attributes_to_context_provider_without_persisting_the
assert result.content == "done"
assert seen[0].attributes == {"tenant": "acme"}
assert seen[0].metadata == {}
snapshot = bot.sessions.export("sdk:attributes")
snapshot = (await bot.sessions.export("sdk:attributes"))
assert snapshot is not None
assert all("attributes" not in message for message in snapshot.messages)
@@ -414,8 +422,8 @@ async def test_persisted_turn_callback_is_best_effort_and_reads_display_safe_ses
failed_sync_attempts += 1
raise RuntimeError("host sync failed")
def on_persisted(event: SessionTurnPersisted) -> None:
seen.append((event, bot.sessions.get(event.context.session_key)))
async def on_persisted(event: SessionTurnPersisted) -> None:
seen.append((event, (await bot.sessions.get(event.context.session_key))))
remove_context = bot.runtime.add_context_provider(provide_context)
remove_failure = bot.runtime.on_session_turn_persisted(fail_sync)
@@ -437,7 +445,7 @@ async def test_persisted_turn_callback_is_best_effort_and_reads_display_safe_ses
assert snapshot.messages[-1]["content"] == "saved reply"
assert result.content == "saved reply"
assert failed_sync_attempts == 1
trusted_snapshot = bot.sessions.export("sdk:persisted")
trusted_snapshot = (await bot.sessions.export("sdk:persisted"))
assert trusted_snapshot is not None
assert "model-only context" in trusted_snapshot.messages[-2]["content"]
@@ -466,7 +474,7 @@ async def test_persisted_turn_callback_observes_saved_command_turn(tmp_path):
await bot.run("/skill", session_key="sdk:command")
assert len(seen) == 1
snapshot = bot.sessions.export("sdk:command")
snapshot = (await bot.sessions.export("sdk:command"))
assert snapshot is not None
assert [message["role"] for message in snapshot.messages[-2:]] == [
"user",
@@ -1462,17 +1470,17 @@ async def test_sessions_ingest_imports_transcript_without_running_model(tmp_path
assert snapshot.messages[1]["source"] == "original-source"
bot._loop.process_direct.assert_not_called()
reloaded = bot.sessions.get("sdk:history")
reloaded = (await bot.sessions.get("sdk:history"))
assert reloaded is not None
assert reloaded.messages == snapshot.messages
await bot.aclose()
async with Nanobot.from_config(config_path, workspace=tmp_path) as restarted:
assert restarted.sessions.export("sdk:history") == snapshot
assert await restarted.sessions.export("sdk:history") == snapshot
@pytest.mark.asyncio
async def test_sessions_ingest_without_save_detaches_inputs_and_can_be_flushed(tmp_path):
async def test_sessions_ingest_detaches_inputs_and_is_immediately_durable(tmp_path):
config_path = _write_config(tmp_path)
metadata = {"import": {"dataset": "original"}}
messages = [{
@@ -1482,7 +1490,7 @@ async def test_sessions_ingest_without_save_detaches_inputs_and_can_be_flushed(t
}]
async with Nanobot.from_config(config_path, workspace=tmp_path) as bot:
snapshot = await bot.sessions.ingest(
"sdk:unsaved", iter(messages), metadata=metadata, save=False,
"sdk:imported", iter(messages), metadata=metadata,
)
metadata["import"]["dataset"] = "changed"
messages[0]["content"][0]["text"] = "changed"
@@ -1492,13 +1500,12 @@ async def test_sessions_ingest_without_save_detaches_inputs_and_can_be_flushed(t
assert snapshot.messages[0]["role"] == "user"
assert snapshot.messages[0]["content"] == [{"type": "text", "text": "hello"}]
assert snapshot.messages[0]["import_info"] == {"index": 1}
assert bot.sessions.get("sdk:unsaved") == snapshot
assert await bot.sessions.get("sdk:imported") == snapshot
async with Nanobot.from_config(config_path, workspace=tmp_path) as reader:
assert reader.sessions.export("sdk:unsaved") is None
assert bot.sessions.flush() == 1
assert await reader.sessions.export("sdk:imported") == snapshot
async with Nanobot.from_config(config_path, workspace=tmp_path) as restarted:
assert restarted.sessions.export("sdk:unsaved") == snapshot
assert await restarted.sessions.export("sdk:imported") == snapshot
@pytest.mark.asyncio
@@ -1518,7 +1525,7 @@ async def test_sessions_ingest_rejects_batch_without_session_changes(
key, [{"role": "user", "content": "original history"}],
metadata={"title": "Original", "import": {"dataset": "original"}},
)
before = bot.sessions.export(key)
before = await bot.sessions.export(key)
with pytest.raises(ValueError, match="role|content"):
await bot.sessions.ingest(
@@ -1527,12 +1534,11 @@ async def test_sessions_ingest_rejects_batch_without_session_changes(
metadata={"title": "Changed", "new_field": "must not leak"},
)
assert bot.sessions.get(key) == before
assert bot.sessions.export(key) == before
bot.sessions.flush()
assert await bot.sessions.get(key) == before
assert await bot.sessions.export(key) == before
async with Nanobot.from_config(config_path, workspace=tmp_path) as restarted:
assert restarted.sessions.export(key) == before
assert await restarted.sessions.export(key) == before
@pytest.mark.asyncio
@@ -1573,33 +1579,31 @@ async def test_session_helpers_get_list_export_clear_delete_flush(tmp_path):
await bot.sessions.ingest("sdk:first", [{"role": "user", "content": "hello"}])
listed = bot.sessions.list()
listed = (await bot.sessions.list())
assert listed
assert isinstance(listed[0], SessionInfo)
assert {row.key for row in listed} == {"sdk:first"}
exported = bot.sessions.export("sdk:first")
exported = (await bot.sessions.export("sdk:first"))
assert exported is not None
exported.messages[0]["content"] = "mutated copy"
assert bot.sessions.get("sdk:first").messages[0]["content"] == "hello"
assert (await bot.sessions.get("sdk:first")).messages[0]["content"] == "hello"
state_before_clear = bot._loop._file_state_store.for_session("sdk:first")
cleared = bot.sessions.clear("sdk:first")
cleared = (await bot.sessions.clear("sdk:first"))
assert cleared.messages == []
state_after_clear = bot._loop._file_state_store.for_session("sdk:first")
assert state_after_clear is not state_before_clear
assert bot.sessions.flush() >= 1
state_before_delete = state_after_clear
assert bot.sessions.delete("sdk:first") is True
assert (await bot.sessions.delete("sdk:first")) is True
assert bot._loop._file_state_store.for_session("sdk:first") is not state_before_delete
assert bot.sessions.get("sdk:first") is None
assert (await bot.sessions.get("sdk:first")) is None
def test_session_helpers_read_live_session_outside_strong_cache(tmp_path):
async def test_session_helpers_read_only_committed_state(tmp_path):
config_path = _write_config(tmp_path)
bot = Nanobot.from_config(config_path, workspace=tmp_path)
sessions = bot._loop.sessions
sessions._max_cached_sessions = 1
active = sessions.get_or_create("sdk:active")
active.add_message("user", "persisted")
sessions.save(active)
@@ -1607,13 +1611,12 @@ def test_session_helpers_read_live_session_outside_strong_cache(tmp_path):
sessions.save(sessions.get_or_create("sdk:other"))
active.add_message("assistant", "not saved yet")
visible = bot.sessions.get("sdk:active")
exported = bot.sessions.export("sdk:active")
visible = (await bot.sessions.get("sdk:active"))
exported = (await bot.sessions.export("sdk:active"))
assert visible is not None
assert exported is not None
assert [message["content"] for message in visible.messages] == [
"persisted",
"not saved yet",
]
assert exported.messages == visible.messages
@@ -1633,14 +1636,14 @@ async def test_session_export_and_restore_preserve_runtime_context(tmp_path):
**{RUNTIME_CONTEXT_HISTORY_META: marker},
)
bot._loop.sessions.save(source)
bot._loop.sessions._cache.pop("sdk:source")
bot._loop.sessions.invalidate("sdk:source")
public = bot.sessions.get("sdk:source")
public = (await bot.sessions.get("sdk:source"))
assert public is not None
assert public.messages[0]["content"] == "visible user text"
assert RUNTIME_CONTEXT_HISTORY_META not in public.messages[0]
exported = bot.sessions.export("sdk:source")
exported = (await bot.sessions.export("sdk:source"))
assert exported is not None
assert exported.messages[0]["content"] == content
assert exported.messages[0][RUNTIME_CONTEXT_HISTORY_META] == marker
@@ -1653,7 +1656,7 @@ async def test_session_export_and_restore_preserve_runtime_context(tmp_path):
restored = bot._loop.sessions.get_or_create("sdk:restored")
assert restored.get_history() == source.get_history()
with pytest.raises(ValueError, match="not empty"):
with pytest.raises(RuntimeError, match="not empty"):
await bot.sessions.restore(exported, session_key="sdk:restored")
@@ -1719,7 +1722,7 @@ async def test_runtime_helpers_expose_model_workspace_and_compact(tmp_path):
bot = Nanobot.from_config(config_path, workspace=tmp_path)
await bot.sessions.ingest("sdk:history", [{"role": "user", "content": "hello"}])
runtime = bot._loop.llm_runtime()
bot._loop.runtime_for_session = MagicMock(return_value=runtime) # type: ignore[method-assign]
bot._loop.runtime_for_session = AsyncMock(return_value=runtime) # type: ignore[method-assign]
compact_session = AsyncMock()
bot._loop.consolidator.compact_idle_session = compact_session