test(agents): capture virtual-provider budget cost misattribution bug (#159) #203

Merged
CoreRasurae merged 1 commit from tdd/m1-virtual-provider-cost-attribution into develop 2026-12-03 11:17:01 +00:00
Member

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_invoke and _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 backend VirtualChatModel (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 to LLMAgent, 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 current develop (no commit since the virtual-provider feature landed touches this).

Two Behave scenarios added to features/virtual_provider.feature (step defs in features/steps/virtual_provider_steps.py, extending the existing pair per the project's step-file rules -- it already covers pooled LLMAgent construction/invocation):

  • AC1: a pooled agent with a distinctly-priced selected backend accumulates cost at the anchor's rate ($0.002) instead of the selected backend's rate ($0.01) for the same token counts.
  • AC2: an unpriced agent-level anchor with a priced selected backend raises ExecutionError(reason="missing_pricing_entry") instead of completing, even though the invocation that actually ran is fully priced.

Both scenarios build a genuine VirtualChatModel wrapping FakeBackendChatModel fakes (features/mocks/, extended with optional prompt_tokens/completion_tokens fields so a fake backend's response carries real LangChain usage_metadata -- additive, default None, every existing scenario's behavior is unchanged) and inject it directly as LLMAgent.chat_model, mirroring the existing "conversation history across a backend switch" scenario. Both are tagged @tdd_issue @tdd_issue_159 @tdd_expected_fail and use plain assert only, 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 by TddExpectedFailPolicy); (2) confirmed each would flip to passing once cost attribution is fixed, by temporarily monkey-patching _accumulate_cost_after_invoke in 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 a bugfix/ branch, which will also remove @tdd_expected_fail from these two scenarios.

Note: per existing project practice (see PR #200), this repository's PRs target develop, not master.

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 -- green
  • nox -s format -- --check -- green
  • nox -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 changed
  • Confirmed each new scenario's assertion fails on unfixed code (bug reproduced) and would pass once the selected-backend's rates are used instead of the agent-level anchor's
## 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_invoke` and `_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 backend `VirtualChatModel` (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 to `LLMAgent`, 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 current `develop` (no commit since the virtual-provider feature landed touches this). Two Behave scenarios added to `features/virtual_provider.feature` (step defs in `features/steps/virtual_provider_steps.py`, extending the existing pair per the project's step-file rules -- it already covers pooled `LLMAgent` construction/invocation): - **AC1**: a pooled agent with a distinctly-priced selected backend accumulates cost at the anchor's rate (`$0.002`) instead of the selected backend's rate (`$0.01`) for the same token counts. - **AC2**: an unpriced agent-level anchor with a priced selected backend raises `ExecutionError(reason="missing_pricing_entry")` instead of completing, even though the invocation that actually ran is fully priced. Both scenarios build a genuine `VirtualChatModel` wrapping `FakeBackendChatModel` fakes (`features/mocks/`, extended with optional `prompt_tokens`/`completion_tokens` fields so a fake backend's response carries real LangChain `usage_metadata` -- additive, default `None`, every existing scenario's behavior is unchanged) and inject it directly as `LLMAgent.chat_model`, mirroring the existing "conversation history across a backend switch" scenario. Both are tagged `@tdd_issue @tdd_issue_159 @tdd_expected_fail` and use plain `assert` only, 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 by `TddExpectedFailPolicy`); (2) confirmed each would flip to passing once cost attribution is fixed, by temporarily monkey-patching `_accumulate_cost_after_invoke` in 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 a `bugfix/` branch, which will also remove `@tdd_expected_fail` from these two scenarios. **Note**: per existing project practice (see PR #200), this repository's PRs target `develop`, not `master`. **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 - [x] `nox -s lint` -- green - [x] `nox -s format -- --check` -- green - [x] `nox -s typecheck` -- green (0 errors, Pyright strict) - [x] `nox -s security_scan` -- green (bandit + semgrep, 0 findings) - [x] `nox -s dead_code` -- green (vulture, 0 findings) - [x] `nox -s unit_tests` -- green (160 features, 3386 scenarios, 15597 steps, 0 failed) - [x] `nox -s coverage_report` -- green (97.3%, >= 96.5% threshold) - [x] `nox -s integration_tests` (Robot/pabot) -- green (382 tests, 0 failed) - [x] `nox -s benchmark_regression -- --quick` (ASV vs origin/develop) -- benchmarks not significantly changed - [x] Confirmed each new scenario's assertion fails on unfixed code (bug reproduced) and would pass once the selected-backend's rates are used instead of the agent-level anchor's
test(agents): capture virtual-provider budget cost misattribution bug (#159)
Some checks failed
CI / lint (pull_request) Successful in 48s
CI / typecheck (pull_request) Successful in 1m29s
CI / security (pull_request) Successful in 1m9s
CI / quality (pull_request) Successful in 2m13s
CI / build (pull_request) Successful in 2m21s
CI / benchmark (pull_request) Failing after 34m44s
CI / unit_tests (pull_request) Successful in 6m17s
CI / integration_tests (pull_request) Successful in 3m31s
CI / coverage (pull_request) Successful in 5m54s
CI / status-check (pull_request) Successful in 2s
2c2d540902
Adds the TDD regression test for issue #159: LLMAgent._check_budget_
before_invoke and _accumulate_cost_after_invoke (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 backend VirtualChatModel (ADR-2038, docs/index.md
§4.4.7) actually selected and invoked for a given pooled-agent call.
VirtualChatModel._select() picks a backend and returns it internally for
retry/streaming pinning, but nothing surfaces that selection back to
LLMAgent, so a pooled agent's cost/budget gate always prices against its
own anchor, regardless of which backend served the call.

Two Behave scenarios were added to features/virtual_provider.feature
(features/steps/virtual_provider_steps.py extended, per the project's
step-file rules -- this feature/step pair already covers pooled LLMAgent
construction and invocation behavior):

- AC1: a pooled agent with a distinctly-priced selected backend
  accumulates cost at the anchor's rate ($0.002) instead of the
  selected backend's rate ($0.01) for the same token counts.
- AC2: an unpriced agent-level anchor with a priced selected backend
  raises ExecutionError(reason="missing_pricing_entry") instead of
  completing, even though the invocation that actually ran is fully
  priced.

Both scenarios build a genuine VirtualChatModel wrapping
FakeBackendChatModel fakes (features/mocks/, extended with optional
prompt_tokens/completion_tokens fields so a fake backend's response
carries real LangChain usage_metadata -- additive, default None,
preserving every existing scenario's behavior unchanged) and inject it
directly as LLMAgent.chat_model, mirroring the existing
"conversation history across a backend switch" scenario's pattern. Each
scenario drives a real process_message() call and reads the accumulated
cost / raised error.

Both are tagged @tdd_issue @tdd_issue_159 @tdd_expected_fail and use
plain assert statements only, per the TDD tag rules. Validity was
verified two ways: (1) confirmed each scenario's assertion genuinely
fails on current code (AssertionError, inverted to a CI pass by
TddExpectedFailPolicy) -- reproducing issue #159's exact symptoms,
not a test-harness mistake; (2) confirmed each would flip to passing
once cost attribution is fixed, by temporarily monkey-patching
_accumulate_cost_after_invoke in isolation to resolve the selected
backend's (provider, model) instead of the anchor's, re-running, and
observing the assertion hold ($0.01 computed, no missing_pricing_entry
raised) -- this patch was never applied to production code, only used
to validate the test's own correctness, consistent with the project's
TDD-capture verification practice (see e.g. commit 5e9ca51's validity
check for a prior TDD ticket).

One iteration note worth recording: the scenario's own "Then" step
originally read current_accumulated_cost.get() from the sync caller
after asyncio.run() returned, which always observed the value set
before the run (0.0) -- asyncio.run() executes its coroutine in a copy
of the current contextvars context, so a ContextVar.set() performed by
production code inside that coroutine never propagates back out. Fixed
by reading the ContextVar from inside the coroutine itself, before it
returns.

Full quality gate, all green:
- nox -s lint, nox -s format -- --check: clean (ruff).
- nox -s typecheck: 0 errors (Pyright strict).
- nox -s security_scan: 0 bandit/semgrep findings.
- nox -s dead_code: clean (vulture).
- nox -s unit_tests: 160 features, 3386 scenarios, 15597 steps, all
  passed (the two new @tdd_expected_fail scenarios pass via inversion;
  TddExpectedFailPolicy confirms the AssertionError was genuinely
  inverted, not a stale tag).
- nox -s coverage_report: 97.3% (>= 96.5% threshold).
- nox -s integration_tests (Robot/pabot): 382 tests, 382 passed,
  0 failed.
- nox -s benchmark_regression -- --quick (ASV vs origin/develop):
  benchmarks not significantly changed.

No CHANGELOG.md entry: this is a test-only commit with no behavior
change, consistent with project precedent for TDD/regression-only
commits (e.g. commit 5e9ca51).

The real fix -- attributing cost/budget evaluation to the selected
backend's (provider, model) instead of the agent-level anchor -- is
tracked on bug issue #159 and lands on a separate bugfix/ branch, which
also removes @tdd_expected_fail from these two scenarios.

Refs: #159, #202
hurui200320 left a comment

PR 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 instead and ExecutionError(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). Full nox -s unit_tests re-run locally: 160 features, 3386 scenarios, 15597 steps, 0 failed; nox -s lint and nox -s typecheck also green (the single Pyright warning is a pre-existing optional-import warning in llm_imports.py, untouched by this PR). No critical or major issues found.

Critical Issues

None

Major Issues

None

Minor Issues

None

Nits

  1. features/steps/virtual_provider_steps.py:939 (step_pooled_agent_billed_first_backend) — names_csv.split(",") uses only names[0]/names[1]; a future scenario passing three names would silently drop the extra fake. A assert len(names) == 2 guard would fail fast. Cosmetic — both current scenarios pass exactly two names.
  2. features/steps/virtual_provider_steps.py:1057 (step_assert_no_missing_pricing_entry, AC2) — the Then step only asserts error 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.
  3. features/steps/virtual_provider_steps.py:962 — the anchor pair in the pricing Given step ("zai"/"glm-5.1") is an independent step parameter that must be kept manually in sync with the agent-level provider/model in the first Given step. Deriving it from context.agent (or asserting equality) would remove a silent-desync foot-gun for future scenarios.
  4. features/mocks/fake_backend_chat_model.py:94 (_build_response_message) — when only one of prompt_tokens/completion_tokens is set (the other None), usage_metadata is 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:

  • Correct bug capture. The scenarios reproduce #159's exact symptoms through a genuine VirtualChatModel wrapping FakeBackendChatModel fakes injected as LLMAgent.chat_model, driving a real process_message() call — the same pattern as the existing pooled-agent scenario in this file. Round-robin determinism (index 0 first) and usage_metadata propagation through VirtualChatModel._agenerate were both verified (_agenerate forwards the backend's ChatResult unmodified).
  • Correct asyncio/contextvars handling. The when step reads current_accumulated_cost inside the coroutine because asyncio.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.
  • Compliant tagging and assertion rules. @tdd_issue @tdd_issue_159 @tdd_expected_fail satisfies the enforced tag-combination rules; assertions use plain assert (AssertionError) so TddExpectedFailPolicy inverts only genuine bug-signal failures — the full-suite run with the policy active confirms the inversions are real, not stale tags.
  • Test hygiene. ContextVar tokens use the exact attribute names (_budget_cost_token, _budget_max_token, _budget_pricing_token) that the after_scenario hook in features/environment.py resets, so no cross-scenario leakage. Mock extension is additive (default None), confined to features/mocks/, and preserves all existing scenario behavior.
  • Atomicity and traceability. Single commit whose first line exactly matches ticket #202's Metadata Commit Message, on the exact Metadata branch, on top of current develop. No CHANGELOG entry is consistent with project precedent for test-only commits (e.g. 5e9ca51).
  • Targeting develop deviates 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 into develop) and is documented in the PR body — noted here only for the record, not treated as an issue.

The two @tdd_expected_fail tags must be removed by the upcoming bugfix/ 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.

## PR 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 instead` and `ExecutionError(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). Full `nox -s unit_tests` re-run locally: **160 features, 3386 scenarios, 15597 steps, 0 failed**; `nox -s lint` and `nox -s typecheck` also green (the single Pyright warning is a pre-existing optional-import warning in `llm_imports.py`, untouched by this PR). No critical or major issues found. ### Critical Issues None ### Major Issues None ### Minor Issues None ### Nits 1. **features/steps/virtual_provider_steps.py:939** (`step_pooled_agent_billed_first_backend`) — `names_csv.split(",")` uses only `names[0]`/`names[1]`; a future scenario passing three names would silently drop the extra fake. A `assert len(names) == 2` guard would fail fast. Cosmetic — both current scenarios pass exactly two names. 2. **features/steps/virtual_provider_steps.py:1057** (`step_assert_no_missing_pricing_entry`, AC2) — the Then step only asserts `error 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. 3. **features/steps/virtual_provider_steps.py:962** — the anchor pair in the pricing Given step (`"zai"/"glm-5.1"`) is an independent step parameter that must be kept manually in sync with the agent-level `provider`/`model` in the first Given step. Deriving it from `context.agent` (or asserting equality) would remove a silent-desync foot-gun for future scenarios. 4. **features/mocks/fake_backend_chat_model.py:94** (`_build_response_message`) — when only one of `prompt_tokens`/`completion_tokens` is set (the other `None`), `usage_metadata` is 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: - **Correct bug capture.** The scenarios reproduce #159's exact symptoms through a genuine `VirtualChatModel` wrapping `FakeBackendChatModel` fakes injected as `LLMAgent.chat_model`, driving a real `process_message()` call — the same pattern as the existing pooled-agent scenario in this file. Round-robin determinism (index 0 first) and `usage_metadata` propagation through `VirtualChatModel._agenerate` were both verified (`_agenerate` forwards the backend's `ChatResult` unmodified). - **Correct `asyncio`/`contextvars` handling.** The `when` step reads `current_accumulated_cost` *inside* the coroutine because `asyncio.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. - **Compliant tagging and assertion rules.** `@tdd_issue @tdd_issue_159 @tdd_expected_fail` satisfies the enforced tag-combination rules; assertions use plain `assert` (AssertionError) so `TddExpectedFailPolicy` inverts only genuine bug-signal failures — the full-suite run with the policy active confirms the inversions are real, not stale tags. - **Test hygiene.** ContextVar tokens use the exact attribute names (`_budget_cost_token`, `_budget_max_token`, `_budget_pricing_token`) that the `after_scenario` hook in `features/environment.py` resets, so no cross-scenario leakage. Mock extension is additive (default `None`), confined to `features/mocks/`, and preserves all existing scenario behavior. - **Atomicity and traceability.** Single commit whose first line exactly matches ticket #202's Metadata Commit Message, on the exact Metadata branch, on top of current `develop`. No CHANGELOG entry is consistent with project precedent for test-only commits (e.g. `5e9ca51`). - Targeting `develop` deviates 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 into `develop`) and is documented in the PR body — noted here only for the record, not treated as an issue. The two `@tdd_expected_fail` tags must be removed by the upcoming `bugfix/` 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.
CoreRasurae force-pushed tdd/m1-virtual-provider-cost-attribution from 2c2d540902
Some checks failed
CI / lint (pull_request) Successful in 48s
CI / typecheck (pull_request) Successful in 1m29s
CI / security (pull_request) Successful in 1m9s
CI / quality (pull_request) Successful in 2m13s
CI / build (pull_request) Successful in 2m21s
CI / benchmark (pull_request) Failing after 34m44s
CI / unit_tests (pull_request) Successful in 6m17s
CI / integration_tests (pull_request) Successful in 3m31s
CI / coverage (pull_request) Successful in 5m54s
CI / status-check (pull_request) Successful in 2s
to 88d65cfa4f
Some checks failed
CI / lint (pull_request) Successful in 40s
CI / typecheck (pull_request) Successful in 1m12s
CI / quality (pull_request) Successful in 1m31s
CI / security (pull_request) Successful in 2m27s
CI / integration_tests (pull_request) Successful in 2m15s
CI / build (pull_request) Successful in 2m15s
CI / unit_tests (pull_request) Successful in 5m57s
CI / benchmark (pull_request) Has been cancelled
CI / coverage (pull_request) Successful in 7m6s
CI / status-check (pull_request) Successful in 5s
CI / lint (push) Successful in 1m18s
CI / typecheck (push) Successful in 1m28s
CI / security (push) Successful in 1m42s
CI / quality (push) Successful in 1m41s
CI / build (push) Successful in 3m26s
CI / integration_tests (push) Successful in 5m33s
CI / unit_tests (push) Successful in 6m57s
CI / benchmark (push) Failing after 18m54s
CI / coverage (push) Failing after 17m47s
CI / status-check (push) Has been cancelled
2026-12-03 10:31:39 +00:00
Compare
CoreRasurae deleted branch tdd/m1-virtual-provider-cost-attribution 2026-12-03 11:17:01 +00:00
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
cleveragents/cleveractors-core!203
No description provided.