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

+70 -50
View File
@@ -4,6 +4,8 @@ import asyncio
import signal
from collections.abc import Awaitable, Callable, Coroutine, Iterable
from contextlib import suppress
from dataclasses import replace
from functools import partial
from pathlib import Path
from typing import Any, cast
@@ -21,6 +23,8 @@ from nanobot.agent.tools.image_generation import (
)
from nanobot.agent.tools.mcp import MCPProvider
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.cli import terminal as cli_terminal
from nanobot.cli.runtime_config import _migrate_cron_store
from nanobot.cli.webui_support import (
@@ -44,7 +48,9 @@ from nanobot.session.keys import (
HEARTBEAT_SESSION_KEY,
UNIFIED_SESSION_KEY,
last_channel_from_metadata,
session_key_for_channel,
)
from nanobot.session.manager import SessionManager
from nanobot.utils.evaluator import evaluate_response, resolve_evaluator_prompt
from nanobot.utils.helpers import sync_workspace_templates
from nanobot.utils.token_encoding import warmup_token_encoding
@@ -57,6 +63,48 @@ __all__ = ["_run_gateway"]
console = Console()
async def _deliver_to_channel(
msg: OutboundMessage,
*,
bus: MessageBus,
session_manager: SessionManager,
unified_session: bool = False,
record: bool = False,
session_key: str | None = None,
session_generation: str | None = None,
) -> None:
"""Publish a user-visible message and mirror it into its admitted session."""
metadata = dict(msg.metadata or {})
record = record or bool(metadata.pop("_record_channel_delivery", False))
raw_key = metadata.pop("_session_key", None)
raw_generation = metadata.pop("_session_generation", None)
expected_generation = (
session_generation
if session_generation is not None
else raw_generation if isinstance(raw_generation, str) else None
)
if metadata != (msg.metadata or {}):
msg = replace(msg, metadata=metadata)
if record and msg.channel != "cli" and msg.content.strip():
key = session_key or (raw_key if isinstance(raw_key, str) else None)
if key is None:
key = session_key_for_channel(
msg.channel, msg.chat_id, unified_session=unified_session,
)
if expected_generation is None:
# Cross-target sends admit their target before recording; subsequent
# deletion or reset must still revoke this delivery's generation.
target = await session_manager.state.get_header(key)
expected_generation = target.generation
extra: dict[str, Any] = {"_channel_delivery": True}
if msg.media:
extra["media"] = list(msg.media)
await session_manager.state.record_delivery(
key, msg.content, extra, expected_generation=expected_generation,
)
await bus.publish_outbound(msg)
class _MCPReadinessHook(AgentHook):
"""Retry application-owned MCP connections before the runner reads tools."""
@@ -519,9 +567,6 @@ def _run_gateway(
schedule_background=_schedule_webui_background,
recovery=recovery,
)
from nanobot.bus.events import OutboundMessage
from nanobot.session.keys import session_key_for_channel
def _channel_session_key(channel: str, chat_id: str) -> str:
return session_key_for_channel(
channel,
@@ -529,41 +574,16 @@ def _run_gateway(
unified_session=config.agents.defaults.unified_session,
)
async def _deliver_to_channel(
msg: OutboundMessage, *, record: bool = False, session_key: str | None = None,
) -> None:
"""Publish a user-visible message and mirror it into that channel's session."""
metadata = dict(msg.metadata or {})
record = record or bool(metadata.pop("_record_channel_delivery", False))
if metadata != (msg.metadata or {}):
msg = OutboundMessage(
channel=msg.channel,
chat_id=msg.chat_id,
content=msg.content,
reply_to=msg.reply_to,
media=msg.media,
metadata=metadata,
buttons=msg.buttons,
)
if (
record
and msg.channel != "cli"
and msg.content.strip()
and hasattr(session_manager, "get_or_create")
and hasattr(session_manager, "save")
):
key = session_key or _channel_session_key(msg.channel, msg.chat_id)
session = session_manager.get_or_create(key)
extra: dict[str, Any] = {"_channel_delivery": True}
if msg.media:
extra["media"] = list(msg.media)
session.add_message("assistant", msg.content, **extra)
session_manager.save(session)
await bus.publish_outbound(msg)
deliver_to_channel = partial(
_deliver_to_channel,
bus=bus,
session_manager=session_manager,
unified_session=config.agents.defaults.unified_session,
)
message_tool = agent.tools.get("message")
if isinstance(message_tool, MessageTool):
message_tool.set_send_callback(_deliver_to_channel)
message_tool.set_send_callback(deliver_to_channel)
# Set cron callback (needs agent)
async def on_cron_job(job: CronJob) -> str | CronRunResult | None:
@@ -576,7 +596,6 @@ def _run_gateway(
from nanobot.agent.memory import MemoryStore
dream_session_key = MemoryStore.dream_session_key
prune_dream_sessions = MemoryStore.prune_dream_sessions
store = agent.context.memory
resp = None
@@ -628,7 +647,7 @@ def _run_gateway(
if sha:
logger.info("Dream commit: {}", sha)
store.compact_history()
prune_dream_sessions(agent.sessions)
await agent.sessions.state.prune_dream_sessions()
return None
# Heartbeat is a system job that checks HEARTBEAT.md for active tasks.
@@ -643,9 +662,14 @@ def _run_gateway(
logger.debug("Heartbeat: HEARTBEAT.md has no active tasks")
return None
channel, chat_id = _pick_heartbeat_target()
channel, chat_id = await _pick_heartbeat_target()
if channel == "cli":
return None
delivery_key = _channel_session_key(channel, chat_id)
delivery_session = await session_manager.state.read(delivery_key)
if delivery_session is None:
return None
delivery_generation = delivery_session.generation
prompt = (
_HEARTBEAT_PREAMBLE
@@ -690,9 +714,11 @@ def _run_gateway(
if should_notify:
logger.info("Heartbeat: completed, delivering response")
await _deliver_to_channel(
await deliver_to_channel(
OutboundMessage(channel=channel, chat_id=chat_id, content=response),
record=True,
session_key=delivery_key,
session_generation=delivery_generation,
)
else:
logger.info("Heartbeat: silenced by post-run evaluation")
@@ -755,17 +781,17 @@ def _run_gateway(
config_path=Path(config_path),
)
def _pick_heartbeat_target() -> tuple[str, str]:
async def _pick_heartbeat_target() -> tuple[str, str]:
"""Pick a routable channel/chat target for heartbeat-triggered messages."""
sidebar_state = read_webui_sidebar_state()
sidebar_state = await asyncio.to_thread(read_webui_sidebar_state)
unified_metadata = None
if config.agents.defaults.unified_session:
record = session_manager.read_session_metadata(UNIFIED_SESSION_KEY)
record = await session_manager.state.read_metadata(UNIFIED_SESSION_KEY)
if isinstance(record, dict) and isinstance(record.get("metadata"), dict):
unified_metadata = record["metadata"]
return _pick_heartbeat_target_from_sessions(
enabled_channels=channels.enabled_channels,
sessions=session_manager.list_sessions(),
sessions=await session_manager.state.list_sessions(),
archived_keys=sidebar_state.get("archived_keys", []),
unified_session_metadata=unified_metadata,
)
@@ -930,6 +956,7 @@ def _run_gateway(
console.print,
)
try:
await agent.subagents.recover_interrupted()
await cron.start()
# Re-read once on first admission to close the watcher subscription window.
agent.runtime_resolver.invalidate()
@@ -1039,12 +1066,6 @@ def _run_gateway(
runtime_tasks,
)
await bus.drain()
# Flush all cached sessions to durable storage before exit.
# This prevents data loss on filesystems with write-back
# caching (rclone VFS, NFS, FUSE mounts, etc.).
flushed = agent.sessions.flush_all()
if flushed:
logger.info("Shutdown: flushed {} session(s) to disk", flushed)
finally:
restore_shutdown_handlers()
@@ -1052,7 +1073,6 @@ def _run_gateway(
gateway_runtime.foreground_instance(gateway_start_options),
webui_turn_coordinator.connected(),
):
agent.subagents.recover_interrupted()
if health_server_enabled:
gateway_runtime.publish_health_host(config.gateway.host)
asyncio.run(run())