diff --git a/AGENTS.md b/AGENTS.md index 5ac13f531..8fd7822ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -383,14 +383,18 @@ orchestrators call it the same way. What callers rely on: `instance_id` makes it an idempotent upsert. After each step `record_step_complete()` writes only the fields that step changed (a path-level diff) and derives `current_step` / `status`; failures go through `record_task_failure()`, retries through `undo_steps()`. -- The instance keeps the run's usage ledger beside the context (`task/usage_ledger.py`): `usage`, every step's +- The instance keeps the run's usage ledger beside the context (`task/usage/ledger.py`): `usage`, every step's `metadata.step_usage` entries keyed by attempt epoch, step and role, and `usage_total`, their sum. Each of those writes merges into it: a completion its step's entries, even one a later attempt refused; `undo_steps()` the rolled-back steps' (`usage=`); `record_task_failure()` and `record_teardown()` the context's; and - `record_task_cancelled()` the `usage=` it is given. A re-register keeps it, so it holds every attempt and - generation. A 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. + `record_task_cancelled()` the `usage=` it is given. While a step runs, `Task.run` writes its entries so far every 15 + seconds in which they changed (`task/usage/running.py`, `record_running_usage()`), so a budget sees a long step's + spend and a worker that dies mid-step keeps it. Those entries are marked `running`, which makes + `usage_total.partial` true, as the turn in flight isn't in them; such a write never takes an entry back + (`usage.ledger.ahead`), and the step's completion replaces them with its final entries. A re-register keeps it, so + it holds every attempt and generation. A 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. - 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/task/store.py b/src/agent_env/task/store.py index cd520919c..885428c91 100644 --- a/src/agent_env/task/store.py +++ b/src/agent_env/task/store.py @@ -28,7 +28,7 @@ commit_ordered, replay_context, ) -from agent_env.task.usage_ledger import LEDGER_KEY, TOTAL_KEY, entries_of, ledger_fields, total +from agent_env.task.usage.ledger import LEDGER_KEY, TOTAL_KEY, ahead, entries_of, ledger_fields, total from agent_env.task_step.context import TaskStepContext from agent_env.task_step.context_ops import ContextUpdateOps from agent_env.task_step.usage import STEP_USAGE_KEY @@ -186,7 +186,7 @@ class TaskInstance: # carries the epoch it was dispatched under and no-ops when older than the stored one, # fencing a writer from a rolled-back attempt. Missing (pre-field docs) reads as 0. attempt_epoch: int = 0 - # The run's usage ledger (``usage_ledger``): every attempt's usage entries and their total, outside ``context``. + # The run's usage ledger (``usage.ledger``): every attempt's usage entries and their total, outside ``context``. usage: list[dict] = field(default_factory=list) usage_total: dict | None = None @@ -839,6 +839,20 @@ def record_teardown_sync(self, instance_id: str, context: "TaskStepContext", att self._end_write(instance_id, entries_of(context.metadata.get(STEP_USAGE_KEY)), lambda doc: {"context": safe}, owns=lambda doc: doc.get("attempt_epoch", 0) <= attempt_epoch) + def record_running_usage_sync(self, instance_id: str, usage: list[dict]) -> None: + """Merge ``usage``, the entries of a step still running, into the ledger alone, marked ``running``, which makes + the run's total a lower bound as the turn in flight isn't in them. Each lands only when it is ahead of the + ledger's (``ahead``), so a write that lands late, as one a cancel left running, never takes counts back. The + step's completion writes the rest, and its final entries replace these.""" + running = [{**entry, "running": True} for entry in usage] + + def _mutate(doc: dict) -> UpdateSpec | None: + spent = ledger_fields(doc, ahead(doc.get(LEDGER_KEY) or [], running)) + 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]) -> None: """A write that ends a run or an attempt, a CAS: ``fields`` of the document when ``owns`` it, and ``usage``, the @@ -995,6 +1009,17 @@ async def record_step_complete( ) +async def record_running_usage(instance_id: str, usage: list[dict]) -> bool: + """Async ``TaskInstanceStore.record_running_usage_sync``; whether it was written. A store error is logged, not + raised, as the step's completion writes its entries again.""" + try: + await asyncio.to_thread(get_task_instance_store().record_running_usage_sync, instance_id, usage) + return True + except Exception: + logger.warning("Failed to record running 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/task.py b/src/agent_env/task/task.py index aac62684c..8be4ba775 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -26,7 +26,8 @@ from agent_env.task_step.preflight import pinned from agent_env.task.outcome import FailedStep from agent_env.task.teardown import env_record_ids -from agent_env.task.usage_ledger import entries_of +from agent_env.task.usage.ledger import entries_of +from agent_env.task.usage.running import running_usage from agent_env.task_step.context import ( ATTEMPT_EPOCH, ENTITY_IDS_KEY, @@ -712,7 +713,8 @@ async def _run_one(step: TaskStep, idx: int, dispatch_epoch: int) -> None: ATTEMPT_EPOCH.set(dispatch_epoch) try: with protocol_v1.authorized({d.environment_url: d.control_headers for d in context.deployed_envs}): - await step.execute(context) + async with running_usage(instance_id, step.id, context): + await step.execute(context) except asyncio.CancelledError: raise except BaseException as exc: diff --git a/src/agent_env/task/usage/__init__.py b/src/agent_env/task/usage/__init__.py new file mode 100644 index 000000000..4a508b8ad --- /dev/null +++ b/src/agent_env/task/usage/__init__.py @@ -0,0 +1,2 @@ +"""A run's usage: its ledger on the task instance (``ledger``) and a running step's entries written to it +(``running``).""" diff --git a/src/agent_env/task/usage_ledger.py b/src/agent_env/task/usage/ledger.py similarity index 79% rename from src/agent_env/task/usage_ledger.py rename to src/agent_env/task/usage/ledger.py index af9704978..0ae1da0cc 100644 --- a/src/agent_env/task/usage_ledger.py +++ b/src/agent_env/task/usage/ledger.py @@ -43,16 +43,23 @@ def merged(ledger: list[dict], entries: list[dict]) -> list[dict]: return out +def ahead(ledger: list[dict], entries: list[dict]) -> list[dict]: + """The entries with more turns than ``ledger``'s entry of their attempt, step and role, or with none there. A + role's turns only grow, so a snapshot of a running step written late never takes back a newer entry.""" + turns = {_key(entry): entry.get("turns") or 0 for entry in ledger} + return [entry for entry in entries if (entry.get("turns") or 0) > turns.get(_key(entry), -1)] + + def total(ledger: list[dict]) -> dict[str, Any]: """The ledger summed, as a budget reads it: the cost and the token counts, each None when no entry has one, never - 0; ``partial`` when an entry's counts are a lower bound; ``unpriced_entries`` the entries with no cost, which - make the cost a lower bound too.""" + 0; ``partial`` when an entry's counts are a lower bound, its own or a running step's (``running``), which lacks the + turn in flight; ``unpriced_entries`` the entries with no cost, which make the cost a lower bound too.""" def sum_of(name: str) -> Any: values = [v for e in ledger if isinstance(v := e.get(name), (int, float)) and not isinstance(v, bool)] return sum(values) if values else None return {"entries": len(ledger), "cost_usd": sum_of("cost_usd"), **{name: sum_of(name) for name in _COUNTS}, - "partial": any(bool(e.get("partial")) for e in ledger), + "partial": any(bool(e.get("partial")) or bool(e.get("running")) for e in ledger), "unpriced_entries": sum(1 for e in ledger if e.get("cost_usd") is None)} diff --git a/src/agent_env/task/usage/running.py b/src/agent_env/task/usage/running.py new file mode 100644 index 000000000..55d777619 --- /dev/null +++ b/src/agent_env/task/usage/running.py @@ -0,0 +1,49 @@ +"""A running step's usage, written to its run's ledger while the step runs, every ``INTERVAL_S`` in which it changed, +so a budget sees a long step's spend before the step ends and a worker that dies mid-step keeps it +(``store.record_running_usage``, which marks the entries ``running``). The step's completion writes its final entries +over these: the ledger keeps an entry by attempt, step and role.""" + +from __future__ import annotations + +import asyncio +import contextlib +import copy +from collections.abc import AsyncIterator + +from agent_env.task import store +from agent_env.task.usage.ledger import entries_of +from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.usage import STEP_USAGE_KEY + +INTERVAL_S = 15.0 + + +@contextlib.asynccontextmanager +async def running_usage(instance_id: str | None, step_id: str, context: TaskStepContext) -> AsyncIterator[None]: + """Writes ``step_id``'s entries in ``context.metadata.step_usage`` to ``instance_id``'s ledger while the block runs, + a write that failed tried again at the next interval; leaving the block waits for a write in flight. Without an + instance, it writes nothing.""" + if not instance_id: + yield + return + stopped = asyncio.Event() + writer = asyncio.create_task(_write(instance_id, step_id, context, stopped)) + try: + yield + finally: + stopped.set() + await writer + + +async def _write(instance_id: str, step_id: str, context: TaskStepContext, stopped: asyncio.Event) -> None: + written = None + while True: + try: + await asyncio.wait_for(stopped.wait(), INTERVAL_S) + return + except TimeoutError: + pass + entries = copy.deepcopy((context.metadata.get(STEP_USAGE_KEY) or {}).get(step_id)) + if entries and entries != written and await store.record_running_usage( + instance_id, entries_of({step_id: entries})): + written = entries diff --git a/tst/unit/task/usage/__init__.py b/tst/unit/task/usage/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tst/unit/task/usage_ledger_test.py b/tst/unit/task/usage/ledger_test.py similarity index 100% rename from tst/unit/task/usage_ledger_test.py rename to tst/unit/task/usage/ledger_test.py diff --git a/tst/unit/task/usage/running_test.py b/tst/unit/task/usage/running_test.py new file mode 100644 index 000000000..557e59eaa --- /dev/null +++ b/tst/unit/task/usage/running_test.py @@ -0,0 +1,155 @@ +"""A running step's usage reaches its run's ledger while the step runs: a budget reading the ledger sees a long step's +turns before the step ends, a worker that dies mid-step keeps them, and the step's completion replaces them with its +final entry. Real LocalSqliteDocumentStore; the steps record usage as a prompt step does.""" + +from __future__ import annotations + +import asyncio + +import pytest +from agentenv_protocol.a2a_agent import Usage + +from agent_env.a2a_agent.protocol import TerminalResponse +from agent_env.config import set_document_store +from agent_env.config.model import ModelRole +from agent_env.store import LocalSqliteDocumentStore +from agent_env.task.usage import running +from agent_env.task.store import TaskInstanceStore, get_task_instance_store, set_task_instance_store +from agent_env.task.task import Task +from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.task_step import TaskStep +from agent_env.task_step.usage import STEP_USAGE_KEY, StepUsage + + +@pytest.fixture +def store(tmp_path, monkeypatch): + monkeypatch.setattr(running, "INTERVAL_S", 0.02) + 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) + + +def _ledger(instance_id): + return [(e["attempt"], e["step_id"], e["turns"], e["input_tokens"], bool(e.get("running"))) + for e in get_task_instance_store().get(instance_id).usage] + + +def _partial(instance_id): + return get_task_instance_store().get(instance_id).usage_total["partial"] + + +async def _until(instance_id, want): + for _ in range(250): + if _ledger(instance_id) == want: + return want + await asyncio.sleep(0.02) + return _ledger(instance_id) + + +class _Turns(TaskStep): + """Records a solver turn on gpt-4.1-mini of each of ``inputs`` input tokens, after each waiting until the ledger + holds the step's turns so far, marked running, and noting whether the run's total said it was partial, then holds + on ``hold`` when given.""" + + type = "turns" + + def __init__(self, id, inputs, hold=None, **kwargs): + super().__init__(id, 1, **kwargs) + self.inputs, self.hold, self.seen, self.partial = inputs, hold, [], [] + + async def execute(self, context): + usage = StepUsage(context, self.id) + usage.start(ModelRole.SOLVER, "gpt-4.1-mini", None) + for turns, tokens in enumerate(self.inputs, start=1): + usage.turn(ModelRole.SOLVER, TerminalResponse(response_text="", usage=Usage( + input_tokens=tokens, output_tokens=10, input_includes_cache=True))) + self.seen.append(await _until(context.instance_id, [(0, self.id, turns, sum(self.inputs[:turns]), True)])) + self.partial.append(_partial(context.instance_id)) + if self.hold is not None: + await self.hold.wait() + return context + + +@pytest.mark.asyncio +async def test_a_long_steps_turns_reach_the_ledger_before_it_ends_and_its_completion_replaces_them(store): + step = _Turns("long", [100, 200]) + context = await Task(id="t", version=1, steps=[step]).run(context=TaskStepContext()) + + assert step.seen == [[(0, "long", 1, 100, True)], [(0, "long", 2, 300, True)]] and step.partial == [True, True] + assert _ledger(context.instance_id) == [(0, "long", 2, 300, False)] + assert get_task_instance_store().get(context.instance_id).usage_total["input_tokens"] == 300 + assert not _partial(context.instance_id) + + +@pytest.mark.asyncio +async def test_a_worker_that_dies_mid_step_keeps_the_turns_written_before(store, monkeypatch): + """The run's end writes never come, as when its worker dies: the step's turn is in the ledger all the same.""" + for write in ("record_step_complete_sync", "record_task_failure_sync", "record_task_cancelled_sync", + "record_teardown_sync"): + monkeypatch.setattr(store, write, lambda *args, **kwargs: None) + context, step = TaskStepContext(), _Turns("dies", [100], hold=asyncio.Event()) + run = asyncio.create_task(Task(id="t", version=1, steps=[step]).run(context=context)) + while not step.seen: + await asyncio.sleep(0.02) + run.cancel() + with pytest.raises(asyncio.CancelledError): + await run + + assert _ledger(context.instance_id) == [(0, "dies", 1, 100, True)] and _partial(context.instance_id) + + +@pytest.mark.asyncio +async def test_usage_is_written_only_when_it_changed_and_stop_waits_for_a_write_in_flight(monkeypatch): + monkeypatch.setattr(running, "INTERVAL_S", 0.01) + writes, landed = asyncio.Event(), [] + + async def slow(instance_id, usage): + writes.set() + await asyncio.sleep(0.1) + landed.append(usage) + return True + + monkeypatch.setattr(running.store, "record_running_usage", slow) + context = TaskStepContext(metadata={STEP_USAGE_KEY: {"s": [{"role": "solver", "attempt": 0, "turns": 1}]}}) + async with running.running_usage("instance", "s", context): + await writes.wait() + assert landed == [[{"role": "solver", "attempt": 0, "turns": 1, "step_id": "s"}]] + + async with running.running_usage("instance", "s", context): + await asyncio.sleep(0.25) + assert len(landed) == 2 + + +@pytest.mark.asyncio +async def test_a_snapshot_that_lands_late_never_takes_the_ledger_back(store): + """As a write a cancel left running in its thread, landing after the step's newer entry: a role's turns only grow, + so the ledger keeps the entry with more of them.""" + context = await Task(id="t", version=1, steps=[_Turns("long", [100, 200])]).run(context=TaskStepContext()) + late = {"attempt": 0, "step_id": "long", "role": "solver", "turns": 1, "input_tokens": 100} + + store.record_running_usage_sync(context.instance_id, [late]) + assert _ledger(context.instance_id) == [(0, "long", 2, 300, False)] + + store.record_running_usage_sync(context.instance_id, [{**late, "turns": 3, "input_tokens": 450}]) + assert _ledger(context.instance_id) == [(0, "long", 3, 450, True)] + + +@pytest.mark.asyncio +async def test_a_write_that_failed_is_tried_again_though_nothing_changed(monkeypatch): + monkeypatch.setattr(running, "INTERVAL_S", 0.01) + tries = [] + + async def flaky(instance_id, usage): + tries.append(usage) + return len(tries) > 1 + + monkeypatch.setattr(running.store, "record_running_usage", flaky) + context = TaskStepContext(metadata={STEP_USAGE_KEY: {"s": [{"role": "solver", "attempt": 0, "turns": 1}]}}) + async with running.running_usage("instance", "s", context): + await asyncio.sleep(0.2) + + assert len(tries) == 2 and tries[0] == tries[1]