perf(subagent): read saved task history by loaded turns (#6634)
This commit is contained in:
1 parent
1196698ecb
commit
eb8546c321
20 files changed
+893
-97
No files matched your search
+58
-15
@@ -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:
|
||||
|
||||
@@ -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():
|
||||
|
||||
Reference in new issue
Block a user