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

+22 -12
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import json
import signal
import socket
import subprocess
import sys
@@ -144,6 +145,7 @@ def _start_gateway(config_path: Path, log_path: Path) -> subprocess.Popen[bytes]
cwd=Path(__file__).resolve().parents[2],
stdout=log_file,
stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if sys.platform == "win32" else 0,
)
finally:
log_file.close()
@@ -153,12 +155,19 @@ def _start_gateway(config_path: Path, log_path: Path) -> subprocess.Popen[bytes]
def _stop_gateway(process: subprocess.Popen[bytes]) -> None:
if process.poll() is not None:
return
process.terminate()
if sys.platform == "win32":
# Target only this gateway's console group and let it close its SQLite worker.
# TerminateProcess also races the child behind a venv's Python launcher.
process.send_signal(signal.CTRL_BREAK_EVENT)
else:
process.terminate()
try:
process.wait(timeout=10)
returncode = process.wait(timeout=30)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=10)
pytest.fail("gateway did not shut down gracefully within 30s")
assert returncode == 0, f"gateway shutdown failed with exit code {returncode}"
def _get_json(url: str, *, token: str | None = None) -> dict:
@@ -195,13 +204,14 @@ def _wait_for_bootstrap(base_url: str, process: subprocess.Popen[bytes], log_pat
async def _recv_until(ws: websockets.WebSocketClientProtocol, event: str) -> dict:
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
raw = await asyncio.wait_for(ws.recv(), timeout=5)
payload = json.loads(raw)
if payload.get("event") == event:
return payload
raise AssertionError(f"websocket event {event!r} was not received")
try:
async with asyncio.timeout(20):
while True:
payload = json.loads(await ws.recv())
if payload.get("event") == event:
return payload
except TimeoutError as exc:
raise AssertionError(f"websocket event {event!r} was not received within 20s") from exc
@pytest.mark.asyncio
@@ -295,11 +305,11 @@ async def test_gateway_recovers_private_children_and_deletes_them_with_parent(tm
sessions.save(parent)
children = SubagentSessions(sessions)
now = time.monotonic()
children.create(SubagentStatus(
await children.create(SubagentStatus(
task_id="finished", label="Finished", task_description="inspect", owner=parent.key,
started_at=now, finished_at=now, completed_at=time.time(), state="done", phase="done", result="Verified",
))
children.create(SubagentStatus(
await children.create(SubagentStatus(
task_id="abandoned", label="Abandoned", task_description="inspect", owner=parent.key,
started_at=now, state="running", phase="thinking", result="Partial findings", partial=True,
receipts={"follow-up": "accepted"},
@@ -425,7 +435,7 @@ def test_gateway_restart_restores_a_completed_answer_without_replaying_model(
"completed_tool_results": [],
"pending_tool_calls": [],
}
sessions.save(session, fsync=True)
sessions.save(session)
second = _start_gateway(config_path, second_log)
try: