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

+18 -16
View File
@@ -141,12 +141,21 @@ def _make_dream_prompt_ctx(tmp_path, raw: str = "/dream-prompt", args: str = "")
return CommandContext(msg=msg, session=None, key=msg.session_key, raw=raw, args=args, loop=loop)
async def _run_dream_command(ctx: CommandContext) -> OutboundMessage:
before = asyncio.all_tasks()
immediate = await cmd_dream(ctx)
try:
await asyncio.gather(*(asyncio.all_tasks() - before))
finally:
await ctx.loop.sessions.state.aclose()
return immediate
@pytest.mark.asyncio
async def test_dream_no_history_explains_how_to_create_input(tmp_path) -> None:
ctx, bus = _make_dream_ctx(tmp_path)
immediate = await cmd_dream(ctx)
await asyncio.sleep(0)
immediate = await _run_dream_command(ctx)
assert immediate.content == "Dreaming..."
assert len(bus.outbound) == 1
@@ -185,8 +194,7 @@ async def test_dream_internal_run_silences_progress(tmp_path) -> None:
)
ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw="/dream", args="", loop=loop)
await cmd_dream(ctx)
await asyncio.sleep(0)
await _run_dream_command(ctx)
assert len(calls) == 1
assert callable(calls[0][1]["on_progress"])
@@ -243,8 +251,7 @@ def _build_runnable_dream(
async def test_dream_advances_cursor_when_diff_nonempty(tmp_path) -> None:
"""A completed run with a real file delta advances the cursor."""
ctx, store = _build_runnable_dream(tmp_path, initialized=True, content_diff="SOUL.md: +1 -0")
await cmd_dream(ctx)
await asyncio.sleep(0)
await _run_dream_command(ctx)
assert store._last_dream_cursor == 42
@@ -252,8 +259,7 @@ async def test_dream_advances_cursor_when_diff_nonempty(tmp_path) -> None:
async def test_dream_advances_cursor_on_completed_noop(tmp_path) -> None:
"""A completed no-op has processed the batch and must not repeat it."""
ctx, store = _build_runnable_dream(tmp_path, initialized=True, content_diff="")
await cmd_dream(ctx)
await asyncio.sleep(0)
await _run_dream_command(ctx)
assert store._last_dream_cursor == 42
assert "no memory changes" in ctx.loop.bus.outbound[0].content
@@ -267,8 +273,7 @@ async def test_dream_keeps_cursor_when_incomplete_with_diff(tmp_path) -> None:
content_diff="SOUL.md: +1 -0",
stop_reason="length",
)
await cmd_dream(ctx)
await asyncio.sleep(0)
await _run_dream_command(ctx)
assert store._last_dream_cursor == 5
assert "did not complete" in ctx.loop.bus.outbound[0].content
@@ -282,8 +287,7 @@ async def test_dream_advances_cursor_when_completed_after_tool_error(tmp_path) -
content_diff="",
tool_error=True,
)
await cmd_dream(ctx)
await asyncio.sleep(0)
await _run_dream_command(ctx)
assert store._last_dream_cursor == 42
assert "no memory changes" in ctx.loop.bus.outbound[0].content
@@ -322,8 +326,7 @@ async def test_dream_noop_batch_unlocks_following_history(tmp_path) -> None:
)
ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw="/dream", args="", loop=loop)
await cmd_dream(ctx)
await asyncio.sleep(0)
await _run_dream_command(ctx)
assert len(processed_prompts) == 1
assert "entry-20" in processed_prompts[0]
@@ -343,8 +346,7 @@ async def test_dream_non_git_falls_back_to_completion_gate(tmp_path) -> None:
ctx, store = _build_runnable_dream(
tmp_path, initialized=False, content_diff="", stop_reason="completed",
)
await cmd_dream(ctx)
await asyncio.sleep(0)
await _run_dream_command(ctx)
assert store._last_dream_cursor == 42 # advanced via completion fallback
+72 -13
View File
@@ -1,6 +1,8 @@
"""Manual context compaction command behavior."""
import asyncio
import sqlite3
import threading
from datetime import datetime, timedelta
from unittest.mock import AsyncMock, MagicMock
@@ -45,6 +47,61 @@ async def loop(tmp_path):
await loop.aclose()
async def test_compact_session_io_runs_outside_event_loop(loop, monkeypatch) -> None:
key = "cli:test"
session = loop.sessions.get_or_create(key)
session.add_message("user", "summarize this conversation")
session.provider_state = ProviderConversationState(
kind="openai_responses", provider="openai:test", model="test-model",
version=1, payload={"items": []},
)
loop.sessions.save(session)
event_loop_thread = threading.get_ident()
calls = []
def observe(name, operation):
def checked(*args, **kwargs):
assert threading.get_ident() != event_loop_thread
calls.append(name)
return operation(*args, **kwargs)
return checked
for name in ("load", "save"):
monkeypatch.setattr(loop.sessions._store, name, observe(name, getattr(loop.sessions._store, name)))
msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="/compact")
await loop.commands.dispatch(CommandContext(
msg=msg, session=None, key=key, raw="/compact", loop=loop,
))
assert "load" in calls and "save" in calls
monkeypatch.undo()
assert loop.sessions.get_or_create(key).provider_state is None
async def test_compact_lock_contention_keeps_heartbeat_running(loop) -> None:
key = "cli:test"
session = loop.sessions.get_or_create(key)
session.add_message("user", "summarize this conversation")
loop.sessions.save(session)
msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="/compact")
blocker = sqlite3.connect(loop.sessions._store.path)
blocker.execute("BEGIN IMMEDIATE")
task = asyncio.create_task(loop.commands.dispatch(CommandContext(
msg=msg, session=session, key=key, raw="/compact", loop=loop,
)))
try:
for _ in range(5):
await asyncio.sleep(0.01)
assert not task.done(), "compaction must wait for storage without blocking the loop"
finally:
blocker.rollback()
blocker.close()
await asyncio.wait_for(task, timeout=2)
@pytest.mark.asyncio
@pytest.mark.parametrize("command", ["/compact", " /COMPACT@nanobot ", "/summarize"])
async def test_compact_emits_one_lifecycle_and_keeps_the_session(loop, command) -> None:
@@ -165,6 +222,7 @@ async def test_empty_compact_finishes_silently_and_does_not_schedule_idle_archiv
if legacy_commands:
session.add_message("user", "/compact", _command=True)
session.add_message("assistant", "Nothing to compact.", _command=True)
session.updated_at = datetime.now() - timedelta(minutes=30)
loop.sessions.save(session)
completions = []
loop.bus.subscribe(completions.append, TurnCompleted)
@@ -183,11 +241,10 @@ async def test_empty_compact_finishes_silently_and_does_not_schedule_idle_archiv
assert reloaded.last_archived == 2
assert loop.consolidator.store.read_unprocessed_history(0) == []
reloaded.updated_at = datetime.now() - timedelta(minutes=30)
loop.sessions.save(reloaded)
loop.auto_compact._ttl = 1
assert loop.auto_compact._is_expired(reloaded.updated_at)
schedule = MagicMock()
loop.auto_compact.check_expired(schedule, loop.runtime_for_session)
await loop.auto_compact.check_expired(schedule, loop.runtime_for_session)
schedule.assert_not_called()
@@ -267,17 +324,18 @@ async def test_compact_is_a_fifo_barrier_during_an_active_turn(loop, command_tex
channel="cli", sender_id="u", chat_id="test", content="initial question",
)))
try:
await asyncio.wait_for(started.wait(), timeout=5)
loop._enqueue_session_message(InboundMessage(
# Include cold context initialization and durable commits on slower CI disks.
await asyncio.wait_for(started.wait(), timeout=30)
(await loop._enqueue_session_message(InboundMessage(
channel="cli", sender_id="u", chat_id="test", content="before compaction",
))
)))
command = InboundMessage(channel="cli", sender_id="u", chat_id="test", content=command_text)
await loop._dispatch_command_inline(command, key, command.content, loop.commands.dispatch)
loop._enqueue_session_message(InboundMessage(
(await loop._enqueue_session_message(InboundMessage(
channel="cli", sender_id="u", chat_id="test", content="after compaction",
))
)))
release.set()
await asyncio.wait_for(task, timeout=5)
await asyncio.wait_for(task, timeout=30)
finally:
release.set()
if not task.done():
@@ -308,9 +366,9 @@ async def test_stop_completes_compact_queued_behind_an_active_turn(loop, command
loop.provider.chat_stream_with_retry = chat
completions = []
loop.bus.subscribe(completions.append, TurnCompleted)
loop._enqueue_session_message(InboundMessage(
(await loop._enqueue_session_message(InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="question",
))
)))
task = next(iter(loop._active_tasks[key]))
await asyncio.wait_for(started.wait(), timeout=5)
command = InboundMessage(
@@ -348,7 +406,7 @@ async def test_stop_finishes_inflight_compaction_as_cancelled(loop, command) ->
channel="websocket", sender_id="user", chat_id="test", content=command,
metadata={"webui_turn_id": "compact-turn"},
)
loop._enqueue_session_message(msg)
(await loop._enqueue_session_message(msg))
task = next(iter(loop._active_tasks[key]))
await asyncio.wait_for(entered.wait(), timeout=5)
@@ -402,9 +460,10 @@ async def test_idle_and_manual_compact_share_persisted_checkpoint(loop) -> None:
assert reloaded.get_history() == []
assert reloaded.metadata["_last_summary"]["text"] == "Portable checkpoint."
reloaded = await loop.sessions.state.get(key)
reloaded.add_message("user", "next question")
reloaded.add_message("assistant", "next answer")
loop.sessions.save(reloaded)
await loop.sessions.state.finish_turn(reloaded)
await loop.consolidator.compact_idle_session(key, runtime=runtime)
loop.sessions.invalidate(key)
reloaded = loop.sessions.get_or_create(key)
+3 -2
View File
@@ -163,6 +163,7 @@ async def test_model_command_reports_provider_configuration_errors(tmp_path) ->
switched = await cmd_model(_ctx(loop, "/model fast", args="fast"))
session = loop.sessions.get_or_create("cli:direct")
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "fast"
loop.sessions.save(session)
status = await cmd_model(_ctx(loop, "/model"))
assert "Could not switch model preset" in switched.content
@@ -264,8 +265,7 @@ async def test_goal_command_preserves_task_and_visible_command(tmp_path, with_se
task = "检查 /tmp/project\n保留现有文件。"
command = f"/goal {task}"
ctx = _ctx_session(loop, command, args=task)
if not with_session:
ctx.session = None
ctx.session = await loop.sessions.state.get(ctx.key) if with_session else None
out = await cmd_goal(ctx)
assert isinstance(out, InboundMessage)
assert ctx.msg.content == command
@@ -287,6 +287,7 @@ async def test_goal_command_registered_on_router(tmp_path) -> None:
register_builtin_commands(router)
loop = _make_loop(tmp_path)
ctx = _ctx_session(loop, "/goal ship it", args="ship it")
ctx.session = await loop.sessions.state.get(ctx.key)
out = await router.dispatch(ctx)
assert isinstance(out, InboundMessage)
assert out.content == "ship it"
+4 -3
View File
@@ -110,8 +110,8 @@ class TestMidTurnCommandDispatchedDirectly:
def fake_loop(self) -> MagicMock:
loop = MagicMock()
loop.sessions = MagicMock()
loop.sessions.get_or_create = MagicMock(return_value=MagicMock(
messages=[], last_archived=0, clear=MagicMock(),
loop.sessions.state.get = AsyncMock(return_value=MagicMock(
key="test:chat1", messages=[], last_archived=0, clear=MagicMock(),
))
loop.sessions.save = MagicMock()
loop.sessions.invalidate = MagicMock()
@@ -137,10 +137,11 @@ class TestMidTurnCommandDispatchedDirectly:
msg=fake_msg, session=None,
key="test:chat1", raw="/new", loop=fake_loop,
)
fake_loop.sessions.state.reset = AsyncMock()
result = await router.dispatch(ctx)
assert result is not None
assert "New session" in result.content
fake_loop.sessions.get_or_create.assert_called_once_with("test:chat1")
fake_loop.sessions.state.reset.assert_awaited_once_with("test:chat1")
@pytest.mark.asyncio
async def test_help_dispatched_with_session_none(
+1 -1
View File
@@ -64,7 +64,7 @@ async def test_user_shell_uses_exec_tool_with_workspace_scope(
scope = SimpleNamespace(project_path=tmp_path)
loop = MagicMock()
loop.tools.get.return_value = tool
loop.sessions.get_or_create.return_value = session
loop.sessions.state.get = AsyncMock(return_value=session)
loop.workspace_scopes.for_turn.return_value = scope
ctx = _context(loop, trusted=True)
if context_session: