From 9fff0f907316fb4b6056a2937b826200a1393e4f Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 14:10:30 -0800 Subject: [PATCH 1/5] feat(task): a running step's usage reaches the run's ledger before the step ends Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 +- src/agent_env/task/running_usage.py | 47 +++++++++++ src/agent_env/task/store.py | 19 +++++ src/agent_env/task/task.py | 8 +- tst/unit/task/running_usage_test.py | 119 ++++++++++++++++++++++++++++ 5 files changed, 196 insertions(+), 3 deletions(-) create mode 100644 src/agent_env/task/running_usage.py create mode 100644 tst/unit/task/running_usage_test.py diff --git a/AGENTS.md b/AGENTS.md index 5ac13f531..6d9ed7a25 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -387,8 +387,10 @@ orchestrators call it the same way. What callers rely on: `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 + `record_task_cancelled()` the `usage=` it is given. While a step runs, `Task.run` writes its entries so far every + 15 s in which they changed (`task/running_usage.py`, `record_usage()`), so a budget sees a long step's spend and a + worker that dies mid-step keeps it; the step's completion replaces them. 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()`; diff --git a/src/agent_env/task/running_usage.py b/src/agent_env/task/running_usage.py new file mode 100644 index 000000000..9a07f41b6 --- /dev/null +++ b/src/agent_env/task/running_usage.py @@ -0,0 +1,47 @@ +"""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. 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 copy + +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 + + +class RunningUsage: + """Writes ``step_id``'s entries in ``context.metadata.step_usage`` to ``instance_id``'s ledger from ``start`` until + ``stop``, which waits for a write in flight, so none lands after the step's completion.""" + + def __init__(self, instance_id: str, step_id: str, context: TaskStepContext) -> None: + self._instance_id, self._step_id, self._context = instance_id, step_id, context + self._stopped = asyncio.Event() + self._task: asyncio.Task | None = None + + def start(self) -> RunningUsage: + self._task = asyncio.create_task(self._run()) + return self + + async def stop(self) -> None: + self._stopped.set() + if self._task is not None: + await self._task + + async def _run(self) -> None: + written = None + while True: + try: + await asyncio.wait_for(self._stopped.wait(), INTERVAL_S) + return + except TimeoutError: + pass + entries = (self._context.metadata.get(STEP_USAGE_KEY) or {}).get(self._step_id) + if entries and entries != written: + written = copy.deepcopy(entries) + await store.record_usage(self._instance_id, entries_of({self._step_id: written})) diff --git a/src/agent_env/task/store.py b/src/agent_env/task/store.py index cd520919c..3dcb24107 100644 --- a/src/agent_env/task/store.py +++ b/src/agent_env/task/store.py @@ -839,6 +839,16 @@ 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_usage_sync(self, instance_id: str, usage: list[dict]) -> None: + """Merge ``usage``, the entries of a step still running, into the ledger alone. The step's completion writes the + rest, and its final entries replace these, being of the same attempt, step and role.""" + def _mutate(doc: dict) -> UpdateSpec | None: + spent = ledger_fields(doc, usage) + 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 +1005,15 @@ async def record_step_complete( ) +async def record_usage(instance_id: str, usage: list[dict]) -> None: + """Async ``TaskInstanceStore.record_usage_sync``; 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_usage_sync, instance_id, usage) + except Exception: + logger.warning("Failed to record running usage for instance_id=%s", instance_id, exc_info=True) + + 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..c8211ca4b 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -26,6 +26,7 @@ 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.running_usage import RunningUsage from agent_env.task.usage_ledger import entries_of from agent_env.task_step.context import ( ATTEMPT_EPOCH, @@ -710,9 +711,14 @@ async def _run_one(step: TaskStep, idx: int, dispatch_epoch: int) -> None: started_utc = datetime.now(timezone.utc).isoformat() # This step's own asyncio task, so a sibling dispatched alongside it doesn't see it. ATTEMPT_EPOCH.set(dispatch_epoch) + running = RunningUsage(instance_id, step.id, context).start() if instance_id else None try: with protocol_v1.authorized({d.environment_url: d.control_headers for d in context.deployed_envs}): - await step.execute(context) + try: + await step.execute(context) + finally: + if running is not None: + await running.stop() except asyncio.CancelledError: raise except BaseException as exc: diff --git a/tst/unit/task/running_usage_test.py b/tst/unit/task/running_usage_test.py new file mode 100644 index 000000000..1b8a621d8 --- /dev/null +++ b/tst/unit/task/running_usage_test.py @@ -0,0 +1,119 @@ +"""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 import running_usage +from agent_env.task.running_usage import RunningUsage +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_usage, "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"]) + for e in get_task_instance_store().get(instance_id).usage] + + +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, 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 = 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]))])) + 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)], [(0, "long", 2, 300)]] + assert _ledger(context.instance_id) == [(0, "long", 2, 300)] + assert get_task_instance_store().get(context.instance_id).usage_total["input_tokens"] == 300 + + +@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)] + + +@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_usage, "INTERVAL_S", 0.01) + writes, landed = asyncio.Event(), [] + + async def slow(instance_id, usage): + writes.set() + await asyncio.sleep(0.1) + landed.append(usage) + + monkeypatch.setattr(running_usage.store, "record_usage", slow) + context = TaskStepContext(metadata={STEP_USAGE_KEY: {"s": [{"role": "solver", "attempt": 0, "turns": 1}]}}) + writer = RunningUsage("instance", "s", context).start() + await writes.wait() + await writer.stop() + assert landed == [[{"role": "solver", "attempt": 0, "turns": 1, "step_id": "s"}]] + + writer = RunningUsage("instance", "s", context).start() + await asyncio.sleep(0.25) + await writer.stop() + assert len(landed) == 2 From 7a3fa83a673ff665f2ab9eda55b0662108e8d47f Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 14:41:15 -0800 Subject: [PATCH 2/5] fix(task): a running write never takes the ledger back, and a failed one is tried again Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 ++- src/agent_env/task/running_usage.py | 11 +++++----- src/agent_env/task/store.py | 17 +++++++++------ src/agent_env/task/usage_ledger.py | 7 ++++++ tst/unit/task/running_usage_test.py | 33 +++++++++++++++++++++++++++++ 5 files changed, 58 insertions(+), 13 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6d9ed7a25..2afa1b875 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -389,7 +389,8 @@ orchestrators call it the same way. What callers rely on: rolled-back steps' (`usage=`); `record_task_failure()` and `record_teardown()` the context's; and `record_task_cancelled()` the `usage=` it is given. While a step runs, `Task.run` writes its entries so far every 15 s in which they changed (`task/running_usage.py`, `record_usage()`), so a budget sees a long step's spend and a - worker that dies mid-step keeps it; the step's completion replaces them. A re-register keeps it, so it holds every + worker that dies mid-step keeps it; such a write never takes an entry back (`usage_ledger.ahead`), and the step's + completion replaces them. 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. diff --git a/src/agent_env/task/running_usage.py b/src/agent_env/task/running_usage.py index 9a07f41b6..59d067396 100644 --- a/src/agent_env/task/running_usage.py +++ b/src/agent_env/task/running_usage.py @@ -17,7 +17,8 @@ class RunningUsage: """Writes ``step_id``'s entries in ``context.metadata.step_usage`` to ``instance_id``'s ledger from ``start`` until - ``stop``, which waits for a write in flight, so none lands after the step's completion.""" + ``stop``, which waits for a write in flight; one a cancel leaves running can't take counts back (``ahead``). A + write that failed is tried again at the next interval.""" def __init__(self, instance_id: str, step_id: str, context: TaskStepContext) -> None: self._instance_id, self._step_id, self._context = instance_id, step_id, context @@ -41,7 +42,7 @@ async def _run(self) -> None: return except TimeoutError: pass - entries = (self._context.metadata.get(STEP_USAGE_KEY) or {}).get(self._step_id) - if entries and entries != written: - written = copy.deepcopy(entries) - await store.record_usage(self._instance_id, entries_of({self._step_id: written})) + entries = copy.deepcopy((self._context.metadata.get(STEP_USAGE_KEY) or {}).get(self._step_id)) + if entries and entries != written and await store.record_usage( + self._instance_id, entries_of({self._step_id: entries})): + written = entries diff --git a/src/agent_env/task/store.py b/src/agent_env/task/store.py index 3dcb24107..626e2937f 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 @@ -840,10 +840,11 @@ def record_teardown_sync(self, instance_id: str, context: "TaskStepContext", att owns=lambda doc: doc.get("attempt_epoch", 0) <= attempt_epoch) def record_usage_sync(self, instance_id: str, usage: list[dict]) -> None: - """Merge ``usage``, the entries of a step still running, into the ledger alone. The step's completion writes the - rest, and its final entries replace these, being of the same attempt, step and role.""" + """Merge ``usage``, the entries of a step still running, into the ledger alone, each 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.""" def _mutate(doc: dict) -> UpdateSpec | None: - spent = ledger_fields(doc, usage) + spent = ledger_fields(doc, ahead(doc.get(LEDGER_KEY) or [], usage)) return UpdateSpec(set=spent) if spent else None compare_and_swap(self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), _mutate, @@ -1005,13 +1006,15 @@ async def record_step_complete( ) -async def record_usage(instance_id: str, usage: list[dict]) -> None: - """Async ``TaskInstanceStore.record_usage_sync``; a store error is logged, not raised, as the step's completion - writes its entries again.""" +async def record_usage(instance_id: str, usage: list[dict]) -> bool: + """Async ``TaskInstanceStore.record_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_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( diff --git a/src/agent_env/task/usage_ledger.py b/src/agent_env/task/usage_ledger.py index af9704978..155944a82 100644 --- a/src/agent_env/task/usage_ledger.py +++ b/src/agent_env/task/usage_ledger.py @@ -43,6 +43,13 @@ 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 diff --git a/tst/unit/task/running_usage_test.py b/tst/unit/task/running_usage_test.py index 1b8a621d8..2bf27e04e 100644 --- a/tst/unit/task/running_usage_test.py +++ b/tst/unit/task/running_usage_test.py @@ -105,6 +105,7 @@ async def slow(instance_id, usage): writes.set() await asyncio.sleep(0.1) landed.append(usage) + return True monkeypatch.setattr(running_usage.store, "record_usage", slow) context = TaskStepContext(metadata={STEP_USAGE_KEY: {"s": [{"role": "solver", "attempt": 0, "turns": 1}]}}) @@ -117,3 +118,35 @@ async def slow(instance_id, usage): await asyncio.sleep(0.25) await writer.stop() 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_usage_sync(context.instance_id, [late]) + assert _ledger(context.instance_id) == [(0, "long", 2, 300)] + + store.record_usage_sync(context.instance_id, [{**late, "turns": 3, "input_tokens": 450}]) + assert _ledger(context.instance_id) == [(0, "long", 3, 450)] + + +@pytest.mark.asyncio +async def test_a_write_that_failed_is_tried_again_though_nothing_changed(monkeypatch): + monkeypatch.setattr(running_usage, "INTERVAL_S", 0.01) + tries = [] + + async def flaky(instance_id, usage): + tries.append(usage) + return len(tries) > 1 + + monkeypatch.setattr(running_usage.store, "record_usage", flaky) + context = TaskStepContext(metadata={STEP_USAGE_KEY: {"s": [{"role": "solver", "attempt": 0, "turns": 1}]}}) + writer = RunningUsage("instance", "s", context).start() + await asyncio.sleep(0.2) + await writer.stop() + + assert len(tries) == 2 and tries[0] == tries[1] From 211b57d756c5621d37289564f007c42e918850c4 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 15:06:01 -0800 Subject: [PATCH 3/5] feat(task): a running step's ledger entries are marked running, and the run's total is partial while any is Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 5 +++-- src/agent_env/task/running_usage.py | 7 ++++--- src/agent_env/task/usage_ledger.py | 6 +++--- tst/unit/task/running_usage_test.py | 29 ++++++++++++++++++----------- 4 files changed, 28 insertions(+), 19 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2afa1b875..99e44e41f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -389,8 +389,9 @@ orchestrators call it the same way. What callers rely on: rolled-back steps' (`usage=`); `record_task_failure()` and `record_teardown()` the context's; and `record_task_cancelled()` the `usage=` it is given. While a step runs, `Task.run` writes its entries so far every 15 s in which they changed (`task/running_usage.py`, `record_usage()`), so a budget sees a long step's spend and a - worker that dies mid-step keeps it; such a write never takes an entry back (`usage_ledger.ahead`), and the step's - completion replaces them. A re-register keeps it, so it holds every + 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. diff --git a/src/agent_env/task/running_usage.py b/src/agent_env/task/running_usage.py index 59d067396..26b43434d 100644 --- a/src/agent_env/task/running_usage.py +++ b/src/agent_env/task/running_usage.py @@ -1,6 +1,7 @@ """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. The step's -completion writes its final entries over these: the ledger keeps an entry by attempt, step and role.""" +so a budget sees a long step's spend before the step ends and a worker that dies mid-step keeps it. Each entry is +marked ``running``, which makes the run's total a lower bound, as the turn in flight isn't in it. The step's completion +writes its final entries over these: the ledger keeps an entry by attempt, step and role.""" from __future__ import annotations @@ -44,5 +45,5 @@ async def _run(self) -> None: pass entries = copy.deepcopy((self._context.metadata.get(STEP_USAGE_KEY) or {}).get(self._step_id)) if entries and entries != written and await store.record_usage( - self._instance_id, entries_of({self._step_id: entries})): + self._instance_id, [{**entry, "running": True} for entry in entries_of({self._step_id: entries})]): written = entries diff --git a/src/agent_env/task/usage_ledger.py b/src/agent_env/task/usage_ledger.py index 155944a82..0ae1da0cc 100644 --- a/src/agent_env/task/usage_ledger.py +++ b/src/agent_env/task/usage_ledger.py @@ -52,14 +52,14 @@ def ahead(ledger: list[dict], entries: list[dict]) -> list[dict]: 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/tst/unit/task/running_usage_test.py b/tst/unit/task/running_usage_test.py index 2bf27e04e..6a5ad18e8 100644 --- a/tst/unit/task/running_usage_test.py +++ b/tst/unit/task/running_usage_test.py @@ -35,10 +35,14 @@ def store(tmp_path, monkeypatch): def _ledger(instance_id): - return [(e["attempt"], e["step_id"], e["turns"], e["input_tokens"]) + 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: @@ -49,13 +53,14 @@ async def _until(instance_id, want): 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, then holds on ``hold`` when given.""" + 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 = inputs, hold, [] + self.inputs, self.hold, self.seen, self.partial = inputs, hold, [], [] async def execute(self, context): usage = StepUsage(context, self.id) @@ -63,7 +68,8 @@ async def execute(self, context): 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]))])) + 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 @@ -74,9 +80,10 @@ async def test_a_long_steps_turns_reach_the_ledger_before_it_ends_and_its_comple step = _Turns("long", [100, 200]) context = await Task(id="t", version=1, steps=[step]).run(context=TaskStepContext()) - assert step.seen == [[(0, "long", 1, 100)], [(0, "long", 2, 300)]] - assert _ledger(context.instance_id) == [(0, "long", 2, 300)] + 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 @@ -93,7 +100,7 @@ async def test_a_worker_that_dies_mid_step_keeps_the_turns_written_before(store, with pytest.raises(asyncio.CancelledError): await run - assert _ledger(context.instance_id) == [(0, "dies", 1, 100)] + assert _ledger(context.instance_id) == [(0, "dies", 1, 100, True)] and _partial(context.instance_id) @pytest.mark.asyncio @@ -112,7 +119,7 @@ async def slow(instance_id, usage): writer = RunningUsage("instance", "s", context).start() await writes.wait() await writer.stop() - assert landed == [[{"role": "solver", "attempt": 0, "turns": 1, "step_id": "s"}]] + assert landed == [[{"role": "solver", "attempt": 0, "turns": 1, "step_id": "s", "running": True}]] writer = RunningUsage("instance", "s", context).start() await asyncio.sleep(0.25) @@ -125,13 +132,13 @@ 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} + late = {"attempt": 0, "step_id": "long", "role": "solver", "turns": 1, "input_tokens": 100, "running": True} store.record_usage_sync(context.instance_id, [late]) - assert _ledger(context.instance_id) == [(0, "long", 2, 300)] + assert _ledger(context.instance_id) == [(0, "long", 2, 300, False)] store.record_usage_sync(context.instance_id, [{**late, "turns": 3, "input_tokens": 450}]) - assert _ledger(context.instance_id) == [(0, "long", 3, 450)] + assert _ledger(context.instance_id) == [(0, "long", 3, 450, True)] @pytest.mark.asyncio From bf49d997b4839351e0c95222ac4a7cf9f63ea96f Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 15:32:05 -0800 Subject: [PATCH 4/5] refactor(task): the running-usage writer is a context manager around the step, and the store's running write marks its entries Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 16 +++---- src/agent_env/task/running_usage.py | 68 ++++++++++++++--------------- src/agent_env/task/store.py | 17 +++++--- src/agent_env/task/task.py | 8 +--- tst/unit/task/running_usage_test.py | 38 ++++++++-------- 5 files changed, 71 insertions(+), 76 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 99e44e41f..c673cec04 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -387,14 +387,14 @@ orchestrators call it the same way. What callers rely on: `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. While a step runs, `Task.run` writes its entries so far every - 15 s in which they changed (`task/running_usage.py`, `record_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. + `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/running_usage.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/running_usage.py b/src/agent_env/task/running_usage.py index 26b43434d..b1d9b40c4 100644 --- a/src/agent_env/task/running_usage.py +++ b/src/agent_env/task/running_usage.py @@ -1,12 +1,14 @@ """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. Each entry is -marked ``running``, which makes the run's total a lower bound, as the turn in flight isn't in it. The step's completion -writes its final entries over these: the ledger keeps an entry by attempt, step and role.""" +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 @@ -16,34 +18,32 @@ INTERVAL_S = 15.0 -class RunningUsage: - """Writes ``step_id``'s entries in ``context.metadata.step_usage`` to ``instance_id``'s ledger from ``start`` until - ``stop``, which waits for a write in flight; one a cancel leaves running can't take counts back (``ahead``). A - write that failed is tried again at the next interval.""" - - def __init__(self, instance_id: str, step_id: str, context: TaskStepContext) -> None: - self._instance_id, self._step_id, self._context = instance_id, step_id, context - self._stopped = asyncio.Event() - self._task: asyncio.Task | None = None - - def start(self) -> RunningUsage: - self._task = asyncio.create_task(self._run()) - return self - - async def stop(self) -> None: - self._stopped.set() - if self._task is not None: - await self._task - - async def _run(self) -> None: - written = None - while True: - try: - await asyncio.wait_for(self._stopped.wait(), INTERVAL_S) - return - except TimeoutError: - pass - entries = copy.deepcopy((self._context.metadata.get(STEP_USAGE_KEY) or {}).get(self._step_id)) - if entries and entries != written and await store.record_usage( - self._instance_id, [{**entry, "running": True} for entry in entries_of({self._step_id: entries})]): - written = entries +@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/src/agent_env/task/store.py b/src/agent_env/task/store.py index 626e2937f..076ec301d 100644 --- a/src/agent_env/task/store.py +++ b/src/agent_env/task/store.py @@ -839,12 +839,15 @@ 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_usage_sync(self, instance_id: str, usage: list[dict]) -> None: - """Merge ``usage``, the entries of a step still running, into the ledger alone, each only when it is ahead of the + 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 [], usage)) + 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, @@ -1006,11 +1009,11 @@ async def record_step_complete( ) -async def record_usage(instance_id: str, usage: list[dict]) -> bool: - """Async ``TaskInstanceStore.record_usage_sync``; whether it was written. A store error is logged, not raised, as - the step's completion writes its entries again.""" +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_usage_sync, instance_id, usage) + 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) diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index c8211ca4b..072ccf5de 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -26,7 +26,7 @@ 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.running_usage import RunningUsage +from agent_env.task.running_usage import running_usage from agent_env.task.usage_ledger import entries_of from agent_env.task_step.context import ( ATTEMPT_EPOCH, @@ -711,14 +711,10 @@ async def _run_one(step: TaskStep, idx: int, dispatch_epoch: int) -> None: started_utc = datetime.now(timezone.utc).isoformat() # This step's own asyncio task, so a sibling dispatched alongside it doesn't see it. ATTEMPT_EPOCH.set(dispatch_epoch) - running = RunningUsage(instance_id, step.id, context).start() if instance_id else None try: with protocol_v1.authorized({d.environment_url: d.control_headers for d in context.deployed_envs}): - try: + async with running_usage(instance_id, step.id, context): await step.execute(context) - finally: - if running is not None: - await running.stop() except asyncio.CancelledError: raise except BaseException as exc: diff --git a/tst/unit/task/running_usage_test.py b/tst/unit/task/running_usage_test.py index 6a5ad18e8..bd106a845 100644 --- a/tst/unit/task/running_usage_test.py +++ b/tst/unit/task/running_usage_test.py @@ -13,8 +13,7 @@ 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 import running_usage -from agent_env.task.running_usage import RunningUsage +from agent_env.task import running_usage as 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 @@ -24,7 +23,7 @@ @pytest.fixture def store(tmp_path, monkeypatch): - monkeypatch.setattr(running_usage, "INTERVAL_S", 0.02) + monkeypatch.setattr(running, "INTERVAL_S", 0.02) set_document_store(LocalSqliteDocumentStore(str(tmp_path / "instances.db"))) s = TaskInstanceStore() set_task_instance_store(s) @@ -105,7 +104,7 @@ async def test_a_worker_that_dies_mid_step_keeps_the_turns_written_before(store, @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_usage, "INTERVAL_S", 0.01) + monkeypatch.setattr(running, "INTERVAL_S", 0.01) writes, landed = asyncio.Event(), [] async def slow(instance_id, usage): @@ -114,16 +113,14 @@ async def slow(instance_id, usage): landed.append(usage) return True - monkeypatch.setattr(running_usage.store, "record_usage", slow) + monkeypatch.setattr(running.store, "record_running_usage", slow) context = TaskStepContext(metadata={STEP_USAGE_KEY: {"s": [{"role": "solver", "attempt": 0, "turns": 1}]}}) - writer = RunningUsage("instance", "s", context).start() - await writes.wait() - await writer.stop() - assert landed == [[{"role": "solver", "attempt": 0, "turns": 1, "step_id": "s", "running": True}]] - - writer = RunningUsage("instance", "s", context).start() - await asyncio.sleep(0.25) - await writer.stop() + 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 @@ -132,28 +129,27 @@ 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, "running": True} + late = {"attempt": 0, "step_id": "long", "role": "solver", "turns": 1, "input_tokens": 100} - store.record_usage_sync(context.instance_id, [late]) + store.record_running_usage_sync(context.instance_id, [late]) assert _ledger(context.instance_id) == [(0, "long", 2, 300, False)] - store.record_usage_sync(context.instance_id, [{**late, "turns": 3, "input_tokens": 450}]) + 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_usage, "INTERVAL_S", 0.01) + monkeypatch.setattr(running, "INTERVAL_S", 0.01) tries = [] async def flaky(instance_id, usage): tries.append(usage) return len(tries) > 1 - monkeypatch.setattr(running_usage.store, "record_usage", flaky) + monkeypatch.setattr(running.store, "record_running_usage", flaky) context = TaskStepContext(metadata={STEP_USAGE_KEY: {"s": [{"role": "solver", "attempt": 0, "turns": 1}]}}) - writer = RunningUsage("instance", "s", context).start() - await asyncio.sleep(0.2) - await writer.stop() + async with running.running_usage("instance", "s", context): + await asyncio.sleep(0.2) assert len(tries) == 2 and tries[0] == tries[1] From c9d481fec06bd582fe416b5ddbae64d5eda811ba Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 18:11:23 -0800 Subject: [PATCH 5/5] refactor(task): a run's usage code is one package, task/usage (ledger, running) Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 +++--- src/agent_env/task/store.py | 4 ++-- src/agent_env/task/task.py | 4 ++-- src/agent_env/task/usage/__init__.py | 2 ++ src/agent_env/task/{usage_ledger.py => usage/ledger.py} | 0 src/agent_env/task/{running_usage.py => usage/running.py} | 2 +- tst/unit/task/usage/__init__.py | 0 .../task/{usage_ledger_test.py => usage/ledger_test.py} | 0 .../task/{running_usage_test.py => usage/running_test.py} | 2 +- 9 files changed, 11 insertions(+), 9 deletions(-) create mode 100644 src/agent_env/task/usage/__init__.py rename src/agent_env/task/{usage_ledger.py => usage/ledger.py} (100%) rename src/agent_env/task/{running_usage.py => usage/running.py} (97%) create mode 100644 tst/unit/task/usage/__init__.py rename tst/unit/task/{usage_ledger_test.py => usage/ledger_test.py} (100%) rename tst/unit/task/{running_usage_test.py => usage/running_test.py} (99%) diff --git a/AGENTS.md b/AGENTS.md index c673cec04..8fd7822ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -383,15 +383,15 @@ 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. While a step runs, `Task.run` writes its entries so far every 15 - seconds in which they changed (`task/running_usage.py`, `record_running_usage()`), so a budget sees a long step's + 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 + (`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. diff --git a/src/agent_env/task/store.py b/src/agent_env/task/store.py index 076ec301d..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, ahead, 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 diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index 072ccf5de..8be4ba775 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -26,8 +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.running_usage import running_usage -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, 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 100% rename from src/agent_env/task/usage_ledger.py rename to src/agent_env/task/usage/ledger.py diff --git a/src/agent_env/task/running_usage.py b/src/agent_env/task/usage/running.py similarity index 97% rename from src/agent_env/task/running_usage.py rename to src/agent_env/task/usage/running.py index b1d9b40c4..55d777619 100644 --- a/src/agent_env/task/running_usage.py +++ b/src/agent_env/task/usage/running.py @@ -11,7 +11,7 @@ from collections.abc import AsyncIterator from agent_env.task import store -from agent_env.task.usage_ledger import entries_of +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 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/running_usage_test.py b/tst/unit/task/usage/running_test.py similarity index 99% rename from tst/unit/task/running_usage_test.py rename to tst/unit/task/usage/running_test.py index bd106a845..557e59eaa 100644 --- a/tst/unit/task/running_usage_test.py +++ b/tst/unit/task/usage/running_test.py @@ -13,7 +13,7 @@ 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 import running_usage as running +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