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:
1 parent
33ff520d12
commit
8f6a5594fb
144 files changed
+8293
-4912
No files matched your search
@@ -161,12 +161,12 @@ def test_agent_loop_llm_runtime_reflects_current_provider_and_model(tmp_path: Pa
|
||||
assert runtime.model == "next-model"
|
||||
|
||||
|
||||
def test_persist_cron_turn_uses_distinct_history_marker(tmp_path: Path) -> None:
|
||||
async def test_persist_cron_turn_uses_distinct_history_marker(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = loop.sessions.get_or_create("websocket:auto")
|
||||
session = await loop.sessions.state.get("websocket:auto")
|
||||
prompt_ref = {"id": "cron.agent_turn.reminder", "version": 1, "sha256": "abc"}
|
||||
|
||||
persisted = loop._persist_user_message_early(
|
||||
persisted = await loop._persist_user_message_early(
|
||||
InboundMessage(
|
||||
channel="websocket",
|
||||
sender_id="cron",
|
||||
@@ -203,9 +203,9 @@ def test_persist_cron_turn_uses_distinct_history_marker(tmp_path: Path) -> None:
|
||||
assert message["cron_prompt_ref"] == prompt_ref
|
||||
|
||||
|
||||
def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> None:
|
||||
async def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = loop.sessions.get_or_create("websocket:chat")
|
||||
session = await loop.sessions.state.get("websocket:chat")
|
||||
session.metadata[PENDING_FOLLOWUPS_KEY] = [
|
||||
{
|
||||
"id": "followup-1",
|
||||
@@ -217,7 +217,7 @@ def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> N
|
||||
}
|
||||
]
|
||||
|
||||
persisted = loop._persist_user_message_early(
|
||||
persisted = await loop._persist_user_message_early(
|
||||
InboundMessage(
|
||||
channel="websocket",
|
||||
sender_id="user",
|
||||
@@ -232,11 +232,11 @@ def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> N
|
||||
assert PENDING_FOLLOWUPS_KEY not in session.metadata
|
||||
|
||||
|
||||
def test_persist_local_trigger_turn_uses_hidden_automation_marker(tmp_path: Path) -> None:
|
||||
async def test_persist_local_trigger_turn_uses_hidden_automation_marker(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = loop.sessions.get_or_create("websocket:auto")
|
||||
session = await loop.sessions.state.get("websocket:auto")
|
||||
|
||||
persisted = loop._persist_user_message_early(
|
||||
persisted = await loop._persist_user_message_early(
|
||||
InboundMessage(
|
||||
channel="websocket",
|
||||
sender_id="trigger",
|
||||
@@ -384,6 +384,7 @@ async def test_generate_webui_title_only_for_marked_webui_sessions(tmp_path: Pat
|
||||
)
|
||||
|
||||
assert generated is True
|
||||
session = await loop.sessions.state.get(session.key)
|
||||
assert session.metadata[WEBUI_TITLE_METADATA_KEY] == "优化 WebUI 侧边栏"
|
||||
loop.provider.chat_stream_with_retry.assert_awaited_once()
|
||||
assert loop.provider.chat_stream_with_retry.await_args.kwargs["max_tokens"] == TITLE_GENERATION_MAX_TOKENS
|
||||
@@ -510,6 +511,7 @@ async def test_projected_title_generation_skips_existing_chat_title(tmp_path: Pa
|
||||
unified.add_message("assistant", "以下是临期 IP 列表。")
|
||||
chat = loop.sessions.get_or_create("websocket:chat-existing")
|
||||
chat.metadata[WEBUI_TITLE_METADATA_KEY] = "Existing title"
|
||||
loop.sessions.save(chat)
|
||||
loop.sessions.save(unified)
|
||||
|
||||
generated = await maybe_generate_webui_title_after_turn(
|
||||
@@ -1064,7 +1066,7 @@ async def test_runtime_checkpoint_keeps_provider_state_out_of_public_metadata(
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(
|
||||
return_value=LLMResponse(content="done", provider_state=state)
|
||||
)
|
||||
session = loop.sessions.get_or_create("cli:private-checkpoint")
|
||||
session = await loop.sessions.state.get("cli:private-checkpoint")
|
||||
|
||||
await loop._run_agent_loop(
|
||||
TranscriptInput(
|
||||
@@ -1089,8 +1091,9 @@ async def test_runtime_checkpoint_keeps_provider_state_out_of_public_metadata(
|
||||
public_payload = loop.sessions.read_session_file(session.key)
|
||||
assert public_payload is not None
|
||||
assert "private-checkpoint-blob" not in json.dumps(public_payload)
|
||||
raw = loop.sessions._get_session_path(session.key).read_text(encoding="utf-8")
|
||||
assert "private-checkpoint-blob" in raw
|
||||
stored = loop.sessions.read_session_snapshot(session.key)
|
||||
assert stored is not None and stored.provider_state is not None
|
||||
assert stored.provider_state.payload == state.payload
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1120,7 +1123,7 @@ async def test_subagent_followup_stages_provider_state_before_turn_runs(
|
||||
session = loop.sessions.get_or_create("cli:subagent-crash")
|
||||
session.provider_state = _provider_state()
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
await save_completed_subagent(loop, "sub-1", session.key)
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="system",
|
||||
@@ -1152,7 +1155,7 @@ async def test_subagent_followup_state_is_durable_before_prompt_assembly(
|
||||
session = loop.sessions.get_or_create("cli:subagent-prompt-crash")
|
||||
session.provider_state = _provider_state()
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
await save_completed_subagent(loop, "sub-1", session.key)
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="system",
|
||||
@@ -1186,7 +1189,7 @@ async def test_subagent_redelivery_does_not_duplicate_staged_provider_input(
|
||||
session = loop.sessions.get_or_create("cli:subagent-redelivery")
|
||||
session.provider_state = _provider_state()
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
await save_completed_subagent(loop, "sub-1", session.key)
|
||||
msg = InboundMessage(
|
||||
channel="system",
|
||||
sender_id="subagent",
|
||||
@@ -1236,7 +1239,7 @@ async def test_subagent_followup_clears_state_before_compatibility_failure(
|
||||
session = loop.sessions.get_or_create("cli:subagent-compat-crash")
|
||||
session.provider_state = _provider_state()
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
await save_completed_subagent(loop, "sub-1", session.key)
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="system",
|
||||
@@ -1712,7 +1715,8 @@ async def test_process_message_uses_explicit_session_for_goal_context(
|
||||
assert result is not None
|
||||
assert result.content == "ok"
|
||||
kwargs = loop._run_agent_loop.call_args.kwargs
|
||||
assert kwargs["session"] is system_session
|
||||
assert kwargs["session"].key == system_session.key
|
||||
assert kwargs["session"] is not system_session
|
||||
assert kwargs["request_context"].session_key == "system"
|
||||
assert GOAL_STATE_KEY not in kwargs["session"].metadata
|
||||
|
||||
@@ -1724,16 +1728,16 @@ async def test_run_agent_loop_continuation_reads_latest_goal_metadata(
|
||||
from nanobot.agent.runner import AgentRunResult
|
||||
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = loop.sessions.get_or_create("websocket:late-goal")
|
||||
session = await loop.sessions.state.get("websocket:late-goal")
|
||||
seen: dict[str, str | None] = {}
|
||||
|
||||
async def fake_run(spec):
|
||||
assert callable(spec.continuation_callback)
|
||||
session.metadata[GOAL_STATE_KEY] = {
|
||||
await loop.sessions.state.update_metadata(session.key, {GOAL_STATE_KEY: {
|
||||
"status": "active",
|
||||
"objective": "Goal created during this runner call.",
|
||||
}
|
||||
seen["goal_continue"] = spec.continuation_callback()
|
||||
}})
|
||||
seen["goal_continue"] = await spec.continuation_callback()
|
||||
return AgentRunResult(
|
||||
final_content="ok",
|
||||
messages=[{"role": "assistant", "content": "ok"}],
|
||||
@@ -1873,7 +1877,7 @@ async def test_stop_preserves_runtime_checkpoint_for_next_turn(tmp_path: Path) -
|
||||
|
||||
async def interrupted_run_agent_loop(_transcript_input, *, session=None, **_kwargs):
|
||||
assert session is not None
|
||||
loop._set_runtime_checkpoint(
|
||||
await loop._set_runtime_checkpoint(
|
||||
session,
|
||||
{
|
||||
"assistant_message": {
|
||||
@@ -1917,7 +1921,21 @@ async def test_stop_preserves_runtime_checkpoint_for_next_turn(tmp_path: Path) -
|
||||
first_msg = InboundMessage(channel="feishu", sender_id="u1", chat_id="c4", content="keep progress")
|
||||
task = asyncio.create_task(loop._process_message(first_msg))
|
||||
loop._active_tasks[first_msg.session_key] = {task}
|
||||
await asyncio.wait_for(checkpoint_saved.wait(), timeout=1.0)
|
||||
checkpoint_wait = asyncio.create_task(checkpoint_saved.wait())
|
||||
try:
|
||||
done, _ = await asyncio.wait(
|
||||
(checkpoint_wait, task), timeout=5, return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
if task in done:
|
||||
await task
|
||||
assert checkpoint_wait in done, "the turn did not reach its durable checkpoint"
|
||||
except BaseException:
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
raise
|
||||
finally:
|
||||
checkpoint_wait.cancel()
|
||||
await asyncio.gather(checkpoint_wait, return_exceptions=True)
|
||||
|
||||
stop_msg = InboundMessage(channel="feishu", sender_id="u1", chat_id="c4", content="/stop")
|
||||
stop_ctx = CommandContext(msg=stop_msg, session=None, key=stop_msg.session_key, raw="/stop", loop=loop)
|
||||
@@ -1976,7 +1994,7 @@ async def test_system_subagent_followup_is_persisted_before_prompt_assembly(tmp_
|
||||
session.add_message("user", "question")
|
||||
session.add_message("assistant", "working")
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
await save_completed_subagent(loop, "sub-1", session.key)
|
||||
|
||||
runtime = loop.llm_runtime()
|
||||
seen: dict[str, object] = {}
|
||||
@@ -2077,7 +2095,7 @@ async def test_turn_usage_is_persisted_with_the_saved_session(tmp_path: Path) ->
|
||||
@pytest.mark.asyncio
|
||||
async def test_system_subagent_followup_does_not_log_content(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
save_completed_subagent(loop, "sub-logs", "cli:logs")
|
||||
await save_completed_subagent(loop, "sub-logs", "cli:logs")
|
||||
|
||||
async def fake_run_agent_loop(transcript_input, **_kwargs):
|
||||
initial_messages = _assembled_messages(loop.context, transcript_input)
|
||||
@@ -2114,7 +2132,7 @@ async def test_system_subagent_followup_does_not_log_content(tmp_path: Path) ->
|
||||
@pytest.mark.asyncio
|
||||
async def test_system_subagent_followup_uses_common_turn_lifecycle(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
save_completed_subagent(loop, "sub-1", "cli:test")
|
||||
await save_completed_subagent(loop, "sub-1", "cli:test")
|
||||
visited: list[str] = []
|
||||
|
||||
for name in (
|
||||
@@ -2243,7 +2261,7 @@ async def test_multiple_subagent_followups_all_persist_as_standalone_history(tmp
|
||||
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
|
||||
|
||||
for idx in range(3):
|
||||
save_completed_subagent(loop, f"sub-{idx}", "cli:multi")
|
||||
await save_completed_subagent(loop, f"sub-{idx}", "cli:multi")
|
||||
await loop._process_message(
|
||||
InboundMessage(
|
||||
channel="system",
|
||||
@@ -2361,7 +2379,7 @@ async def test_system_subagent_followup_uses_thread_session_and_slack_metadata(t
|
||||
thread_session = loop.sessions.get_or_create("slack:C123:1700.42")
|
||||
thread_session.add_message("user", "thread question")
|
||||
loop.sessions.save(thread_session)
|
||||
save_completed_subagent(loop, "sub-1", thread_session.key)
|
||||
await save_completed_subagent(loop, "sub-1", thread_session.key)
|
||||
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
|
||||
Reference in new issue
Block a user