test(agents): capture virtual-provider budget cost misattribution bug (#159) #203
No reviewers
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
2 participants
Notifications
Due date
No due date set.
Blocks
Reference
cleveragents/cleveractors-core!203
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "tdd/m1-virtual-provider-cost-attribution"
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?
Summary
Adds the mandatory TDD issue-capture test for bug #159 ("virtual-provider budget cost is priced against the agent-level (provider, model), not the selected backend"), per the companion TDD ticket #202.
LLMAgent._check_budget_before_invokeand_accumulate_cost_after_invoke(src/cleveractors/agents/llm.py) resolve pricing/zero-cost status via the agent-level(self.provider, self.model)anchor pair -- set once at construction from the agent's own top-level config -- never the backendVirtualChatModel(ADR-2038,docs/index.md§4.4.7) actually selected and invoked for a given pooled-agent call.VirtualChatModel._select()picks a backend internally (for retry/streaming pinning) but never surfaces that selection back toLLMAgent, so a pooled agent's cost/budget gate always prices against its own anchor regardless of which backend served the call. Confirmed this still reproduces against currentdevelop(no commit since the virtual-provider feature landed touches this).Two Behave scenarios added to
features/virtual_provider.feature(step defs infeatures/steps/virtual_provider_steps.py, extending the existing pair per the project's step-file rules -- it already covers pooledLLMAgentconstruction/invocation):$0.002) instead of the selected backend's rate ($0.01) for the same token counts.ExecutionError(reason="missing_pricing_entry")instead of completing, even though the invocation that actually ran is fully priced.Both scenarios build a genuine
VirtualChatModelwrappingFakeBackendChatModelfakes (features/mocks/, extended with optionalprompt_tokens/completion_tokensfields so a fake backend's response carries real LangChainusage_metadata-- additive, defaultNone, every existing scenario's behavior is unchanged) and inject it directly asLLMAgent.chat_model, mirroring the existing "conversation history across a backend switch" scenario. Both are tagged@tdd_issue @tdd_issue_159 @tdd_expected_failand use plainassertonly, per the TDD tag rules.Validity verified two ways: (1) confirmed each scenario's assertion genuinely fails on current code (
AssertionError, inverted to a CI pass byTddExpectedFailPolicy); (2) confirmed each would flip to passing once cost attribution is fixed, by temporarily monkey-patching_accumulate_cost_after_invokein an isolated script to resolve the selected backend's(provider, model)instead of the anchor's and observing the assertion hold -- never applied to production code, only used to validate the test itself.No CHANGELOG.md entry: test-only commit, no behavior change (project precedent, e.g. commit
5e9ca51).This PR does not fix bug #159 -- the real fix (attributing cost/budget evaluation to the selected backend's
(provider, model)) lands separately on abugfix/branch, which will also remove@tdd_expected_failfrom these two scenarios.Note: per existing project practice (see PR #200), this repository's PRs target
develop, notmaster.Issue #202 state: left in
State/Unverified-- contributors don't self-triage per project rules; maintainer triage/verification can proceed alongside this PR's review.Closes #202
Refs #159
Test plan
nox -s lint-- greennox -s format -- --check-- greennox -s typecheck-- green (0 errors, Pyright strict)nox -s security_scan-- green (bandit + semgrep, 0 findings)nox -s dead_code-- green (vulture, 0 findings)nox -s unit_tests-- green (160 features, 3386 scenarios, 15597 steps, 0 failed)nox -s coverage_report-- green (97.3%, >= 96.5% threshold)nox -s integration_tests(Robot/pabot) -- green (382 tests, 0 failed)nox -s benchmark_regression -- --quick(ASV vs origin/develop) -- benchmarks not significantly changedPR Review: !203 (Ticket #202)
Verdict: Approve
Test-only TDD capture PR for bug #159, executed exactly per the project's mandatory Bug Fix TDD workflow. Both scenarios were verified locally to fail for exactly the right reasons on the unfixed code (observed assertion messages:
Expected accumulated cost $0.010000 (the selected backend's rate), got $0.002000 -- the agent-level anchor's rate was used insteadandExecutionError(kind='cost', reason='missing_pricing_entry')), and to flip to passing once selected-backend attribution is applied (independently re-verified via an isolated in-process monkey-patch validation script — no production code touched). Fullnox -s unit_testsre-run locally: 160 features, 3386 scenarios, 15597 steps, 0 failed;nox -s lintandnox -s typecheckalso green (the single Pyright warning is a pre-existing optional-import warning inllm_imports.py, untouched by this PR). No critical or major issues found.Critical Issues
None
Major Issues
None
Minor Issues
None
Nits
step_pooled_agent_billed_first_backend) —names_csv.split(",")uses onlynames[0]/names[1]; a future scenario passing three names would silently drop the extra fake. Aassert len(names) == 2guard would fail fast. Cosmetic — both current scenarios pass exactly two names.step_assert_no_missing_pricing_entry, AC2) — the Then step only assertserror is None; it could additionally assert the accumulated cost equals the backend-rate value ($0.01). This matches #159 AC2's literal "run completes; no missing_pricing_entry" bar (the AC1 scenario already guards the rate), but asserting the value would also catch a hypothetical partial fix that skips cost accumulation for unpriced anchors instead of attributing to the selected backend."zai"/"glm-5.1") is an independent step parameter that must be kept manually in sync with the agent-levelprovider/modelin the first Given step. Deriving it fromcontext.agent(or asserting equality) would remove a silent-desync foot-gun for future scenarios._build_response_message) — when only one ofprompt_tokens/completion_tokensis set (the otherNone),usage_metadatais silently omitted. Documented behavior for a test fake, but an both-or-neither assert would surface misuse faster.Summary
A high-quality, faithful TDD issue-capture PR:
VirtualChatModelwrappingFakeBackendChatModelfakes injected asLLMAgent.chat_model, driving a realprocess_message()call — the same pattern as the existing pooled-agent scenario in this file. Round-robin determinism (index 0 first) andusage_metadatapropagation throughVirtualChatModel._ageneratewere both verified (_agenerateforwards the backend'sChatResultunmodified).asyncio/contextvarshandling. Thewhenstep readscurrent_accumulated_costinside the coroutine becauseasyncio.run()copies the context — well-documented in the step docstring and commit message, and it is the correct fix for what would otherwise be an always-0.0 observation.@tdd_issue @tdd_issue_159 @tdd_expected_failsatisfies the enforced tag-combination rules; assertions use plainassert(AssertionError) soTddExpectedFailPolicyinverts only genuine bug-signal failures — the full-suite run with the policy active confirms the inversions are real, not stale tags._budget_cost_token,_budget_max_token,_budget_pricing_token) that theafter_scenariohook infeatures/environment.pyresets, so no cross-scenario leakage. Mock extension is additive (defaultNone), confined tofeatures/mocks/, and preserves all existing scenario behavior.develop. No CHANGELOG entry is consistent with project precedent for test-only commits (e.g.5e9ca51).developdeviates from CONTRIBUTING's literal "PR to master" TDD wording, but follows the established repo practice (the directly analogous TDD capture PR !200 also targeted and merged intodevelop) and is documented in the PR body — noted here only for the record, not treated as an issue.The two
@tdd_expected_failtags must be removed by the upcomingbugfix/PR for #159 (as that PR's own plan states); until then these scenarios will correctly keep CI green while the bug is present. Recommended for merge.2c2d54090288d65cfa4f