From 165c83f8802057fcd9d4f6e68af58d3efcd5b3cb Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 19:15:25 -0800 Subject: [PATCH 01/10] feat(usage): a run's colleagues, its env triggers' executors, count in its cost An env's gateway calls a trigger's executor (an AI-played contact) when the trigger fires. No prompt step prompts it, so no step recorded its usage and a run's ledger never held what its colleagues spent. - The gateway keeps every executor call with the usage its final message reported, as sent, and serves the list at GET /triggers/usage (the triggers extension's new `usage` method) under the engine's own boot id. `clear` keeps it: it was spent. - `prompt_agent` and `always_on` as they end, and the teardown, write the list as one `colleague` entry per env and gateway boot (`task_step/colleagues.py`), with no attempt, under the `register_env_triggers` step that set the executors up. A call that reported nothing makes the entry a lower bound, never $0; calls are priced by model from their per-model rows. - The ledger keys an entry by `gateway_boot` too, so each write is the whole list and replaces the last: a call counts once whichever step or attempt wrote it, and a gateway a retry redeployed is kept beside the first. - A step's completion takes the context's colleague entries into the ledger with its own; the teardown writes its own through the new `record_usage()`, which merges finished entries into a run's ledger alone, for any embedder. - `UsageRole` adds `colleague`, `validator` (a step that checks a run without grading it) and `playground` (an embedder's chat with a run's agent outside its steps). They aren't `[model.roles]` keys; `summarize` lists them after the solver, user simulator and judge, and `StepUsage` takes them. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 11 ++ src/agent_env/config/model.py | 10 ++ src/agent_env/env/gateway/constants.py | 5 +- src/agent_env/env/gateway/gateway.py | 4 + src/agent_env/env/gateway/triggers.py | 27 +++- src/agent_env/task/store.py | 32 ++++- src/agent_env/task/teardown.py | 8 +- src/agent_env/task/usage/ledger.py | 5 +- src/agent_env/task/usage/summary.py | 4 +- src/agent_env/task_step/colleagues.py | 103 +++++++++++++++ .../task_step/task_steps/prompt_agent.py | 5 +- src/agent_env/task_step/usage.py | 32 ++--- tst/unit/env/gateway/executor_usage_test.py | 95 ++++++++++++++ tst/unit/env/gateway/gateway_card_test.py | 5 +- tst/unit/task/usage/colleague_ledger_test.py | 121 ++++++++++++++++++ tst/unit/task/usage/summary_test.py | 13 ++ tst/unit/task_step/colleagues_test.py | 104 +++++++++++++++ .../task_step/test_prompt_agent_triggers.py | 24 ++++ 18 files changed, 577 insertions(+), 31 deletions(-) create mode 100644 src/agent_env/task_step/colleagues.py create mode 100644 tst/unit/env/gateway/executor_usage_test.py create mode 100644 tst/unit/task/usage/colleague_ledger_test.py create mode 100644 tst/unit/task_step/colleagues_test.py diff --git a/AGENTS.md b/AGENTS.md index 181ad45b9..4e719158c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -440,6 +440,17 @@ orchestrators call it the same way. What callers rely on: runner that doesn't set `ATTEMPT_EPOCH` writes entries with no attempt, kept by step and role alone: exact for a run without retries, a lower bound for one with. A runner that writes the instance some other way loses that spend from the ledger. +- A run's colleagues, the executors an env's gateway calls when a trigger fires, are spent outside any prompt: the + gateway lists every such call with the usage its final message reported (`GET /triggers/usage`, under its own boot + id, kept through a `clear`). `prompt_agent` and `always_on` as they end, and the teardown, write the list as one + `colleague` entry per env and gateway boot (`task_step/colleagues.py`), with no attempt, under the + `register_env_triggers` step that set the executors up; the ledger keeps it by `gateway_boot` too, so each write is + the whole list and replaces the last, a call counts once whichever step or attempt wrote it, and a gateway a retry + redeployed is kept beside the first. A step's completion takes the context's colleague entries with its own, and + the teardown writes its own through `record_usage()`, which merges any finished entries into the ledger alone, as + an embedder's chat with a run's agent outside its steps (`playground`). `validator` is the role for a step that + checks a run without grading it. None of the three (`UsageRole`) is a `[model.roles]` key; `summarize` lists them + after the solver, user simulator and judge. - The runner writes its run identifier to `context.metadata["workflow_id"]` before calling `run()`; core stores it opaquely with the instance. - Each step runs under `protocol_v1.authorized` for the deployed envs in its context: a protocol-client diff --git a/src/agent_env/config/model.py b/src/agent_env/config/model.py index 030e8aef6..43d3d4e3b 100644 --- a/src/agent_env/config/model.py +++ b/src/agent_env/config/model.py @@ -56,6 +56,16 @@ def record_key(self) -> str: return "user simulator" if self is ModelRole.USER_SIMULATOR else self.value +class UsageRole(StrEnum): + """A role a run's usage is recorded under that no ``[model.roles]`` key configures: an env trigger's executor, + which the env's gateway calls (``colleague``); a step that checks a run without grading it (``validator``); and a + chat an embedder holds with a run's agent outside its steps (``playground``).""" + + COLLEAGUE = "colleague" + VALIDATOR = "validator" + PLAYGROUND = "playground" + + ROLE_SYNONYMS: dict[str, ModelRole] = {"agent": ModelRole.SOLVER, "user": ModelRole.USER_SIMULATOR} # What a run's overrides name for each role, read by the steps that call the role's model and by an eval's intent lock, diff --git a/src/agent_env/env/gateway/constants.py b/src/agent_env/env/gateway/constants.py index a82888c79..b714830bf 100644 --- a/src/agent_env/env/gateway/constants.py +++ b/src/agent_env/env/gateway/constants.py @@ -293,13 +293,14 @@ def random_mcp_server_name() -> str: }, { "uri": EXT_TRIGGERS_URI, - "description": "Register (additive add-by-id), remove, clear, or read (state) typed Action/State triggers + the firing log (harness control path). config sets the engine's opt-in setting concurrent_fires (a repeat trigger whose actions are all contact replies (nl) or notifications (notify) runs its fires side by side instead of queueing).", + "description": "Register (additive add-by-id), remove, clear, or read (state) typed Action/State triggers + the firing log (harness control path); usage lists every call made to an executor so far with the usage it reported, under the gateway's boot id. config sets the engine's opt-in setting concurrent_fires (a repeat trigger whose actions are all contact replies (nl) or notifications (notify) runs its fires side by side instead of queueing).", "params": {"endpoint": "/triggers/register", "features": list(TRIGGER_FEATURES), "methods": { "register": {"method": "POST", "endpoint": "/triggers/register", "request": {"type": "object", "properties": {"watch_roles": {"type": "array", "items": {"type": "string"}}, "executor": {"type": "object"}, "executors": {"type": "object"}, "triggers": {"type": "array"}}, "required": ["triggers"]}}, "config": {"method": "POST", "endpoint": "/triggers/config", "request": {"type": "object", "properties": {"concurrent_fires": {"type": "boolean"}}}}, "remove": {"method": "POST", "endpoint": "/triggers/remove", "request": {"type": "object", "properties": {"ids": {"type": "array", "items": {"type": "string"}}}, "required": ["ids"]}}, "clear": {"method": "POST", "endpoint": "/triggers/clear", "request": {"type": "object", "properties": {}}}, - "state": {"method": "GET", "endpoint": "/triggers/state", "request": {"type": "object", "properties": {}}}}}, + "state": {"method": "GET", "endpoint": "/triggers/state", "request": {"type": "object", "properties": {}}}, + "usage": {"method": "GET", "endpoint": "/triggers/usage", "request": {"type": "object", "properties": {}}}}}, "required": False, }, { diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 5605a5834..569e22c53 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -396,6 +396,10 @@ async def triggers_clear(request: Request) -> Response: async def triggers_state(request: Request) -> Response: return self._json_response(self._deferred.in_state(self._trigger_engine.state()), 200) + @self._mcp.custom_route("/triggers/usage", methods=["GET"]) + async def triggers_usage(request: Request) -> Response: + return self._json_response(self._trigger_engine.usage(), 200) + @self._mcp.custom_route("/clock/set-time", methods=["PUT"]) async def clock_set_time(request: Request) -> Response: if GET_TIME_TOOL_NAME in self._tool_server_urls: diff --git a/src/agent_env/env/gateway/triggers.py b/src/agent_env/env/gateway/triggers.py index 47f70dc9d..d84e03a01 100644 --- a/src/agent_env/env/gateway/triggers.py +++ b/src/agent_env/env/gateway/triggers.py @@ -13,6 +13,7 @@ import math import random import re +import secrets import uuid from collections import deque from datetime import datetime, time, timedelta, timezone, tzinfo @@ -464,6 +465,9 @@ def __init__(self, gateway): # One turn at a time per executor conversation (its URL and context id): fires of one trigger running side by # side would otherwise resume the same session at once. self._executor_locks: dict[tuple[str, str], asyncio.Lock] = {} + # Every call made to an executor, with the usage it reported (`usage`), under this engine's own id. + self._executor_usage: list[dict] = [] + self._usage_boot = secrets.token_hex(6) def register(self, body: Any) -> dict: """Additively add each trigger by id (idempotent upsert; conflicting id or bad shape -> 400); watch_roles and @@ -571,7 +575,8 @@ def remove(self, body: Any) -> dict: return {"ok": True, "removed": removed} def clear(self) -> dict: - """Full reset — triggers, config, and the event log (setup/testing only; never mid-task).""" + """Full reset — triggers, config, and the event log (setup/testing only; never mid-task). The executor calls + made so far stay in ``usage``: they were spent.""" for task in list(self._tasks): task.cancel() self._tasks.clear() @@ -984,6 +989,12 @@ def state(self) -> dict: "events_dropped": max(0, self._seq - len(events)), } + def usage(self) -> dict: + """Every call made to an executor so far (GET /triggers/usage): each one's ``role``, the executor's, and the + ``usage`` its final message reported, as it sent it, None when it reported none or no reply was read; ``boot`` + is this engine's own id, so a reader that keeps the calls by it tells a restarted gateway's apart.""" + return {"boot": self._usage_boot, "calls": [dict(call) for call in self._executor_usage]} + def on_tool_call(self, role: str, name: str, arguments: dict, result: Any) -> tuple[list[asyncio.Task], float | None]: """Synchronous post-call detection hook (invoked from the gateway's role-filter wrapper). @@ -1755,8 +1766,18 @@ async def _nap(self, seconds: float) -> None: moved.cancel() async def _call_executor(self, executor: dict | None, instruction: str, context_id: str) -> str | None: + """The executor's reply to ``instruction``, None when it gave none in time; the call and the usage its final + message reported go into ``usage`` however it ends, a call whose usage never came back included.""" if executor is None: return None + reported: list[Any] = [] + try: + return await self._send_to_executor(executor, instruction, context_id, reported) + finally: + self._executor_usage.append({"role": executor["role"], "usage": reported[-1] if reported else None}) + + async def _send_to_executor(self, executor: dict, instruction: str, context_id: str, + reported: list[Any]) -> str | None: url = f"{executor['a2a_url']}/a2a" deadline = asyncio.get_running_loop().time() + executor["timeout_seconds"] async with httpx.AsyncClient(timeout=_EXECUTOR_HTTP_TIMEOUT_S) as client: @@ -1787,9 +1808,11 @@ async def _call_executor(self, executor: dict | None, instruction: str, context_ "method": "tasks/get", "params": {"id": task_id}}) poll.raise_for_status() status = ((poll.json().get("result") or {}).get("status") or {}) + parts = (status.get("message") or {}).get("parts") or [] + reported.extend(p["data"]["usage"] for p in parts if p.get("kind") == "data" + and isinstance(p.get("data"), dict) and p["data"].get("usage") is not None) if status.get("state") != "completed": return None - parts = (status.get("message") or {}).get("parts") or [] return "\n".join(p.get("text", "") for p in parts if p.get("kind") == "text") def _cancel(self, tid: str, trig: dict, **cause) -> None: diff --git a/src/agent_env/task/store.py b/src/agent_env/task/store.py index 4b7d400a2..108c15f4e 100644 --- a/src/agent_env/task/store.py +++ b/src/agent_env/task/store.py @@ -16,6 +16,7 @@ from agent_env.store.base import NotFoundError from agent_env.config import get_config +from agent_env.config.model import UsageRole from agent_env.store.document_store import DocumentStore, DuplicateKeyError, Filter, Lte, Ne, Sort, SortKey, UnknownDocumentTypeError, UpdateSpec, VersionedEntityStore, VersionedEntityStoreCache, compare_and_swap from agent_env.store.query import QueryBuilder, to_document_query from agent_env.task.step_journal import ( @@ -368,8 +369,9 @@ def _owns_attempt(doc: dict, attempt_epoch: int | None) -> bool: def _step_usage_after(doc: dict, ops: "ContextUpdateOps", step_id: str) -> list[dict]: - """``step_id``'s ledger entries as its completion leaves them in the stored context: the document's step usage - with the step's diff applied, the diff's writes to it or to a parent of it.""" + """``step_id``'s ledger entries as its completion leaves them in the stored context, the document's step usage with + the step's diff applied (the diff's writes to it or to a parent of it), and the context's colleague entries, which + a step records under the step that set its env's executors up (``task_step.colleagues``).""" def touches(path: str) -> bool: return path == _STEP_USAGE_PATH or path.startswith(_STEP_USAGE_PATH + ".") or _STEP_USAGE_PATH.startswith( path + ".") @@ -382,7 +384,10 @@ def touches(path: str) -> bool: add_to_sets={p: v for p, v in ops.add_to_sets.items() if touches(p)}, )) step_usage = _get_path(scratch, _STEP_USAGE_PATH) - return entries_of({step_id: step_usage.get(step_id)} if isinstance(step_usage, dict) else None) + if not isinstance(step_usage, dict): + return [] + colleagues = [entry for entry in entries_of(step_usage) if entry.get("role") == UsageRole.COLLEAGUE] + return [*entries_of({step_id: step_usage.get(step_id)}), *colleagues] class TaskInstanceStore: @@ -968,6 +973,17 @@ def _mutate(doc: dict) -> UpdateSpec | None: compare_and_swap(self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), _mutate, counter_field=_REV) + def record_usage_sync(self, instance_id: str, entries: list[dict]) -> None: + """Merge ``entries``, finished usage entries each naming its ``step_id``, into ``instance_id``'s ledger alone, + by attempt, step and role (``ledger.merged``), so one sent again replaces itself: usage a run spent outside + its steps' own writes, as its colleagues' (``task_step.colleagues``) or an embedder's chat with its agent.""" + def _mutate(doc: dict) -> UpdateSpec | None: + spent = ledger_fields(doc, entries) + return UpdateSpec(set=spent) if spent else None + + compare_and_swap(self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), _mutate, + counter_field=_REV) + def _end_write(self, instance_id: str, usage: list[dict], fields: Callable[[dict], dict], *, owns: Callable[[dict], bool], also: Callable[[dict], dict] | None = None) -> None: """A write that ends a run or an attempt, a CAS: ``fields`` of the document when ``owns`` it, ``also``'s whatever @@ -1142,6 +1158,16 @@ async def record_running_usage(instance_id: str, usage: list[dict]) -> bool: return False +async def record_usage(instance_id: str, entries: list[dict]) -> bool: + """Async ``TaskInstanceStore.record_usage_sync``; whether it was written. A store error is logged, not raised.""" + try: + await asyncio.to_thread(get_task_instance_store().record_usage_sync, instance_id, entries) + return True + except Exception: + logger.warning("Failed to record usage for instance_id=%s", instance_id, exc_info=True) + return False + + async def undo_steps( instance_id: str, step_ids: set[str], diff --git a/src/agent_env/task/teardown.py b/src/agent_env/task/teardown.py index 7716f8fc1..1d6957c5e 100644 --- a/src/agent_env/task/teardown.py +++ b/src/agent_env/task/teardown.py @@ -31,8 +31,9 @@ ) from agent_env.store.routing import run_scope from agent_env.task.interrupts import tearing_down -from agent_env.task.store import get_task_instance_store +from agent_env.task.store import get_task_instance_store, record_usage from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.colleagues import record_colleague_usage from agent_env.task_step.task_steps.computer_recording import end_open_recordings, register_open_recordings from agent_env.task_step.task_steps.browser.recording import (end_open_browser_recordings, register_open_browser_recordings) @@ -133,7 +134,8 @@ async def teardown_run(context: TaskStepContext, *, timeout: float = TERMINATE_T async def tear_down(context: TaskStepContext, sandboxes: Sequence[RecordedSandbox], envs: Sequence[DeployedEnv], *, timeout: float) -> TeardownReport: - """End the recordings the run left open on ``envs``, its computers' and its browsers', with fresh grants, close each + """Record what ``envs``' trigger executors spent (``record_colleague_usage``), end the recordings the run left open + on them, its computers' and its browsers', with fresh grants, close each env still up, register any recording still open from its namespace, then terminate each of ``sandboxes`` by id, all at once and each within ``timeout`` seconds, and remove a local one's work folder once it's down. A close that fails is logged: its env's sandboxes are terminated by id regardless, which leaves one the close took down as it is. Cancelling it returns what it reached, with the rest in ``left``.""" @@ -141,6 +143,8 @@ async def tear_down(context: TaskStepContext, sandboxes: Sequence[RecordedSandbo up = {sandbox.sandbox_id for sandbox in pending} env_ids = [env.env_id for env in envs] try: + if (colleagues := await record_colleague_usage(context, envs)) and context.instance_id: + await record_usage(context.instance_id, colleagues) try: async with asyncio.timeout(timeout): await end_open_recordings(context, env_ids) diff --git a/src/agent_env/task/usage/ledger.py b/src/agent_env/task/usage/ledger.py index 0ae1da0cc..b27a3050e 100644 --- a/src/agent_env/task/usage/ledger.py +++ b/src/agent_env/task/usage/ledger.py @@ -24,13 +24,14 @@ def entries_of(step_usage: Optional[Mapping], step_ids: Optional[Collection[str] def _key(entry: dict) -> tuple: - return entry.get("attempt"), entry.get("step_id"), entry.get("role") + return entry.get("attempt"), entry.get("step_id"), entry.get("role"), entry.get("gateway_boot") def merged(ledger: list[dict], entries: list[dict]) -> list[dict]: """``ledger`` with ``entries`` in it. An entry replaces the one of its attempt, step and role: a step's entry is its sum so far, so a write sent again, or a later one of the same attempt, never counts twice. A retry or a resume - runs under a new attempt epoch, so its entries are new ones.""" + runs under a new attempt epoch, so its entries are new ones. A colleague entry is one env gateway's executor calls + so far, kept by that gateway's ``gateway_boot`` too, so a gateway a retry redeployed adds its own.""" out = list(ledger) at = {_key(entry): i for i, entry in enumerate(out)} for entry in entries: diff --git a/src/agent_env/task/usage/summary.py b/src/agent_env/task/usage/summary.py index fda5c3aaf..a3776f0b4 100644 --- a/src/agent_env/task/usage/summary.py +++ b/src/agent_env/task/usage/summary.py @@ -12,14 +12,14 @@ from functools import reduce from typing import TYPE_CHECKING, Any -from agent_env.config.model import ModelRole +from agent_env.config.model import ModelRole, UsageRole from agent_env.config.model_pricing import Assumed, Errs if TYPE_CHECKING: from agent_env.task_step.usage import ModelEntry, UsageEntry # The order roles are shown in; any other comes after them. -_ROLES = tuple(role.value for role in ModelRole) +_ROLES = tuple(role.value for role in (*ModelRole, *UsageRole)) class Bound(StrEnum): diff --git a/src/agent_env/task_step/colleagues.py b/src/agent_env/task_step/colleagues.py new file mode 100644 index 000000000..df65b19ec --- /dev/null +++ b/src/agent_env/task_step/colleagues.py @@ -0,0 +1,103 @@ +"""What a run's colleagues spent: the calls an env's gateway makes to its triggers' executors, which no step prompts, +so no step's turns count them. + +Each env's gateway lists every such call with the usage it reported (``GET /triggers/usage``). A step that reads the +env's triggers as it ends (``prompt_agent``, ``always_on``) and the run's teardown write that list as one ``colleague`` +entry per env and gateway boot into the context's step usage, under the ``register_env_triggers`` step that set its +executors up; every step's completion takes the context's colleague entries into the ledger with its own, and the +teardown writes its own there (``teardown.tear_down``). Each write is the whole list so far, so it replaces the one +before (``ledger.merged``): a call counts once whoever writes it, and a gateway a retry redeployed, with a boot of its +own, is kept beside the first.""" + +from __future__ import annotations + +import logging +from collections.abc import Iterable, Mapping, Sequence +from typing import TYPE_CHECKING, Optional + +from agent_env.a2a_agent.protocol import read_usage +from agent_env.config.model import UsageRole +from agent_env.config.model_pricing import PriceSource, configured_prices +from agent_env.env.gateway.constants import EXT_TRIGGERS_URI +from agent_env.task_step.usage import STEP_USAGE_KEY, RoleUsage, UsageEntry, unreported + +if TYPE_CHECKING: + from agent_env.env.env import DeployedEnv + from agent_env.task_step.context import TaskStepContext + +logger = logging.getLogger(__name__) + +#: How long each env's list may take to read, in seconds. +READ_TIMEOUT_SECONDS = 15 + + +def colleague_entry(calls: Iterable[Mapping], *, gateway_boot: str, env_id: str, endpoint_host: Optional[str], + prices: PriceSource) -> Optional[UsageEntry]: + """One env gateway's executor calls as one ``colleague`` entry: each call's usage read as its executor reported it + (``read_usage``), one that reported none counted as a call of unknown usage, which makes the entry a lower bound, + never $0; priced as any role's turns are, by model where the executors gave their counts by model. It has no + attempt, since it holds the gateway's calls whichever attempt made them. None when there were no calls.""" + role = RoleUsage(UsageRole.COLLEAGUE.value, endpoint_host=endpoint_host, attempt=None) + for call in calls: + usage, unparsed = read_usage(call.get("usage")) + role.add(usage if usage is not None else unreported(), unparsed) + if not role.turns: + return None + entry = role.entry(prices) + entry["env_id"] = env_id + entry["gateway_boot"] = gateway_boot + return entry + + +async def record_colleague_usage(context: TaskStepContext, envs: Sequence[DeployedEnv]) -> list[dict]: + """Write each of ``envs``' colleagues' usage so far (``colleague_entry``) into ``context``'s step usage, under the + ``register_env_triggers`` step that set its executors up, and return them as ledger entries, each naming that step. + An env no such step set executors up on, or whose gateway doesn't list its calls, is skipped; a read that fails is + logged. Never raises.""" + registrations = _registrations(context) + written = [] + for env in envs: + registration = registrations.get(env.env_id) + if registration is None or not env.supports(EXT_TRIGGERS_URI, "usage"): + continue + try: + report = await env.invoke(EXT_TRIGGERS_URI, "usage", timeout=READ_TIMEOUT_SECONDS) + entry = colleague_entry(report.get("calls") or [], gateway_boot=str(report.get("boot")), + env_id=env.env_id, endpoint_host=_executors_host(context, registration), + prices=configured_prices()) + except Exception as e: # noqa: BLE001 - a colleague's usage never fails its step or the teardown + logger.warning("the colleague usage on env %s wasn't read: %s", env.env_id, e) + continue + if entry is not None: + _keep(context, registration["step_id"], entry) + written.append({**entry, "step_id": registration["step_id"]}) + return written + + +def _registrations(context: TaskStepContext) -> dict[str, dict]: + """Each env's first ``register_env_triggers`` record that set executors up, by env id.""" + found: dict[str, dict] = {} + for registration in context.metadata.get("env_trigger_registrations") or []: + if (isinstance(registration, dict) and registration.get("env_id") and registration.get("step_id") + and _executor_names(registration)): + found.setdefault(registration["env_id"], registration) + return found + + +def _executor_names(registration: dict) -> set[str]: + return {name for name in (registration.get("executor_agent_name"), *(registration.get("executor_agent_names") + or ())) if name} + + +def _executors_host(context: TaskStepContext, registration: dict) -> Optional[str]: + """The host of the model endpoint the registration's executors were given, when they share one.""" + names = _executor_names(registration) + hosts = {agent.model_endpoint_host for agent in context.deployed_agents if agent.agent_name in names} + return hosts.pop() if len(hosts) == 1 else None + + +def _keep(context: TaskStepContext, step_id: str, entry: UsageEntry) -> None: + """``entry`` in ``step_id``'s step usage, in place of that gateway's earlier one.""" + kept = context.metadata.setdefault(STEP_USAGE_KEY, {}).setdefault(step_id, []) + kept[:] = [*(e for e in kept if not (e.get("role") == entry["role"] + and e.get("gateway_boot") == entry["gateway_boot"])), entry] diff --git a/src/agent_env/task_step/task_steps/prompt_agent.py b/src/agent_env/task_step/task_steps/prompt_agent.py index 82cc1e3b4..c224deed7 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -40,6 +40,7 @@ ) from agent_env.store import DuplicateKeyError, get_config from agent_env.store.object_store import ObjectStore +from agent_env.task_step.colleagues import record_colleague_usage from agent_env.task_step.context import ( DeployedAgent, PromptResponse, @@ -1041,7 +1042,8 @@ async def _decide(self, decide_url: str, turn: int, solver_message: str, context async def _persist_env_trigger_state(self, context: TaskStepContext) -> None: """Snapshot each trigger-registered env's /triggers/state to the configured object store, plus a - metadata summary. Never raises and is bounded by _CAPTURE_BUDGET_SECONDS.""" + metadata summary, bounded by _CAPTURE_BUDGET_SECONDS, then record what its executors have spent so far + (``record_colleague_usage``). Never raises.""" try: await asyncio.wait_for( self._capture_env_trigger_state(context), timeout=self._CAPTURE_BUDGET_SECONDS) @@ -1060,6 +1062,7 @@ async def _persist_env_trigger_state(self, context: TaskStepContext) -> None: "captured_at_utc": datetime.now(timezone.utc).isoformat(), "capture_step_id": self.id, } + await record_colleague_usage(context, context.deployed_envs) @staticmethod def _registered_env_ids(context: TaskStepContext) -> set[str]: diff --git a/src/agent_env/task_step/usage.py b/src/agent_env/task_step/usage.py index 26e87e61e..81f3ee2af 100644 --- a/src/agent_env/task_step/usage.py +++ b/src/agent_env/task_step/usage.py @@ -12,7 +12,7 @@ from agentenv_protocol.a2a_agent import SERVICE_LEVEL_FIELDS, Usage, agreed_service_level, ttl_sum -from agent_env.config.model import ModelRole +from agent_env.config.model import ModelRole, UsageRole from agent_env.config.model_pricing import ( Cost, CostStatus, PriceSource, ReportedBy, Tokens, configured_prices, price, ) @@ -88,6 +88,8 @@ class UsageEntry(CostFields): unreported_calls: NotRequired[int] unparsed: NotRequired[list[dict]] unparsed_turns: NotRequired[int] + env_id: NotRequired[str] + gateway_boot: NotRequired[str] @dataclass @@ -267,7 +269,7 @@ def _combined(costs: list[Cost]) -> Cost: cache_write_ttl_tokens=ttl_sum(c.cache_write_ttl_tokens for c in priced)) -def _unreported() -> Usage: +def unreported() -> Usage: """A turn or call whose usage never came back.""" return Usage(provider_details={"unreported": True}) @@ -286,17 +288,17 @@ class StepUsage: def __init__(self, context: TaskStepContext, step_id: str) -> None: self._context = context self._step_id = step_id - self._roles: dict[ModelRole, RoleUsage] = {} + self._roles: dict[ModelRole | UsageRole, RoleUsage] = {} self._prices = configured_prices() - def start(self, role: ModelRole, model: Optional[str], agent: Optional[DeployedAgent]) -> None: + def start(self, role: ModelRole | UsageRole, model: Optional[str], agent: Optional[DeployedAgent]) -> None: """Count ``role``'s turns on ``model``, recording the model and the host of the endpoint ``agent`` was given in ``metadata.model_endpoints``, under the role's own name.""" host = agent.model_endpoint_host if agent else None self._context.record_model_endpoint(role.value, self._step_id, model, host) self._roles[role] = RoleUsage(role.value, model, host) - def turn(self, role: ModelRole, reply: TerminalResponse) -> None: + def turn(self, role: ModelRole | UsageRole, reply: TerminalResponse) -> None: """One finished turn of ``role``, written at once, so a step that raises later keeps it. A role that wasn't started, a human peer's, is skipped.""" usage = self._roles.get(role) @@ -304,14 +306,14 @@ def turn(self, role: ModelRole, reply: TerminalResponse) -> None: usage.add(reply.usage, reply.usage_unparsed) self.entries() - def call(self, role: ModelRole, usage: Optional[Usage], *, model: Optional[str], endpoint_host: Optional[str], - reported_by: ReportedBy = ReportedBy.HARNESS) -> None: + def call(self, role: ModelRole | UsageRole, usage: Optional[Usage], *, model: Optional[str], + endpoint_host: Optional[str], reported_by: ReportedBy = ReportedBy.HARNESS) -> None: """One model call of ``role`` that isn't an agent's turn, as a judge's, written at once. The role starts at its first call, with the model and the endpoint host that call reached; ``reported_by`` says whose figure a call's ``cost_usd`` is, and the role keeps its first call's.""" self._add_call(role, usage, model, endpoint_host, reported_by) - def reply(self, role: ModelRole, reply: ModelReply) -> None: + def reply(self, role: ModelRole | UsageRole, reply: ModelReply) -> None: """One model call the step made itself as ``role`` through ``model_call`` (a user-sim gate's judge), written at once. Its cost is kept as the call was costed (``_combined`` sums them); one with no cost leaves the entry a lower bound, as ``cut_off`` does.""" @@ -323,7 +325,7 @@ def reply(self, role: ModelRole, reply: ModelReply) -> None: usage.add(counts) self.entries() - def _role_for_call(self, role: ModelRole, model: Optional[str], endpoint_host: Optional[str], + def _role_for_call(self, role: ModelRole | UsageRole, model: Optional[str], endpoint_host: Optional[str], reported_by: ReportedBy) -> RoleUsage: """The role a call is counted under, started at its first call.""" if role not in self._roles: @@ -331,25 +333,25 @@ def _role_for_call(self, role: ModelRole, model: Optional[str], endpoint_host: O self._roles[role] = RoleUsage(role.value, model, endpoint_host, reported_by=reported_by) return self._roles[role] - def cut_off(self, role: ModelRole) -> None: + def cut_off(self, role: ModelRole | UsageRole) -> None: """A turn of ``role`` that was sent but never replied: cut off by a time limit, by a cancel, or by its agent no longer answering (``AgentUnreachableError``, a ``TimeoutError``). Its calls are billed but their usage is unknown, so it counts as a turn of unknown usage, marking the role's entry a lower bound. A role that wasn't started, a human peer's, is skipped.""" usage = self._roles.get(role) if usage is not None: - usage.add(_unreported()) + usage.add(unreported()) self.entries() - def cut_off_call(self, role: ModelRole, *, model: Optional[str], endpoint_host: Optional[str], + def cut_off_call(self, role: ModelRole | UsageRole, *, model: Optional[str], endpoint_host: Optional[str], reported_by: ReportedBy = ReportedBy.HARNESS) -> None: """A model call of ``role`` that was sent but never answered, cut off by a time limit or a cancel: a call of unknown usage, marking the role's entry a lower bound as ``cut_off`` marks a turn's, recorded as ``call`` records one, so it starts the role when it's the first.""" - self._add_call(role, _unreported(), model, endpoint_host, reported_by) + self._add_call(role, unreported(), model, endpoint_host, reported_by) - def _add_call(self, role: ModelRole, usage: Optional[Usage], model: Optional[str], endpoint_host: Optional[str], - reported_by: ReportedBy) -> None: + def _add_call(self, role: ModelRole | UsageRole, usage: Optional[Usage], model: Optional[str], + endpoint_host: Optional[str], reported_by: ReportedBy) -> None: self._role_for_call(role, model, endpoint_host, reported_by).add(usage) self.entries() diff --git a/tst/unit/env/gateway/executor_usage_test.py b/tst/unit/env/gateway/executor_usage_test.py new file mode 100644 index 000000000..abfb1ea9a --- /dev/null +++ b/tst/unit/env/gateway/executor_usage_test.py @@ -0,0 +1,95 @@ +"""The gateway's list of every call made to a trigger's executor, with the usage its final message reported +(``TriggerEngine.usage``, GET /triggers/usage), which a run's steps and teardown price as its colleagues' usage.""" +from __future__ import annotations + +import httpx +import pytest + +from agent_env.env.gateway import gateway as gw_mod +from agent_env.env.gateway import triggers as triggers_mod +from agent_env.env.gateway.clock import Clock +from agent_env.env.gateway.constants import EXT_TRIGGERS_URI, GATEWAY_EXTENSIONS +from agent_env.env.gateway.gateway import Gateway +from agent_env.env.gateway.triggers import TriggerEngine +from tst.unit.env.gateway.triggers_time_test import FakeNow, _FakeGateway + +EXECUTOR = {"a2a_url": "http://elias", "timeout_seconds": 5.0, "role": "elias"} +_CLIENT = httpx.AsyncClient +USAGE = {"input_tokens": 1200, "output_tokens": 80, "models": [ + {"model": "claude-sonnet-5-5", "input_tokens": 1200, "output_tokens": 80}]} + + +def _engine() -> TriggerEngine: + return TriggerEngine(_FakeGateway(Clock(now_fn=FakeNow()))) + + +def _executor_answers(monkeypatch, reply) -> None: + """The executor's A2A server, answering every request with ``reply(request)``.""" + monkeypatch.setattr(triggers_mod.httpx, "AsyncClient", + lambda **kwargs: _CLIENT(transport=httpx.MockTransport(reply), **kwargs)) + + +def _task(state: str, *parts: dict) -> httpx.Response: + return httpx.Response(200, json={"jsonrpc": "2.0", "id": "1", "result": { + "id": "task-1", "status": {"state": state, "message": {"role": "agent", "parts": list(parts)}}}}) + + +@pytest.mark.asyncio +async def test_a_reply_and_the_usage_its_final_message_reported_are_kept(monkeypatch): + engine = _engine() + _executor_answers(monkeypatch, lambda request: _task( + "completed", {"kind": "text", "text": "Sure, I'll take it."}, {"kind": "data", "data": {"usage": USAGE}})) + + reply = await engine._call_executor(EXECUTOR, "Reply to Dana", context_id="trigger-t1") + + assert reply == "Sure, I'll take it." + assert engine.usage()["calls"] == [{"role": "elias", "usage": USAGE}] + + +@pytest.mark.asyncio +async def test_a_call_that_ends_without_a_reply_is_kept_with_what_it_reported(monkeypatch): + engine = _engine() + _executor_answers(monkeypatch, lambda request: _task("failed", {"kind": "data", "data": {"usage": USAGE}})) + assert await engine._call_executor(EXECUTOR, "Reply", context_id="trigger-t1") is None + + _executor_answers(monkeypatch, lambda request: httpx.Response(502)) + with pytest.raises(httpx.HTTPStatusError): + await engine._call_executor(EXECUTOR, "Reply", context_id="trigger-t1") + + _executor_answers(monkeypatch, lambda request: _task("completed", {"kind": "text", "text": "ok"})) + await engine._call_executor(EXECUTOR, "Reply", context_id="trigger-t1") + + assert engine.usage()["calls"] == [{"role": "elias", "usage": USAGE}, {"role": "elias", "usage": None}, + {"role": "elias", "usage": None}] + + +@pytest.mark.asyncio +async def test_a_cleared_engine_keeps_the_calls_made_and_its_boot(monkeypatch): + engine = _engine() + _executor_answers(monkeypatch, lambda request: _task( + "completed", {"kind": "text", "text": "ok"}, {"kind": "data", "data": {"usage": USAGE}})) + await engine._call_executor(EXECUTOR, "Reply", context_id="trigger-t1") + before = engine.usage() + + engine.clear() + + assert engine.usage() == before and len(before["calls"]) == 1 + assert _engine().usage()["boot"] != before["boot"] + + +@pytest.mark.asyncio +async def test_the_gateway_serves_the_list_and_its_card_offers_it(tmp_path, monkeypatch): + monkeypatch.setattr(gw_mod, "GATEWAY_TRAJECTORY_FILE", str(tmp_path / "trajectory.jsonl")) + gw = Gateway(host="127.0.0.1", port=0, server_name="AgentEnvGateway", internal_mcp_servers=[]) + try: + gw._trigger_engine._executor_usage.append({"role": "elias", "usage": USAGE}) + transport = httpx.ASGITransport(app=gw._mcp.streamable_http_app()) + async with httpx.AsyncClient(transport=transport, base_url="http://gateway") as client: + served = (await client.get("/triggers/usage")).json() + finally: + gw._close_trajectory_file() + + assert served == {"boot": gw._trigger_engine.usage()["boot"], "calls": [{"role": "elias", "usage": USAGE}]} + [triggers] = [ext for ext in GATEWAY_EXTENSIONS if ext["uri"] == EXT_TRIGGERS_URI] + assert triggers["params"]["methods"]["usage"] == { + "method": "GET", "endpoint": "/triggers/usage", "request": {"type": "object", "properties": {}}} diff --git a/tst/unit/env/gateway/gateway_card_test.py b/tst/unit/env/gateway/gateway_card_test.py index 73c5fd09d..0a293d6de 100644 --- a/tst/unit/env/gateway/gateway_card_test.py +++ b/tst/unit/env/gateway/gateway_card_test.py @@ -389,11 +389,12 @@ async def test_env_data_plane_unknown_method(): def test_triggers_advertised_as_one_extension(): - """Triggers ride a single urn:agentenv:triggers/v1 (register/config/remove/clear/state) — no separate get URI.""" + """Triggers ride a single urn:agentenv:triggers/v1 (register/config/remove/clear/state/usage) — no separate get + URI.""" exts = _gateway({})._gateway_extensions() trigger = [e for e in exts if e["uri"] == "urn:agentenv:triggers/v1"] assert len(trigger) == 1 - assert set(trigger[0]["params"]["methods"]) == {"register", "config", "remove", "clear", "state"} + assert set(trigger[0]["params"]["methods"]) == {"register", "config", "remove", "clear", "state", "usage"} assert not any(e["uri"] == "urn:agentenv:get-triggers/v1" for e in exts) diff --git a/tst/unit/task/usage/colleague_ledger_test.py b/tst/unit/task/usage/colleague_ledger_test.py new file mode 100644 index 000000000..d36ab93f5 --- /dev/null +++ b/tst/unit/task/usage/colleague_ledger_test.py @@ -0,0 +1,121 @@ +"""A run's colleagues' usage in its ledger through ``Task.run`` and its teardown: the context's colleague entry joins +the ledger as each step completes, each executor call counts once whichever step or attempt wrote it, and the +teardown writes the calls that came after the last step. Real LocalSqliteDocumentStore.""" + +from __future__ import annotations + +import pytest + +from agent_env.config import set_document_store +from agent_env.store import LocalSqliteDocumentStore +from agent_env.task.store import TaskInstanceStore, set_task_instance_store +from agent_env.task.task import Task +from agent_env.task.teardown import tear_down +from agent_env.task.usage.ledger import merged +from agent_env.task_step.colleagues import record_colleague_usage +from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.task_step import RetryConfig, TaskStep +from tst.unit.task_step.colleagues_test import _call, _Env + + +@pytest.fixture +def store(tmp_path): + set_document_store(LocalSqliteDocumentStore(str(tmp_path / "instances.db"))) + s = TaskInstanceStore() + set_task_instance_store(s) + try: + yield s + finally: + set_task_instance_store(None) + + +class _Registers(TaskStep): + """Sets the executors of ``env`` up, as register_env_triggers records it.""" + + type = "registers" + + async def execute(self, context): + context.metadata.setdefault("env_trigger_registrations", []).append( + {"step_id": self.id, "env_id": "office", "added": [], "executor_agent_name": "elias", + "executor_agent_names": []}) + return context + + +class _Asks(TaskStep): + """A step whose agent a colleague answers once, recording the colleagues' usage as it ends; it fails on the attempts + ``fail_on`` names.""" + + type = "asks" + + def __init__(self, id, env, *, fail_on=(), **kwargs): + super().__init__(id, 1, **kwargs) + self.env, self.fail_on, self.attempts = env, set(fail_on), 0 + + async def execute(self, context): + self.attempts += 1 + self.env.calls.append(_call()) + await record_colleague_usage(context, [self.env]) + if self.attempts in self.fail_on: + raise RuntimeError(f"{self.id} fails on attempt {self.attempts}") + return context + + +class _Reads(TaskStep): + type = "reads" + + def __init__(self, id, store, **kwargs): + super().__init__(id, 1, **kwargs) + self.store, self.seen = store, None + + async def execute(self, context): + self.seen = _colleagues(self.store, context.instance_id) + return context + + +def _colleagues(store, instance_id): + return [(e["attempt"], e["step_id"], e["turns"]) for e in store.get(instance_id).usage if e["role"] == "colleague"] + + +@pytest.mark.asyncio +async def test_the_colleague_entry_joins_the_ledger_as_each_step_completes_and_counts_each_call_once(store): + env = _Env() + reads = _Reads("reads", store) + steps = [_Registers("triggers", 1), _Asks("ask", env), reads, _Asks("follow-up", env)] + + context = await Task(id="t", version=1, steps=steps).run(context=TaskStepContext()) + + assert reads.seen == [(None, "triggers", 1)] + assert _colleagues(store, context.instance_id) == [(None, "triggers", 2)] + assert store.get(context.instance_id).usage_total["input_tokens"] == 2000 + + +@pytest.mark.asyncio +async def test_a_retried_span_counts_each_executor_call_once(store): + env = _Env() + steps = [_Registers("triggers", 1), _Asks("ask", env), + _Asks("follow-up", env, fail_on={1}, retry_config=RetryConfig(retry_from_step_id="ask"))] + + context = await Task(id="t", version=1, steps=steps).run(context=TaskStepContext()) + + assert len(env.calls) == 4 + assert _colleagues(store, context.instance_id) == [(None, "triggers", 4)] + + +@pytest.mark.asyncio +async def test_the_teardown_writes_the_calls_that_came_after_the_last_step(store): + env = _Env() + context = await Task(id="t", version=1, steps=[_Registers("triggers", 1), _Asks("ask", env)]).run( + context=TaskStepContext()) + env.calls.append(_call()) + + await tear_down(context, (), [env], timeout=5) + + assert _colleagues(store, context.instance_id) == [(None, "triggers", 2)] + + +def test_a_gateways_colleague_entry_replaces_its_last_one_and_another_gateways_is_kept(): + first = {"attempt": None, "step_id": "triggers", "role": "colleague", "gateway_boot": "b1", "turns": 1} + + ledger = merged([first], [{**first, "turns": 2}, {**first, "gateway_boot": "b2", "turns": 1}]) + + assert [(entry["gateway_boot"], entry["turns"]) for entry in ledger] == [("b1", 2), ("b2", 1)] diff --git a/tst/unit/task/usage/summary_test.py b/tst/unit/task/usage/summary_test.py index 1bd9fcf66..6ed751e3a 100644 --- a/tst/unit/task/usage/summary_test.py +++ b/tst/unit/task/usage/summary_test.py @@ -24,6 +24,19 @@ def _bounds(summary): return summary.bound, [share.bound for share in summary.shares] +def test_the_roles_a_run_spends_outside_its_prompts_come_after_the_judge(): + summary = summarize([ + _entry("playground", "gpt-4.1-mini", 10, 1, 0.001), + _entry("colleague", "claude-sonnet-5-5", 20, 2, 0.002, attempt=None, step_id="triggers"), + _entry("judge", "gpt-4.1", 30, 3, 0.003), + _entry("validator", "gpt-4.1-nano", 40, 4, 0.004), + _entry("solver", "gpt-4.1-mini", 50, 5, 0.005), + ]) + + assert [share.role for share in summary.shares] == ["solver", "judge", "colleague", "validator", "playground"] + assert "; colleague claude-sonnet-5-5 $0.0020, 20 in, 2 out;" in cost_line(summary) + + def test_a_ledger_is_split_by_role_in_order_then_by_model_and_summed_across_steps(): summary = summarize([ _entry("judge", "claude-sonnet-4-6", 2900, 120, 0.0104), diff --git a/tst/unit/task_step/colleagues_test.py b/tst/unit/task_step/colleagues_test.py new file mode 100644 index 000000000..cf19280b6 --- /dev/null +++ b/tst/unit/task_step/colleagues_test.py @@ -0,0 +1,104 @@ +"""A run's colleagues' usage: an env gateway's executor calls as one ``colleague`` entry, written under the +``register_env_triggers`` step that set its executors up (``task_step.colleagues``).""" +from __future__ import annotations + +import logging + +import pytest + +from agent_env.config.model_pricing import configured_prices +from agent_env.env.gateway.constants import EXT_TRIGGERS_URI +from agent_env.task_step.colleagues import colleague_entry, record_colleague_usage +from agent_env.task_step.context import DeployedAgent, TaskStepContext + + +def _call(model: str = "gpt-4.1-mini", input_tokens: int = 1000, output_tokens: int = 100) -> dict: + return {"role": "elias", "usage": {"input_tokens": input_tokens, "output_tokens": output_tokens, "models": [ + {"model": model, "input_tokens": input_tokens, "output_tokens": output_tokens}]}} + + +def _entry(calls: list[dict]): + return colleague_entry(calls, gateway_boot="b1", env_id="office", endpoint_host=None, prices=configured_prices()) + + +def test_an_envs_executor_calls_are_one_colleague_entry_priced_model_by_model(): + entry = _entry([_call(), _call("gpt-4.1", input_tokens=2000)]) + + assert (entry["role"], entry["attempt"], entry["turns"], entry["env_id"], entry["gateway_boot"]) == ( + "colleague", None, 2, "office", "b1") + assert (entry["input_tokens"], entry["output_tokens"], entry["cost_status"], entry["partial"]) == ( + 3000, 200, "priced", False) + assert {row["model"]: row["input_tokens"] for row in entry["models"]} == {"gpt-4.1-mini": 1000, "gpt-4.1": 2000} + assert entry["cost_usd"] == pytest.approx(sum(row["cost_usd"] for row in entry["models"])) + + +def test_a_call_that_reported_nothing_makes_the_entry_a_lower_bound_never_zero(): + some = _entry([_call(), {"role": "elias", "usage": None}]) + none = _entry([{"role": "elias", "usage": None}]) + + assert (some["partial"], some["turns"], some["input_tokens"]) == (True, 2, 1000) and some["cost_usd"] > 0 + assert (none["cost_status"], none["cost_usd"], none["partial"]) == ("unpriced", None, True) + assert _entry([]) is None + + +class _Env: + """An env whose gateway lists ``calls`` under ``boot``, or fails the read with ``error``.""" + + def __init__(self, env_id: str = "office", calls=(), *, boot: str = "b1", lists: bool = True, error=None): + self.env_id, self.calls, self.boot, self.lists, self.error, self.reads = env_id, list(calls), boot, lists, error, 0 + + def supports(self, uri: str, method: str) -> bool: + return self.lists and (uri, method) == (EXT_TRIGGERS_URI, "usage") + + async def invoke(self, uri: str, method: str, params=None, *, timeout=None): + self.reads += 1 + if self.error is not None: + raise self.error + return {"boot": self.boot, "calls": list(self.calls)} + + +def _context(*envs: str) -> TaskStepContext: + context = TaskStepContext() + context.metadata["env_trigger_registrations"] = [ + {"step_id": f"triggers-{env_id}", "env_id": env_id, "added": [], "executor_agent_name": None, + "executor_agent_names": ["elias"]} for env_id in envs] + context.deployed_agents.append(DeployedAgent(agent_name="elias", api_url="http://elias", role="elias", + model_endpoint_host="models.example")) + return context + + +@pytest.mark.asyncio +async def test_the_entry_goes_under_the_step_that_set_the_executors_up_and_each_write_replaces_the_last(): + context, env = _context("office"), _Env(calls=[_call()]) + + first = await record_colleague_usage(context, [env]) + env.calls.append(_call()) + second = await record_colleague_usage(context, [env]) + + [kept] = context.metadata["step_usage"]["triggers-office"] + assert (kept["turns"], kept["endpoint_host"]) == (2, "models.example") + assert [(e["step_id"], e["turns"]) for e in first + second] == [("triggers-office", 1), ("triggers-office", 2)] + + +@pytest.mark.asyncio +async def test_a_redeployed_gateways_calls_are_kept_beside_the_first_ones(): + context = _context("office") + await record_colleague_usage(context, [_Env(calls=[_call()], boot="b1")]) + await record_colleague_usage(context, [_Env(calls=[_call(), _call()], boot="b2")]) + + kept = context.metadata["step_usage"]["triggers-office"] + assert [(e["gateway_boot"], e["turns"]) for e in kept] == [("b1", 1), ("b2", 2)] + + +@pytest.mark.asyncio +async def test_an_env_without_executors_or_a_list_is_skipped_and_a_failed_read_is_logged(caplog): + context = _context("office", "lab") + unregistered, unlisted = _Env("garage", [_call()]), _Env("lab", [_call()], lists=False) + failing = _Env("office", error=TimeoutError("no answer")) + + with caplog.at_level(logging.WARNING, logger="agent_env.task_step.colleagues"): + assert await record_colleague_usage(context, [unregistered, unlisted, failing]) == [] + + assert (unregistered.reads, unlisted.reads, failing.reads) == (0, 0, 1) + assert "step_usage" not in context.metadata + assert any("office" in record.getMessage() for record in caplog.records) diff --git a/tst/unit/task_step/test_prompt_agent_triggers.py b/tst/unit/task_step/test_prompt_agent_triggers.py index 3f4e16634..043c51805 100644 --- a/tst/unit/task_step/test_prompt_agent_triggers.py +++ b/tst/unit/task_step/test_prompt_agent_triggers.py @@ -254,6 +254,30 @@ async def fake_get(self, url, timeout, params=None, headers=None): assert calls["n"] == 1 +@pytest.mark.asyncio +async def test_a_capture_records_what_the_envs_executors_spent_under_the_step_that_set_them_up(): + usage = {"boot": "b1", "calls": [{"role": "elias", "usage": {"input_tokens": 1000, "output_tokens": 100}}, + {"role": "elias", "usage": None}]} + + async def fake_get(self, url, timeout, params=None, headers=None): + if url.endswith("/clock/state"): + return _resp(200, _CLOCK) + return _resp(200, usage if url.endswith("/triggers/usage") else _STATE) + + ctx = TaskStepContext( + deployed_envs=[_env("env-a", "http://gw-a")], deployed_agents=[], instance_id="inst-1", + metadata={"env_trigger_registrations": [ + {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": "elias"}]}) + + _, cfg_patch = _patched_store() + with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: + await _capture_step()._persist_env_trigger_state(ctx) + + [entry] = ctx.metadata["step_usage"]["reg-1"] + assert (entry["role"], entry["turns"], entry["input_tokens"], entry["partial"], entry["gateway_boot"]) == ( + "colleague", 2, 1000, True, "b1") + + @pytest.mark.asyncio async def test_capture_is_kept_under_the_fixture_prefix(): async def fake_get(self, url, timeout, params=None, headers=None): From ebbabfb12f1fa78fa96300401fea7feedf95c661 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 19:45:14 -0800 Subject: [PATCH 02/10] fix(usage): list an executor call while it runs, keep the later copy of a gateway's list, count real attempts - The gateway lists a call to an executor as it starts, with no usage until its reply ends, so a teardown that reads while a colleague is still answering counts that call, as one of unknown usage, and the entry is a lower bound rather than exact. - `GET /triggers/usage` carries a `version` every change to the list raises, kept on the entry (`gateway_version`). The ledger, and a step's context, never replace a gateway's colleague entry with one read from an earlier copy of its list (`older`), which a parallel step's completion write can land with after a newer one. - `summarize` counts the attempts entries name; an attempt-less colleague entry isn't one of its own. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/triggers.py | 27 ++++++++++++++------ src/agent_env/task/usage/ledger.py | 8 ++++-- src/agent_env/task/usage/summary.py | 3 ++- src/agent_env/task_step/colleagues.py | 27 ++++++++++++-------- src/agent_env/task_step/usage.py | 8 ++++++ tst/unit/env/gateway/executor_usage_test.py | 25 +++++++++++++++++- tst/unit/task/usage/colleague_ledger_test.py | 10 ++++++++ tst/unit/task/usage/summary_test.py | 1 + tst/unit/task_step/colleagues_test.py | 16 ++++++++++-- 9 files changed, 100 insertions(+), 25 deletions(-) diff --git a/src/agent_env/env/gateway/triggers.py b/src/agent_env/env/gateway/triggers.py index d84e03a01..7bf1d7004 100644 --- a/src/agent_env/env/gateway/triggers.py +++ b/src/agent_env/env/gateway/triggers.py @@ -465,9 +465,11 @@ def __init__(self, gateway): # One turn at a time per executor conversation (its URL and context id): fires of one trigger running side by # side would otherwise resume the same session at once. self._executor_locks: dict[tuple[str, str], asyncio.Lock] = {} - # Every call made to an executor, with the usage it reported (`usage`), under this engine's own id. + # Every call made to an executor, with the usage it reported (`usage`), under this engine's own id and a + # version every change to the list raises. self._executor_usage: list[dict] = [] self._usage_boot = secrets.token_hex(6) + self._usage_version = 0 def register(self, body: Any) -> dict: """Additively add each trigger by id (idempotent upsert; conflicting id or bad shape -> 400); watch_roles and @@ -990,10 +992,13 @@ def state(self) -> dict: } def usage(self) -> dict: - """Every call made to an executor so far (GET /triggers/usage): each one's ``role``, the executor's, and the - ``usage`` its final message reported, as it sent it, None when it reported none or no reply was read; ``boot`` - is this engine's own id, so a reader that keeps the calls by it tells a restarted gateway's apart.""" - return {"boot": self._usage_boot, "calls": [dict(call) for call in self._executor_usage]} + """Every call made to an executor so far (GET /triggers/usage), a call still waiting for its reply included: + each one's ``role``, the executor's, and the ``usage`` its final message reported, as it sent it, None while it + runs and when it reported none or no reply was read. ``boot`` is this engine's own id, so a reader that keeps + the calls by it tells a restarted gateway's apart, and ``version`` rises with every change to the list, so a + reader holding two copies keeps the later.""" + return {"boot": self._usage_boot, "version": self._usage_version, + "calls": [dict(call) for call in self._executor_usage]} def on_tool_call(self, role: str, name: str, arguments: dict, result: Any) -> tuple[list[asyncio.Task], float | None]: @@ -1766,15 +1771,21 @@ async def _nap(self, seconds: float) -> None: moved.cancel() async def _call_executor(self, executor: dict | None, instruction: str, context_id: str) -> str | None: - """The executor's reply to ``instruction``, None when it gave none in time; the call and the usage its final - message reported go into ``usage`` however it ends, a call whose usage never came back included.""" + """The executor's reply to ``instruction``, None when it gave none in time. The call goes into ``usage`` as it + starts, with no usage while it runs, and takes the usage its final message reported when it ends, however it + ends; one whose usage never came back keeps none.""" if executor is None: return None + call: dict[str, Any] = {"role": executor["role"], "usage": None} + self._executor_usage.append(call) + self._usage_version += 1 reported: list[Any] = [] try: return await self._send_to_executor(executor, instruction, context_id, reported) finally: - self._executor_usage.append({"role": executor["role"], "usage": reported[-1] if reported else None}) + if reported: + call["usage"] = reported[-1] + self._usage_version += 1 async def _send_to_executor(self, executor: dict, instruction: str, context_id: str, reported: list[Any]) -> str | None: diff --git a/src/agent_env/task/usage/ledger.py b/src/agent_env/task/usage/ledger.py index b27a3050e..e3ccfe430 100644 --- a/src/agent_env/task/usage/ledger.py +++ b/src/agent_env/task/usage/ledger.py @@ -8,6 +8,8 @@ from collections.abc import Collection, Mapping from typing import Any, Optional +from agent_env.task_step.usage import older + LEDGER_KEY = "usage" TOTAL_KEY = "usage_total" _COUNTS = ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens") @@ -31,13 +33,15 @@ def merged(ledger: list[dict], entries: list[dict]) -> list[dict]: """``ledger`` with ``entries`` in it. An entry replaces the one of its attempt, step and role: a step's entry is its sum so far, so a write sent again, or a later one of the same attempt, never counts twice. A retry or a resume runs under a new attempt epoch, so its entries are new ones. A colleague entry is one env gateway's executor calls - so far, kept by that gateway's ``gateway_boot`` too, so a gateway a retry redeployed adds its own.""" + so far, kept by that gateway's ``gateway_boot`` too, so a gateway a retry redeployed adds its own, and never + replaced by an earlier copy of the gateway's list (``older``), which a parallel step's write can land with.""" out = list(ledger) at = {_key(entry): i for i, entry in enumerate(out)} for entry in entries: key = _key(entry) if key in at: - out[at[key]] = entry + if not older(entry, out[at[key]]): + out[at[key]] = entry else: at[key] = len(out) out.append(entry) diff --git a/src/agent_env/task/usage/summary.py b/src/agent_env/task/usage/summary.py index a3776f0b4..dcd144456 100644 --- a/src/agent_env/task/usage/summary.py +++ b/src/agent_env/task/usage/summary.py @@ -151,7 +151,8 @@ def summarize(ledger: Iterable[UsageEntry]) -> UsageSummary | None: if part.get("cost_usd") is not None and part.get("cost_source"): sources.add(part["cost_source"]) ordered = sorted(shares.values(), key=lambda share: (_rank(share.role), share.role, share.model or "")) - return UsageSummary(shares=tuple(ordered), attempts=len({entry.get("attempt") for entry in entries}), + numbered = {entry.get("attempt") for entry in entries if entry.get("attempt") is not None} + return UsageSummary(shares=tuple(ordered), attempts=len(numbered) or 1, sources=tuple(sorted(sources))) diff --git a/src/agent_env/task_step/colleagues.py b/src/agent_env/task_step/colleagues.py index df65b19ec..1b7260fec 100644 --- a/src/agent_env/task_step/colleagues.py +++ b/src/agent_env/task_step/colleagues.py @@ -19,7 +19,7 @@ from agent_env.config.model import UsageRole from agent_env.config.model_pricing import PriceSource, configured_prices from agent_env.env.gateway.constants import EXT_TRIGGERS_URI -from agent_env.task_step.usage import STEP_USAGE_KEY, RoleUsage, UsageEntry, unreported +from agent_env.task_step.usage import STEP_USAGE_KEY, RoleUsage, UsageEntry, older, unreported if TYPE_CHECKING: from agent_env.env.env import DeployedEnv @@ -31,12 +31,13 @@ READ_TIMEOUT_SECONDS = 15 -def colleague_entry(calls: Iterable[Mapping], *, gateway_boot: str, env_id: str, endpoint_host: Optional[str], - prices: PriceSource) -> Optional[UsageEntry]: +def colleague_entry(calls: Iterable[Mapping], *, gateway_boot: str, gateway_version: int, env_id: str, + endpoint_host: Optional[str], prices: PriceSource) -> Optional[UsageEntry]: """One env gateway's executor calls as one ``colleague`` entry: each call's usage read as its executor reported it - (``read_usage``), one that reported none counted as a call of unknown usage, which makes the entry a lower bound, - never $0; priced as any role's turns are, by model where the executors gave their counts by model. It has no - attempt, since it holds the gateway's calls whichever attempt made them. None when there were no calls.""" + (``read_usage``), one still running or that reported none counted as a call of unknown usage, which makes the entry + a lower bound, never $0; priced as any role's turns are, by model where the executors gave their counts by model. + It has no attempt, since it holds the gateway's calls whichever attempt made them, and it keeps the version of the + list it was read from (``ledger.older``). None when there were no calls.""" role = RoleUsage(UsageRole.COLLEAGUE.value, endpoint_host=endpoint_host, attempt=None) for call in calls: usage, unparsed = read_usage(call.get("usage")) @@ -46,6 +47,7 @@ def colleague_entry(calls: Iterable[Mapping], *, gateway_boot: str, env_id: str, entry = role.entry(prices) entry["env_id"] = env_id entry["gateway_boot"] = gateway_boot + entry["gateway_version"] = gateway_version return entry @@ -63,8 +65,8 @@ async def record_colleague_usage(context: TaskStepContext, envs: Sequence[Deploy try: report = await env.invoke(EXT_TRIGGERS_URI, "usage", timeout=READ_TIMEOUT_SECONDS) entry = colleague_entry(report.get("calls") or [], gateway_boot=str(report.get("boot")), - env_id=env.env_id, endpoint_host=_executors_host(context, registration), - prices=configured_prices()) + gateway_version=int(report.get("version") or 0), env_id=env.env_id, + endpoint_host=_executors_host(context, registration), prices=configured_prices()) except Exception as e: # noqa: BLE001 - a colleague's usage never fails its step or the teardown logger.warning("the colleague usage on env %s wasn't read: %s", env.env_id, e) continue @@ -97,7 +99,10 @@ def _executors_host(context: TaskStepContext, registration: dict) -> Optional[st def _keep(context: TaskStepContext, step_id: str, entry: UsageEntry) -> None: - """``entry`` in ``step_id``'s step usage, in place of that gateway's earlier one.""" + """``entry`` in ``step_id``'s step usage, in place of that gateway's earlier one, unless it was read from an + earlier copy of the gateway's list, as a step running beside another can read it.""" kept = context.metadata.setdefault(STEP_USAGE_KEY, {}).setdefault(step_id, []) - kept[:] = [*(e for e in kept if not (e.get("role") == entry["role"] - and e.get("gateway_boot") == entry["gateway_boot"])), entry] + same = [e for e in kept if e.get("role") == entry["role"] and e.get("gateway_boot") == entry["gateway_boot"]] + if any(older(entry, e) for e in same): + return + kept[:] = [*(e for e in kept if e not in same), entry] diff --git a/src/agent_env/task_step/usage.py b/src/agent_env/task_step/usage.py index 81f3ee2af..18f74c8d1 100644 --- a/src/agent_env/task_step/usage.py +++ b/src/agent_env/task_step/usage.py @@ -90,6 +90,7 @@ class UsageEntry(CostFields): unparsed_turns: NotRequired[int] env_id: NotRequired[str] gateway_boot: NotRequired[str] + gateway_version: NotRequired[int] @dataclass @@ -269,6 +270,13 @@ def _combined(costs: list[Cost]) -> Cost: cache_write_ttl_tokens=ttl_sum(c.cache_write_ttl_tokens for c in priced)) +def older(entry: dict, than: dict) -> bool: + """Whether ``entry`` was read from an earlier copy of its gateway's executor calls than ``than`` was + (``gateway_version``); never for an entry that isn't a colleague's.""" + version, kept = entry.get("gateway_version"), than.get("gateway_version") + return isinstance(version, int) and isinstance(kept, int) and version < kept + + def unreported() -> Usage: """A turn or call whose usage never came back.""" return Usage(provider_details={"unreported": True}) diff --git a/tst/unit/env/gateway/executor_usage_test.py b/tst/unit/env/gateway/executor_usage_test.py index abfb1ea9a..20bebd97f 100644 --- a/tst/unit/env/gateway/executor_usage_test.py +++ b/tst/unit/env/gateway/executor_usage_test.py @@ -2,6 +2,8 @@ (``TriggerEngine.usage``, GET /triggers/usage), which a run's steps and teardown price as its colleagues' usage.""" from __future__ import annotations +import asyncio + import httpx import pytest @@ -63,6 +65,26 @@ async def test_a_call_that_ends_without_a_reply_is_kept_with_what_it_reported(mo {"role": "elias", "usage": None}] +@pytest.mark.asyncio +async def test_a_call_is_listed_while_it_waits_for_its_reply_and_every_change_raises_the_version(monkeypatch): + engine, release = _engine(), asyncio.Event() + + async def replies_later(self, executor, instruction, context_id, reported): + await release.wait() + reported.append(USAGE) + return "ok" + + monkeypatch.setattr(TriggerEngine, "_send_to_executor", replies_later) + call = asyncio.ensure_future(engine._call_executor(EXECUTOR, "Reply", context_id="trigger-t1")) + await asyncio.sleep(0) + waiting = engine.usage() + release.set() + await call + + assert (waiting["version"], waiting["calls"]) == (1, [{"role": "elias", "usage": None}]) + assert (engine.usage()["version"], engine.usage()["calls"]) == (2, [{"role": "elias", "usage": USAGE}]) + + @pytest.mark.asyncio async def test_a_cleared_engine_keeps_the_calls_made_and_its_boot(monkeypatch): engine = _engine() @@ -89,7 +111,8 @@ async def test_the_gateway_serves_the_list_and_its_card_offers_it(tmp_path, monk finally: gw._close_trajectory_file() - assert served == {"boot": gw._trigger_engine.usage()["boot"], "calls": [{"role": "elias", "usage": USAGE}]} + assert served == {"boot": gw._trigger_engine.usage()["boot"], "version": 0, + "calls": [{"role": "elias", "usage": USAGE}]} [triggers] = [ext for ext in GATEWAY_EXTENSIONS if ext["uri"] == EXT_TRIGGERS_URI] assert triggers["params"]["methods"]["usage"] == { "method": "GET", "endpoint": "/triggers/usage", "request": {"type": "object", "properties": {}}} diff --git a/tst/unit/task/usage/colleague_ledger_test.py b/tst/unit/task/usage/colleague_ledger_test.py index d36ab93f5..cc5530577 100644 --- a/tst/unit/task/usage/colleague_ledger_test.py +++ b/tst/unit/task/usage/colleague_ledger_test.py @@ -119,3 +119,13 @@ def test_a_gateways_colleague_entry_replaces_its_last_one_and_another_gateways_i ledger = merged([first], [{**first, "turns": 2}, {**first, "gateway_boot": "b2", "turns": 1}]) assert [(entry["gateway_boot"], entry["turns"]) for entry in ledger] == [("b1", 2), ("b2", 1)] + + +def test_a_write_of_an_earlier_list_never_takes_calls_back(): + later = {"attempt": None, "step_id": "triggers", "role": "colleague", "gateway_boot": "b1", "gateway_version": 4, + "turns": 2} + + ledger = merged([later], [{**later, "gateway_version": 2, "turns": 1}]) + + assert [(entry["gateway_version"], entry["turns"]) for entry in ledger] == [(4, 2)] + diff --git a/tst/unit/task/usage/summary_test.py b/tst/unit/task/usage/summary_test.py index 6ed751e3a..cd5cbf951 100644 --- a/tst/unit/task/usage/summary_test.py +++ b/tst/unit/task/usage/summary_test.py @@ -35,6 +35,7 @@ def test_the_roles_a_run_spends_outside_its_prompts_come_after_the_judge(): assert [share.role for share in summary.shares] == ["solver", "judge", "colleague", "validator", "playground"] assert "; colleague claude-sonnet-5-5 $0.0020, 20 in, 2 out;" in cost_line(summary) + assert summary.attempts == 1 def test_a_ledger_is_split_by_role_in_order_then_by_model_and_summed_across_steps(): diff --git a/tst/unit/task_step/colleagues_test.py b/tst/unit/task_step/colleagues_test.py index cf19280b6..a59001884 100644 --- a/tst/unit/task_step/colleagues_test.py +++ b/tst/unit/task_step/colleagues_test.py @@ -18,7 +18,8 @@ def _call(model: str = "gpt-4.1-mini", input_tokens: int = 1000, output_tokens: def _entry(calls: list[dict]): - return colleague_entry(calls, gateway_boot="b1", env_id="office", endpoint_host=None, prices=configured_prices()) + return colleague_entry(calls, gateway_boot="b1", gateway_version=len(calls), env_id="office", endpoint_host=None, + prices=configured_prices()) def test_an_envs_executor_calls_are_one_colleague_entry_priced_model_by_model(): @@ -54,7 +55,7 @@ async def invoke(self, uri: str, method: str, params=None, *, timeout=None): self.reads += 1 if self.error is not None: raise self.error - return {"boot": self.boot, "calls": list(self.calls)} + return {"boot": self.boot, "version": len(self.calls), "calls": list(self.calls)} def _context(*envs: str) -> TaskStepContext: @@ -80,6 +81,17 @@ async def test_the_entry_goes_under_the_step_that_set_the_executors_up_and_each_ assert [(e["step_id"], e["turns"]) for e in first + second] == [("triggers-office", 1), ("triggers-office", 2)] +@pytest.mark.asyncio +async def test_a_read_of_an_earlier_list_never_replaces_a_later_one(): + context, env = _context("office"), _Env(calls=[_call(), _call()]) + await record_colleague_usage(context, [env]) + + await record_colleague_usage(context, [_Env(calls=[_call()])]) + + [kept] = context.metadata["step_usage"]["triggers-office"] + assert (kept["turns"], kept["gateway_version"]) == (2, 2) + + @pytest.mark.asyncio async def test_a_redeployed_gateways_calls_are_kept_beside_the_first_ones(): context = _context("office") From 34cbfb95ed155f8fd934a1b2498eb6cb67260868 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 21:45:28 -0800 Subject: [PATCH 03/10] feat(usage): a reply past its time limit is still read for its usage An executor that answers past its time limit is still working, and still spending. Its call was recorded with no usage, so its run's colleague entry stayed a lower bound with those dollars unknown. The gateway now hands that call's read to the background when it gives up on it: the send still waiting for its reply, or the task still to poll, up to `_LATE_REPLY_S` (10 minutes) more. When the task ends, the usage its final message reports goes on the call and raises the list's version, so the next write of the run's colleague entry prices it. The fire sees what it always did: `ReadTimeout` for a send held past its window, no reply for a task still working at its deadline. A `clear` leaves the reads to finish. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/triggers.py | 122 +++++++++++++++----- tst/unit/env/gateway/executor_usage_test.py | 52 ++++++++- 2 files changed, 142 insertions(+), 32 deletions(-) diff --git a/src/agent_env/env/gateway/triggers.py b/src/agent_env/env/gateway/triggers.py index 7bf1d7004..92e4d8fe9 100644 --- a/src/agent_env/env/gateway/triggers.py +++ b/src/agent_env/env/gateway/triggers.py @@ -66,6 +66,8 @@ _VIRTUAL_RESOLUTION_S = 1e-6 # Seconds an executor call waits to connect, and for a task poll's answer. _EXECUTOR_HTTP_TIMEOUT_S = 30.0 +# How much longer a call past its time limit is still read, for the usage its reply reports, in seconds. +_LATE_REPLY_S = 600.0 # An allowlist, not a size bound: identifier/metadata keys only, since bodies and addresses are PII. _ECHO_KEYS = frozenset({ "action", "createdTime", "fileName", "kind", "mimeType", "modifiedTime", "name", "role", @@ -442,6 +444,15 @@ def _validate_check(check: Any, where: str) -> dict: return {"steps": steps} + +async def _task_status(client: httpx.AsyncClient, url: str, task_id: str) -> dict: + """An executor's A2A task's status, polled with ``tasks/get``.""" + poll = await client.post(url, json={"jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": "tasks/get", + "params": {"id": task_id}}) + poll.raise_for_status() + return (poll.json().get("result") or {}).get("status") or {} + + class TriggerEngine: def __init__(self, gateway): self._gw = gateway @@ -470,6 +481,8 @@ def __init__(self, gateway): self._executor_usage: list[dict] = [] self._usage_boot = secrets.token_hex(6) self._usage_version = 0 + # The reads of calls still going, a late one's included, which a `clear` leaves to finish. + self._executor_reads: set[asyncio.Task] = set() def register(self, body: Any) -> dict: """Additively add each trigger by id (idempotent upsert; conflicting id or bad shape -> 400); watch_roles and @@ -1773,36 +1786,42 @@ async def _nap(self, seconds: float) -> None: async def _call_executor(self, executor: dict | None, instruction: str, context_id: str) -> str | None: """The executor's reply to ``instruction``, None when it gave none in time. The call goes into ``usage`` as it starts, with no usage while it runs, and takes the usage its final message reported when it ends, however it - ends; one whose usage never came back keeps none.""" + ends; a reply past the time limit is still read for that usage, in the background, up to ``_LATE_REPLY_S`` + more (``_read_late``), since a late reply is spent too. One whose usage never came back keeps none.""" if executor is None: return None call: dict[str, Any] = {"role": executor["role"], "usage": None} self._executor_usage.append(call) self._usage_version += 1 - reported: list[Any] = [] - try: - return await self._send_to_executor(executor, instruction, context_id, reported) - finally: - if reported: - call["usage"] = reported[-1] - self._usage_version += 1 + return await self._send_to_executor(executor, instruction, context_id, call) - async def _send_to_executor(self, executor: dict, instruction: str, context_id: str, - reported: list[Any]) -> str | None: + async def _send_to_executor(self, executor: dict, instruction: str, context_id: str, call: dict) -> str | None: url = f"{executor['a2a_url']}/a2a" deadline = asyncio.get_running_loop().time() + executor["timeout_seconds"] - async with httpx.AsyncClient(timeout=_EXECUTOR_HTTP_TIMEOUT_S) as client: + client = httpx.AsyncClient(timeout=_EXECUTOR_HTTP_TIMEOUT_S) + handed_on = False + try: # An executor holds message/send open until its task ends, so the read waits as long as the executor may - # take, and a little longer, so a reply that completes just past the time limit is still read. + # take, and a little longer, so a reply that completes just past the time limit is still read; past that + # the call times out, and its read goes on in the background for the usage alone. read_s = max(_EXECUTOR_HTTP_TIMEOUT_S, executor["timeout_seconds"]) + _EXECUTOR_HTTP_TIMEOUT_S - send = await client.post(url, timeout=httpx.Timeout(_EXECUTOR_HTTP_TIMEOUT_S, read=read_s), json={ - "jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": "message/send", - "params": {"message": {"role": "user", "messageId": uuid.uuid4().hex, - "contextId": context_id, - "parts": [{"kind": "text", "text": instruction}]}}, - }) - send.raise_for_status() - result = send.json().get("result") or {} + send = asyncio.ensure_future(client.post( + url, timeout=httpx.Timeout(_EXECUTOR_HTTP_TIMEOUT_S, read=read_s + _LATE_REPLY_S), json={ + "jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": "message/send", + "params": {"message": {"role": "user", "messageId": uuid.uuid4().hex, + "contextId": context_id, + "parts": [{"kind": "text", "text": instruction}]}}, + })) + try: + response = await asyncio.wait_for(asyncio.shield(send), timeout=read_s) + except TimeoutError: + handed_on = self._read_late(client, url, call, send=send) + raise httpx.ReadTimeout("") from None # as the read itself timed out before + except asyncio.CancelledError: # a call its fire gave up on is spent too + handed_on = self._read_late(client, url, call, send=send) + raise + response.raise_for_status() + result = response.json().get("result") or {} task_id = result.get("id") if not task_id: return None @@ -1811,20 +1830,63 @@ async def _send_to_executor(self, executor: dict, instruction: str, context_id: last = False while status.get("state") not in _TERMINAL_A2A_STATES: if last: + handed_on = self._read_late(client, url, call, task_id=task_id) return None last = asyncio.get_running_loop().time() >= deadline if not last: await asyncio.sleep(2) - poll = await client.post(url, json={"jsonrpc": "2.0", "id": str(uuid.uuid4()), - "method": "tasks/get", "params": {"id": task_id}}) - poll.raise_for_status() - status = ((poll.json().get("result") or {}).get("status") or {}) - parts = (status.get("message") or {}).get("parts") or [] - reported.extend(p["data"]["usage"] for p in parts if p.get("kind") == "data" - and isinstance(p.get("data"), dict) and p["data"].get("usage") is not None) - if status.get("state") != "completed": - return None - return "\n".join(p.get("text", "") for p in parts if p.get("kind") == "text") + status = await _task_status(client, url, task_id) + return self._replied(status, call) + finally: + if not handed_on: + await client.aclose() + + def _replied(self, status: dict, call: dict) -> str | None: + """The text of an ended executor task's final message when it completed; the usage that message reported goes + on ``call``.""" + parts = (status.get("message") or {}).get("parts") or [] + reported = [p["data"]["usage"] for p in parts if p.get("kind") == "data" + and isinstance(p.get("data"), dict) and p["data"].get("usage") is not None] + if reported: + call["usage"] = reported[-1] + self._usage_version += 1 + if status.get("state") != "completed": + return None + return "\n".join(p.get("text", "") for p in parts if p.get("kind") == "text") + + def _read_late(self, client: httpx.AsyncClient, url: str, call: dict, *, send: asyncio.Future | None = None, + task_id: str | None = None) -> bool: + """Read a call that ran past its time limit until its task ends, at most ``_LATE_REPLY_S``, in the background, + for the usage its final message reports: the ``send`` still waiting for its reply, or the task to poll. Closes + ``client`` when done; a `clear` leaves it to finish.""" + async def read() -> None: + try: + tid, status = task_id, {} + if send is not None: + response = await send + response.raise_for_status() + result = response.json().get("result") or {} + tid, status = result.get("id"), result.get("status") or {} + until = asyncio.get_running_loop().time() + _LATE_REPLY_S + while tid and status.get("state") not in _TERMINAL_A2A_STATES: + if asyncio.get_running_loop().time() >= until: + return + await asyncio.sleep(2) + status = await _task_status(client, url, tid) + if status.get("state") in _TERMINAL_A2A_STATES: + self._replied(status, call) + finally: + await client.aclose() + + late = asyncio.ensure_future(read()) + self._executor_reads.add(late) + late.add_done_callback(self._read_done) + return True + + def _read_done(self, read: asyncio.Task) -> None: + self._executor_reads.discard(read) + if not read.cancelled(): + read.exception() # a late read that fails leaves its call's usage unknown, never an error def _cancel(self, tid: str, trig: dict, **cause) -> None: """Retire a deadline its `unless` call answered, and the time triggers anchored on it, which can no longer fire.""" diff --git a/tst/unit/env/gateway/executor_usage_test.py b/tst/unit/env/gateway/executor_usage_test.py index 20bebd97f..4d01efc16 100644 --- a/tst/unit/env/gateway/executor_usage_test.py +++ b/tst/unit/env/gateway/executor_usage_test.py @@ -31,6 +31,13 @@ def _executor_answers(monkeypatch, reply) -> None: lambda **kwargs: _CLIENT(transport=httpx.MockTransport(reply), **kwargs)) +_SLEEP = asyncio.sleep + + +async def _no_wait(seconds: float) -> None: + await _SLEEP(0) + + def _task(state: str, *parts: dict) -> httpx.Response: return httpx.Response(200, json={"jsonrpc": "2.0", "id": "1", "result": { "id": "task-1", "status": {"state": state, "message": {"role": "agent", "parts": list(parts)}}}}) @@ -69,9 +76,10 @@ async def test_a_call_that_ends_without_a_reply_is_kept_with_what_it_reported(mo async def test_a_call_is_listed_while_it_waits_for_its_reply_and_every_change_raises_the_version(monkeypatch): engine, release = _engine(), asyncio.Event() - async def replies_later(self, executor, instruction, context_id, reported): + async def replies_later(self, executor, instruction, context_id, call): await release.wait() - reported.append(USAGE) + call["usage"] = USAGE + self._usage_version += 1 return "ok" monkeypatch.setattr(TriggerEngine, "_send_to_executor", replies_later) @@ -85,6 +93,46 @@ async def replies_later(self, executor, instruction, context_id, reported): assert (engine.usage()["version"], engine.usage()["calls"]) == (2, [{"role": "elias", "usage": USAGE}]) +@pytest.mark.asyncio +async def test_a_reply_held_past_its_time_limit_times_out_and_is_still_read_for_its_usage(monkeypatch): + monkeypatch.setattr(triggers_mod, "_EXECUTOR_HTTP_TIMEOUT_S", 0.05) + engine, release = _engine(), asyncio.Event() + + async def answers_late(request: httpx.Request) -> httpx.Response: + await release.wait() + return _task("completed", {"kind": "text", "text": "late"}, {"kind": "data", "data": {"usage": USAGE}}) + + _executor_answers(monkeypatch, answers_late) + with pytest.raises(httpx.ReadTimeout): + await engine._call_executor({**EXECUTOR, "timeout_seconds": 0.05}, "Reply", context_id="trigger-t1") + late = engine.usage() + engine.clear() + release.set() + await asyncio.gather(*engine._executor_reads) + + assert late["calls"] == [{"role": "elias", "usage": None}] + assert (engine.usage()["version"], engine.usage()["calls"]) == (2, [{"role": "elias", "usage": USAGE}]) + + +@pytest.mark.asyncio +async def test_a_task_still_working_at_its_time_limit_is_none_and_still_polled_for_its_usage(monkeypatch): + monkeypatch.setattr(triggers_mod.asyncio, "sleep", _no_wait) + engine, done = _engine(), asyncio.Event() + + def answers(request: httpx.Request) -> httpx.Response: + if done.is_set() and b"tasks/get" in request.content: + return _task("completed", {"kind": "text", "text": "late"}, {"kind": "data", "data": {"usage": USAGE}}) + return _task("working") + + _executor_answers(monkeypatch, answers) + reply = await engine._call_executor({**EXECUTOR, "timeout_seconds": 0.0}, "Reply", context_id="trigger-t1") + done.set() + await asyncio.gather(*engine._executor_reads) + + assert reply is None + assert (engine.usage()["version"], engine.usage()["calls"]) == (2, [{"role": "elias", "usage": USAGE}]) + + @pytest.mark.asyncio async def test_a_cleared_engine_keeps_the_calls_made_and_its_boot(monkeypatch): engine = _engine() From 94c08bbbd38ccd2d4b71d349b7f7dedfabdb89bd Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 21:53:09 -0800 Subject: [PATCH 04/10] docs(agents): a reply past its time limit is still read for its usage Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4e719158c..96cd64b4c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -441,8 +441,9 @@ orchestrators call it the same way. What callers rely on: without retries, a lower bound for one with. A runner that writes the instance some other way loses that spend from the ledger. - A run's colleagues, the executors an env's gateway calls when a trigger fires, are spent outside any prompt: the - gateway lists every such call with the usage its final message reported (`GET /triggers/usage`, under its own boot - id, kept through a `clear`). `prompt_agent` and `always_on` as they end, and the teardown, write the list as one + gateway lists every such call as it starts, with the usage its final message reported once it ends + (`GET /triggers/usage`, under its own boot id and a version every change raises, kept through a `clear`), a reply + past its time limit still read for that usage in the background, for up to ten minutes more. `prompt_agent` and `always_on` as they end, and the teardown, write the list as one `colleague` entry per env and gateway boot (`task_step/colleagues.py`), with no attempt, under the `register_env_triggers` step that set the executors up; the ledger keeps it by `gateway_boot` too, so each write is the whole list and replaces the last, a call counts once whichever step or attempt wrote it, and a gateway a retry From fc8e82e5f59b0fc13ce89194b82e4a3734c402b4 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 1 Dec 2026 05:43:33 -0800 Subject: [PATCH 05/10] fix(gateway): a call cancelled while its task is polled is still read for its usage A fire that `clear` or `remove` cancelled while it polled its executor's task closed the client and left the call unpriced. The poll now hands the task to the background read (`_read_late`), as a cancelled send already does. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/triggers.py | 20 ++++++++++------- tst/unit/env/gateway/executor_usage_test.py | 24 +++++++++++++++++++++ 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/src/agent_env/env/gateway/triggers.py b/src/agent_env/env/gateway/triggers.py index 92e4d8fe9..77174f295 100644 --- a/src/agent_env/env/gateway/triggers.py +++ b/src/agent_env/env/gateway/triggers.py @@ -1828,14 +1828,18 @@ async def _send_to_executor(self, executor: dict, instruction: str, context_id: status = result.get("status") or {} # Polled until the time limit, then once more: a reply that completed in the last poll's gap is kept. last = False - while status.get("state") not in _TERMINAL_A2A_STATES: - if last: - handed_on = self._read_late(client, url, call, task_id=task_id) - return None - last = asyncio.get_running_loop().time() >= deadline - if not last: - await asyncio.sleep(2) - status = await _task_status(client, url, task_id) + try: + while status.get("state") not in _TERMINAL_A2A_STATES: + if last: + handed_on = self._read_late(client, url, call, task_id=task_id) + return None + last = asyncio.get_running_loop().time() >= deadline + if not last: + await asyncio.sleep(2) + status = await _task_status(client, url, task_id) + except asyncio.CancelledError: # a call its fire gave up on is spent too + handed_on = self._read_late(client, url, call, task_id=task_id) + raise return self._replied(status, call) finally: if not handed_on: diff --git a/tst/unit/env/gateway/executor_usage_test.py b/tst/unit/env/gateway/executor_usage_test.py index 4d01efc16..8a132f649 100644 --- a/tst/unit/env/gateway/executor_usage_test.py +++ b/tst/unit/env/gateway/executor_usage_test.py @@ -133,6 +133,30 @@ def answers(request: httpx.Request) -> httpx.Response: assert (engine.usage()["version"], engine.usage()["calls"]) == (2, [{"role": "elias", "usage": USAGE}]) +@pytest.mark.asyncio +async def test_a_call_cancelled_while_its_task_is_polled_is_still_read_for_its_usage(monkeypatch): + engine, polled, done = _engine(), asyncio.Event(), asyncio.Event() + + def answers(request: httpx.Request) -> httpx.Response: + if b"tasks/get" in request.content: + polled.set() + if done.is_set(): + return _task("completed", {"kind": "text", "text": "ok"}, {"kind": "data", "data": {"usage": USAGE}}) + return _task("working") + + _executor_answers(monkeypatch, answers) + monkeypatch.setattr(triggers_mod.asyncio, "sleep", _no_wait) + call = asyncio.ensure_future(engine._call_executor(EXECUTOR, "Reply", context_id="trigger-t1")) + await polled.wait() + call.cancel() + with pytest.raises(asyncio.CancelledError): + await call + done.set() + await asyncio.gather(*engine._executor_reads) + + assert (engine.usage()["version"], engine.usage()["calls"]) == (2, [{"role": "elias", "usage": USAGE}]) + + @pytest.mark.asyncio async def test_a_cleared_engine_keeps_the_calls_made_and_its_boot(monkeypatch): engine = _engine() From e9baa6202d5c8d76a544b656acf9932f2344a4d4 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 1 Dec 2026 06:43:00 -0800 Subject: [PATCH 06/10] feat(usage): the teardown waits for colleague replies still being read before it records them A reply still running when its run ended stayed unpriced: the teardown read the gateway's list, then closed the env, and the reply's read went with it. `GET /triggers/usage` now says how many calls the gateway is still reading (`reading`, a late reply's included), and the teardown reads each env's list again every 2 seconds until none is, for at most `TEARDOWN_WAIT_SECONDS` (60), before it records; envs are read side by side. Prompt steps don't wait here: they already wait out replies in flight. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 +- src/agent_env/env/gateway/triggers.py | 12 +++-- src/agent_env/task/teardown.py | 8 ++-- src/agent_env/task_step/colleagues.py | 49 +++++++++++++------- tst/unit/env/gateway/executor_usage_test.py | 7 +-- tst/unit/task/usage/colleague_ledger_test.py | 14 ++++++ tst/unit/task_step/colleagues_test.py | 31 +++++++++++-- 7 files changed, 95 insertions(+), 29 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 96cd64b4c..b4ef0a9d9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -444,7 +444,8 @@ orchestrators call it the same way. What callers rely on: gateway lists every such call as it starts, with the usage its final message reported once it ends (`GET /triggers/usage`, under its own boot id and a version every change raises, kept through a `clear`), a reply past its time limit still read for that usage in the background, for up to ten minutes more. `prompt_agent` and `always_on` as they end, and the teardown, write the list as one - `colleague` entry per env and gateway boot (`task_step/colleagues.py`), with no attempt, under the + `colleague` entry per env and gateway boot (`task_step/colleagues.py`), the teardown first waiting up to a minute for + calls the gateway is still reading (`reading`), with no attempt, under the `register_env_triggers` step that set the executors up; the ledger keeps it by `gateway_boot` too, so each write is the whole list and replaces the last, a call counts once whichever step or attempt wrote it, and a gateway a retry redeployed is kept beside the first. A step's completion takes the context's colleague entries with its own, and diff --git a/src/agent_env/env/gateway/triggers.py b/src/agent_env/env/gateway/triggers.py index 77174f295..5eab8e648 100644 --- a/src/agent_env/env/gateway/triggers.py +++ b/src/agent_env/env/gateway/triggers.py @@ -481,8 +481,10 @@ def __init__(self, gateway): self._executor_usage: list[dict] = [] self._usage_boot = secrets.token_hex(6) self._usage_version = 0 - # The reads of calls still going, a late one's included, which a `clear` leaves to finish. + # The late reads of calls past their time limit, which a `clear` leaves to finish, and how many calls are + # still being read, those inside their time limit included. self._executor_reads: set[asyncio.Task] = set() + self._reading = 0 def register(self, body: Any) -> dict: """Additively add each trigger by id (idempotent upsert; conflicting id or bad shape -> 400); watch_roles and @@ -1009,8 +1011,9 @@ def usage(self) -> dict: each one's ``role``, the executor's, and the ``usage`` its final message reported, as it sent it, None while it runs and when it reported none or no reply was read. ``boot`` is this engine's own id, so a reader that keeps the calls by it tells a restarted gateway's apart, and ``version`` rises with every change to the list, so a - reader holding two copies keeps the later.""" - return {"boot": self._usage_boot, "version": self._usage_version, + reader holding two copies keeps the later. ``reading`` is how many calls are still being read, a late one's + included, which a reader about to close the env can wait out.""" + return {"boot": self._usage_boot, "version": self._usage_version, "reading": self._reading, "calls": [dict(call) for call in self._executor_usage]} def on_tool_call(self, role: str, name: str, arguments: dict, @@ -1793,6 +1796,7 @@ async def _call_executor(self, executor: dict | None, instruction: str, context_ call: dict[str, Any] = {"role": executor["role"], "usage": None} self._executor_usage.append(call) self._usage_version += 1 + self._reading += 1 return await self._send_to_executor(executor, instruction, context_id, call) async def _send_to_executor(self, executor: dict, instruction: str, context_id: str, call: dict) -> str | None: @@ -1843,6 +1847,7 @@ async def _send_to_executor(self, executor: dict, instruction: str, context_id: return self._replied(status, call) finally: if not handed_on: + self._reading -= 1 await client.aclose() def _replied(self, status: dict, call: dict) -> str | None: @@ -1880,6 +1885,7 @@ async def read() -> None: if status.get("state") in _TERMINAL_A2A_STATES: self._replied(status, call) finally: + self._reading -= 1 await client.aclose() late = asyncio.ensure_future(read()) diff --git a/src/agent_env/task/teardown.py b/src/agent_env/task/teardown.py index 1d6957c5e..d02e22f27 100644 --- a/src/agent_env/task/teardown.py +++ b/src/agent_env/task/teardown.py @@ -33,7 +33,7 @@ from agent_env.task.interrupts import tearing_down from agent_env.task.store import get_task_instance_store, record_usage from agent_env.task_step.context import TaskStepContext -from agent_env.task_step.colleagues import record_colleague_usage +from agent_env.task_step.colleagues import TEARDOWN_WAIT_SECONDS, record_colleague_usage from agent_env.task_step.task_steps.computer_recording import end_open_recordings, register_open_recordings from agent_env.task_step.task_steps.browser.recording import (end_open_browser_recordings, register_open_browser_recordings) @@ -134,7 +134,8 @@ async def teardown_run(context: TaskStepContext, *, timeout: float = TERMINATE_T async def tear_down(context: TaskStepContext, sandboxes: Sequence[RecordedSandbox], envs: Sequence[DeployedEnv], *, timeout: float) -> TeardownReport: - """Record what ``envs``' trigger executors spent (``record_colleague_usage``), end the recordings the run left open + """Record what ``envs``' trigger executors spent (``record_colleague_usage``), waiting up to + ``TEARDOWN_WAIT_SECONDS`` for replies still being read, end the recordings the run left open on them, its computers' and its browsers', with fresh grants, close each env still up, register any recording still open from its namespace, then terminate each of ``sandboxes`` by id, all at once and each within ``timeout`` seconds, and remove a local one's work folder once it's down. A close that fails is logged: its env's sandboxes are terminated by id regardless, which leaves one the @@ -143,7 +144,8 @@ async def tear_down(context: TaskStepContext, sandboxes: Sequence[RecordedSandbo up = {sandbox.sandbox_id for sandbox in pending} env_ids = [env.env_id for env in envs] try: - if (colleagues := await record_colleague_usage(context, envs)) and context.instance_id: + colleagues = await record_colleague_usage(context, envs, wait_seconds=TEARDOWN_WAIT_SECONDS) + if colleagues and context.instance_id: await record_usage(context.instance_id, colleagues) try: async with asyncio.timeout(timeout): diff --git a/src/agent_env/task_step/colleagues.py b/src/agent_env/task_step/colleagues.py index 1b7260fec..5cebe9f3a 100644 --- a/src/agent_env/task_step/colleagues.py +++ b/src/agent_env/task_step/colleagues.py @@ -11,6 +11,7 @@ from __future__ import annotations +import asyncio import logging from collections.abc import Iterable, Mapping, Sequence from typing import TYPE_CHECKING, Optional @@ -29,6 +30,10 @@ #: How long each env's list may take to read, in seconds. READ_TIMEOUT_SECONDS = 15 +#: How long the teardown waits for an env's executor calls still being read before it records them, in seconds. +TEARDOWN_WAIT_SECONDS = 60 +#: How often a wait reads the list again, in seconds. +WAIT_POLL_SECONDS = 2 def colleague_entry(calls: Iterable[Mapping], *, gateway_boot: str, gateway_version: int, env_id: str, @@ -51,31 +56,43 @@ def colleague_entry(calls: Iterable[Mapping], *, gateway_boot: str, gateway_vers return entry -async def record_colleague_usage(context: TaskStepContext, envs: Sequence[DeployedEnv]) -> list[dict]: +async def record_colleague_usage(context: TaskStepContext, envs: Sequence[DeployedEnv], *, + wait_seconds: float = 0) -> list[dict]: """Write each of ``envs``' colleagues' usage so far (``colleague_entry``) into ``context``'s step usage, under the ``register_env_triggers`` step that set its executors up, and return them as ledger entries, each naming that step. + With ``wait_seconds``, as the teardown gives it, an env whose gateway is still reading calls (a late reply's + included) is read again until it isn't, for at most that long, so a reply its env's close would cut off is counted. An env no such step set executors up on, or whose gateway doesn't list its calls, is skipped; a read that fails is logged. Never raises.""" registrations = _registrations(context) + found = await asyncio.gather(*(_read(context, env, registrations[env.env_id], wait_seconds) for env in envs + if env.env_id in registrations and env.supports(EXT_TRIGGERS_URI, "usage"))) written = [] - for env in envs: - registration = registrations.get(env.env_id) - if registration is None or not env.supports(EXT_TRIGGERS_URI, "usage"): - continue - try: - report = await env.invoke(EXT_TRIGGERS_URI, "usage", timeout=READ_TIMEOUT_SECONDS) - entry = colleague_entry(report.get("calls") or [], gateway_boot=str(report.get("boot")), - gateway_version=int(report.get("version") or 0), env_id=env.env_id, - endpoint_host=_executors_host(context, registration), prices=configured_prices()) - except Exception as e: # noqa: BLE001 - a colleague's usage never fails its step or the teardown - logger.warning("the colleague usage on env %s wasn't read: %s", env.env_id, e) - continue - if entry is not None: - _keep(context, registration["step_id"], entry) - written.append({**entry, "step_id": registration["step_id"]}) + for registration, entry in (pair for pair in found if pair is not None): + _keep(context, registration["step_id"], entry) + written.append({**entry, "step_id": registration["step_id"]}) return written +async def _read(context: TaskStepContext, env: DeployedEnv, registration: dict, + wait_seconds: float) -> Optional[tuple[dict, UsageEntry]]: + """``env``'s colleague entry, read once its gateway has no calls left to read or ``wait_seconds`` have passed; + None when it had no calls or couldn't be read.""" + try: + until = asyncio.get_running_loop().time() + wait_seconds + report = await env.invoke(EXT_TRIGGERS_URI, "usage", timeout=READ_TIMEOUT_SECONDS) + while report.get("reading") and asyncio.get_running_loop().time() < until: + await asyncio.sleep(WAIT_POLL_SECONDS) + report = await env.invoke(EXT_TRIGGERS_URI, "usage", timeout=READ_TIMEOUT_SECONDS) + entry = colleague_entry(report.get("calls") or [], gateway_boot=str(report.get("boot")), + gateway_version=int(report.get("version") or 0), env_id=env.env_id, + endpoint_host=_executors_host(context, registration), prices=configured_prices()) + except Exception as e: # noqa: BLE001 - a colleague's usage never fails its step or the teardown + logger.warning("the colleague usage on env %s wasn't read: %s", env.env_id, e) + return None + return None if entry is None else (registration, entry) + + def _registrations(context: TaskStepContext) -> dict[str, dict]: """Each env's first ``register_env_triggers`` record that set executors up, by env id.""" found: dict[str, dict] = {} diff --git a/tst/unit/env/gateway/executor_usage_test.py b/tst/unit/env/gateway/executor_usage_test.py index 8a132f649..b007d8714 100644 --- a/tst/unit/env/gateway/executor_usage_test.py +++ b/tst/unit/env/gateway/executor_usage_test.py @@ -52,7 +52,7 @@ async def test_a_reply_and_the_usage_its_final_message_reported_are_kept(monkeyp reply = await engine._call_executor(EXECUTOR, "Reply to Dana", context_id="trigger-t1") assert reply == "Sure, I'll take it." - assert engine.usage()["calls"] == [{"role": "elias", "usage": USAGE}] + assert (engine.usage()["calls"], engine.usage()["reading"]) == ([{"role": "elias", "usage": USAGE}], 0) @pytest.mark.asyncio @@ -110,8 +110,9 @@ async def answers_late(request: httpx.Request) -> httpx.Response: release.set() await asyncio.gather(*engine._executor_reads) - assert late["calls"] == [{"role": "elias", "usage": None}] + assert (late["calls"], late["reading"]) == ([{"role": "elias", "usage": None}], 1) assert (engine.usage()["version"], engine.usage()["calls"]) == (2, [{"role": "elias", "usage": USAGE}]) + assert engine.usage()["reading"] == 0 @pytest.mark.asyncio @@ -183,7 +184,7 @@ async def test_the_gateway_serves_the_list_and_its_card_offers_it(tmp_path, monk finally: gw._close_trajectory_file() - assert served == {"boot": gw._trigger_engine.usage()["boot"], "version": 0, + assert served == {"boot": gw._trigger_engine.usage()["boot"], "version": 0, "reading": 0, "calls": [{"role": "elias", "usage": USAGE}]} [triggers] = [ext for ext in GATEWAY_EXTENSIONS if ext["uri"] == EXT_TRIGGERS_URI] assert triggers["params"]["methods"]["usage"] == { diff --git a/tst/unit/task/usage/colleague_ledger_test.py b/tst/unit/task/usage/colleague_ledger_test.py index cc5530577..ae1f6355b 100644 --- a/tst/unit/task/usage/colleague_ledger_test.py +++ b/tst/unit/task/usage/colleague_ledger_test.py @@ -12,6 +12,7 @@ from agent_env.task.task import Task from agent_env.task.teardown import tear_down from agent_env.task.usage.ledger import merged +from agent_env.task_step import colleagues from agent_env.task_step.colleagues import record_colleague_usage from agent_env.task_step.context import TaskStepContext from agent_env.task_step.task_step import RetryConfig, TaskStep @@ -101,6 +102,19 @@ async def test_a_retried_span_counts_each_executor_call_once(store): assert _colleagues(store, context.instance_id) == [(None, "triggers", 4)] +@pytest.mark.asyncio +async def test_the_teardown_waits_for_a_reply_still_being_read(store, monkeypatch): + monkeypatch.setattr(colleagues, "WAIT_POLL_SECONDS", 0) + env = _Env() + context = await Task(id="t", version=1, steps=[_Registers("triggers", 1), _Asks("ask", env)]).run( + context=TaskStepContext()) + env.reads, env.reading, env.arriving = 0, 2, [_call()] + + await tear_down(context, (), [env], timeout=5) + + assert _colleagues(store, context.instance_id) == [(None, "triggers", 2)] + + @pytest.mark.asyncio async def test_the_teardown_writes_the_calls_that_came_after_the_last_step(store): env = _Env() diff --git a/tst/unit/task_step/colleagues_test.py b/tst/unit/task_step/colleagues_test.py index a59001884..94c56a0b7 100644 --- a/tst/unit/task_step/colleagues_test.py +++ b/tst/unit/task_step/colleagues_test.py @@ -8,6 +8,7 @@ from agent_env.config.model_pricing import configured_prices from agent_env.env.gateway.constants import EXT_TRIGGERS_URI +from agent_env.task_step import colleagues from agent_env.task_step.colleagues import colleague_entry, record_colleague_usage from agent_env.task_step.context import DeployedAgent, TaskStepContext @@ -43,10 +44,13 @@ def test_a_call_that_reported_nothing_makes_the_entry_a_lower_bound_never_zero() class _Env: - """An env whose gateway lists ``calls`` under ``boot``, or fails the read with ``error``.""" + """An env whose gateway lists ``calls`` under ``boot``, or fails the read with ``error``; with ``reading`` calls still + being read, each read takes one off, and the last one off lists ``arriving``.""" - def __init__(self, env_id: str = "office", calls=(), *, boot: str = "b1", lists: bool = True, error=None): + def __init__(self, env_id: str = "office", calls=(), *, boot: str = "b1", lists: bool = True, error=None, + reading: int = 0, arriving=()): self.env_id, self.calls, self.boot, self.lists, self.error, self.reads = env_id, list(calls), boot, lists, error, 0 + self.reading, self.arriving = reading, list(arriving) def supports(self, uri: str, method: str) -> bool: return self.lists and (uri, method) == (EXT_TRIGGERS_URI, "usage") @@ -55,7 +59,12 @@ async def invoke(self, uri: str, method: str, params=None, *, timeout=None): self.reads += 1 if self.error is not None: raise self.error - return {"boot": self.boot, "version": len(self.calls), "calls": list(self.calls)} + if self.reading and self.reads > 1: + self.reading -= 1 + if not self.reading: + self.calls += self.arriving + return {"boot": self.boot, "version": len(self.calls) + self.reading, "reading": self.reading, + "calls": list(self.calls)} def _context(*envs: str) -> TaskStepContext: @@ -92,6 +101,22 @@ async def test_a_read_of_an_earlier_list_never_replaces_a_later_one(): assert (kept["turns"], kept["gateway_version"]) == (2, 2) +@pytest.mark.asyncio +async def test_a_wait_reads_until_no_call_is_still_being_read_and_no_longer_than_it_was_given(monkeypatch): + monkeypatch.setattr(colleagues, "WAIT_POLL_SECONDS", 0) + finishing = _Env(calls=[_call()], reading=2, arriving=[_call()]) + stuck = _Env("lab", calls=[_call()], reading=10**9) + + waited = await record_colleague_usage(_context("office"), [finishing], wait_seconds=30) + capped = await record_colleague_usage(_context("lab"), [stuck], wait_seconds=0.05) + prompt = _Env(calls=[_call()], reading=2, arriving=[_call()]) + unwaited = await record_colleague_usage(_context("office"), [prompt]) + + assert ([e["turns"] for e in waited], finishing.reads) == ([2], 3) + assert [e["turns"] for e in capped] == [1] and stuck.reads > 1 + assert ([e["turns"] for e in unwaited], prompt.reads) == ([1], 1) + + @pytest.mark.asyncio async def test_a_redeployed_gateways_calls_are_kept_beside_the_first_ones(): context = _context("office") From 74c4fb32e9739dec2654a7d6657dbd7f6c2aac86 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 1 Dec 2026 06:56:12 -0800 Subject: [PATCH 07/10] fix(usage): a teardown wait whose later read fails records the list it last read The teardown's wait for calls still being read dropped the env's whole list when a read after the first failed, so the calls it had already read went unrecorded. It now logs the failure and records the last list it read. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task_step/colleagues.py | 19 ++++++++++++++----- tst/unit/task_step/colleagues_test.py | 15 +++++++++++++-- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/agent_env/task_step/colleagues.py b/src/agent_env/task_step/colleagues.py index 5cebe9f3a..0b484435f 100644 --- a/src/agent_env/task_step/colleagues.py +++ b/src/agent_env/task_step/colleagues.py @@ -76,14 +76,23 @@ async def record_colleague_usage(context: TaskStepContext, envs: Sequence[Deploy async def _read(context: TaskStepContext, env: DeployedEnv, registration: dict, wait_seconds: float) -> Optional[tuple[dict, UsageEntry]]: - """``env``'s colleague entry, read once its gateway has no calls left to read or ``wait_seconds`` have passed; - None when it had no calls or couldn't be read.""" + """``env``'s colleague entry, read once its gateway has no calls left to read or ``wait_seconds`` have passed, from + the last list read when a later read fails; None when it had no calls or couldn't be read at all.""" + until = asyncio.get_running_loop().time() + wait_seconds try: - until = asyncio.get_running_loop().time() + wait_seconds report = await env.invoke(EXT_TRIGGERS_URI, "usage", timeout=READ_TIMEOUT_SECONDS) - while report.get("reading") and asyncio.get_running_loop().time() < until: - await asyncio.sleep(WAIT_POLL_SECONDS) + except Exception as e: # noqa: BLE001 - a colleague's usage never fails its step or the teardown + logger.warning("the colleague usage on env %s wasn't read: %s", env.env_id, e) + return None + while report.get("reading") and asyncio.get_running_loop().time() < until: + await asyncio.sleep(WAIT_POLL_SECONDS) + try: report = await env.invoke(EXT_TRIGGERS_URI, "usage", timeout=READ_TIMEOUT_SECONDS) + except Exception as e: # noqa: BLE001 - the last list read is recorded + logger.warning("the colleague usage on env %s wasn't read again, so its last read is recorded: %s", + env.env_id, e) + break + try: entry = colleague_entry(report.get("calls") or [], gateway_boot=str(report.get("boot")), gateway_version=int(report.get("version") or 0), env_id=env.env_id, endpoint_host=_executors_host(context, registration), prices=configured_prices()) diff --git a/tst/unit/task_step/colleagues_test.py b/tst/unit/task_step/colleagues_test.py index 94c56a0b7..0f7a5e36c 100644 --- a/tst/unit/task_step/colleagues_test.py +++ b/tst/unit/task_step/colleagues_test.py @@ -50,14 +50,14 @@ class _Env: def __init__(self, env_id: str = "office", calls=(), *, boot: str = "b1", lists: bool = True, error=None, reading: int = 0, arriving=()): self.env_id, self.calls, self.boot, self.lists, self.error, self.reads = env_id, list(calls), boot, lists, error, 0 - self.reading, self.arriving = reading, list(arriving) + self.reading, self.arriving, self.fails_after = reading, list(arriving), 0 def supports(self, uri: str, method: str) -> bool: return self.lists and (uri, method) == (EXT_TRIGGERS_URI, "usage") async def invoke(self, uri: str, method: str, params=None, *, timeout=None): self.reads += 1 - if self.error is not None: + if self.error is not None and self.reads > self.fails_after: raise self.error if self.reading and self.reads > 1: self.reading -= 1 @@ -117,6 +117,17 @@ async def test_a_wait_reads_until_no_call_is_still_being_read_and_no_longer_than assert ([e["turns"] for e in unwaited], prompt.reads) == ([1], 1) +@pytest.mark.asyncio +async def test_a_wait_whose_later_read_fails_records_the_list_it_last_read(monkeypatch): + monkeypatch.setattr(colleagues, "WAIT_POLL_SECONDS", 0) + env = _Env(calls=[_call(), _call()], reading=5, error=TimeoutError("no answer")) + env.fails_after = 1 + + [entry] = await record_colleague_usage(_context("office"), [env], wait_seconds=30) + + assert (entry["turns"], env.reads) == (2, 2) + + @pytest.mark.asyncio async def test_a_redeployed_gateways_calls_are_kept_beside_the_first_ones(): context = _context("office") From 9f6c62b7ed0fc692559642a18421804dd69081b0 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 1 Dec 2026 07:11:43 -0800 Subject: [PATCH 08/10] fix(registry): a read the network dropped is sent once more A bundle run failed when one manifest read from GHCR timed out (`couldn't read its manifest from ghcr.io: ReadTimeout`), as integration CI does now and then. The registry client sends a GET or HEAD a transport error dropped (a timeout, a reset connection) once more after a second; a write is never sent twice. The error a write raises said "couldn't writs manifeste its manifest"; it now says "couldn't write its manifest". Co-Authored-By: Claude Opus 5.5 --- .../store/image_store/registry_api.py | 70 +++++++++++-------- tst/unit/store/registry_api_test.py | 43 ++++++++++++ 2 files changed, 85 insertions(+), 28 deletions(-) diff --git a/src/agent_env/store/image_store/registry_api.py b/src/agent_env/store/image_store/registry_api.py index 07d92a8ed..638a33920 100644 --- a/src/agent_env/store/image_store/registry_api.py +++ b/src/agent_env/store/image_store/registry_api.py @@ -9,6 +9,7 @@ import json import re import tempfile +import time from collections.abc import Iterator from dataclasses import dataclass from pathlib import Path @@ -31,6 +32,8 @@ _DIGEST = re.compile(r"^(?:sha256:[a-f0-9]{64}|sha384:[a-f0-9]{96}|sha512:[a-f0-9]{128})$") _DOCKER_HUB_API = "registry-1.docker.io" _TIMEOUT_SECONDS = 30 +# A read the network dropped (a timeout, a reset connection) is sent once more after this many seconds. +_RETRY_AFTER_SECONDS = 1.0 class NoSuchImageError(ValueError): @@ -323,38 +326,49 @@ def stream(self, path: str) -> Iterator[httpx.Response]: def _send(self, method: str, path: str, accept: str | None, *, stream: bool, content: bytes | Path | None = None, content_type: str | None = None) -> httpx.Response: - """``path`` is under the repository, or a whole URL the registry gave; a file's ``content`` streams from disk.""" + """``path`` is under the repository, or a whole URL the registry gave; a file's ``content`` streams from disk. A + GET or HEAD the network dropped is sent once more, as a registry, GHCR among them, now and then times out.""" url = path if path.startswith(("http://", "https://")) else f"{self._base}/{path}" try: - for attempt in range(2): - headers = {"Accept": accept} if accept else {} - if content_type: - headers["Content-Type"] = content_type - if self._token: - headers["Authorization"] = f"Bearer {self._token}" - with contextlib.ExitStack() as opened: - body = content - if isinstance(content, Path): - headers["Content-Length"] = str(content.stat().st_size) - body = opened.enter_context(content.open("rb")) - request = self._client.build_request(method, url, headers=headers, content=body) - # Basic credentials go with every request until a Bearer token replaces them. - response = self._client.send(request, auth=None if self._token else self._basic, stream=stream) - # A held token is asked for again once: GHCR scopes it to the first challenge, a pull's before a push. - if response.status_code != 401 or attempt: - return response - if stream: - response.read() - response.close() - if (token := _bearer_token(self._client, response, self._basic, self._what)) is None: - return response - self._token = token - return response + try: + return self._sent(method, url, accept, stream=stream, content=content, content_type=content_type) + except httpx.TransportError: + if method not in ("GET", "HEAD"): + raise + time.sleep(_RETRY_AFTER_SECONDS) + return self._sent(method, url, accept, stream=stream, content=content, content_type=content_type) except httpx.HTTPError as e: thing = "its manifest" if path.startswith("manifests/") else f"the blob {path.removeprefix('blobs/')}" - verb = "write it to" if method == "PUT" else "read it from" - raise ValueError(f"{self._what}: couldn't {verb.replace('it', thing)} {self._host}: " - f"{type(e).__name__}: {e}") from e + what = f"write {thing} to" if method == "PUT" else f"read {thing} from" + raise ValueError(f"{self._what}: couldn't {what} {self._host}: {type(e).__name__}: {e}") from e + + def _sent(self, method: str, url: str, accept: str | None, *, stream: bool, content: bytes | Path | None, + content_type: str | None) -> httpx.Response: + """One send of the request, asking a held token again once when the registry refuses it.""" + for attempt in range(2): + headers = {"Accept": accept} if accept else {} + if content_type: + headers["Content-Type"] = content_type + if self._token: + headers["Authorization"] = f"Bearer {self._token}" + with contextlib.ExitStack() as opened: + body = content + if isinstance(content, Path): + headers["Content-Length"] = str(content.stat().st_size) + body = opened.enter_context(content.open("rb")) + request = self._client.build_request(method, url, headers=headers, content=body) + # Basic credentials go with every request until a Bearer token replaces them. + response = self._client.send(request, auth=None if self._token else self._basic, stream=stream) + # A held token is asked for again once: GHCR scopes it to the first challenge, a pull's before a push. + if response.status_code != 401 or attempt: + return response + if stream: + response.read() + response.close() + if (token := _bearer_token(self._client, response, self._basic, self._what)) is None: + return response + self._token = token + return response def _raise_for(self, response: httpx.Response) -> None: if response.status_code == 200: diff --git a/tst/unit/store/registry_api_test.py b/tst/unit/store/registry_api_test.py index 120992dd8..7620b8618 100644 --- a/tst/unit/store/registry_api_test.py +++ b/tst/unit/store/registry_api_test.py @@ -268,6 +268,49 @@ def served(request): assert "application/vnd.oci.image.index.v1+json" in seen[0].headers["accept"] +def test_a_read_the_network_drops_is_sent_once_more(fake_registry, monkeypatch): + monkeypatch.setattr(registry_api, "_RETRY_AFTER_SECONDS", 0) + index = {"mediaType": "application/vnd.oci.image.index.v1+json", "manifests": []} + + def drops_the_first(request): + if len(seen) == 1: + raise httpx.ReadTimeout("The read operation timed out", request=request) + return httpx.Response(200, json=index) + + seen = fake_registry(drops_the_first) + + assert read_manifest("localhost:5000/desk:1", None) == index + assert len(seen) == 2 + + +def test_a_read_dropped_twice_names_the_registry_and_what_it_hit(fake_registry, monkeypatch): + monkeypatch.setattr(registry_api, "_RETRY_AFTER_SECONDS", 0) + + def drops(request): + raise httpx.ReadTimeout("The read operation timed out", request=request) + + seen = fake_registry(drops) + + with pytest.raises(ValueError, match="couldn't read its manifest from localhost:5000: ReadTimeout"): + read_manifest("localhost:5000/desk:1", None) + assert len(seen) == 2 + + +def test_a_write_the_network_drops_is_not_sent_again(fake_registry, monkeypatch): + monkeypatch.setattr(registry_api, "_RETRY_AFTER_SECONDS", 0) + + def drops_writes(request): + if request.method == "PUT": + raise httpx.ReadTimeout("The read operation timed out", request=request) + return httpx.Response(200, content=b"{}", headers={"Content-Type": DOCKER_IMAGE}) + + seen = fake_registry(drops_writes) + + with pytest.raises(ValueError, match="couldn't write its manifest to localhost:5000: ReadTimeout"): + registry_api.write_index("localhost:5000/desk:1", {"linux/amd64": f"localhost:5000/desk@{DIGEST}"}, None) + assert [r.method for r in seen] == ["GET", "PUT"] + + def test_a_blob_that_doesnt_hash_to_its_digest_is_refused_and_not_kept(fake_registry, tmp_path): fake_registry(lambda request: httpx.Response(200, content=b"something else")) From d77941d426e6f3ee2b4562c37b139af5b5c6566e Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 1 Dec 2026 09:25:32 -0800 Subject: [PATCH 09/10] refactor(usage): name the role of a trigger executor's usage `executor`, not `colleague` The calls an env's gateway makes to a trigger's executor are recorded under the role `executor` (`UsageRole.EXECUTOR`), the framework's own name for that agent (`register_env_triggers`' `executor_agent_name` and `executors`), rather than `colleague`, one benchmark's word for it. `task_step/colleagues.py` is `task_step/executors.py`, with `record_executor_usage` and `executor_entry`. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 26 ++++++------ src/agent_env/config/model.py | 4 +- src/agent_env/task/store.py | 10 ++--- src/agent_env/task/teardown.py | 10 ++--- src/agent_env/task/usage/ledger.py | 2 +- .../task_step/{colleagues.py => executors.py} | 32 +++++++------- .../task_step/task_steps/prompt_agent.py | 6 +-- src/agent_env/task_step/usage.py | 2 +- tst/unit/env/gateway/executor_usage_test.py | 2 +- ...ledger_test.py => executor_ledger_test.py} | 36 ++++++++-------- tst/unit/task/usage/summary_test.py | 6 +-- .../{colleagues_test.py => executors_test.py} | 42 +++++++++---------- .../task_step/test_prompt_agent_triggers.py | 2 +- 13 files changed, 90 insertions(+), 90 deletions(-) rename src/agent_env/task_step/{colleagues.py => executors.py} (81%) rename tst/unit/task/usage/{colleague_ledger_test.py => executor_ledger_test.py} (74%) rename tst/unit/task_step/{colleagues_test.py => executors_test.py} (79%) diff --git a/AGENTS.md b/AGENTS.md index b4ef0a9d9..eedbdc2f1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -440,19 +440,19 @@ orchestrators call it the same way. What callers rely on: runner that doesn't set `ATTEMPT_EPOCH` writes entries with no attempt, kept by step and role alone: exact for a run without retries, a lower bound for one with. A runner that writes the instance some other way loses that spend from the ledger. -- A run's colleagues, the executors an env's gateway calls when a trigger fires, are spent outside any prompt: the - gateway lists every such call as it starts, with the usage its final message reported once it ends - (`GET /triggers/usage`, under its own boot id and a version every change raises, kept through a `clear`), a reply - past its time limit still read for that usage in the background, for up to ten minutes more. `prompt_agent` and `always_on` as they end, and the teardown, write the list as one - `colleague` entry per env and gateway boot (`task_step/colleagues.py`), the teardown first waiting up to a minute for - calls the gateway is still reading (`reading`), with no attempt, under the - `register_env_triggers` step that set the executors up; the ledger keeps it by `gateway_boot` too, so each write is - the whole list and replaces the last, a call counts once whichever step or attempt wrote it, and a gateway a retry - redeployed is kept beside the first. A step's completion takes the context's colleague entries with its own, and - the teardown writes its own through `record_usage()`, which merges any finished entries into the ledger alone, as - an embedder's chat with a run's agent outside its steps (`playground`). `validator` is the role for a step that - checks a run without grading it. None of the three (`UsageRole`) is a `[model.roles]` key; `summarize` lists them - after the solver, user simulator and judge. +- A run's trigger executors, the agents an env's gateway calls when a trigger fires, spend outside any prompt: the + gateway lists every such call as it starts, with the usage its final message reported once it ends (`GET + /triggers/usage`, under its own boot id and a version every change raises, kept through a `clear`), a reply past its + time limit still read for that usage in the background, for up to ten minutes more. `prompt_agent` and `always_on` + as they end, and the teardown, write the list as one `executor` entry per env and gateway boot + (`task_step/executors.py`), the teardown first waiting up to a minute for calls the gateway is still reading + (`reading`), with no attempt, under the `register_env_triggers` step that set the executors up; the ledger keeps it + by `gateway_boot` too, so each write is the whole list and replaces the last, a call counts once whichever step or + attempt wrote it, and a gateway a retry redeployed is kept beside the first. A step's completion takes the context's + executor entries with its own, and the teardown writes its own through `record_usage()`, which merges any finished + entries into the ledger alone, as an embedder's chat with a run's agent outside its steps (`playground`). + `validator` is the role for a step that checks a run without grading it. None of the three (`UsageRole`) is a + `[model.roles]` key; `summarize` lists them after the solver, user simulator and judge. - The runner writes its run identifier to `context.metadata["workflow_id"]` before calling `run()`; core stores it opaquely with the instance. - Each step runs under `protocol_v1.authorized` for the deployed envs in its context: a protocol-client diff --git a/src/agent_env/config/model.py b/src/agent_env/config/model.py index 43d3d4e3b..1e510f6b5 100644 --- a/src/agent_env/config/model.py +++ b/src/agent_env/config/model.py @@ -58,10 +58,10 @@ def record_key(self) -> str: class UsageRole(StrEnum): """A role a run's usage is recorded under that no ``[model.roles]`` key configures: an env trigger's executor, - which the env's gateway calls (``colleague``); a step that checks a run without grading it (``validator``); and a + which the env's gateway calls (``executor``); a step that checks a run without grading it (``validator``); and a chat an embedder holds with a run's agent outside its steps (``playground``).""" - COLLEAGUE = "colleague" + EXECUTOR = "executor" VALIDATOR = "validator" PLAYGROUND = "playground" diff --git a/src/agent_env/task/store.py b/src/agent_env/task/store.py index 108c15f4e..1871251fe 100644 --- a/src/agent_env/task/store.py +++ b/src/agent_env/task/store.py @@ -370,8 +370,8 @@ def _owns_attempt(doc: dict, attempt_epoch: int | None) -> bool: def _step_usage_after(doc: dict, ops: "ContextUpdateOps", step_id: str) -> list[dict]: """``step_id``'s ledger entries as its completion leaves them in the stored context, the document's step usage with - the step's diff applied (the diff's writes to it or to a parent of it), and the context's colleague entries, which - a step records under the step that set its env's executors up (``task_step.colleagues``).""" + the step's diff applied (the diff's writes to it or to a parent of it), and the context's executor entries, which + a step records under the step that set its env's executors up (``task_step.executors``).""" def touches(path: str) -> bool: return path == _STEP_USAGE_PATH or path.startswith(_STEP_USAGE_PATH + ".") or _STEP_USAGE_PATH.startswith( path + ".") @@ -386,8 +386,8 @@ def touches(path: str) -> bool: step_usage = _get_path(scratch, _STEP_USAGE_PATH) if not isinstance(step_usage, dict): return [] - colleagues = [entry for entry in entries_of(step_usage) if entry.get("role") == UsageRole.COLLEAGUE] - return [*entries_of({step_id: step_usage.get(step_id)}), *colleagues] + executors = [entry for entry in entries_of(step_usage) if entry.get("role") == UsageRole.EXECUTOR] + return [*entries_of({step_id: step_usage.get(step_id)}), *executors] class TaskInstanceStore: @@ -976,7 +976,7 @@ def _mutate(doc: dict) -> UpdateSpec | None: def record_usage_sync(self, instance_id: str, entries: list[dict]) -> None: """Merge ``entries``, finished usage entries each naming its ``step_id``, into ``instance_id``'s ledger alone, by attempt, step and role (``ledger.merged``), so one sent again replaces itself: usage a run spent outside - its steps' own writes, as its colleagues' (``task_step.colleagues``) or an embedder's chat with its agent.""" + its steps' own writes, as its executors' (``task_step.executors``) or an embedder's chat with its agent.""" def _mutate(doc: dict) -> UpdateSpec | None: spent = ledger_fields(doc, entries) return UpdateSpec(set=spent) if spent else None diff --git a/src/agent_env/task/teardown.py b/src/agent_env/task/teardown.py index d02e22f27..4bb2070ee 100644 --- a/src/agent_env/task/teardown.py +++ b/src/agent_env/task/teardown.py @@ -33,7 +33,7 @@ from agent_env.task.interrupts import tearing_down from agent_env.task.store import get_task_instance_store, record_usage from agent_env.task_step.context import TaskStepContext -from agent_env.task_step.colleagues import TEARDOWN_WAIT_SECONDS, record_colleague_usage +from agent_env.task_step.executors import TEARDOWN_WAIT_SECONDS, record_executor_usage from agent_env.task_step.task_steps.computer_recording import end_open_recordings, register_open_recordings from agent_env.task_step.task_steps.browser.recording import (end_open_browser_recordings, register_open_browser_recordings) @@ -134,7 +134,7 @@ async def teardown_run(context: TaskStepContext, *, timeout: float = TERMINATE_T async def tear_down(context: TaskStepContext, sandboxes: Sequence[RecordedSandbox], envs: Sequence[DeployedEnv], *, timeout: float) -> TeardownReport: - """Record what ``envs``' trigger executors spent (``record_colleague_usage``), waiting up to + """Record what ``envs``' trigger executors spent (``record_executor_usage``), waiting up to ``TEARDOWN_WAIT_SECONDS`` for replies still being read, end the recordings the run left open on them, its computers' and its browsers', with fresh grants, close each env still up, register any recording still open from its namespace, then terminate each of ``sandboxes`` by id, all at once and each within @@ -144,9 +144,9 @@ async def tear_down(context: TaskStepContext, sandboxes: Sequence[RecordedSandbo up = {sandbox.sandbox_id for sandbox in pending} env_ids = [env.env_id for env in envs] try: - colleagues = await record_colleague_usage(context, envs, wait_seconds=TEARDOWN_WAIT_SECONDS) - if colleagues and context.instance_id: - await record_usage(context.instance_id, colleagues) + executors = await record_executor_usage(context, envs, wait_seconds=TEARDOWN_WAIT_SECONDS) + if executors and context.instance_id: + await record_usage(context.instance_id, executors) try: async with asyncio.timeout(timeout): await end_open_recordings(context, env_ids) diff --git a/src/agent_env/task/usage/ledger.py b/src/agent_env/task/usage/ledger.py index e3ccfe430..6b09d547e 100644 --- a/src/agent_env/task/usage/ledger.py +++ b/src/agent_env/task/usage/ledger.py @@ -32,7 +32,7 @@ def _key(entry: dict) -> tuple: def merged(ledger: list[dict], entries: list[dict]) -> list[dict]: """``ledger`` with ``entries`` in it. An entry replaces the one of its attempt, step and role: a step's entry is its sum so far, so a write sent again, or a later one of the same attempt, never counts twice. A retry or a resume - runs under a new attempt epoch, so its entries are new ones. A colleague entry is one env gateway's executor calls + runs under a new attempt epoch, so its entries are new ones. An executor entry is one env gateway's executor calls so far, kept by that gateway's ``gateway_boot`` too, so a gateway a retry redeployed adds its own, and never replaced by an earlier copy of the gateway's list (``older``), which a parallel step's write can land with.""" out = list(ledger) diff --git a/src/agent_env/task_step/colleagues.py b/src/agent_env/task_step/executors.py similarity index 81% rename from src/agent_env/task_step/colleagues.py rename to src/agent_env/task_step/executors.py index 0b484435f..38af641fb 100644 --- a/src/agent_env/task_step/colleagues.py +++ b/src/agent_env/task_step/executors.py @@ -1,10 +1,10 @@ -"""What a run's colleagues spent: the calls an env's gateway makes to its triggers' executors, which no step prompts, -so no step's turns count them. +"""What a run's trigger executors spent: the calls an env's gateway makes to them when a trigger fires, which no step +prompts, so no step's turns count them. Each env's gateway lists every such call with the usage it reported (``GET /triggers/usage``). A step that reads the -env's triggers as it ends (``prompt_agent``, ``always_on``) and the run's teardown write that list as one ``colleague`` +env's triggers as it ends (``prompt_agent``, ``always_on``) and the run's teardown write that list as one ``executor`` entry per env and gateway boot into the context's step usage, under the ``register_env_triggers`` step that set its -executors up; every step's completion takes the context's colleague entries into the ledger with its own, and the +executors up; every step's completion takes the context's executor entries into the ledger with its own, and the teardown writes its own there (``teardown.tear_down``). Each write is the whole list so far, so it replaces the one before (``ledger.merged``): a call counts once whoever writes it, and a gateway a retry redeployed, with a boot of its own, is kept beside the first.""" @@ -36,14 +36,14 @@ WAIT_POLL_SECONDS = 2 -def colleague_entry(calls: Iterable[Mapping], *, gateway_boot: str, gateway_version: int, env_id: str, +def executor_entry(calls: Iterable[Mapping], *, gateway_boot: str, gateway_version: int, env_id: str, endpoint_host: Optional[str], prices: PriceSource) -> Optional[UsageEntry]: - """One env gateway's executor calls as one ``colleague`` entry: each call's usage read as its executor reported it + """One env gateway's executor calls as one ``executor`` entry: each call's usage read as its executor reported it (``read_usage``), one still running or that reported none counted as a call of unknown usage, which makes the entry a lower bound, never $0; priced as any role's turns are, by model where the executors gave their counts by model. It has no attempt, since it holds the gateway's calls whichever attempt made them, and it keeps the version of the list it was read from (``ledger.older``). None when there were no calls.""" - role = RoleUsage(UsageRole.COLLEAGUE.value, endpoint_host=endpoint_host, attempt=None) + role = RoleUsage(UsageRole.EXECUTOR.value, endpoint_host=endpoint_host, attempt=None) for call in calls: usage, unparsed = read_usage(call.get("usage")) role.add(usage if usage is not None else unreported(), unparsed) @@ -56,9 +56,9 @@ def colleague_entry(calls: Iterable[Mapping], *, gateway_boot: str, gateway_vers return entry -async def record_colleague_usage(context: TaskStepContext, envs: Sequence[DeployedEnv], *, +async def record_executor_usage(context: TaskStepContext, envs: Sequence[DeployedEnv], *, wait_seconds: float = 0) -> list[dict]: - """Write each of ``envs``' colleagues' usage so far (``colleague_entry``) into ``context``'s step usage, under the + """Write each of ``envs``' executors' usage so far (``executor_entry``) into ``context``'s step usage, under the ``register_env_triggers`` step that set its executors up, and return them as ledger entries, each naming that step. With ``wait_seconds``, as the teardown gives it, an env whose gateway is still reading calls (a late reply's included) is read again until it isn't, for at most that long, so a reply its env's close would cut off is counted. @@ -76,28 +76,28 @@ async def record_colleague_usage(context: TaskStepContext, envs: Sequence[Deploy async def _read(context: TaskStepContext, env: DeployedEnv, registration: dict, wait_seconds: float) -> Optional[tuple[dict, UsageEntry]]: - """``env``'s colleague entry, read once its gateway has no calls left to read or ``wait_seconds`` have passed, from + """``env``'s executor entry, read once its gateway has no calls left to read or ``wait_seconds`` have passed, from the last list read when a later read fails; None when it had no calls or couldn't be read at all.""" until = asyncio.get_running_loop().time() + wait_seconds try: report = await env.invoke(EXT_TRIGGERS_URI, "usage", timeout=READ_TIMEOUT_SECONDS) - except Exception as e: # noqa: BLE001 - a colleague's usage never fails its step or the teardown - logger.warning("the colleague usage on env %s wasn't read: %s", env.env_id, e) + except Exception as e: # noqa: BLE001 - an executor's usage never fails its step or the teardown + logger.warning("the executor usage on env %s wasn't read: %s", env.env_id, e) return None while report.get("reading") and asyncio.get_running_loop().time() < until: await asyncio.sleep(WAIT_POLL_SECONDS) try: report = await env.invoke(EXT_TRIGGERS_URI, "usage", timeout=READ_TIMEOUT_SECONDS) except Exception as e: # noqa: BLE001 - the last list read is recorded - logger.warning("the colleague usage on env %s wasn't read again, so its last read is recorded: %s", + logger.warning("the executor usage on env %s wasn't read again, so its last read is recorded: %s", env.env_id, e) break try: - entry = colleague_entry(report.get("calls") or [], gateway_boot=str(report.get("boot")), + entry = executor_entry(report.get("calls") or [], gateway_boot=str(report.get("boot")), gateway_version=int(report.get("version") or 0), env_id=env.env_id, endpoint_host=_executors_host(context, registration), prices=configured_prices()) - except Exception as e: # noqa: BLE001 - a colleague's usage never fails its step or the teardown - logger.warning("the colleague usage on env %s wasn't read: %s", env.env_id, e) + except Exception as e: # noqa: BLE001 - an executor's usage never fails its step or the teardown + logger.warning("the executor usage on env %s wasn't read: %s", env.env_id, e) return None return None if entry is None else (registration, entry) diff --git a/src/agent_env/task_step/task_steps/prompt_agent.py b/src/agent_env/task_step/task_steps/prompt_agent.py index c224deed7..1088f9c1e 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -40,7 +40,7 @@ ) from agent_env.store import DuplicateKeyError, get_config from agent_env.store.object_store import ObjectStore -from agent_env.task_step.colleagues import record_colleague_usage +from agent_env.task_step.executors import record_executor_usage from agent_env.task_step.context import ( DeployedAgent, PromptResponse, @@ -1043,7 +1043,7 @@ async def _decide(self, decide_url: str, turn: int, solver_message: str, context async def _persist_env_trigger_state(self, context: TaskStepContext) -> None: """Snapshot each trigger-registered env's /triggers/state to the configured object store, plus a metadata summary, bounded by _CAPTURE_BUDGET_SECONDS, then record what its executors have spent so far - (``record_colleague_usage``). Never raises.""" + (``record_executor_usage``). Never raises.""" try: await asyncio.wait_for( self._capture_env_trigger_state(context), timeout=self._CAPTURE_BUDGET_SECONDS) @@ -1062,7 +1062,7 @@ async def _persist_env_trigger_state(self, context: TaskStepContext) -> None: "captured_at_utc": datetime.now(timezone.utc).isoformat(), "capture_step_id": self.id, } - await record_colleague_usage(context, context.deployed_envs) + await record_executor_usage(context, context.deployed_envs) @staticmethod def _registered_env_ids(context: TaskStepContext) -> set[str]: diff --git a/src/agent_env/task_step/usage.py b/src/agent_env/task_step/usage.py index 18f74c8d1..57229bba7 100644 --- a/src/agent_env/task_step/usage.py +++ b/src/agent_env/task_step/usage.py @@ -272,7 +272,7 @@ def _combined(costs: list[Cost]) -> Cost: def older(entry: dict, than: dict) -> bool: """Whether ``entry`` was read from an earlier copy of its gateway's executor calls than ``than`` was - (``gateway_version``); never for an entry that isn't a colleague's.""" + (``gateway_version``); never for an entry that isn't an executor's.""" version, kept = entry.get("gateway_version"), than.get("gateway_version") return isinstance(version, int) and isinstance(kept, int) and version < kept diff --git a/tst/unit/env/gateway/executor_usage_test.py b/tst/unit/env/gateway/executor_usage_test.py index b007d8714..c7ac1ef0b 100644 --- a/tst/unit/env/gateway/executor_usage_test.py +++ b/tst/unit/env/gateway/executor_usage_test.py @@ -1,5 +1,5 @@ """The gateway's list of every call made to a trigger's executor, with the usage its final message reported -(``TriggerEngine.usage``, GET /triggers/usage), which a run's steps and teardown price as its colleagues' usage.""" +(``TriggerEngine.usage``, GET /triggers/usage), which a run's steps and teardown price as its trigger executors' usage.""" from __future__ import annotations import asyncio diff --git a/tst/unit/task/usage/colleague_ledger_test.py b/tst/unit/task/usage/executor_ledger_test.py similarity index 74% rename from tst/unit/task/usage/colleague_ledger_test.py rename to tst/unit/task/usage/executor_ledger_test.py index ae1f6355b..d62be949c 100644 --- a/tst/unit/task/usage/colleague_ledger_test.py +++ b/tst/unit/task/usage/executor_ledger_test.py @@ -1,4 +1,4 @@ -"""A run's colleagues' usage in its ledger through ``Task.run`` and its teardown: the context's colleague entry joins +"""A run's executors' usage in its ledger through ``Task.run`` and its teardown: the context's executor entry joins the ledger as each step completes, each executor call counts once whichever step or attempt wrote it, and the teardown writes the calls that came after the last step. Real LocalSqliteDocumentStore.""" @@ -12,11 +12,11 @@ from agent_env.task.task import Task from agent_env.task.teardown import tear_down from agent_env.task.usage.ledger import merged -from agent_env.task_step import colleagues -from agent_env.task_step.colleagues import record_colleague_usage +from agent_env.task_step import executors +from agent_env.task_step.executors import record_executor_usage from agent_env.task_step.context import TaskStepContext from agent_env.task_step.task_step import RetryConfig, TaskStep -from tst.unit.task_step.colleagues_test import _call, _Env +from tst.unit.task_step.executors_test import _call, _Env @pytest.fixture @@ -43,7 +43,7 @@ async def execute(self, context): class _Asks(TaskStep): - """A step whose agent a colleague answers once, recording the colleagues' usage as it ends; it fails on the attempts + """A step whose agent an executor answers once, recording the executors' usage as it ends; it fails on the attempts ``fail_on`` names.""" type = "asks" @@ -55,7 +55,7 @@ def __init__(self, id, env, *, fail_on=(), **kwargs): async def execute(self, context): self.attempts += 1 self.env.calls.append(_call()) - await record_colleague_usage(context, [self.env]) + await record_executor_usage(context, [self.env]) if self.attempts in self.fail_on: raise RuntimeError(f"{self.id} fails on attempt {self.attempts}") return context @@ -69,16 +69,16 @@ def __init__(self, id, store, **kwargs): self.store, self.seen = store, None async def execute(self, context): - self.seen = _colleagues(self.store, context.instance_id) + self.seen = _executors(self.store, context.instance_id) return context -def _colleagues(store, instance_id): - return [(e["attempt"], e["step_id"], e["turns"]) for e in store.get(instance_id).usage if e["role"] == "colleague"] +def _executors(store, instance_id): + return [(e["attempt"], e["step_id"], e["turns"]) for e in store.get(instance_id).usage if e["role"] == "executor"] @pytest.mark.asyncio -async def test_the_colleague_entry_joins_the_ledger_as_each_step_completes_and_counts_each_call_once(store): +async def test_the_executor_entry_joins_the_ledger_as_each_step_completes_and_counts_each_call_once(store): env = _Env() reads = _Reads("reads", store) steps = [_Registers("triggers", 1), _Asks("ask", env), reads, _Asks("follow-up", env)] @@ -86,7 +86,7 @@ async def test_the_colleague_entry_joins_the_ledger_as_each_step_completes_and_c context = await Task(id="t", version=1, steps=steps).run(context=TaskStepContext()) assert reads.seen == [(None, "triggers", 1)] - assert _colleagues(store, context.instance_id) == [(None, "triggers", 2)] + assert _executors(store, context.instance_id) == [(None, "triggers", 2)] assert store.get(context.instance_id).usage_total["input_tokens"] == 2000 @@ -99,12 +99,12 @@ async def test_a_retried_span_counts_each_executor_call_once(store): context = await Task(id="t", version=1, steps=steps).run(context=TaskStepContext()) assert len(env.calls) == 4 - assert _colleagues(store, context.instance_id) == [(None, "triggers", 4)] + assert _executors(store, context.instance_id) == [(None, "triggers", 4)] @pytest.mark.asyncio async def test_the_teardown_waits_for_a_reply_still_being_read(store, monkeypatch): - monkeypatch.setattr(colleagues, "WAIT_POLL_SECONDS", 0) + monkeypatch.setattr(executors, "WAIT_POLL_SECONDS", 0) env = _Env() context = await Task(id="t", version=1, steps=[_Registers("triggers", 1), _Asks("ask", env)]).run( context=TaskStepContext()) @@ -112,7 +112,7 @@ async def test_the_teardown_waits_for_a_reply_still_being_read(store, monkeypatc await tear_down(context, (), [env], timeout=5) - assert _colleagues(store, context.instance_id) == [(None, "triggers", 2)] + assert _executors(store, context.instance_id) == [(None, "triggers", 2)] @pytest.mark.asyncio @@ -124,11 +124,11 @@ async def test_the_teardown_writes_the_calls_that_came_after_the_last_step(store await tear_down(context, (), [env], timeout=5) - assert _colleagues(store, context.instance_id) == [(None, "triggers", 2)] + assert _executors(store, context.instance_id) == [(None, "triggers", 2)] -def test_a_gateways_colleague_entry_replaces_its_last_one_and_another_gateways_is_kept(): - first = {"attempt": None, "step_id": "triggers", "role": "colleague", "gateway_boot": "b1", "turns": 1} +def test_a_gateways_executor_entry_replaces_its_last_one_and_another_gateways_is_kept(): + first = {"attempt": None, "step_id": "triggers", "role": "executor", "gateway_boot": "b1", "turns": 1} ledger = merged([first], [{**first, "turns": 2}, {**first, "gateway_boot": "b2", "turns": 1}]) @@ -136,7 +136,7 @@ def test_a_gateways_colleague_entry_replaces_its_last_one_and_another_gateways_i def test_a_write_of_an_earlier_list_never_takes_calls_back(): - later = {"attempt": None, "step_id": "triggers", "role": "colleague", "gateway_boot": "b1", "gateway_version": 4, + later = {"attempt": None, "step_id": "triggers", "role": "executor", "gateway_boot": "b1", "gateway_version": 4, "turns": 2} ledger = merged([later], [{**later, "gateway_version": 2, "turns": 1}]) diff --git a/tst/unit/task/usage/summary_test.py b/tst/unit/task/usage/summary_test.py index cd5cbf951..d6961f9c3 100644 --- a/tst/unit/task/usage/summary_test.py +++ b/tst/unit/task/usage/summary_test.py @@ -27,14 +27,14 @@ def _bounds(summary): def test_the_roles_a_run_spends_outside_its_prompts_come_after_the_judge(): summary = summarize([ _entry("playground", "gpt-4.1-mini", 10, 1, 0.001), - _entry("colleague", "claude-sonnet-5-5", 20, 2, 0.002, attempt=None, step_id="triggers"), + _entry("executor", "claude-sonnet-5-5", 20, 2, 0.002, attempt=None, step_id="triggers"), _entry("judge", "gpt-4.1", 30, 3, 0.003), _entry("validator", "gpt-4.1-nano", 40, 4, 0.004), _entry("solver", "gpt-4.1-mini", 50, 5, 0.005), ]) - assert [share.role for share in summary.shares] == ["solver", "judge", "colleague", "validator", "playground"] - assert "; colleague claude-sonnet-5-5 $0.0020, 20 in, 2 out;" in cost_line(summary) + assert [share.role for share in summary.shares] == ["solver", "judge", "executor", "validator", "playground"] + assert "; executor claude-sonnet-5-5 $0.0020, 20 in, 2 out;" in cost_line(summary) assert summary.attempts == 1 diff --git a/tst/unit/task_step/colleagues_test.py b/tst/unit/task_step/executors_test.py similarity index 79% rename from tst/unit/task_step/colleagues_test.py rename to tst/unit/task_step/executors_test.py index 0f7a5e36c..c0ec75c99 100644 --- a/tst/unit/task_step/colleagues_test.py +++ b/tst/unit/task_step/executors_test.py @@ -1,5 +1,5 @@ -"""A run's colleagues' usage: an env gateway's executor calls as one ``colleague`` entry, written under the -``register_env_triggers`` step that set its executors up (``task_step.colleagues``).""" +"""A run's executors' usage: an env gateway's executor calls as one ``executor`` entry, written under the +``register_env_triggers`` step that set its executors up (``task_step.executors``).""" from __future__ import annotations import logging @@ -8,8 +8,8 @@ from agent_env.config.model_pricing import configured_prices from agent_env.env.gateway.constants import EXT_TRIGGERS_URI -from agent_env.task_step import colleagues -from agent_env.task_step.colleagues import colleague_entry, record_colleague_usage +from agent_env.task_step import executors +from agent_env.task_step.executors import executor_entry, record_executor_usage from agent_env.task_step.context import DeployedAgent, TaskStepContext @@ -19,15 +19,15 @@ def _call(model: str = "gpt-4.1-mini", input_tokens: int = 1000, output_tokens: def _entry(calls: list[dict]): - return colleague_entry(calls, gateway_boot="b1", gateway_version=len(calls), env_id="office", endpoint_host=None, + return executor_entry(calls, gateway_boot="b1", gateway_version=len(calls), env_id="office", endpoint_host=None, prices=configured_prices()) -def test_an_envs_executor_calls_are_one_colleague_entry_priced_model_by_model(): +def test_an_envs_executor_calls_are_one_executor_entry_priced_model_by_model(): entry = _entry([_call(), _call("gpt-4.1", input_tokens=2000)]) assert (entry["role"], entry["attempt"], entry["turns"], entry["env_id"], entry["gateway_boot"]) == ( - "colleague", None, 2, "office", "b1") + "executor", None, 2, "office", "b1") assert (entry["input_tokens"], entry["output_tokens"], entry["cost_status"], entry["partial"]) == ( 3000, 200, "priced", False) assert {row["model"]: row["input_tokens"] for row in entry["models"]} == {"gpt-4.1-mini": 1000, "gpt-4.1": 2000} @@ -81,9 +81,9 @@ def _context(*envs: str) -> TaskStepContext: async def test_the_entry_goes_under_the_step_that_set_the_executors_up_and_each_write_replaces_the_last(): context, env = _context("office"), _Env(calls=[_call()]) - first = await record_colleague_usage(context, [env]) + first = await record_executor_usage(context, [env]) env.calls.append(_call()) - second = await record_colleague_usage(context, [env]) + second = await record_executor_usage(context, [env]) [kept] = context.metadata["step_usage"]["triggers-office"] assert (kept["turns"], kept["endpoint_host"]) == (2, "models.example") @@ -93,9 +93,9 @@ async def test_the_entry_goes_under_the_step_that_set_the_executors_up_and_each_ @pytest.mark.asyncio async def test_a_read_of_an_earlier_list_never_replaces_a_later_one(): context, env = _context("office"), _Env(calls=[_call(), _call()]) - await record_colleague_usage(context, [env]) + await record_executor_usage(context, [env]) - await record_colleague_usage(context, [_Env(calls=[_call()])]) + await record_executor_usage(context, [_Env(calls=[_call()])]) [kept] = context.metadata["step_usage"]["triggers-office"] assert (kept["turns"], kept["gateway_version"]) == (2, 2) @@ -103,14 +103,14 @@ async def test_a_read_of_an_earlier_list_never_replaces_a_later_one(): @pytest.mark.asyncio async def test_a_wait_reads_until_no_call_is_still_being_read_and_no_longer_than_it_was_given(monkeypatch): - monkeypatch.setattr(colleagues, "WAIT_POLL_SECONDS", 0) + monkeypatch.setattr(executors, "WAIT_POLL_SECONDS", 0) finishing = _Env(calls=[_call()], reading=2, arriving=[_call()]) stuck = _Env("lab", calls=[_call()], reading=10**9) - waited = await record_colleague_usage(_context("office"), [finishing], wait_seconds=30) - capped = await record_colleague_usage(_context("lab"), [stuck], wait_seconds=0.05) + waited = await record_executor_usage(_context("office"), [finishing], wait_seconds=30) + capped = await record_executor_usage(_context("lab"), [stuck], wait_seconds=0.05) prompt = _Env(calls=[_call()], reading=2, arriving=[_call()]) - unwaited = await record_colleague_usage(_context("office"), [prompt]) + unwaited = await record_executor_usage(_context("office"), [prompt]) assert ([e["turns"] for e in waited], finishing.reads) == ([2], 3) assert [e["turns"] for e in capped] == [1] and stuck.reads > 1 @@ -119,11 +119,11 @@ async def test_a_wait_reads_until_no_call_is_still_being_read_and_no_longer_than @pytest.mark.asyncio async def test_a_wait_whose_later_read_fails_records_the_list_it_last_read(monkeypatch): - monkeypatch.setattr(colleagues, "WAIT_POLL_SECONDS", 0) + monkeypatch.setattr(executors, "WAIT_POLL_SECONDS", 0) env = _Env(calls=[_call(), _call()], reading=5, error=TimeoutError("no answer")) env.fails_after = 1 - [entry] = await record_colleague_usage(_context("office"), [env], wait_seconds=30) + [entry] = await record_executor_usage(_context("office"), [env], wait_seconds=30) assert (entry["turns"], env.reads) == (2, 2) @@ -131,8 +131,8 @@ async def test_a_wait_whose_later_read_fails_records_the_list_it_last_read(monke @pytest.mark.asyncio async def test_a_redeployed_gateways_calls_are_kept_beside_the_first_ones(): context = _context("office") - await record_colleague_usage(context, [_Env(calls=[_call()], boot="b1")]) - await record_colleague_usage(context, [_Env(calls=[_call(), _call()], boot="b2")]) + await record_executor_usage(context, [_Env(calls=[_call()], boot="b1")]) + await record_executor_usage(context, [_Env(calls=[_call(), _call()], boot="b2")]) kept = context.metadata["step_usage"]["triggers-office"] assert [(e["gateway_boot"], e["turns"]) for e in kept] == [("b1", 1), ("b2", 2)] @@ -144,8 +144,8 @@ async def test_an_env_without_executors_or_a_list_is_skipped_and_a_failed_read_i unregistered, unlisted = _Env("garage", [_call()]), _Env("lab", [_call()], lists=False) failing = _Env("office", error=TimeoutError("no answer")) - with caplog.at_level(logging.WARNING, logger="agent_env.task_step.colleagues"): - assert await record_colleague_usage(context, [unregistered, unlisted, failing]) == [] + with caplog.at_level(logging.WARNING, logger="agent_env.task_step.executors"): + assert await record_executor_usage(context, [unregistered, unlisted, failing]) == [] assert (unregistered.reads, unlisted.reads, failing.reads) == (0, 0, 1) assert "step_usage" not in context.metadata diff --git a/tst/unit/task_step/test_prompt_agent_triggers.py b/tst/unit/task_step/test_prompt_agent_triggers.py index 043c51805..0872bd80e 100644 --- a/tst/unit/task_step/test_prompt_agent_triggers.py +++ b/tst/unit/task_step/test_prompt_agent_triggers.py @@ -275,7 +275,7 @@ async def fake_get(self, url, timeout, params=None, headers=None): [entry] = ctx.metadata["step_usage"]["reg-1"] assert (entry["role"], entry["turns"], entry["input_tokens"], entry["partial"], entry["gateway_boot"]) == ( - "colleague", 2, 1000, True, "b1") + "executor", 2, 1000, True, "b1") @pytest.mark.asyncio From 1067a58daacea7fd9ed17371d90504f3c7896a1e Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 1 Dec 2026 12:05:16 -0800 Subject: [PATCH 10/10] refactor(usage): one task owns each executor call, teardown ends recordings while it waits, and an unlisting gateway makes the cost a lower bound - The gateway runs each executor call as one exchange task that owns its client from the send to the last read; the fire awaits a future the exchange settles (the reply, None at the time limit, ReadTimeout past it, or the error), and `reading` is the count of exchanges still running, so no exit path has to hand the call on or count it down. - Teardown reads its executors' usage while it ends the run's recordings, so its wait for a late reply overlaps time it spends anyway. - An env whose gateway doesn't list its executors' calls counts as one call of unknown usage, said once per run, so the run's cost reads as a lower bound rather than exact. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 5 +- src/agent_env/env/gateway/triggers.py | 150 ++++++++------------ src/agent_env/task/teardown.py | 24 ++-- src/agent_env/task_step/executors.py | 53 +++++-- tst/unit/env/gateway/executor_usage_test.py | 32 ++++- tst/unit/task/usage/executor_ledger_test.py | 19 +++ tst/unit/task_step/executors_test.py | 25 +++- 7 files changed, 184 insertions(+), 124 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index eedbdc2f1..e3e72bba3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -445,8 +445,9 @@ orchestrators call it the same way. What callers rely on: /triggers/usage`, under its own boot id and a version every change raises, kept through a `clear`), a reply past its time limit still read for that usage in the background, for up to ten minutes more. `prompt_agent` and `always_on` as they end, and the teardown, write the list as one `executor` entry per env and gateway boot - (`task_step/executors.py`), the teardown first waiting up to a minute for calls the gateway is still reading - (`reading`), with no attempt, under the `register_env_triggers` step that set the executors up; the ledger keeps it + (`task_step/executors.py`), the teardown waiting up to a minute, while it ends the run's recordings, for calls the + gateway is still reading (`reading`), with no attempt, under the `register_env_triggers` step that set the executors + up, an env whose gateway doesn't list its calls counting as one call of unknown usage; the ledger keeps it by `gateway_boot` too, so each write is the whole list and replaces the last, a call counts once whichever step or attempt wrote it, and a gateway a retry redeployed is kept beside the first. A step's completion takes the context's executor entries with its own, and the teardown writes its own through `record_usage()`, which merges any finished diff --git a/src/agent_env/env/gateway/triggers.py b/src/agent_env/env/gateway/triggers.py index 5eab8e648..90a799914 100644 --- a/src/agent_env/env/gateway/triggers.py +++ b/src/agent_env/env/gateway/triggers.py @@ -481,10 +481,9 @@ def __init__(self, gateway): self._executor_usage: list[dict] = [] self._usage_boot = secrets.token_hex(6) self._usage_version = 0 - # The late reads of calls past their time limit, which a `clear` leaves to finish, and how many calls are - # still being read, those inside their time limit included. - self._executor_reads: set[asyncio.Task] = set() - self._reading = 0 + # Each call's exchange with its executor still being read, past its time limit included, which a `clear` leaves + # to finish. + self._exchanges: set[asyncio.Task] = set() def register(self, body: Any) -> dict: """Additively add each trigger by id (idempotent upsert; conflicting id or bad shape -> 400); watch_roles and @@ -1013,7 +1012,8 @@ def usage(self) -> dict: the calls by it tells a restarted gateway's apart, and ``version`` rises with every change to the list, so a reader holding two copies keeps the later. ``reading`` is how many calls are still being read, a late one's included, which a reader about to close the env can wait out.""" - return {"boot": self._usage_boot, "version": self._usage_version, "reading": self._reading, + return {"boot": self._usage_boot, "version": self._usage_version, + "reading": sum(not exchange.done() for exchange in self._exchanges), "calls": [dict(call) for call in self._executor_usage]} def on_tool_call(self, role: str, name: str, arguments: dict, @@ -1789,66 +1789,77 @@ async def _nap(self, seconds: float) -> None: async def _call_executor(self, executor: dict | None, instruction: str, context_id: str) -> str | None: """The executor's reply to ``instruction``, None when it gave none in time. The call goes into ``usage`` as it starts, with no usage while it runs, and takes the usage its final message reported when it ends, however it - ends; a reply past the time limit is still read for that usage, in the background, up to ``_LATE_REPLY_S`` - more (``_read_late``), since a late reply is spent too. One whose usage never came back keeps none.""" + ends: its exchange (``_exchange``) runs in a task of its own, which reads on past the time limit, or past a fire + that gave up on it, for up to ``_LATE_REPLY_S`` more, since a late reply is spent too.""" if executor is None: return None call: dict[str, Any] = {"role": executor["role"], "usage": None} self._executor_usage.append(call) self._usage_version += 1 - self._reading += 1 - return await self._send_to_executor(executor, instruction, context_id, call) + answer: asyncio.Future = asyncio.get_running_loop().create_future() + exchange = asyncio.ensure_future(self._exchange(executor, instruction, context_id, call, answer)) + self._exchanges.add(exchange) + exchange.add_done_callback(self._exchanges.discard) + return await answer + + async def _exchange(self, executor: dict, instruction: str, context_id: str, call: dict, + answer: asyncio.Future) -> None: + """Send ``instruction`` and read the executor's reply to its end for the usage its final message reports, + settling ``answer`` as the fire sees it: the reply; None for a task still working at the time limit; + ``ReadTimeout`` for a reply still held past it; or the error it failed with. Once ``answer`` is settled the read + goes on for the usage alone, until ``_LATE_REPLY_S`` past the fire's wait; a read that fails then leaves the + call's usage unknown.""" + def settle(reply: str | None = None, error: Exception | None = None) -> None: + if answer.done(): + return + if error is not None: + answer.set_exception(error) + else: + answer.set_result(reply) - async def _send_to_executor(self, executor: dict, instruction: str, context_id: str, call: dict) -> str | None: + loop = asyncio.get_running_loop() url = f"{executor['a2a_url']}/a2a" - deadline = asyncio.get_running_loop().time() + executor["timeout_seconds"] - client = httpx.AsyncClient(timeout=_EXECUTOR_HTTP_TIMEOUT_S) - handed_on = False + deadline = loop.time() + executor["timeout_seconds"] + # An executor holds message/send open until its task ends, so the fire waits as long as the executor may take, + # and a little longer, so a reply that completes just past the time limit is still its reply. + read_s = max(_EXECUTOR_HTTP_TIMEOUT_S, executor["timeout_seconds"]) + _EXECUTOR_HTTP_TIMEOUT_S + until = loop.time() + read_s + _LATE_REPLY_S try: - # An executor holds message/send open until its task ends, so the read waits as long as the executor may - # take, and a little longer, so a reply that completes just past the time limit is still read; past that - # the call times out, and its read goes on in the background for the usage alone. - read_s = max(_EXECUTOR_HTTP_TIMEOUT_S, executor["timeout_seconds"]) + _EXECUTOR_HTTP_TIMEOUT_S - send = asyncio.ensure_future(client.post( - url, timeout=httpx.Timeout(_EXECUTOR_HTTP_TIMEOUT_S, read=read_s + _LATE_REPLY_S), json={ - "jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": "message/send", - "params": {"message": {"role": "user", "messageId": uuid.uuid4().hex, - "contextId": context_id, - "parts": [{"kind": "text", "text": instruction}]}}, - })) - try: - response = await asyncio.wait_for(asyncio.shield(send), timeout=read_s) - except TimeoutError: - handed_on = self._read_late(client, url, call, send=send) - raise httpx.ReadTimeout("") from None # as the read itself timed out before - except asyncio.CancelledError: # a call its fire gave up on is spent too - handed_on = self._read_late(client, url, call, send=send) - raise - response.raise_for_status() - result = response.json().get("result") or {} - task_id = result.get("id") - if not task_id: - return None - status = result.get("status") or {} - # Polled until the time limit, then once more: a reply that completed in the last poll's gap is kept. - last = False - try: + async with httpx.AsyncClient(timeout=_EXECUTOR_HTTP_TIMEOUT_S) as client: + held = loop.call_later(read_s, settle, None, httpx.ReadTimeout("")) + try: + response = await client.post( + url, timeout=httpx.Timeout(_EXECUTOR_HTTP_TIMEOUT_S, read=read_s + _LATE_REPLY_S), json={ + "jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": "message/send", + "params": {"message": {"role": "user", "messageId": uuid.uuid4().hex, + "contextId": context_id, + "parts": [{"kind": "text", "text": instruction}]}}, + }) + finally: + held.cancel() + response.raise_for_status() + result = response.json().get("result") or {} + task_id, status = result.get("id"), result.get("status") or {} + if not task_id: + settle(None) + return + # Polled until the time limit, then once more at once, so a reply that completed in the last poll's + # gap is the fire's; after that, for the usage alone. while status.get("state") not in _TERMINAL_A2A_STATES: - if last: - handed_on = self._read_late(client, url, call, task_id=task_id) - return None - last = asyncio.get_running_loop().time() >= deadline + if loop.time() >= until: + return + last = not answer.done() and loop.time() >= deadline if not last: await asyncio.sleep(2) status = await _task_status(client, url, task_id) - except asyncio.CancelledError: # a call its fire gave up on is spent too - handed_on = self._read_late(client, url, call, task_id=task_id) - raise - return self._replied(status, call) + if last and status.get("state") not in _TERMINAL_A2A_STATES: + settle(None) + settle(self._replied(status, call)) + except Exception as e: # noqa: BLE001 - the fire's error; once it has its answer, the usage stays unknown + settle(error=e) finally: - if not handed_on: - self._reading -= 1 - await client.aclose() + if not answer.done(): + answer.cancel() def _replied(self, status: dict, call: dict) -> str | None: """The text of an ended executor task's final message when it completed; the usage that message reported goes @@ -1863,41 +1874,6 @@ def _replied(self, status: dict, call: dict) -> str | None: return None return "\n".join(p.get("text", "") for p in parts if p.get("kind") == "text") - def _read_late(self, client: httpx.AsyncClient, url: str, call: dict, *, send: asyncio.Future | None = None, - task_id: str | None = None) -> bool: - """Read a call that ran past its time limit until its task ends, at most ``_LATE_REPLY_S``, in the background, - for the usage its final message reports: the ``send`` still waiting for its reply, or the task to poll. Closes - ``client`` when done; a `clear` leaves it to finish.""" - async def read() -> None: - try: - tid, status = task_id, {} - if send is not None: - response = await send - response.raise_for_status() - result = response.json().get("result") or {} - tid, status = result.get("id"), result.get("status") or {} - until = asyncio.get_running_loop().time() + _LATE_REPLY_S - while tid and status.get("state") not in _TERMINAL_A2A_STATES: - if asyncio.get_running_loop().time() >= until: - return - await asyncio.sleep(2) - status = await _task_status(client, url, tid) - if status.get("state") in _TERMINAL_A2A_STATES: - self._replied(status, call) - finally: - self._reading -= 1 - await client.aclose() - - late = asyncio.ensure_future(read()) - self._executor_reads.add(late) - late.add_done_callback(self._read_done) - return True - - def _read_done(self, read: asyncio.Task) -> None: - self._executor_reads.discard(read) - if not read.cancelled(): - read.exception() # a late read that fails leaves its call's usage unknown, never an error - def _cancel(self, tid: str, trig: dict, **cause) -> None: """Retire a deadline its `unless` call answered, and the time triggers anchored on it, which can no longer fire.""" trig["status"] = "cancelled" diff --git a/src/agent_env/task/teardown.py b/src/agent_env/task/teardown.py index 4bb2070ee..e679ad3a3 100644 --- a/src/agent_env/task/teardown.py +++ b/src/agent_env/task/teardown.py @@ -132,11 +132,21 @@ async def teardown_run(context: TaskStepContext, *, timeout: float = TERMINATE_T return await tear_down(context, recorded_sandboxes(context), context.deployed_envs, timeout=timeout) +async def _end_recordings(context: TaskStepContext, env_ids: list[str], timeout: float) -> None: + """End the recordings the run left open on ``env_ids``, its computers' and its browsers', within ``timeout``.""" + try: + async with asyncio.timeout(timeout): + await end_open_recordings(context, env_ids) + await end_open_browser_recordings(context, env_ids) + except TimeoutError: + logger.warning("teardown: the run's open recordings weren't all ended within %gs", timeout) + + async def tear_down(context: TaskStepContext, sandboxes: Sequence[RecordedSandbox], envs: Sequence[DeployedEnv], *, timeout: float) -> TeardownReport: """Record what ``envs``' trigger executors spent (``record_executor_usage``), waiting up to - ``TEARDOWN_WAIT_SECONDS`` for replies still being read, end the recordings the run left open - on them, its computers' and its browsers', with fresh grants, close each + ``TEARDOWN_WAIT_SECONDS`` for replies still being read while it ends the recordings the run left open + on them, its computers' and its browsers', with fresh grants, then close each env still up, register any recording still open from its namespace, then terminate each of ``sandboxes`` by id, all at once and each within ``timeout`` seconds, and remove a local one's work folder once it's down. A close that fails is logged: its env's sandboxes are terminated by id regardless, which leaves one the close took down as it is. Cancelling it returns what it reached, with the rest in ``left``.""" @@ -144,15 +154,11 @@ async def tear_down(context: TaskStepContext, sandboxes: Sequence[RecordedSandbo up = {sandbox.sandbox_id for sandbox in pending} env_ids = [env.env_id for env in envs] try: - executors = await record_executor_usage(context, envs, wait_seconds=TEARDOWN_WAIT_SECONDS) + executors, _ = await asyncio.gather( + record_executor_usage(context, envs, wait_seconds=TEARDOWN_WAIT_SECONDS), + _end_recordings(context, env_ids, timeout)) if executors and context.instance_id: await record_usage(context.instance_id, executors) - try: - async with asyncio.timeout(timeout): - await end_open_recordings(context, env_ids) - await end_open_browser_recordings(context, env_ids) - except TimeoutError: - logger.warning("teardown: the run's open recordings weren't all ended within %gs", timeout) await asyncio.gather(*(_close(env, timeout) for env in envs if any(sandbox_id in up for sandbox_id, _ in env_sandbox_ids(env)))) await asyncio.to_thread(register_open_recordings, context, env_ids) diff --git a/src/agent_env/task_step/executors.py b/src/agent_env/task_step/executors.py index 38af641fb..07181e868 100644 --- a/src/agent_env/task_step/executors.py +++ b/src/agent_env/task_step/executors.py @@ -36,6 +36,11 @@ WAIT_POLL_SECONDS = 2 +# What an env whose gateway doesn't list its executors' calls is read as: one call of unknown usage, under a boot of +# its own, which makes its entry, and the run's cost, a lower bound. +UNLISTED = {"boot": "unlisted", "version": 0, "reading": 0, "calls": [{"usage": None}]} + + def executor_entry(calls: Iterable[Mapping], *, gateway_boot: str, gateway_version: int, env_id: str, endpoint_host: Optional[str], prices: PriceSource) -> Optional[UsageEntry]: """One env gateway's executor calls as one ``executor`` entry: each call's usage read as its executor reported it @@ -62,11 +67,12 @@ async def record_executor_usage(context: TaskStepContext, envs: Sequence[Deploye ``register_env_triggers`` step that set its executors up, and return them as ledger entries, each naming that step. With ``wait_seconds``, as the teardown gives it, an env whose gateway is still reading calls (a late reply's included) is read again until it isn't, for at most that long, so a reply its env's close would cut off is counted. - An env no such step set executors up on, or whose gateway doesn't list its calls, is skipped; a read that fails is - logged. Never raises.""" + An env whose gateway doesn't list its calls counts as one call of unknown usage (``UNLISTED``), so the run's cost + reads as a lower bound; an env no such step set executors up on is skipped; a read that fails is logged. Never + raises.""" registrations = _registrations(context) found = await asyncio.gather(*(_read(context, env, registrations[env.env_id], wait_seconds) for env in envs - if env.env_id in registrations and env.supports(EXT_TRIGGERS_URI, "usage"))) + if env.env_id in registrations)) written = [] for registration, entry in (pair for pair in found if pair is not None): _keep(context, registration["step_id"], entry) @@ -76,8 +82,30 @@ async def record_executor_usage(context: TaskStepContext, envs: Sequence[Deploye async def _read(context: TaskStepContext, env: DeployedEnv, registration: dict, wait_seconds: float) -> Optional[tuple[dict, UsageEntry]]: - """``env``'s executor entry, read once its gateway has no calls left to read or ``wait_seconds`` have passed, from - the last list read when a later read fails; None when it had no calls or couldn't be read at all.""" + """``env``'s executor entry, from its gateway's list (``_listed``), or ``UNLISTED`` when its gateway doesn't list + its calls, said the first time a run reads it; None when it had no calls or couldn't be read at all.""" + if env.supports(EXT_TRIGGERS_URI, "usage"): + report = await _listed(env, wait_seconds) + else: + report = UNLISTED + if not _kept(context, registration["step_id"], env.env_id): + logger.warning("env %s's gateway doesn't list its executors' calls, so what they spent is unknown and the " + "run's cost is a lower bound", env.env_id) + if report is None: + return None + try: + entry = executor_entry(report.get("calls") or [], gateway_boot=str(report.get("boot")), + gateway_version=int(report.get("version") or 0), env_id=env.env_id, + endpoint_host=_executors_host(context, registration), prices=configured_prices()) + except Exception as e: # noqa: BLE001 - an executor's usage never fails its step or the teardown + logger.warning("the executor usage on env %s wasn't read: %s", env.env_id, e) + return None + return None if entry is None else (registration, entry) + + +async def _listed(env: DeployedEnv, wait_seconds: float) -> Optional[dict]: + """``env``'s gateway's list of executor calls, read again while it is still reading some, for at most + ``wait_seconds``; the last list read when a later read fails, None when none could be read.""" until = asyncio.get_running_loop().time() + wait_seconds try: report = await env.invoke(EXT_TRIGGERS_URI, "usage", timeout=READ_TIMEOUT_SECONDS) @@ -92,14 +120,13 @@ async def _read(context: TaskStepContext, env: DeployedEnv, registration: dict, logger.warning("the executor usage on env %s wasn't read again, so its last read is recorded: %s", env.env_id, e) break - try: - entry = executor_entry(report.get("calls") or [], gateway_boot=str(report.get("boot")), - gateway_version=int(report.get("version") or 0), env_id=env.env_id, - endpoint_host=_executors_host(context, registration), prices=configured_prices()) - except Exception as e: # noqa: BLE001 - an executor's usage never fails its step or the teardown - logger.warning("the executor usage on env %s wasn't read: %s", env.env_id, e) - return None - return None if entry is None else (registration, entry) + return report + + +def _kept(context: TaskStepContext, step_id: str, env_id: str) -> bool: + """Whether ``context`` already holds ``env_id``'s executor entry under ``step_id``.""" + return any(entry.get("role") == UsageRole.EXECUTOR and entry.get("env_id") == env_id + for entry in context.metadata.get(STEP_USAGE_KEY, {}).get(step_id) or []) def _registrations(context: TaskStepContext) -> dict[str, dict]: diff --git a/tst/unit/env/gateway/executor_usage_test.py b/tst/unit/env/gateway/executor_usage_test.py index c7ac1ef0b..1c540fd37 100644 --- a/tst/unit/env/gateway/executor_usage_test.py +++ b/tst/unit/env/gateway/executor_usage_test.py @@ -76,21 +76,22 @@ async def test_a_call_that_ends_without_a_reply_is_kept_with_what_it_reported(mo async def test_a_call_is_listed_while_it_waits_for_its_reply_and_every_change_raises_the_version(monkeypatch): engine, release = _engine(), asyncio.Event() - async def replies_later(self, executor, instruction, context_id, call): + async def replies_later(self, executor, instruction, context_id, call, answer): await release.wait() call["usage"] = USAGE self._usage_version += 1 - return "ok" + answer.set_result("ok") - monkeypatch.setattr(TriggerEngine, "_send_to_executor", replies_later) + monkeypatch.setattr(TriggerEngine, "_exchange", replies_later) call = asyncio.ensure_future(engine._call_executor(EXECUTOR, "Reply", context_id="trigger-t1")) await asyncio.sleep(0) waiting = engine.usage() release.set() await call - assert (waiting["version"], waiting["calls"]) == (1, [{"role": "elias", "usage": None}]) + assert (waiting["version"], waiting["reading"], waiting["calls"]) == (1, 1, [{"role": "elias", "usage": None}]) assert (engine.usage()["version"], engine.usage()["calls"]) == (2, [{"role": "elias", "usage": USAGE}]) + assert engine.usage()["reading"] == 0 @pytest.mark.asyncio @@ -108,7 +109,7 @@ async def answers_late(request: httpx.Request) -> httpx.Response: late = engine.usage() engine.clear() release.set() - await asyncio.gather(*engine._executor_reads) + await asyncio.gather(*engine._exchanges) assert (late["calls"], late["reading"]) == ([{"role": "elias", "usage": None}], 1) assert (engine.usage()["version"], engine.usage()["calls"]) == (2, [{"role": "elias", "usage": USAGE}]) @@ -128,7 +129,7 @@ def answers(request: httpx.Request) -> httpx.Response: _executor_answers(monkeypatch, answers) reply = await engine._call_executor({**EXECUTOR, "timeout_seconds": 0.0}, "Reply", context_id="trigger-t1") done.set() - await asyncio.gather(*engine._executor_reads) + await asyncio.gather(*engine._exchanges) assert reply is None assert (engine.usage()["version"], engine.usage()["calls"]) == (2, [{"role": "elias", "usage": USAGE}]) @@ -153,11 +154,28 @@ def answers(request: httpx.Request) -> httpx.Response: with pytest.raises(asyncio.CancelledError): await call done.set() - await asyncio.gather(*engine._executor_reads) + await asyncio.gather(*engine._exchanges) assert (engine.usage()["version"], engine.usage()["calls"]) == (2, [{"role": "elias", "usage": USAGE}]) +@pytest.mark.asyncio +async def test_a_read_that_fails_after_the_fire_has_its_answer_leaves_the_usage_unknown(monkeypatch): + monkeypatch.setattr(triggers_mod.asyncio, "sleep", _no_wait) + engine, broken = _engine(), asyncio.Event() + + def answers(request: httpx.Request) -> httpx.Response: + return httpx.Response(502) if broken.is_set() else _task("working") + + _executor_answers(monkeypatch, answers) + reply = await engine._call_executor({**EXECUTOR, "timeout_seconds": 0.0}, "Reply", context_id="trigger-t1") + broken.set() + await asyncio.gather(*engine._exchanges) + + assert reply is None + assert (engine.usage()["calls"], engine.usage()["reading"]) == ([{"role": "elias", "usage": None}], 0) + + @pytest.mark.asyncio async def test_a_cleared_engine_keeps_the_calls_made_and_its_boot(monkeypatch): engine = _engine() diff --git a/tst/unit/task/usage/executor_ledger_test.py b/tst/unit/task/usage/executor_ledger_test.py index d62be949c..20839eb11 100644 --- a/tst/unit/task/usage/executor_ledger_test.py +++ b/tst/unit/task/usage/executor_ledger_test.py @@ -9,6 +9,7 @@ from agent_env.config import set_document_store from agent_env.store import LocalSqliteDocumentStore from agent_env.task.store import TaskInstanceStore, set_task_instance_store +from agent_env.task import teardown from agent_env.task.task import Task from agent_env.task.teardown import tear_down from agent_env.task.usage.ledger import merged @@ -115,6 +116,24 @@ async def test_the_teardown_waits_for_a_reply_still_being_read(store, monkeypatc assert _executors(store, context.instance_id) == [(None, "triggers", 2)] +@pytest.mark.asyncio +async def test_the_teardown_ends_the_recordings_while_it_waits_for_a_reply(store, monkeypatch): + monkeypatch.setattr(executors, "WAIT_POLL_SECONDS", 0) + monkeypatch.setattr(teardown, "TEARDOWN_WAIT_SECONDS", 5) + env = _Env() + context = await Task(id="t", version=1, steps=[_Registers("triggers", 1), _Asks("ask", env)]).run( + context=TaskStepContext()) + env.reads, env.reading, env.arriving = 0, 10**9, [_call()] + + async def end_open_recordings(context, env_ids): # the reply lands only once the recordings have ended + env.reading = 1 + + monkeypatch.setattr(teardown, "end_open_recordings", end_open_recordings) + await tear_down(context, (), [env], timeout=5) + + assert _executors(store, context.instance_id) == [(None, "triggers", 2)] + + @pytest.mark.asyncio async def test_the_teardown_writes_the_calls_that_came_after_the_last_step(store): env = _Env() diff --git a/tst/unit/task_step/executors_test.py b/tst/unit/task_step/executors_test.py index c0ec75c99..443cc5dab 100644 --- a/tst/unit/task_step/executors_test.py +++ b/tst/unit/task_step/executors_test.py @@ -139,14 +139,27 @@ async def test_a_redeployed_gateways_calls_are_kept_beside_the_first_ones(): @pytest.mark.asyncio -async def test_an_env_without_executors_or_a_list_is_skipped_and_a_failed_read_is_logged(caplog): - context = _context("office", "lab") - unregistered, unlisted = _Env("garage", [_call()]), _Env("lab", [_call()], lists=False) - failing = _Env("office", error=TimeoutError("no answer")) +async def test_an_env_without_executors_is_skipped_and_a_failed_read_is_logged(caplog): + context = _context("office") + unregistered, failing = _Env("garage", [_call()]), _Env("office", error=TimeoutError("no answer")) with caplog.at_level(logging.WARNING, logger="agent_env.task_step.executors"): - assert await record_executor_usage(context, [unregistered, unlisted, failing]) == [] + assert await record_executor_usage(context, [unregistered, failing]) == [] - assert (unregistered.reads, unlisted.reads, failing.reads) == (0, 0, 1) + assert (unregistered.reads, failing.reads) == (0, 1) assert "step_usage" not in context.metadata assert any("office" in record.getMessage() for record in caplog.records) + + +@pytest.mark.asyncio +async def test_an_env_whose_gateway_doesnt_list_its_calls_makes_the_cost_a_lower_bound_and_says_so_once(caplog): + context, unlisted = _context("lab"), _Env("lab", [_call()], lists=False) + + with caplog.at_level(logging.WARNING, logger="agent_env.task_step.executors"): + [first] = await record_executor_usage(context, [unlisted]) + [again] = await record_executor_usage(context, [unlisted]) + + assert (first["gateway_boot"], first["turns"], first["partial"], first["cost_status"]) == ( + "unlisted", 1, True, "unpriced") + assert again == first and unlisted.reads == 0 + assert len([record for record in caplog.records if "lab" in record.getMessage()]) == 1