bug(agents): LLM token consumption undercounted — pruning model calls untracked, earlier loop rounds overwritten #65
Labels
No labels
auto/blocked-by-deps
auto/ci-timeout
auto/claimed-implementer
auto/claimed-merge
auto/claimed-reviewer
auto/driver-down
auto/invariant-violation
auto/last-attempt-tier-0
auto/last-attempt-tier-1
auto/last-attempt-tier-2
auto/last-attempt-tier-min
Automation Tracking
auto/needs-conflict-resolution
auto/needs-implementer
auto/postmortem
auto/ready-to-merge
auto/restart-throttled
auto/revert
auto/sentinel
auto/stale-inactivity
auto/unstable
Blocked
Bounty
$100
Bounty
$1000
Bounty
$10000
Bounty
$20
Bounty
$2000
Bounty
$250
Bounty
$50
Bounty
$500
Bounty
$5000
Bounty
$750
MoSCoW
Could have
MoSCoW
Must have
MoSCoW
Should have
Needs Feedback
Points
1
Points
13
Points
2
Points
21
Points
3
Points
34
Points
5
Points
55
Points
8
Points
88
Priority
Backlog
Priority
CI Blocker
Priority
Critical
Priority
High
Priority
Low
Priority
Medium
Signed-off: Owner
Signed-off: Scrum Master
Signed-off: Tech Lead
Spike
State
Completed
State
Duplicate
State
In Progress
State
In Review
State
Paused
State
Unverified
State
Verified
State
Wont Do
Type
Automation
Type
Bug
Type
Discussion
Type
Documentation
Type
Epic
Type
Feature
Type
Legendary
Type
Refactor
Type
Support
Type
Task
Type
Testing
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Blocks
Depends on
#77 Epic: LLM Agent Runtime Stabilization — reliability, resource enforcement & correctness hardening
cleveragents/cleveractors-core
#66 fix(actors): llm token consumption undercounted
cleveragents/cleveractors-core
Reference
cleveragents/cleveractors-core#65
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Metadata
Commit Message: fix(actors): llm token consumption undercounted
Branch: bugfix/m2-lllm-token-consumption-undercounted
Summary
Three related defects in
LLMAgent.process_message()cause actual LLM token consumption to be undercounted inActorResult/NodeUsage:Pruning model LLM calls are never tracked.
_run_pruning_pass()creates a separatebuild_chat_model()instance and callsainvoke(), but never extractsusage_metadatafrom the response. The provider charges for these tokens; billing reports do not reflect them.Earlier tool-loop rounds' output tokens are overwritten. The tool-call loop reuses the
responsevariable across iterations. Only the final round'susage_metadatais captured at line 1252. Each earlier round's completion tokens are lost.ADR D-6 actual-usage-based estimates unimplemented.
_estimate_token_count()does not reference_last_token_usageto refine estimates from prior rounds' actual consumption — it relies solely onget_num_tokens()or alen//4heuristic.Root Cause
Gap 1:
_run_pruning_pass(llm.py:468–536)The response object carries
usage_metadata.input_tokens+usage_metadata.output_tokens, but these are never read. Meanwhile_last_token_usage(line 1252) is set only from the main model's finalresponseafter the tool-loop exits.Gap 2: Loop variable reuse (llm.py:759–1051)
For a 5-round loop, ~80% of completion token counts are missing from billing.
Gap 3:
_estimate_token_count(llm.py:371–386)Does not use
self._last_token_usage— onlyget_num_tokens()orlen//4heuristic. The ADR D-6 intent to "use this actual consumption data to improve estimation accuracy" was not wired up.Affected Code
src/cleveractors/agents/llm.py_run_pruning_pass()— dropsusage_metadatasrc/cleveractors/agents/llm.pyresponseoverwritten each roundsrc/cleveractors/agents/llm.pysrc/cleveractors/agents/llm.py_estimate_token_count()— ignores prior actualsImportant thing to take into account
pruning_modelconfiguration property), and this needs to be accounted for in the token usage, or cost calculation. If this is not feasible, inform in implementation report, in which case a proper approach will need to be devised by the sofware architect.Temporary Limitations (implemented in PR #66)
1.
pruning_modelmust matchmodel(deviation from ADR-2031 §4.4.8)A
ConfigurationErroris raised at agent creation time ifpruning_modelis set to a value different frommodel. This is because token tracking across separate LangChain model instances (main model vs pruning model) has not yet been plumbed throughNodeUsage. TheNodeUsagetype currently holds a single(prompt_tokens, completion_tokens)tuple per node; there is no mechanism to attribute tokens to the pruning model vs the main model.To lift this limitation,
NodeUsage(insrc/cleveractors/result.py) would need:pruner_prompt_tokens/pruner_completion_tokens, or a more generalper_model: dict[str, tuple[int, int]]breakdown.runtime_dispatch.py) would need to sum these fields together for total cost, or expose them separately for per-model billing.Until this is done, any agent that attempts to configure a separate
pruning_modelwill fail fast on construction.2. Pruning token usage metadata is enforced (deviation from ADR-2031 §4.4.8)
If the pruning model's response lacks
usage_metadata(and has noresponse_metadata["token_usage"]fallback), aRuntimeErroris raised immediately — the old silent fallback to(0, 0)is removed. This ensures the caller is always alerted when billing data would be incomplete.The error propagates through
process_message()'s outerexcept Exceptionhandler and is re-raised asExecutionError("LLM processing failed: ...")with the original message preserved.Impact
usage_metadata(Anthropic, OpenAI, and most LangChain-compatible providers do). Models that do not return usage info cannot be used with pruning enabled.pruning_modelfield is effectively disabled until cross-model token tracking is implemented inNodeUsage.Impact
max_cost_usdenforcement inruntime_dispatch.pyuses the same undercountedNodeUsagedata, so the budget guardrail is weaker than intended.budget_warning,budget_exhausted) and token-budget estimation both underestimate true consumption.No Existing Coverage
ActorResult/NodeUsage.features/llm_agent_tool_calling.featurecovers pruning mechanics (schema augmentation, marker parsing, error fallback) but omits token-tracking assertions.Suggested Fix Direction
_run_pruning_pass, captureusage_metadata(orresponse_metadata.token_usage) from the pruning model's response and return it alongside the parsed content.ainvoke()response's metadata) instead of overwriting._estimate_token_count()blend prior_last_token_usageactuals with the heuristic for better budget warnings.Discovered during code review of
src/cleveractors/agents/llm.pyagainst ADR-2031 and ADR-2027.