diff --git a/AGENTS.md b/AGENTS.md index 181ad45b9..e3e72bba3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -440,6 +440,20 @@ 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 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 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 + 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..1e510f6b5 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 (``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``).""" + + EXECUTOR = "executor" + 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..90a799914 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 @@ -65,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", @@ -441,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 @@ -464,6 +476,14 @@ 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 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 + # 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 @@ -571,7 +591,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 +1005,17 @@ 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), 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. ``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": 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, result: Any) -> tuple[list[asyncio.Task], float | None]: """Synchronous post-call detection hook (invoked from the gateway's role-filter wrapper). @@ -1755,42 +1787,92 @@ 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 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: 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 + 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) + + loop = asyncio.get_running_loop() 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: - # 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. - 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 {} - 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 - while status.get("state") not in _TERMINAL_A2A_STATES: - if last: - 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 {}) - 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") + 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: + 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 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) + 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 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 + 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 _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/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/src/agent_env/task/store.py b/src/agent_env/task/store.py index 4b7d400a2..1871251fe 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 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 + ".") @@ -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 [] + 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: @@ -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 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 + + 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..e679ad3a3 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.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) @@ -131,9 +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: - """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_executor_usage``), waiting up to + ``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``.""" @@ -141,12 +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: - 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) + 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) 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/usage/ledger.py b/src/agent_env/task/usage/ledger.py index 0ae1da0cc..6b09d547e 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") @@ -24,19 +26,22 @@ 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. 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) 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 fda5c3aaf..dcd144456 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): @@ -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/executors.py b/src/agent_env/task_step/executors.py new file mode 100644 index 000000000..07181e868 --- /dev/null +++ b/src/agent_env/task_step/executors.py @@ -0,0 +1,161 @@ +"""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 ``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 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.""" + +from __future__ import annotations + +import asyncio +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, older, 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 +#: 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 + + +# 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 + (``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.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) + if not role.turns: + return None + entry = role.entry(prices) + entry["env_id"] = env_id + entry["gateway_boot"] = gateway_boot + entry["gateway_version"] = gateway_version + return entry + + +async def record_executor_usage(context: TaskStepContext, envs: Sequence[DeployedEnv], *, + wait_seconds: float = 0) -> list[dict]: + """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. + 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)) + written = [] + 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 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) + 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 executor usage on env %s wasn't read again, so its last read is recorded: %s", + env.env_id, e) + break + 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]: + """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, 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, []) + 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/task_steps/prompt_agent.py b/src/agent_env/task_step/task_steps/prompt_agent.py index 82cc1e3b4..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,6 +40,7 @@ ) from agent_env.store import DuplicateKeyError, get_config from agent_env.store.object_store import ObjectStore +from agent_env.task_step.executors import record_executor_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_executor_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_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 26e87e61e..57229bba7 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,9 @@ class UsageEntry(CostFields): unreported_calls: NotRequired[int] unparsed: NotRequired[list[dict]] unparsed_turns: NotRequired[int] + env_id: NotRequired[str] + gateway_boot: NotRequired[str] + gateway_version: NotRequired[int] @dataclass @@ -267,7 +270,14 @@ 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 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 an executor'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}) @@ -286,17 +296,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 +314,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 +333,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 +341,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..1c540fd37 --- /dev/null +++ b/tst/unit/env/gateway/executor_usage_test.py @@ -0,0 +1,209 @@ +"""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 trigger executors' usage.""" +from __future__ import annotations + +import asyncio + +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)) + + +_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)}}}}) + + +@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"], engine.usage()["reading"]) == ([{"role": "elias", "usage": USAGE}], 0) + + +@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_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, answer): + await release.wait() + call["usage"] = USAGE + self._usage_version += 1 + answer.set_result("ok") + + 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["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 +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._exchanges) + + 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 +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._exchanges) + + assert reply is None + 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._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() + _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"], "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"] == { + "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/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")) diff --git a/tst/unit/task/usage/executor_ledger_test.py b/tst/unit/task/usage/executor_ledger_test.py new file mode 100644 index 000000000..20839eb11 --- /dev/null +++ b/tst/unit/task/usage/executor_ledger_test.py @@ -0,0 +1,164 @@ +"""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.""" + +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 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 +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.executors_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 an executor answers once, recording the executors' 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_executor_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 = _executors(self.store, context.instance_id) + return context + + +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_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)] + + context = await Task(id="t", version=1, steps=steps).run(context=TaskStepContext()) + + assert reads.seen == [(None, "triggers", 1)] + assert _executors(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 _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(executors, "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 _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() + 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 _executors(store, context.instance_id) == [(None, "triggers", 2)] + + +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}]) + + 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": "executor", "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 1bd9fcf66..d6961f9c3 100644 --- a/tst/unit/task/usage/summary_test.py +++ b/tst/unit/task/usage/summary_test.py @@ -24,6 +24,20 @@ 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("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", "executor", "validator", "playground"] + assert "; executor 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(): summary = summarize([ _entry("judge", "claude-sonnet-4-6", 2900, 120, 0.0104), diff --git a/tst/unit/task_step/executors_test.py b/tst/unit/task_step/executors_test.py new file mode 100644 index 000000000..443cc5dab --- /dev/null +++ b/tst/unit/task_step/executors_test.py @@ -0,0 +1,165 @@ +"""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 + +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 import executors +from agent_env.task_step.executors import executor_entry, record_executor_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 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_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"]) == ( + "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} + 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``; 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, + 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, 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 and self.reads > self.fails_after: + raise self.error + 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: + 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_executor_usage(context, [env]) + env.calls.append(_call()) + second = await record_executor_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_read_of_an_earlier_list_never_replaces_a_later_one(): + context, env = _context("office"), _Env(calls=[_call(), _call()]) + await record_executor_usage(context, [env]) + + await record_executor_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_wait_reads_until_no_call_is_still_being_read_and_no_longer_than_it_was_given(monkeypatch): + 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_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_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 + 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(executors, "WAIT_POLL_SECONDS", 0) + env = _Env(calls=[_call(), _call()], reading=5, error=TimeoutError("no answer")) + env.fails_after = 1 + + [entry] = await record_executor_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") + 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)] + + +@pytest.mark.asyncio +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, failing]) == [] + + 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 diff --git a/tst/unit/task_step/test_prompt_agent_triggers.py b/tst/unit/task_step/test_prompt_agent_triggers.py index 3f4e16634..0872bd80e 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"]) == ( + "executor", 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):