fix(subagents): keep batch item token usage across attempts (#8647)

* fix(subagents): keep batch item token usage across attempts

finalize_item replaced the item's token_usage with the finishing attempt's
usage, so a retried item kept only its last attempt and the exception path
(token_usage=None) erased what was stored. Add each attempt's counts to the
stored total instead.

Refs #8646

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>

* fix(subagents): keep an attempt's token usage when its finalize fails

When the finalize that carried an attempt's usage raised (for example a
rolled-back commit), the exception handler finalized the item again with
token_usage=None, so that attempt's tokens were lost. Carry the collected
usage and model name into that call. If the first finalize did commit,
the lease is already released and the second call writes nothing, so
nothing is counted twice.

Refs #8646

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>

---------

Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bas Cancrinus 2026-11-26 15:40:19 +01:00 committed by GitHub
parent c0eefedc4f
commit 349540c13f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 154 additions and 3 deletions

View File

@ -60,6 +60,27 @@ _ITEM_PUBLIC_FIELDS = (
_ITEM_TIMESTAMP_FIELDS = ("started_at", "completed_at", "created_at", "updated_at")
def _accumulate_token_usage(stored: dict[str, Any] | None, attempt: dict[str, Any] | None) -> dict[str, Any] | None:
"""Add one attempt's token counts to the item's stored total.
An item can run several attempts (automatic retries, a manual retry), and
each one spends tokens. Replacing the stored value would keep only the last
attempt; an attempt without usage (e.g. the exception path) keeps it as is.
"""
if not attempt:
return stored
if not stored:
return dict(attempt)
total = dict(stored)
for key, value in attempt.items():
if isinstance(value, int) and not isinstance(value, bool):
previous = total.get(key)
total[key] = (previous if isinstance(previous, int) and not isinstance(previous, bool) else 0) + value
else:
total[key] = value
return total
class SubagentBatchRepository:
"""Durable batch/item state with lease-based multi-worker claiming."""
@ -675,7 +696,7 @@ class SubagentBatchRepository:
"lease_expires_at": None,
"model_name": model_name,
"stop_reason": stop_reason,
"token_usage": token_usage,
"token_usage": _accumulate_token_usage(item.token_usage, token_usage),
"updated_at": completed_at,
"acceptance_verdict": None,
"result_artifact": None,

View File

@ -501,6 +501,8 @@ class SubagentBatchService:
async def _execute_leased_item(self, item: dict[str, Any], lease: BatchItemLease) -> None:
item_id = item["id"]
execution_id: str | None = None
result = None
effective_model: str | None = None
try:
batch = item["batch"]
self._item_batches[item_id] = batch["id"]
@ -671,6 +673,10 @@ class SubagentBatchService:
"Durable subagent batch item failed (item_id=%s)",
item_id,
)
# Keep the tokens this attempt spent, e.g. when the finalize that
# carried them rolled back. If that finalize committed, the lease
# is gone and this call writes nothing, so nothing counts twice.
usage = _usage(getattr(result, "token_usage_records", None))
await self._repository.finalize_item(
item_id,
lease_owner=lease.owner,
@ -680,8 +686,8 @@ class SubagentBatchService:
result_truncated=False,
error=str(exc)[:4_000],
stop_reason=None,
token_usage=None,
model_name=None,
token_usage=usage,
model_name=effective_model if usage else None,
completed_at=datetime.now(UTC),
)
finally:

View File

@ -257,6 +257,57 @@ async def test_finalize_retries_then_terminalizes_and_completes_batch(tmp_path)
assert batch["counts"]["succeeded"] == 1
async def _finalize(repo: SubagentBatchRepository, item_id: str, owner: str, *, succeeded: bool, token_usage, at: datetime) -> None:
assert await repo.finalize_item(
item_id,
lease_owner=owner,
succeeded=succeeded,
result="done" if succeeded else None,
result_preview="done" if succeeded else None,
result_truncated=False,
error=None if succeeded else "temporary",
stop_reason=None,
token_usage=token_usage,
model_name="model-a",
completed_at=at,
)
@pytest.mark.asyncio
async def test_finalize_accumulates_token_usage_over_retried_attempts(tmp_path) -> None:
repo = await _repo(tmp_path)
await _create(repo, count=1, max_live=1, max_running=1, max_attempts=3)
now = datetime.now(UTC)
first = (await repo.claim_items(now=now, lease_owner="worker-1", lease_seconds=60, limit=1))[0]
await _finalize(repo, first["id"], "worker-1", succeeded=False, token_usage={"input_tokens": 100, "output_tokens": 20, "total_tokens": 120}, at=now)
# An attempt without usage (the service's exception path) keeps what is stored.
second = (await repo.claim_items(now=now + timedelta(seconds=1), lease_owner="worker-2", lease_seconds=60, limit=1))[0]
await _finalize(repo, second["id"], "worker-2", succeeded=False, token_usage=None, at=now + timedelta(seconds=2))
third = (await repo.claim_items(now=now + timedelta(seconds=3), lease_owner="worker-3", lease_seconds=60, limit=1))[0]
await _finalize(repo, third["id"], "worker-3", succeeded=True, token_usage={"input_tokens": 40, "output_tokens": 5, "total_tokens": 45}, at=now + timedelta(seconds=4))
item = (await repo.list_items("batch-1", user_id="user-1"))[0]
assert item["status"] == "succeeded"
assert item["token_usage"] == {"input_tokens": 140, "output_tokens": 25, "total_tokens": 165}
@pytest.mark.asyncio
async def test_manual_retry_adds_to_the_failed_attempts_token_usage(tmp_path) -> None:
repo = await _repo(tmp_path)
await _create(repo, count=1, max_live=1, max_running=1, max_attempts=1)
now = datetime.now(UTC)
failed = (await repo.claim_items(now=now, lease_owner="worker-1", lease_seconds=60, limit=1))[0]
await _finalize(repo, failed["id"], "worker-1", succeeded=False, token_usage={"total_tokens": 70}, at=now)
assert (await repo.list_items("batch-1", user_id="user-1"))[0]["status"] == "failed"
assert await repo.retry_item("batch-1", failed["id"], user_id="user-1") is not None
again = (await repo.claim_items(now=now + timedelta(seconds=1), lease_owner="worker-2", lease_seconds=60, limit=1))[0]
await _finalize(repo, again["id"], "worker-2", succeeded=True, token_usage={"total_tokens": 30}, at=now + timedelta(seconds=2))
assert (await repo.list_items("batch-1", user_id="user-1"))[0]["token_usage"] == {"total_tokens": 100}
@pytest.mark.asyncio
async def test_pause_resume_cancel_and_owner_scope(tmp_path) -> None:
repo = await _repo(tmp_path)

View File

@ -484,6 +484,79 @@ async def test_execute_item_polls_completion_without_waiting_for_lease_renewal(m
assert repository.renews == 2
@pytest.mark.asyncio
async def test_failed_finalize_keeps_the_attempts_token_usage(monkeypatch) -> None:
result = SimpleNamespace(
status=FakeStatus.COMPLETED,
result="done",
error=None,
stop_reason=None,
token_usage_records=[{"input_tokens": 30, "output_tokens": 15, "total_tokens": 45}],
)
class Repository:
def __init__(self) -> None:
self.calls = []
async def claim_items(self, **_kwargs):
return [
{
"id": "item-1",
"item_key": "record-1",
"prompt": "Process record 1",
"batch": {
"id": "batch-1",
"thread_id": "thread-1",
"user_id": "user-1",
"run_id": "run-1",
"execution_spec": _request().execution_spec,
},
}
]
async def mark_item_running(self, *_args, **_kwargs):
return True
async def renew_item_lease(self, *_args, **_kwargs):
return {"valid": True, "cancel_requested": False}
async def finalize_item(self, *_args, **kwargs):
self.calls.append(kwargs)
if len(self.calls) == 1:
raise RuntimeError("commit rolled back")
return True
class Executor:
def __init__(self, **_kwargs) -> None:
pass
def execute_async(self, _prompt, task_id=None):
return "execution-1"
repository = Repository()
monkeypatch.setattr(service_module, "get_app_config", lambda: SimpleNamespace())
monkeypatch.setattr(service_module, "resolve_subagent_model_name", lambda *_args, **_kwargs: "model-a")
monkeypatch.setattr(service_module, "SubagentExecutor", Executor)
monkeypatch.setattr(service_module, "SubagentStatus", FakeStatus)
monkeypatch.setattr(service_module, "get_background_task_result", lambda _execution_id: result)
monkeypatch.setattr(service_module, "cleanup_background_task", lambda _execution_id: None)
monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **_kwargs: [])
service = SubagentBatchService(
repository=repository,
config=SubagentBatchesConfig(poll_interval_seconds=0.1, lease_seconds=120),
runtime_config=SubagentRuntimeConfig(max_running=1),
)
await service.run_once(now=service_module.datetime.now(service_module.UTC))
await asyncio.wait_for(asyncio.gather(*list(service._executions.values())), timeout=1)
assert len(repository.calls) == 2
retry = repository.calls[1]
assert retry["succeeded"] is False
assert retry["token_usage"] == {"input_tokens": 30, "output_tokens": 15, "total_tokens": 45}
assert retry["model_name"] == "model-a"
class _Registry:
"""Executor registry double with the real cleanup and cancellation timing."""