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

+14 -28
View File
@@ -68,7 +68,7 @@ def _raise_if_cancelling() -> None:
raise asyncio.CancelledError
ContinuationCallback = Callable[[], str | None]
ContinuationCallback = Callable[[], Awaitable[str | None]]
CheckpointCallback = Callable[[dict[str, Any]], Awaitable[None]]
InjectionCallback = Callable[[], Awaitable[Iterable[Any] | None]]
@@ -158,29 +158,15 @@ class AgentRunner:
self, operation: Callable[_PromptArgs, _PromptResult],
*args: _PromptArgs.args, **kwargs: _PromptArgs.kwargs,
) -> _PromptResult:
"""Share the bounded worker for read-only prompt preparation."""
"""Share the bounded context worker for prompt filesystem preparation."""
return await self.context_governor.prepare_in_background(operation, *args, **kwargs)
@staticmethod
async def copy_messages_on_loop(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Detach loop-owned records while yielding between bounded batches."""
copied: list[dict[str, Any]] = []
memo: dict[int, Any] = {id(messages): copied}
for start in range(0, len(messages), 64):
copied.extend(deepcopy(message, memo) for message in messages[start:start + 64])
await asyncio.sleep(0)
return copied
async def _run_context_snapshot(
self, messages: list[dict[str, Any]],
self, hook: AgentHook, messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
if not messages:
if not messages or not hook.has_run_hooks():
return []
task = asyncio.current_task()
if task is not None and task.cancelling():
# Cancellation cleanup must not queue behind its own unfinished worker.
return await self.copy_messages_on_loop(messages)
return await self.prepare_prompt(deepcopy, messages)
return await asyncio.to_thread(deepcopy, messages)
@staticmethod
def _append_injected_messages(
@@ -208,7 +194,7 @@ class AgentRunner:
injections = await self._drain_injections(spec) if drain_callback else []
real_injection = bool(injections)
if not injections and allow_continuation and assistant_message is not None:
continuation = self._build_continuation_message(spec)
continuation = await self._build_continuation_message(spec)
if continuation is not None:
injections = [continuation]
if (
@@ -260,12 +246,12 @@ class AgentRunner:
return True, injection_cycles
@staticmethod
def _build_continuation_message(spec: AgentRunSpec) -> dict[str, str] | None:
async def _build_continuation_message(spec: AgentRunSpec) -> dict[str, str] | None:
callback = spec.continuation_callback
if callback is None:
return None
try:
content = callback()
content = await callback()
except Exception:
logger.opt(exception=tool_log_content_allowed()).error("continuation_callback failed")
return None
@@ -332,18 +318,18 @@ class AgentRunner:
try:
try:
messages, compaction = await self.prepare_prompt(self._initial_transcript_and_compaction, spec)
context.messages = await self._run_context_snapshot(messages) if has_run_hooks else []
context.messages = await self._run_context_snapshot(hook, messages) if has_run_hooks else []
await hook.before_run(context)
result = await self._run_core(spec, hook, messages, compaction)
except Exception as exc:
context.messages = await self._run_context_snapshot(messages) if has_run_hooks else []
context.messages = await self._run_context_snapshot(hook, messages) if has_run_hooks else []
context.stop_reason = "error"
context.error = f"Error: {type(exc).__name__}: {exc}"
context.exception = exc
await hook.on_error(context)
raise
else:
context.messages = await self._run_context_snapshot(result.messages) if has_run_hooks else []
context.messages = await self._run_context_snapshot(hook, result.messages) if has_run_hooks else []
context.final_content = result.final_content
context.tools_used = list(result.tools_used)
context.usage = result.usage
@@ -365,14 +351,14 @@ class AgentRunner:
if has_run_hooks:
try:
if isinstance(context.exception, asyncio.CancelledError):
context.messages = await self.copy_messages_on_loop(messages)
context.messages = await self._run_context_snapshot(hook, messages)
else:
context.messages = await self._run_context_snapshot(messages)
context.messages = await self._run_context_snapshot(hook, messages)
except asyncio.CancelledError as exc:
context.stop_reason = "cancelled"
context.error = None
context.exception = exc
context.messages = await self.copy_messages_on_loop(messages)
context.messages = await self._run_context_snapshot(hook, messages)
raise
finally:
try: