perf(subagent): read saved task history by loaded turns (#6634)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-12 21:37:08 +08:00
1 parent 1196698ecb
commit eb8546c321
20 files changed
+893 -97

No files matched your search

+58 -15
View File
@@ -5,7 +5,7 @@ import json
import time
import uuid
import warnings
from collections.abc import Awaitable, Callable, Mapping
from collections.abc import Awaitable, Callable, Collection, Mapping
from copy import deepcopy
from dataclasses import dataclass, field, replace
from functools import partial
@@ -441,35 +441,78 @@ class SubagentManager:
if status.owner == session_key},
}
def _turn_statuses_for_session(
self, session_key: str, *, turns: Collection[str], tracked: Collection[str],
) -> dict[str, SubagentStatus]:
"""Keep live work plus the tasks the caller still tracks outside the loaded turns."""
return {
**{tid: record.snapshot() for tid, record in self._tasks.items()
if record.status.owner == session_key and record.status.finished_at is None},
**{tid: deepcopy(status) for tid, status in self._terminal_statuses.items()
if status.owner == session_key
and (tid in tracked or status.origin_turn_id in turns)},
}
def _runtime_for_request(
self, session_key: str, turns: Collection[str] | None, tracked: Collection[str],
) -> dict[str, SubagentStatus]:
if turns is None:
return self._runtime_statuses_for_session(session_key)
return self._turn_statuses_for_session(session_key, turns=set(turns), tracked=set(tracked))
def _merge_session_statuses(
self, session_key: str, runtime: Mapping[str, SubagentStatus], *, include_history: bool,
turns: Collection[str] | None = None, tracked: Collection[str] = (),
) -> Mapping[str, SubagentStatus]:
if self.sessions is not None and not self.sessions.exists(session_key):
return {}
statuses = self.sessions.load(session_key) if include_history and self.sessions is not None else {}
for task_id, status in runtime.items():
if self.sessions is not None and not self.sessions.contains(task_id, session_key):
continue
persisted = statuses.get(task_id)
if persisted is None or status.revision >= persisted.revision:
statuses[task_id] = status
return statuses
sessions = self.sessions
if sessions is None:
return dict(runtime)
def read() -> Mapping[str, SubagentStatus]:
if not sessions.exists(session_key):
return {}
if not include_history:
statuses: dict[str, SubagentStatus] = {}
elif turns is None:
statuses = sessions.load(session_key)
else:
statuses = sessions.load_turns(session_key, turn_ids=list(turns))
outside = [task_id for task_id in tracked if task_id not in statuses]
if outside:
statuses.update(sessions.load_tracked(session_key, outside))
for task_id, status in runtime.items():
if not sessions.contains(task_id, session_key):
continue
persisted = statuses.get(task_id)
if persisted is None or status.revision >= persisted.revision:
statuses[task_id] = status
return statuses
# One connection per request: existence, the turn read, tracked fallbacks and
# ownership checks are separate transactions on the same worker.
return sessions.read_batch(read)
def statuses_for_session(
self, session_key: str | None, *, include_history: bool = True,
turns: Collection[str] | None = None, tracked: Collection[str] = (),
) -> Mapping[str, SubagentStatus]:
"""Return only tasks owned by the given session, never a global fallback."""
if not session_key:
return {}
return self._merge_session_statuses(
session_key, self._runtime_statuses_for_session(session_key), include_history=include_history,
session_key, self._runtime_for_request(session_key, turns, tracked),
include_history=include_history, turns=turns, tracked=tracked,
)
async def read_statuses_for_session(self, session_key: str) -> Mapping[str, SubagentStatus]:
async def read_statuses_for_session(
self, session_key: str, *, turns: Collection[str] | None = None,
tracked: Collection[str] = (),
) -> Mapping[str, SubagentStatus]:
"""Capture runtime observations on the owner loop; read stored metadata on a worker."""
runtime = self._runtime_statuses_for_session(session_key)
return await asyncio.to_thread(
self._merge_session_statuses, session_key, runtime, include_history=True,
self._merge_session_statuses, session_key,
self._runtime_for_request(session_key, turns, tracked),
include_history=True, turns=turns, tracked=tracked,
)
def set_provider(self, provider: LLMProvider, model: str) -> None:
+33 -3
View File
@@ -2,14 +2,20 @@ from __future__ import annotations
import math
import time
from typing import Any, cast
from collections.abc import Callable, Sequence
from typing import Any, TypeVar, cast
from loguru import logger
from pydantic import TypeAdapter, ValidationError
from nanobot.agent.subagent_status import SubagentSessionError as SubagentSessionError
from nanobot.agent.subagent_status import SubagentStatus
from nanobot.session.manager import Session, SessionManager, SessionPolicy
from nanobot.session.manager import (
Session,
SessionManager,
SessionMetadataPayload,
SessionPolicy,
)
from nanobot.session.sqlite_store import SessionConflictError
from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY, SessionType
@@ -17,6 +23,7 @@ SUBAGENT = SessionType("subagent", needs_handle=False, public_history=False)
TASK_METADATA_KEY = "subagent_task"
_STATUS = TypeAdapter(SubagentStatus)
_ACTIVE_STATES = {"queued", "running", "stopping"}
_T = TypeVar("_T")
class SubagentSessions:
@@ -109,8 +116,27 @@ class SubagentSessions:
return status
def load(self, owner: str) -> dict[str, SubagentStatus]:
return self._statuses(owner, self.sessions.list_child_session_metadata(owner))
def load_turns(self, owner: str, *, turn_ids: Sequence[str]) -> dict[str, SubagentStatus]:
"""Read subagent headers attributed to the requested parent turns."""
return self._statuses(
owner, self.sessions.list_subagent_session_metadata(owner, turn_ids=turn_ids),
)
def load_tracked(self, owner: str, task_ids: Sequence[str]) -> dict[str, SubagentStatus]:
"""Read already observed tasks in one query when they fall outside the loaded turns."""
return self._statuses(
owner, self.sessions.read_child_session_metadata(
owner, [self.key(task_id) for task_id in task_ids],
),
)
def _statuses(
self, owner: str, rows: Sequence[SessionMetadataPayload],
) -> dict[str, SubagentStatus]:
result: dict[str, SubagentStatus] = {}
for row in self.sessions.list_child_session_metadata(owner):
for row in rows:
key = row["key"]
task_id = key.removeprefix("subagent:")
if key != self.key(task_id):
@@ -120,6 +146,10 @@ class SubagentSessions:
result[task_id] = status
return result
def read_batch(self, operation: Callable[[], _T]) -> _T:
"""Share one store connection across the reads of a single request."""
return self.sessions.read_batch(operation)
async def interrupt_pending(self) -> None:
"""Seal abandoned work after the gateway acquires execution ownership."""
for row in self.sessions.list_sessions():
+13 -1
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import asyncio
import re
import threading
from collections.abc import Iterator
from collections.abc import Iterator, Sequence
from copy import deepcopy
from dataclasses import dataclass, field
from datetime import datetime
@@ -516,6 +516,18 @@ class SessionManager:
"""Read persisted child headers without transcripts, checkpoints, or pending inputs."""
return self._store.list_child_session_metadata(parent_key)
def list_subagent_session_metadata(
self, parent_key: str, *, turn_ids: Sequence[str],
) -> list[SessionMetadataPayload]:
"""Read persisted subagent headers attributed to the requested parent turns."""
return self._store.list_subagent_session_metadata(parent_key, turn_ids=turn_ids)
def read_child_session_metadata(
self, parent_key: str, child_keys: Sequence[str],
) -> list[SessionMetadataPayload]:
"""Read named persisted child headers without transcripts or pending inputs."""
return self._store.read_child_session_metadata(parent_key, child_keys)
def save(self, session: Session) -> None:
"""Commit an offline administrative snapshot, rejecting obsolete history."""
self._require_offline_mutation()
+54 -2
View File
@@ -4,7 +4,7 @@ import json
import os
import sqlite3
import threading
from collections.abc import Callable, Generator, Iterator
from collections.abc import Callable, Generator, Iterator, Sequence
from concurrent.futures import CancelledError
from contextlib import contextmanager, suppress
from datetime import datetime
@@ -25,12 +25,27 @@ from nanobot.session.manager import (
metadata_title,
)
from nanobot.session.summary import is_summary_checkpoint
from nanobot.session.types import PARENT_SESSION_KEY
from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY
_CHECKPOINT = "runtime_checkpoint"
_INPUTS = ("pending_user_followups",)
_T = TypeVar("_T")
# The expression below defines the v6 partial index and must stay stable for upgrades.
_SUBAGENT_ORIGIN = "origin_turn_id"
_SUBAGENT_PARENT = f"json_extract(metadata, '$.{PARENT_SESSION_KEY}')"
_SUBAGENT_ORIGIN_FILTER = (
f"json_extract(metadata, '$.{SESSION_TYPE_KEY}')='subagent' "
f"AND json_type(metadata, '$.{PARENT_SESSION_KEY}')='text' "
f"AND json_type(metadata, '$.subagent_task.{_SUBAGENT_ORIGIN}')='text'"
)
# Field names above are fixed by the schema; all caller-supplied values are bound.
_SUBAGENT_METADATA_QUERY = f"""SELECT key, created_at, updated_at, metadata FROM sessions
WHERE {_SUBAGENT_ORIGIN_FILTER}
AND {_SUBAGENT_PARENT}=?
AND json_extract(metadata, '$.subagent_task.{_SUBAGENT_ORIGIN}') IN (SELECT value FROM json_each(?))"""
def _encode(value: object) -> str:
return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
@@ -123,9 +138,16 @@ def _create_schema_v5(db: sqlite3.Connection) -> None:
) WHERE kind='input'""")
def _create_schema_v6(db: sqlite3.Connection) -> None:
db.execute(f"""CREATE INDEX sessions_subagent_{_SUBAGENT_ORIGIN} ON sessions (
{_SUBAGENT_PARENT}, json_extract(metadata, '$.subagent_task.{_SUBAGENT_ORIGIN}')
) WHERE {_SUBAGENT_ORIGIN_FILTER}""")
# Entries upgrade version N to N+1. Preserve released entries and append upgrades.
_SCHEMA_MIGRATIONS: tuple[Callable[[sqlite3.Connection], None], ...] = (
_create_schema_v1, _create_schema_v2, _create_schema_v3, _create_schema_v4, _create_schema_v5,
_create_schema_v6,
)
@@ -728,6 +750,36 @@ class SqliteSessionStore:
(parent_key,),
)]
def list_subagent_session_metadata(
self, parent_key: str, *, turn_ids: Sequence[str],
) -> list[SessionMetadataPayload]:
"""Read only subagent headers attributed to the requested parent turns."""
turns = [value for value in turn_ids if value]
if not turns:
return []
with self.transaction(write=False) as db:
return [{"key": row[0], "created_at": row[1], "updated_at": row[2],
"metadata": _object(row[3])}
for row in db.execute(_SUBAGENT_METADATA_QUERY, (parent_key, _encode(turns)))]
def read_child_session_metadata(
self, parent_key: str, child_keys: Sequence[str],
) -> list[SessionMetadataPayload]:
"""Read named child headers in one query, excluding checkpoints and pending inputs."""
keys = [key for key in child_keys if key]
if not keys:
return []
with self.transaction(write=False) as db:
return [{"key": row[0], "created_at": row[1], "updated_at": row[2],
"metadata": _object(row[3])}
for row in db.execute(
f"""SELECT key, created_at, updated_at, metadata FROM sessions
WHERE key IN (SELECT value FROM json_each(?))
AND json_extract(metadata, '$.{PARENT_SESSION_KEY}')=?
AND json_type(metadata, '$.{PARENT_SESSION_KEY}')='text'""",
(_encode(keys), parent_key),
)]
def list_metadata(self) -> list[dict[str, Any]]:
with self.transaction(write=False) as db:
# Fetch one value so a large list does not cross the Python/SQLite
+15 -1
View File
@@ -920,8 +920,22 @@ class GatewayHTTPHandler:
return _http_error(404, "session not found")
if self.subagent_manager is None:
return _http_error(503, "subagent manager unavailable")
query = _parse_query(request.path)
scope = query.get("scope")
if scope is not None and scope != ["window"]:
return _http_error(400, "invalid task scope")
turns = query.get("turn_id", [])
tracked = query.get("track", [])
if scope == ["window"] and (len(turns) + len(tracked) > 512
or any(not value or len(value) > 512 for value in (*turns, *tracked))):
return _http_error(400, "invalid task window")
try:
statuses = await self.subagent_manager.read_statuses_for_session(session_key)
if scope == ["window"]:
statuses = await self.subagent_manager.read_statuses_for_session(
session_key, turns=turns, tracked=tracked,
)
else:
statuses = await self.subagent_manager.read_statuses_for_session(session_key)
except (OSError, SubagentSessionError):
return _http_error(503, "task history unavailable")
return _http_json_response({