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

+104
View File
@@ -0,0 +1,104 @@
"""Message tools preserve target identity through gateway delivery recording."""
from functools import partial
import pytest
from nanobot.agent.tools.context import RequestContext, request_context
from nanobot.agent.tools.message import MessageTool
from nanobot.bus.queue import MessageBus
from nanobot.cli.gateway_runtime import _deliver_to_channel
from nanobot.session.manager import SessionManager
@pytest.fixture
async def delivery(tmp_path):
workspace = tmp_path / "workspace"
workspace.mkdir()
(workspace / "attachment.txt").write_text("attachment", encoding="utf-8")
sessions = SessionManager(workspace, sessions_root=tmp_path / "sessions")
bus = MessageBus()
tool = MessageTool(
send_callback=partial(_deliver_to_channel, bus=bus, session_manager=sessions),
workspace=workspace,
)
try:
yield sessions, bus, tool
finally:
await sessions.state.aclose()
@pytest.mark.parametrize("channel,chat_id,key,metadata", [
("slack", "C123", "slack:C123:111.222", {"slack": {"thread_ts": "111.222"}}),
("telegram", "-100123", "telegram:-100123:topic:42", {"message_thread_id": 42}),
])
async def test_thread_media_is_recorded_in_its_admitted_session(delivery, channel, chat_id, key, metadata):
sessions, bus, tool = delivery
session = await sessions.state.get(key)
coarse_key = f"{channel}:{chat_id}"
await sessions.state.get(coarse_key)
with request_context(RequestContext(
channel, chat_id, session_key=key, session_generation=session.generation, metadata=metadata,
)):
result = await tool.execute(content="caption", media=["attachment.txt"])
assert result == f"Message sent to {channel}:{chat_id} with 1 attachments"
sent = bus.outbound.get_nowait()
assert sent.metadata == metadata
assert len(sent.media) == 1
assert [message["content"] for message in (await sessions.state.read(key)).messages] == ["caption"]
assert (await sessions.state.read(coarse_key)).messages == []
async def test_first_cross_target_media_creates_its_own_session(delivery):
sessions, bus, tool = delivery
origin = await sessions.state.get("websocket:origin")
with request_context(RequestContext(
"websocket", "origin", session_key=origin.key, session_generation=origin.generation,
)):
result = await tool.execute(
content="caption", channel="email", chat_id="fresh@example.invalid",
media=["attachment.txt"],
)
assert result == "Message sent to email:fresh@example.invalid with 1 attachments"
sent = bus.outbound.get_nowait()
assert sent.metadata == {}
target = await sessions.state.read("email:fresh@example.invalid")
assert [message["content"] for message in target.messages] == ["caption"]
assert (await sessions.state.read(origin.key)).messages == []
@pytest.mark.parametrize("operation", ["reset", "delete"])
async def test_old_turn_media_cannot_recreate_or_write_a_replaced_target(delivery, operation):
sessions, bus, tool = delivery
session = await sessions.state.get("slack:C123:111.222")
await getattr(sessions.state, operation)(session.key)
with request_context(RequestContext(
"slack", "C123", session_key=session.key, session_generation=session.generation,
)):
result = await tool.execute(content="late caption", media=["attachment.txt"])
assert result.startswith("Error sending message:")
assert bus.outbound.empty()
target = await sessions.state.read(session.key)
assert target is None or target.messages == []
assert await sessions.state.read("slack:C123") is None
async def test_cross_target_reset_after_admission_revokes_media(delivery, monkeypatch):
sessions, bus, tool = delivery
original = sessions.state.record_delivery
async def reset_before_recording(key, *args, **kwargs):
await sessions.state.reset(key)
await original(key, *args, **kwargs)
monkeypatch.setattr(sessions.state, "record_delivery", reset_before_recording)
result = await tool.execute(
content="late caption", channel="email", chat_id="fresh@example.invalid",
media=["attachment.txt"],
)
assert "replaced session" in result
assert bus.outbound.empty()
assert (await sessions.state.read("email:fresh@example.invalid")).messages == []
+17 -15
View File
@@ -124,8 +124,16 @@ class _EmptyGatewaySessionManager:
def list_sessions(self) -> list[dict[str, object]]:
return []
def flush_all(self) -> int:
return 0
def list_session_metadata(self) -> list[dict[str, object]]:
return []
@property
def state(self):
return SimpleNamespace(
list_sessions=AsyncMock(return_value=[]),
record_delivery=AsyncMock(),
aclose=AsyncMock(),
)
def test_gateway_signal_handler_first_signal_stops_and_second_forces() -> None:
@@ -2157,7 +2165,7 @@ def test_heartbeat_empty_response_is_not_evaluated(
bus.publish_outbound = AsyncMock()
seen: dict[str, object] = {}
class _FakeSessionManager:
class _FakeSessionManager(_EmptyGatewaySessionManager):
def __init__(self, _workspace: Path) -> None:
pass
@@ -3197,7 +3205,7 @@ def test_gateway_unbound_agent_cron_is_skipped(
def add_message(self, role: str, content: str, **kwargs) -> None:
self.messages.append({"role": role, "content": content, **kwargs})
class _FakeSessionManager:
class _FakeSessionManager(_EmptyGatewaySessionManager):
def __init__(self, _workspace: Path) -> None:
self.session = _FakeSession()
seen["session_manager"] = self
@@ -3318,7 +3326,7 @@ def test_gateway_bound_cron_runs_as_session_turn(
)
monkeypatch.setattr("nanobot.bus.queue.MessageBus", lambda: bus)
class _FakeSessionManager:
class _FakeSessionManager(_EmptyGatewaySessionManager):
def __init__(self, _workspace: Path) -> None:
pass
@@ -3533,7 +3541,7 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
class _FakeContext:
memory = _FakeMemory()
class _FakeSessionManager:
class _FakeSessionManager(_EmptyGatewaySessionManager):
def flush_all(self) -> int:
return 0
@@ -3833,7 +3841,7 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(
config.gateway.port = 18791
captured: dict[str, object] = {}
class _FakeSessionManager:
class _FakeSessionManager(_EmptyGatewaySessionManager):
def flush_all(self) -> int:
return 0
@@ -4036,7 +4044,7 @@ def test_gateway_agent_task_owns_initial_mcp_provider_close(
config.gateway.port = 18791
seen: dict[str, object] = {}
class _FakeSessionManager:
class _FakeSessionManager(_EmptyGatewaySessionManager):
def flush_all(self) -> int:
return 0
@@ -4190,11 +4198,6 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
channel_finished = asyncio.Event()
channels_stopping = asyncio.Event()
class _FakeSessionManager:
def flush_all(self) -> int:
seen["sessions_flushed"] = True
return 0
class _FakeAgentLoop(_GatewayAgentContractStub):
@classmethod
def from_config(cls, config, bus=None, **extra):
@@ -4203,7 +4206,7 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
def __init__(self, **_kwargs) -> None:
self.model = "test-model"
self.provider = object()
self.sessions = _FakeSessionManager()
self.sessions = _EmptyGatewaySessionManager()
self.runtime_resolver = MagicMock()
def llm_runtime(self) -> None:
@@ -4326,7 +4329,6 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
assert seen["channel_task_cleaned_up"] is True
assert seen["channels_stopped"] is True
assert seen["cron_stopped"] is True
assert seen["sessions_flushed"] is True
assert seen["shutdown_handlers_restored"] is True
if shutdown_signal is not None:
assert seen["graceful_shutdown_requested"] is True
+14 -9
View File
@@ -14,6 +14,8 @@ import pytest
from nanobot.agent.context import TranscriptInput
from nanobot.bus.events import InboundMessage
from nanobot.providers.base import LLMResponse, LLMUsage
from nanobot.session.manager import Session
from nanobot.session.state import SessionState
def _make_loop():
@@ -28,8 +30,11 @@ def _make_loop():
workspace.__truediv__ = MagicMock(return_value=MagicMock())
with patch("nanobot.agent.loop.ContextBuilder"), \
patch("nanobot.agent.loop.SessionManager"), \
patch("nanobot.agent.loop.SessionManager") as mock_sessions, \
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
mock_sessions.return_value.state = MagicMock(spec=SessionState)
mock_sessions.return_value.state.get = AsyncMock(side_effect=lambda key: Session(key))
mock_sessions.return_value.state.peek.return_value = None
mock_sub_mgr.return_value.close = AsyncMock()
loop = AgentLoop(bus=bus, provider=provider, workspace=workspace)
return loop, bus
@@ -240,7 +245,7 @@ class TestRestartCommand:
session.metadata = {
"_last_usage": LLMUsage.reported(input_tokens=0, output_tokens=0).to_dict()
}
loop.sessions.get_or_create.return_value = session
loop.sessions.state.get = AsyncMock(return_value=session)
loop._start_time = time.time() - 125
loop.consolidator.estimate_session_prompt_tokens = MagicMock(
return_value=(20500, "tiktoken")
@@ -277,7 +282,7 @@ class TestRestartCommand:
loop, _bus = _make_loop()
session = MagicMock()
session.get_history.return_value = [{"role": "user"}]
loop.sessions.get_or_create.return_value = session
loop.sessions.state.get = AsyncMock(return_value=session)
loop.consolidator.estimate_session_prompt_tokens = MagicMock(
return_value=(1000, "tiktoken")
)
@@ -332,7 +337,7 @@ class TestRestartCommand:
session.metadata = {
"_last_usage": LLMUsage.reported(input_tokens=1200, output_tokens=34).to_dict()
}
loop.sessions.get_or_create.return_value = session
loop.sessions.state.get = AsyncMock(return_value=session)
loop.consolidator.estimate_session_prompt_tokens = MagicMock(
return_value=(0, "none")
)
@@ -358,7 +363,7 @@ class TestRestartCommand:
{"role": "user", "content": "How are you?"},
{"role": "assistant", "content": "I am doing well."},
]
loop.sessions.get_or_create.return_value = session
loop.sessions.state.get = AsyncMock(return_value=session)
msg = InboundMessage(channel="telegram", sender_id="u1", chat_id="c1", content="/history")
response = await loop._process_message(msg)
@@ -376,7 +381,7 @@ class TestRestartCommand:
session.get_history.return_value = [
{"role": "user", "content": f"message {i}"} for i in range(20)
]
loop.sessions.get_or_create.return_value = session
loop.sessions.state.get = AsyncMock(return_value=session)
msg = InboundMessage(channel="telegram", sender_id="u1", chat_id="c1", content="/history 3")
response = await loop._process_message(msg)
@@ -400,7 +405,7 @@ class TestRestartCommand:
},
*({"role": "assistant", "content": f"reply {i}"} for i in range(60)),
]
loop.sessions.get_or_create.return_value = session
loop.sessions.state.get = AsyncMock(return_value=session)
msg = InboundMessage(channel="telegram", sender_id="u1", chat_id="c1", content="/history 999")
response = await loop._process_message(msg)
@@ -426,7 +431,7 @@ class TestRestartCommand:
loop, _bus = _make_loop()
session = MagicMock()
session.get_history.return_value = []
loop.sessions.get_or_create.return_value = session
loop.sessions.state.get = AsyncMock(return_value=session)
msg = InboundMessage(channel="telegram", sender_id="u1", chat_id="c1", content="/history")
response = await loop._process_message(msg)
@@ -439,7 +444,7 @@ class TestRestartCommand:
loop, _bus = _make_loop()
session = MagicMock()
session.get_history.return_value = []
loop.sessions.get_or_create.return_value = session
loop.sessions.state.get = AsyncMock(return_value=session)
loop.subagents.get_running_count.return_value = 0
loop.subagents.get_running_count_by_session.return_value = 0
-31
View File
@@ -1,31 +0,0 @@
from pathlib import Path
from typer.testing import CliRunner
from nanobot.cli import commands
from nanobot.config.loader import load_config
from nanobot.session.manager import SessionManager
def test_sessions_restore_workspace_command_prepares_downgrade(
tmp_path: Path,
monkeypatch,
) -> None:
workspace = tmp_path / "workspace"
config_path = tmp_path / "instance" / "config.json"
config = load_config(config_path)
config.agents.defaults.workspace = str(workspace)
manager = SessionManager(workspace, sessions_root=config_path.parent / "sessions")
session = manager.get_or_create("cli:rollback")
session.add_message("user", "restore-me")
manager.save(session, fsync=True)
monkeypatch.setattr(commands, "_load_runtime_config", lambda *_args: config)
result = CliRunner().invoke(commands.app, ["sessions", "restore-workspace"])
assert result.exit_code == 0, result.output
assert "Restored 1 session file(s)" in result.output
restored = workspace / "sessions" / manager._get_session_path(session.key).name
assert restored.exists()
assert "restore-me" in restored.read_text(encoding="utf-8")
assert manager._get_session_path(session.key).exists()