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

+109 -20
View File
@@ -1,6 +1,7 @@
"""Independent turns and internal controls retain their session inbox semantics."""
import asyncio
import threading
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -23,7 +24,6 @@ from nanobot.session.recovery import (
PENDING_FOLLOWUPS_KEY,
REQUEST_ORIGIN_METADATA_KEY,
pending_followups,
record_pending_followup,
)
from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META
from nanobot.webui.recovery import RecoveryCoordinator
@@ -46,6 +46,95 @@ async def loop(tmp_path):
await agent.aclose()
@pytest.mark.parametrize("rejection", ["stop", "followup", "replaced-followup", "idle"])
async def test_rejected_input_does_not_stop_other_sessions(loop, monkeypatch, rejection):
state = loop.sessions.state
session = await state.get("websocket:busy")
model_started, release_model = asyncio.Event(), asyncio.Event()
readers_started, release_readers = threading.Event(), threading.Event()
idle_checked = asyncio.Event()
active_turn = rejection in {"followup", "replaced-followup"}
readers = []
async def chat(**kwargs):
if active_turn and not model_started.is_set():
model_started.set()
await release_model.wait()
return LLMResponse(content="still responsive")
async def reply(chat_id):
async with asyncio.timeout(5):
while True:
message = await loop.bus.consume_outbound()
if message.chat_id == chat_id and message.event is None:
return message
original_list = loop.sessions._store.list_metadata
def blocked_list():
readers_started.set()
assert release_readers.wait(5)
return original_list()
loop.provider.chat_stream_with_retry = chat
if rejection == "idle":
original_check = loop.auto_compact.check_expired
async def observed_check(*args, **kwargs):
try:
await original_check(*args, **kwargs)
finally:
idle_checked.set()
monkeypatch.setattr(loop.auto_compact, "check_expired", observed_check)
loop._next_idle_compact_check_at = 0
run_task = asyncio.create_task(loop.run())
try:
if active_turn:
await loop.bus.publish_inbound(InboundMessage(
channel="websocket", sender_id="u", chat_id="busy", content="first",
metadata={"webui": True}, session_generation=session.generation,
))
await asyncio.wait_for(model_started.wait(), timeout=3)
if rejection == "replaced-followup":
await state.reset(session.key)
else:
monkeypatch.setattr(loop.sessions._store, "list_metadata", blocked_list)
readers = [asyncio.create_task(state.list_metadata()) for _ in range(64)]
assert await asyncio.to_thread(readers_started.wait, 2)
if rejection == "idle":
await asyncio.wait_for(idle_checked.wait(), timeout=3)
else:
rejected = InboundMessage(
channel="telegram" if rejection == "stop" else "websocket",
sender_id="u", chat_id="busy",
content="/stop" if rejection == "stop" else "rejected follow-up",
metadata={"webui": True}, session_generation=session.generation,
)
await loop.bus.publish_inbound(rejected)
assert (await reply("busy")).content == "Sorry, I encountered an error."
assert not run_task.done()
release_readers.set()
await asyncio.gather(*readers)
await loop.bus.publish_inbound(InboundMessage(
channel="telegram", sender_id="u", chat_id="other", content="hello",
))
assert (await reply("other")).content == "still responsive"
if active_turn:
assert not release_model.is_set()
assert loop._pending_queues[session.key].empty()
saved = await state.read(session.key)
assert pending_followups(saved) == []
finally:
release_readers.set()
await asyncio.gather(*readers, return_exceptions=True)
loop.stop()
run_task.cancel()
await asyncio.gather(run_task, return_exceptions=True)
def _automation_message(kind: str, name: str) -> InboundMessage:
metadata = (
{
@@ -83,9 +172,6 @@ async def test_automation_turn_is_deferred_while_session_active(loop, kind):
async with asyncio.timeout(3):
while not coordinator.deferred_queues.get(key):
await asyncio.sleep(0)
loop.stop()
await asyncio.wait_for(run_task, timeout=3)
assert pending.empty()
assert loop._active_tasks == {}
assert coordinator.deferred_queues[key] == [msg]
@@ -106,7 +192,7 @@ async def test_automation_turn_is_deferred_while_session_active(loop, kind):
@pytest.mark.parametrize("kind", ["cron", "local_trigger"])
async def test_submitted_automation_reports_pending_until_completed(loop, kind):
coordinator = loop._cron_turns if kind == "cron" else loop._local_trigger_turns
coordinator._enqueue = MagicMock()
coordinator._enqueue = AsyncMock()
submit = loop.submit_cron_turn if kind == "cron" else loop.submit_local_trigger_turn
pending_ids = (
loop.pending_cron_job_ids_for_session
@@ -256,15 +342,15 @@ async def test_stopped_followups_are_not_recovered_but_shutdown_preserves_them(
loop.provider.chat_stream_with_retry = chat
key = "websocket:test"
loop._enqueue_session_message(InboundMessage(
(await loop._enqueue_session_message(InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="first",
metadata={"webui": True},
))
)))
await asyncio.wait_for(started.wait(), timeout=3)
loop._enqueue_session_message(InboundMessage(
(await loop._enqueue_session_message(InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="cancel me",
metadata={"webui": True},
))
)))
if not followup_still_queued:
consumed = loop._pending_queues[key].get_nowait()
@@ -300,16 +386,15 @@ async def test_stopped_followups_are_not_recovered_but_shutdown_preserves_them(
async def test_cancel_preserves_followups_accepted_after_cancellation_started(loop):
key = "websocket:test"
session = loop.sessions.get_or_create(key)
session = await loop.sessions.state.get(key)
def journal(content):
record_pending_followup(session, InboundMessage(
async def journal(content):
await loop.sessions.state.queue_followup(key, InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content=content,
metadata={"webui": True},
metadata={"webui": True}, session_generation=session.generation,
))
loop.sessions.save(session)
journal("old followup")
await journal("old followup")
started = asyncio.Event()
cancelling = asyncio.Event()
release = asyncio.Event()
@@ -328,7 +413,7 @@ async def test_cancel_preserves_followups_accepted_after_cancellation_started(lo
stop = asyncio.create_task(loop._cancel_active_tasks(key))
try:
await asyncio.wait_for(cancelling.wait(), timeout=3)
journal("new followup")
await journal("new followup")
finally:
release.set()
await stop
@@ -422,7 +507,7 @@ async def test_ingress_sources_share_one_session_worker(loop, bus_running):
if bus_running:
await loop.bus.publish_inbound(first)
else:
loop._enqueue_session_message(first)
(await loop._enqueue_session_message(first))
await asyncio.wait_for(started.wait(), timeout=3)
cron = asyncio.create_task(loop.submit_cron_turn(_automation_message("cron", "cron")))
trigger = asyncio.create_task(loop.submit_local_trigger_turn(
@@ -437,7 +522,7 @@ async def test_ingress_sources_share_one_session_worker(loop, bus_running):
while loop._pending_queues[key].empty():
await asyncio.sleep(0)
else:
loop._enqueue_session_message(second)
(await loop._enqueue_session_message(second))
compact = InboundMessage(channel="websocket", sender_id="u", chat_id="test", content="/compact")
await loop._dispatch_command_inline(compact, key, compact.content, loop.commands.dispatch)
assert len(loop._active_tasks[key]) == 1
@@ -528,7 +613,9 @@ async def test_goal_continuation_after_followup_keeps_control_identity(loop, com
while loop._pending_queues["cli:test"].empty():
await asyncio.sleep(0)
elif complete_on_followup or len(requests) == 3:
session.metadata[GOAL_STATE_KEY]["status"] = "complete"
await loop.sessions.state.update_metadata(session.key, {
GOAL_STATE_KEY: {"status": "complete", "objective": "Finish the long goal"},
})
return LLMResponse(content="done")
return LLMResponse(
content="working", finish_reason="tool_calls",
@@ -587,7 +674,9 @@ async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop
persisted = SessionManager(loop.workspace).get_or_create(key)
persisted_origin = persisted.metadata[REQUEST_ORIGIN_METADATA_KEY]
await loop.tools.get("message").execute(content="Continuation reply")
session.metadata[GOAL_STATE_KEY]["status"] = "complete"
await loop.sessions.state.mutate_metadata(
key, lambda metadata: metadata[GOAL_STATE_KEY].update(status="complete"),
)
return LLMResponse(content="done")
return LLMResponse(content="working", finish_reason="tool_calls", tool_calls=[
ToolCallRequest(id=f"call-{len(requests)}", name="noop", arguments={}),