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

+15 -8
View File
@@ -28,7 +28,7 @@ from nanobot.bus.runtime_events import TurnRunStatusChanged
from nanobot.config import Config
from nanobot.nanobot import Nanobot
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
from nanobot.session.manager import SessionManager
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, SessionManager
from nanobot.session.webui_turns import WebuiTurnRoutePolicy
from nanobot.utils.llm_runtime import LLMRuntime
@@ -101,7 +101,7 @@ async def test_sdk_ephemeral_delegation_never_persists_on_later_flush(
if existing_parent:
parent.add_message("user", "Earlier durable question")
loop.sessions.save(parent)
before = {path.name: path.read_bytes() for path in loop.sessions.sessions_dir.glob("*.jsonl")}
before = loop.sessions.read_session_file(key)
secret = "private-delegation-marker"
source = loop.workspace / f"{secret}.txt"
source.write_text(secret * 1000, encoding="utf-8")
@@ -138,19 +138,18 @@ async def test_sdk_ephemeral_delegation_never_persists_on_later_flush(
assert result.content == f"Parent conclusion: {secret}"
assert all(ctx is not None and not ctx.log_content and not ctx.persist_session for ctx in requests)
assert secret not in "\n".join(logs)
assert {path.name: path.read_bytes() for path in loop.sessions.sessions_dir.glob("*.jsonl")} == before
assert loop.sessions.read_session_file(key) == before
assert not list(loop.sessions.sessions_dir.glob("*.checkpoint.json"))
assert not (loop.workspace / ".nanobot" / "tool-results").exists()
assert loop.bus.inbound_size == 0
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Durable answer"))
await bot.run("Durable follow-up", session_key=key)
bot.sessions.flush()
saved = "\n".join(path.read_text() for path in loop.sessions.sessions_dir.glob("*.jsonl"))
saved = json.dumps(loop.sessions.read_session_file(key))
assert "Durable answer" in saved
assert ("Earlier durable question" in saved) is existing_parent
assert secret not in saved
assert len(list(loop.sessions.sessions_dir.glob("*.jsonl"))) == 1
assert [row["key"] for row in loop.sessions.list_sessions()] == [key]
finally:
loop.stop()
await asyncio.wait_for(consumer, timeout=2)
@@ -181,7 +180,10 @@ async def test_child_origin_uses_the_channel_turn_identity(loop_factory):
@pytest.mark.asyncio
async def test_default_loop_keeps_slack_thread_for_late_subagent_result(tmp_path, monkeypatch):
@pytest.mark.parametrize("cache_invalidation", ["handles", "eviction"])
async def test_default_loop_keeps_slack_thread_for_late_subagent_result(
tmp_path, monkeypatch, cache_invalidation,
):
monkeypatch.setattr("nanobot.agent.loop._SUBAGENT_TERMINAL_WAIT_SECONDS", 0.01)
child_started, release_child, parent_idle = (asyncio.Event() for _ in range(3))
@@ -245,6 +247,11 @@ async def test_default_loop_keeps_slack_thread_for_late_subagent_result(tmp_path
saved = SessionManager(workspace, sessions_root=sessions_root).get_existing(session_key)
assert saved is not None
saved_route = saved.metadata["_compaction_route"]
if cache_invalidation == "handles":
await sessions.state.ensure_session_handles()
else:
for i in range(SESSION_CACHE_MAX_SIZE + 1):
await sessions.state.get_header(f"telegram:other-{i}")
release_child.set()
late_reply = await next_reply("Late follow-up")
@@ -265,7 +272,7 @@ async def test_owner_canonical_fallback_and_absent_context(tmp_path):
manager, _, ctx = setup(tmp_path)
manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="private"))
task_id = await spawn(manager, ctx)
receipt = manager.send(task_id, "owner", "follow-up")
receipt = await manager.send(task_id, "owner", "follow-up")
snapshot = manager.statuses_for_session("owner")[task_id]
snapshot.state = "cancelled"
snapshot.owner = "other"