fix(agents): attribute virtual-provider cost to the selected backend #204

Merged
CoreRasurae merged 1 commit from bugfix/m1-virtual-provider-cost-attribution into develop 2026-12-03 20:50:23 +00:00
Member

Summary

Fixes #159: a pooled (virtual-provider, ADR-2038) LLMAgent's budget pre-flight
check and cost accumulation always resolved pricing/zero-cost status against the
agent-level (provider, model) anchor, never the backend VirtualChatModel
actually selected and invoked for a given call.

  • VirtualChatModel.select_backend() now surfaces the selected backend's own
    (provider, model) identity alongside the backend instance and its URL.
  • LLMAgent._resolve_invocation_target() performs that one per-invocation
    selection up front and threads it through the pre-flight budget check, the
    pinned call (_retry_ainvoke and the stream_message() astream path), and
    the post-call cost accumulation, so all three agree on the backend that
    actually serves the call.
  • The repeated check → invoke → extract → accumulate pattern across the
    tool-loop call sites and the no-tools path is consolidated into a new
    _invoke_and_track_cost() helper.
  • Non-virtual agents are unaffected (falls back to (self.provider, self.model)).

Acceptance criteria (from issue #159)

  1. ✅ Pooled agent with backends from distinct priced providers → cost uses the selected backend's rates.
  2. ✅ Agent-level model unpriced + selected backend priced → run completes; no missing_pricing_entry.
  3. ✅ Zero-cost carve-out evaluates the selected backend's rates.
  4. ✅ Non-virtual agents behave exactly as before.
  5. ✅ nox -s typecheck, nox -s unit_tests, and the coverage threshold stay green.

Test plan

  • nox -s unit_tests — 160 features, 3387 scenarios, 15601 steps, all passed
    (the two @tdd_issue_159 scenarios from #202 now pass normally with
    @tdd_expected_fail removed; a third new scenario covers the streaming path)
  • nox -s coverage_report — 97.3% (≥ 97% threshold)
  • nox -s lint, nox -s format -- --check — clean
  • nox -s typecheck — 0 errors (1 pre-existing, unrelated warning)
  • nox -s security_scan — 0 findings
  • nox -s dead_code — clean
  • nox -s integration_tests — 382/382 Robot tests passed

Closes #159

## Summary Fixes #159: a pooled (virtual-provider, ADR-2038) `LLMAgent`'s budget pre-flight check and cost accumulation always resolved pricing/zero-cost status against the agent-level `(provider, model)` anchor, never the backend `VirtualChatModel` actually selected and invoked for a given call. - `VirtualChatModel.select_backend()` now surfaces the selected backend's own `(provider, model)` identity alongside the backend instance and its URL. - `LLMAgent._resolve_invocation_target()` performs that one per-invocation selection up front and threads it through the pre-flight budget check, the pinned call (`_retry_ainvoke` and the `stream_message()` astream path), and the post-call cost accumulation, so all three agree on the backend that actually serves the call. - The repeated check → invoke → extract → accumulate pattern across the tool-loop call sites and the no-tools path is consolidated into a new `_invoke_and_track_cost()` helper. - Non-virtual agents are unaffected (falls back to `(self.provider, self.model)`). ## Acceptance criteria (from issue #159) 1. ✅ Pooled agent with backends from distinct priced providers → cost uses the selected backend's rates. 2. ✅ Agent-level model unpriced + selected backend priced → run completes; no `missing_pricing_entry`. 3. ✅ Zero-cost carve-out evaluates the selected backend's rates. 4. ✅ Non-virtual agents behave exactly as before. 5. ✅ `nox -s typecheck`, `nox -s unit_tests`, and the coverage threshold stay green. ## Test plan - [x] `nox -s unit_tests` — 160 features, 3387 scenarios, 15601 steps, all passed (the two `@tdd_issue_159` scenarios from #202 now pass normally with `@tdd_expected_fail` removed; a third new scenario covers the streaming path) - [x] `nox -s coverage_report` — 97.3% (≥ 97% threshold) - [x] `nox -s lint`, `nox -s format -- --check` — clean - [x] `nox -s typecheck` — 0 errors (1 pre-existing, unrelated warning) - [x] `nox -s security_scan` — 0 findings - [x] `nox -s dead_code` — clean - [x] `nox -s integration_tests` — 382/382 Robot tests passed Closes #159
CoreRasurae added this to the v2.1.0 milestone 2026-12-03 12:01:11 +00:00
fix(agents): attribute virtual-provider cost to the selected backend
Some checks failed
CI / lint (pull_request) Successful in 48s
CI / typecheck (pull_request) Successful in 1m46s
CI / quality (pull_request) Successful in 1m47s
CI / security (pull_request) Successful in 2m10s
CI / build (pull_request) Successful in 1m35s
CI / integration_tests (pull_request) Successful in 3m7s
CI / unit_tests (pull_request) Successful in 7m5s
CI / coverage (pull_request) Failing after 13m57s
CI / benchmark (pull_request) Failing after 20m20s
CI / status-check (pull_request) Has been cancelled
f110605728
LLMAgent._check_budget_before_invoke and _accumulate_cost_after_invoke
(agents/llm.py) resolved pricing/zero-cost status exclusively via the
agent-level (self.provider, self.model) anchor, even for a pooled
agent (ADR-2038 virtual-provider routing, docs/index.md §4.4.7) whose
VirtualChatModel actually selected a different backend with its own
provider/model for that call. This priced a pooled agent's spend at
the anchor's rates instead of the serving backend's, could raise a
spurious missing_pricing_entry after a successful call when the
anchor was unpriced but the selected backend was priced, and could
block a provably-free selected backend behind a non-zero-rated
anchor.

VirtualChatModel.select_backend() (llm_virtual_provider.py) now
surfaces the selected backend's own identity alongside the backend
instance and its retry URL. LLMAgent._resolve_invocation_target()
performs that one per-external-invocation selection up front and
threads the result through the pre-flight budget check, the pinned
call (_retry_ainvoke, and the equivalent astream() path in
stream_message), and the post-call cost accumulation, so all three
agree on the backend that actually serves the call. The six
tool-loop call sites and the no-tools path were consolidated behind a
new _invoke_and_track_cost() helper to keep that invariant in one
place rather than repeated at each site. Non-virtual agents are
unaffected: _resolve_invocation_target falls back to
(self.provider, self.model) whenever chat_model is not a
VirtualChatModel, byte-identical to the prior behavior.

The two @tdd_issue_159 Behave scenarios added by the companion TDD
commit (#202) now pass normally with @tdd_expected_fail removed; a
third scenario covers the same attribution for the streaming path.
features/mocks/fake_backend_chat_model.py gained a chunk_position="last"
marker on its final streamed chunk alongside usage_metadata, matching
how a real provider integration avoids LangChain's auto-appended
empty trailing stream chunk. docs/adr/ADR-2038-budget-gate-zero-cost-
carveout.md's D-3 section is corrected to describe the fixed
behavior.

ISSUES CLOSED: #159
hurui200320 requested changes 2026-12-03 13:20:42 +00:00
Dismissed
hurui200320 left a comment

PR Review: !204 (Ticket #159)

Verdict: Request Changes

The core fix is correct and well-constructed: the one-per-invocation selection is now surfaced via VirtualChatModel.select_backend() and threaded through pre-flight check → pinned call → cost accumulation, the ADR-2032/ADR-2038 pinning rules still hold (retries and streams target the pinned backend; no re-selection), non-virtual agents fall back byte-identically, and the consolidation into _invoke_and_track_cost() removed real duplication across seven call sites. Verified locally: nox -s unit_tests (160 features / 3387 scenarios / 15601 steps, all pass), nox -s typecheck (0 errors, 1 pre-existing unrelated warning), nox -s lint (clean) — all matching the PR's reported results.

Request Changes because the PR's checklist marks issue #159's acceptance criterion 3 (zero-cost carve-out evaluates the selected backend's rates) as ✅, but no test exercises it — the changed carve-out parameterization is never executed with a pooled agent.

Critical Issues

None.

Major Issues

  1. Missing test for AC3 — zero-cost carve-out with a selected backend (PR body claims ✅). features/virtual_provider.feature (lines 243–262) covers AC1 (distinct rates), the streaming path, and AC2 (unpriced anchor). No scenario anywhere drives LLMAgent._check_budget_before_invoke's carve-out branch (src/cleveractors/agents/llm.py:681–697) with a pooled agent:

    • Scenario 3 sets max_cost_usd = 10.0 with accumulated = 0.0, so the gate never trips and the carve-out is never reached.
    • Scenarios 1–2 set max_cost_usd = None, so there is no gate at all.
    • The only zero-rated carve-out tests in the repo (features/budget_gate_single_llm.feature, features/execution_limits.feature) exercise the single-LLM PureLangGraph/runtime_dispatch path, not the LLMAgent tool-loop path changed here.

    Consequently the code this PR actually changed — provider/model kwargs flowing into _is_zero_rated_invocation for a virtual agent — has zero test coverage, and both directions of AC3's semantics are unverified: (a) a provably-free selected backend passing an exhausted gate while the anchor is non-zero-rated/unpriced, and (b) the consistent converse that a non-zero-rated selected backend now blocks even when the anchor pair is zero-rated (a real behavior change for pooled agents that nothing pins down).

    Recommendation: add a scenario, e.g. pricing {deepseek: 0.0/0.0, zai: 5.0/5.0} with accumulated = 10.0, max_cost_usd = 10.0 → the pooled run completes and accumulated cost stays 0.0; ideally add the converse (priced selected backend + zero-rated anchor → budget_exhausted). Until then, please remove the ✅ on AC3 in the PR description or mark it as covered-by-code-review only.

Minor Issues

  1. False docstring claim: "the pruning chat model is always built directly, never virtual" — src/cleveractors/agents/llm.py:749–750. For a pooled agent, _run_pruning_pass (llm.py:1004) calls build_chat_model(config=self.config, ...), and build_chat_model (src/cleveractors/agents/llm_client.py:102–113) returns a fresh VirtualChatModel whenever config["backends"] is present. So a pooled agent's pruning pass selects a backend internally (with its own provider/model) while _accumulate_cost_after_invoke(..., "pruning", model=self.model) bills it at the agent-level anchor pair — the same mis-attribution class #159 fixes for the main path, still live for pruning spend (including the missing_pricing_entry raise for an unpriced anchor, swallowed by the tool loop as a per-tool error). This is pre-existing, not a regression of this PR, and out of #159's stated ACs — but the new docstring asserts the opposite and will mislead maintainers.
    Recommendation: correct the docstring to state that pruning-pass attribution for pooled agents still resolves the anchor pair, and file a follow-up issue to wire selected-backend attribution into the pruning accumulation (or explicitly defer it on #159).

Nits

  1. Inaccurate docstring in _resolve_invocation_target (src/cleveractors/agents/llm.py:587–594). It claims init failure "is reported by _retry_ainvoke's own eager self.chat_model access (unchanged, and still the single place that raises) instead of here" and that the method does "not force construction". In fact self._ensure_chat_model() (line 595) constructs the model and propagates ConfigurationError from here — _retry_ainvoke is never reached when init fails, and a malformed backends config on an exhausted budget now raises ConfigurationError before budget_exhausted (slight error-precedence change; fast-fail outside the retry loop is still preserved). Suggest rewording to describe the actual behavior.
  2. Stale implementation note in the routing ADR (docs/adr/ADR-2038-virtual-provider-load-balanced-backend-routing.md:178–189). The non-normative note still describes this repo's implementation as selecting "once per external call and perform[ing] retries against that one backend internally, rather than relying solely on the outer, already-existing retry wrapper" — the new implementation does rely on the outer wrapper, pinning by passing target.backend so re-entry cannot re-select (the normative pinning rule still holds). Since the budget-gate ADR got a dated correction, consider a matching one-line note update here.
  3. _InvocationTarget.backend: Any (src/cleveractors/agents/llm.py:239). BaseChatModel is already imported under TYPE_CHECKING in this module (lines 35–36) and used in annotations (llm.py:466); with from __future__ import annotations the field could be typed BaseChatModel | None precisely, per CONTRIBUTING's "Full Annotations".
  4. No length-consistency guard for backend_providers/backend_models (src/cleveractors/agents/llm_virtual_provider.py:256–259). A partially populated pair (one list shorter than backends) silently mixes a backend provider with the anchor model. Unreachable via build_virtual_chat_model (always consistent), but a cheap construction-time check would make the invariant explicit.
  5. Observation — blocked rounds now advance selection state. Because _resolve_invocation_target() selects before _check_budget_before_invoke, a budget_exhausted block consumes a round-robin slot even though no call fires (previously selection happened inside ainvoke, after the gate). Appears benign for load-balancing fairness (the blocked turn legitimately consumed capacity) and no existing test depends on the sequence, but it is a subtle routing-sequence change worth being aware of; a sentence in the ADR correction would document it.

Summary

A high-quality, well-documented fix that resolves the real #159 defect: per-invocation backend selection is surfaced (SelectedBackend), the pre-flight gate, pinned call, and cost accumulation now agree on the backend that actually serves each call, and the six duplicated check→invoke→extract→accumulate sites are consolidated behind _invoke_and_track_cost() without changing call-site semantics (verified: all seven sites — main, synthesis, synthesis_followup, stuck_model, stuck_model_followup, no-tools, stream — pass equivalent kwargs and labels; pruning builds its own model and is untouched; ADR-2038 pinning holds for retries and streams). Test additions are meaningful (distinct anchor/backend rates make mis-attribution numerically detectable; the unpriced-anchor assertion explicitly guards against a skip-accumulation partial fix; the mock's chunk_position="last" change is verified correct against langchain-core 1.8.5's astream sentinel behavior). Local verification matches the PR report: unit tests 3387/3387, typecheck 0 errors, lint clean.

Two things block approval: the claimed-✅ AC3 has no test (Major), and the new "_accumulate_cost_after_invoke" docstring misstates the pruning path for pooled agents (Minor). Both are small, targeted follow-ups on an otherwise solid PR. Per the request, red-tape items (labels, commit footer, branch-name metadata) were excluded; the PR thread contains no prior reviewer comments and nothing was ruled out-of-scope there; the #159 gism0 memory journal was unavailable (no gism0 tools in this session), so the review relied on the ticket, PR description, ADRs, and docs/index.md (§4.4.7 documents only config surface/routing — no cost content, so no spec edit was required there).

## PR Review: !204 (Ticket #159) ### Verdict: Request Changes The core fix is correct and well-constructed: the one-per-invocation selection is now surfaced via `VirtualChatModel.select_backend()` and threaded through pre-flight check → pinned call → cost accumulation, the ADR-2032/ADR-2038 pinning rules still hold (retries and streams target the pinned backend; no re-selection), non-virtual agents fall back byte-identically, and the consolidation into `_invoke_and_track_cost()` removed real duplication across seven call sites. Verified locally: `nox -s unit_tests` (160 features / 3387 scenarios / 15601 steps, all pass), `nox -s typecheck` (0 errors, 1 pre-existing unrelated warning), `nox -s lint` (clean) — all matching the PR's reported results. **Request Changes** because the PR's checklist marks issue #159's acceptance criterion 3 (zero-cost carve-out evaluates the selected backend's rates) as ✅, but no test exercises it — the changed carve-out parameterization is never executed with a pooled agent. ### Critical Issues None. ### Major Issues 1. **Missing test for AC3 — zero-cost carve-out with a selected backend (PR body claims ✅).** `features/virtual_provider.feature` (lines 243–262) covers AC1 (distinct rates), the streaming path, and AC2 (unpriced anchor). No scenario anywhere drives `LLMAgent._check_budget_before_invoke`'s carve-out branch (`src/cleveractors/agents/llm.py:681–697`) with a pooled agent: - Scenario 3 sets `max_cost_usd = 10.0` with `accumulated = 0.0`, so the gate never trips and the carve-out is never reached. - Scenarios 1–2 set `max_cost_usd = None`, so there is no gate at all. - The only zero-rated carve-out tests in the repo (`features/budget_gate_single_llm.feature`, `features/execution_limits.feature`) exercise the single-LLM `PureLangGraph`/`runtime_dispatch` path, not the `LLMAgent` tool-loop path changed here. Consequently the code this PR actually changed — `provider`/`model` kwargs flowing into `_is_zero_rated_invocation` for a virtual agent — has zero test coverage, and both directions of AC3's semantics are unverified: (a) a provably-free selected backend passing an exhausted gate while the anchor is non-zero-rated/unpriced, and (b) the consistent converse that a non-zero-rated selected backend now *blocks* even when the anchor pair is zero-rated (a real behavior change for pooled agents that nothing pins down). **Recommendation:** add a scenario, e.g. pricing `{deepseek: 0.0/0.0, zai: 5.0/5.0}` with `accumulated = 10.0`, `max_cost_usd = 10.0` → the pooled run completes and accumulated cost stays `0.0`; ideally add the converse (priced selected backend + zero-rated anchor → `budget_exhausted`). Until then, please remove the ✅ on AC3 in the PR description or mark it as covered-by-code-review only. ### Minor Issues 1. **False docstring claim: "the pruning chat model is always built directly, never virtual" — `src/cleveractors/agents/llm.py:749–750`.** For a pooled agent, `_run_pruning_pass` (`llm.py:1004`) calls `build_chat_model(config=self.config, ...)`, and `build_chat_model` (`src/cleveractors/agents/llm_client.py:102–113`) returns a fresh `VirtualChatModel` whenever `config["backends"]` is present. So a pooled agent's pruning pass selects a backend internally (with its own provider/model) while `_accumulate_cost_after_invoke(..., "pruning", model=self.model)` bills it at the agent-level anchor pair — the same mis-attribution class #159 fixes for the main path, still live for pruning spend (including the `missing_pricing_entry` raise for an unpriced anchor, swallowed by the tool loop as a per-tool error). This is pre-existing, not a regression of this PR, and out of #159's stated ACs — but the new docstring asserts the opposite and will mislead maintainers. **Recommendation:** correct the docstring to state that pruning-pass attribution for pooled agents still resolves the anchor pair, and file a follow-up issue to wire selected-backend attribution into the pruning accumulation (or explicitly defer it on #159). ### Nits 1. **Inaccurate docstring in `_resolve_invocation_target` (`src/cleveractors/agents/llm.py:587–594`).** It claims init failure "is reported by `_retry_ainvoke`'s own eager `self.chat_model` access (unchanged, and still the single place that raises) instead of here" and that the method does "not force construction". In fact `self._ensure_chat_model()` (line 595) constructs the model and propagates `ConfigurationError` from *here* — `_retry_ainvoke` is never reached when init fails, and a malformed `backends` config on an exhausted budget now raises `ConfigurationError` before `budget_exhausted` (slight error-precedence change; fast-fail outside the retry loop is still preserved). Suggest rewording to describe the actual behavior. 2. **Stale implementation note in the routing ADR (`docs/adr/ADR-2038-virtual-provider-load-balanced-backend-routing.md:178–189`).** The non-normative note still describes this repo's implementation as selecting "once per external call and perform[ing] retries against that one backend internally, rather than relying solely on the outer, already-existing retry wrapper" — the new implementation *does* rely on the outer wrapper, pinning by passing `target.backend` so re-entry cannot re-select (the normative pinning rule still holds). Since the budget-gate ADR got a dated correction, consider a matching one-line note update here. 3. **`_InvocationTarget.backend: Any` (`src/cleveractors/agents/llm.py:239`).** `BaseChatModel` is already imported under `TYPE_CHECKING` in this module (lines 35–36) and used in annotations (`llm.py:466`); with `from __future__ import annotations` the field could be typed `BaseChatModel | None` precisely, per CONTRIBUTING's "Full Annotations". 4. **No length-consistency guard for `backend_providers`/`backend_models` (`src/cleveractors/agents/llm_virtual_provider.py:256–259`).** A partially populated pair (one list shorter than `backends`) silently mixes a backend provider with the anchor model. Unreachable via `build_virtual_chat_model` (always consistent), but a cheap construction-time check would make the invariant explicit. 5. **Observation — blocked rounds now advance selection state.** Because `_resolve_invocation_target()` selects *before* `_check_budget_before_invoke`, a `budget_exhausted` block consumes a round-robin slot even though no call fires (previously selection happened inside `ainvoke`, after the gate). Appears benign for load-balancing fairness (the blocked turn legitimately consumed capacity) and no existing test depends on the sequence, but it is a subtle routing-sequence change worth being aware of; a sentence in the ADR correction would document it. ### Summary A high-quality, well-documented fix that resolves the real #159 defect: per-invocation backend selection is surfaced (`SelectedBackend`), the pre-flight gate, pinned call, and cost accumulation now agree on the backend that actually serves each call, and the six duplicated check→invoke→extract→accumulate sites are consolidated behind `_invoke_and_track_cost()` without changing call-site semantics (verified: all seven sites — main, synthesis, synthesis_followup, stuck_model, stuck_model_followup, no-tools, stream — pass equivalent kwargs and labels; pruning builds its own model and is untouched; ADR-2038 pinning holds for retries and streams). Test additions are meaningful (distinct anchor/backend rates make mis-attribution numerically detectable; the unpriced-anchor assertion explicitly guards against a skip-accumulation partial fix; the mock's `chunk_position="last"` change is verified correct against langchain-core 1.8.5's astream sentinel behavior). Local verification matches the PR report: unit tests 3387/3387, typecheck 0 errors, lint clean. Two things block approval: the claimed-✅ AC3 has no test (Major), and the new "_accumulate_cost_after_invoke" docstring misstates the pruning path for pooled agents (Minor). Both are small, targeted follow-ups on an otherwise solid PR. Per the request, red-tape items (labels, commit footer, branch-name metadata) were excluded; the PR thread contains no prior reviewer comments and nothing was ruled out-of-scope there; the #159 gism0 memory journal was unavailable (no gism0 tools in this session), so the review relied on the ticket, PR description, ADRs, and `docs/index.md` (§4.4.7 documents only config surface/routing — no cost content, so no spec edit was required there).
hurui200320 requested changes 2026-12-03 13:21:34 +00:00
Dismissed
hurui200320 left a comment

PR Review: !204 (Ticket #159)

Verdict: Request Changes

The core fix is correct and well-constructed: the one-per-invocation selection is now surfaced via VirtualChatModel.select_backend() and threaded through pre-flight check → pinned call → cost accumulation, the ADR-2032/ADR-2038 pinning rules still hold (retries and streams target the pinned backend; no re-selection), non-virtual agents fall back byte-identically, and the consolidation into _invoke_and_track_cost() removed real duplication across seven call sites. Verified locally: nox -s unit_tests (160 features / 3387 scenarios / 15601 steps, all pass), nox -s typecheck (0 errors, 1 pre-existing unrelated warning), nox -s lint (clean) — all matching the PR's reported results.

Request Changes because the PR's checklist marks issue #159's acceptance criterion 3 (zero-cost carve-out evaluates the selected backend's rates) as ✅, but no test exercises it — the changed carve-out parameterization is never executed with a pooled agent.

Critical Issues

None.

Major Issues

  1. Missing test for AC3 — zero-cost carve-out with a selected backend (PR body claims ✅). features/virtual_provider.feature (lines 243–262) covers AC1 (distinct rates), the streaming path, and AC2 (unpriced anchor). No scenario anywhere drives LLMAgent._check_budget_before_invoke's carve-out branch (src/cleveractors/agents/llm.py:681–697) with a pooled agent:

    • Scenario 3 sets max_cost_usd = 10.0 with accumulated = 0.0, so the gate never trips and the carve-out is never reached.
    • Scenarios 1–2 set max_cost_usd = None, so there is no gate at all.
    • The only zero-rated carve-out tests in the repo (features/budget_gate_single_llm.feature, features/execution_limits.feature) exercise the single-LLM PureLangGraph/runtime_dispatch path, not the LLMAgent tool-loop path changed here.

    Consequently the code this PR actually changed — provider/model kwargs flowing into _is_zero_rated_invocation for a virtual agent — has zero test coverage, and both directions of AC3's semantics are unverified: (a) a provably-free selected backend passing an exhausted gate while the anchor is non-zero-rated/unpriced, and (b) the consistent converse that a non-zero-rated selected backend now blocks even when the anchor pair is zero-rated (a real behavior change for pooled agents that nothing pins down).

    Recommendation: add a scenario, e.g. pricing {deepseek: 0.0/0.0, zai: 5.0/5.0} with accumulated = 10.0, max_cost_usd = 10.0 → the pooled run completes and accumulated cost stays 0.0; ideally add the converse (priced selected backend + zero-rated anchor → budget_exhausted). Until then, please remove the ✅ on AC3 in the PR description or mark it as covered-by-code-review only.

Minor Issues

  1. False docstring claim: "the pruning chat model is always built directly, never virtual" — src/cleveractors/agents/llm.py:749–750. For a pooled agent, _run_pruning_pass (llm.py:1004) calls build_chat_model(config=self.config, ...), and build_chat_model (src/cleveractors/agents/llm_client.py:102–113) returns a fresh VirtualChatModel whenever config["backends"] is present. So a pooled agent's pruning pass selects a backend internally (with its own provider/model) while _accumulate_cost_after_invoke(..., "pruning", model=self.model) bills it at the agent-level anchor pair — the same mis-attribution class #159 fixes for the main path, still live for pruning spend (including the missing_pricing_entry raise for an unpriced anchor, swallowed by the tool loop as a per-tool error). This is pre-existing, not a regression of this PR, and out of #159's stated ACs — but the new docstring asserts the opposite and will mislead maintainers.
    Recommendation: correct the docstring to state that pruning-pass attribution for pooled agents still resolves the anchor pair, and file a follow-up issue to wire selected-backend attribution into the pruning accumulation (or explicitly defer it on #159).

Nits

  1. Inaccurate docstring in _resolve_invocation_target (src/cleveractors/agents/llm.py:587–594). It claims init failure "is reported by _retry_ainvoke's own eager self.chat_model access (unchanged, and still the single place that raises) instead of here" and that the method does "not force construction". In fact self._ensure_chat_model() (line 595) constructs the model and propagates ConfigurationError from here — _retry_ainvoke is never reached when init fails, and a malformed backends config on an exhausted budget now raises ConfigurationError before budget_exhausted (slight error-precedence change; fast-fail outside the retry loop is still preserved). Suggest rewording to describe the actual behavior.
  2. Stale implementation note in the routing ADR (docs/adr/ADR-2038-virtual-provider-load-balanced-backend-routing.md:178–189). The non-normative note still describes this repo's implementation as selecting "once per external call and perform[ing] retries against that one backend internally, rather than relying solely on the outer, already-existing retry wrapper" — the new implementation does rely on the outer wrapper, pinning by passing target.backend so re-entry cannot re-select (the normative pinning rule still holds). Since the budget-gate ADR got a dated correction, consider a matching one-line note update here.
  3. _InvocationTarget.backend: Any (src/cleveractors/agents/llm.py:239). BaseChatModel is already imported under TYPE_CHECKING in this module (lines 35–36) and used in annotations (llm.py:466); with from __future__ import annotations the field could be typed BaseChatModel | None precisely, per CONTRIBUTING's "Full Annotations".
  4. No length-consistency guard for backend_providers/backend_models (src/cleveractors/agents/llm_virtual_provider.py:256–259). A partially populated pair (one list shorter than backends) silently mixes a backend provider with the anchor model. Unreachable via build_virtual_chat_model (always consistent), but a cheap construction-time check would make the invariant explicit.
  5. Observation — blocked rounds now advance selection state. Because _resolve_invocation_target() selects before _check_budget_before_invoke, a budget_exhausted block consumes a round-robin slot even though no call fires (previously selection happened inside ainvoke, after the gate). Appears benign for load-balancing fairness (the blocked turn legitimately consumed capacity) and no existing test depends on the sequence, but it is a subtle routing-sequence change worth being aware of; a sentence in the ADR correction would document it.

Summary

A high-quality, well-documented fix that resolves the real #159 defect: per-invocation backend selection is surfaced (SelectedBackend), the pre-flight gate, pinned call, and cost accumulation now agree on the backend that actually serves each call, and the six duplicated check→invoke→extract→accumulate sites are consolidated behind _invoke_and_track_cost() without changing call-site semantics (verified: all seven sites — main, synthesis, synthesis_followup, stuck_model, stuck_model_followup, no-tools, stream — pass equivalent kwargs and labels; pruning builds its own model and is untouched; ADR-2038 pinning holds for retries and streams). Test additions are meaningful (distinct anchor/backend rates make mis-attribution numerically detectable; the unpriced-anchor assertion explicitly guards against a skip-accumulation partial fix; the mock's chunk_position="last" change is verified correct against langchain-core 1.8.5's astream sentinel behavior). Local verification matches the PR report: unit tests 3387/3387, typecheck 0 errors, lint clean.

Two things block approval: the claimed-✅ AC3 has no test (Major), and the new _accumulate_cost_after_invoke docstring misstates the pruning path for pooled agents (Minor). Both are small, targeted follow-ups on an otherwise solid PR. Per the request, red-tape items (labels, commit footer, branch-name metadata) were excluded; the PR thread contains no prior reviewer comments and nothing was ruled out-of-scope there; the #159 gism0 memory journal was unavailable (no gism0 tools in this session), so the review relied on the ticket, PR description, ADRs, and docs/index.md (§4.4.7 documents only config surface/routing — no cost content, so no spec edit was required there).

## PR Review: !204 (Ticket #159) ### Verdict: Request Changes The core fix is correct and well-constructed: the one-per-invocation selection is now surfaced via `VirtualChatModel.select_backend()` and threaded through pre-flight check → pinned call → cost accumulation, the ADR-2032/ADR-2038 pinning rules still hold (retries and streams target the pinned backend; no re-selection), non-virtual agents fall back byte-identically, and the consolidation into `_invoke_and_track_cost()` removed real duplication across seven call sites. Verified locally: `nox -s unit_tests` (160 features / 3387 scenarios / 15601 steps, all pass), `nox -s typecheck` (0 errors, 1 pre-existing unrelated warning), `nox -s lint` (clean) — all matching the PR's reported results. **Request Changes** because the PR's checklist marks issue #159's acceptance criterion 3 (zero-cost carve-out evaluates the selected backend's rates) as ✅, but no test exercises it — the changed carve-out parameterization is never executed with a pooled agent. ### Critical Issues None. ### Major Issues 1. **Missing test for AC3 — zero-cost carve-out with a selected backend (PR body claims ✅).** `features/virtual_provider.feature` (lines 243–262) covers AC1 (distinct rates), the streaming path, and AC2 (unpriced anchor). No scenario anywhere drives `LLMAgent._check_budget_before_invoke`'s carve-out branch (`src/cleveractors/agents/llm.py:681–697`) with a pooled agent: - Scenario 3 sets `max_cost_usd = 10.0` with `accumulated = 0.0`, so the gate never trips and the carve-out is never reached. - Scenarios 1–2 set `max_cost_usd = None`, so there is no gate at all. - The only zero-rated carve-out tests in the repo (`features/budget_gate_single_llm.feature`, `features/execution_limits.feature`) exercise the single-LLM `PureLangGraph`/`runtime_dispatch` path, not the `LLMAgent` tool-loop path changed here. Consequently the code this PR actually changed — `provider`/`model` kwargs flowing into `_is_zero_rated_invocation` for a virtual agent — has zero test coverage, and both directions of AC3's semantics are unverified: (a) a provably-free selected backend passing an exhausted gate while the anchor is non-zero-rated/unpriced, and (b) the consistent converse that a non-zero-rated selected backend now *blocks* even when the anchor pair is zero-rated (a real behavior change for pooled agents that nothing pins down). **Recommendation:** add a scenario, e.g. pricing `{deepseek: 0.0/0.0, zai: 5.0/5.0}` with `accumulated = 10.0`, `max_cost_usd = 10.0` → the pooled run completes and accumulated cost stays `0.0`; ideally add the converse (priced selected backend + zero-rated anchor → `budget_exhausted`). Until then, please remove the ✅ on AC3 in the PR description or mark it as covered-by-code-review only. ### Minor Issues 1. **False docstring claim: "the pruning chat model is always built directly, never virtual" — `src/cleveractors/agents/llm.py:749–750`.** For a pooled agent, `_run_pruning_pass` (`llm.py:1004`) calls `build_chat_model(config=self.config, ...)`, and `build_chat_model` (`src/cleveractors/agents/llm_client.py:102–113`) returns a fresh `VirtualChatModel` whenever `config["backends"]` is present. So a pooled agent's pruning pass selects a backend internally (with its own provider/model) while `_accumulate_cost_after_invoke(..., "pruning", model=self.model)` bills it at the agent-level anchor pair — the same mis-attribution class #159 fixes for the main path, still live for pruning spend (including the `missing_pricing_entry` raise for an unpriced anchor, swallowed by the tool loop as a per-tool error). This is pre-existing, not a regression of this PR, and out of #159's stated ACs — but the new docstring asserts the opposite and will mislead maintainers. **Recommendation:** correct the docstring to state that pruning-pass attribution for pooled agents still resolves the anchor pair, and file a follow-up issue to wire selected-backend attribution into the pruning accumulation (or explicitly defer it on #159). ### Nits 1. **Inaccurate docstring in `_resolve_invocation_target` (`src/cleveractors/agents/llm.py:587–594`).** It claims init failure "is reported by `_retry_ainvoke`'s own eager `self.chat_model` access (unchanged, and still the single place that raises) instead of here" and that the method does "not force construction". In fact `self._ensure_chat_model()` (line 595) constructs the model and propagates `ConfigurationError` from *here* — `_retry_ainvoke` is never reached when init fails, and a malformed `backends` config on an exhausted budget now raises `ConfigurationError` before `budget_exhausted` (slight error-precedence change; fast-fail outside the retry loop is still preserved). Suggest rewording to describe the actual behavior. 2. **Stale implementation note in the routing ADR (`docs/adr/ADR-2038-virtual-provider-load-balanced-backend-routing.md:178–189`).** The non-normative note still describes this repo's implementation as selecting "once per external call and perform[ing] retries against that one backend internally, rather than relying solely on the outer, already-existing retry wrapper" — the new implementation *does* rely on the outer wrapper, pinning by passing `target.backend` so re-entry cannot re-select (the normative pinning rule still holds). Since the budget-gate ADR got a dated correction, consider a matching one-line note update here. 3. **`_InvocationTarget.backend: Any` (`src/cleveractors/agents/llm.py:239`).** `BaseChatModel` is already imported under `TYPE_CHECKING` in this module (lines 35–36) and used in annotations (`llm.py:466`); with `from __future__ import annotations` the field could be typed `BaseChatModel | None` precisely, per CONTRIBUTING's "Full Annotations". 4. **No length-consistency guard for `backend_providers`/`backend_models` (`src/cleveractors/agents/llm_virtual_provider.py:256–259`).** A partially populated pair (one list shorter than `backends`) silently mixes a backend provider with the anchor model. Unreachable via `build_virtual_chat_model` (always consistent), but a cheap construction-time check would make the invariant explicit. 5. **Observation — blocked rounds now advance selection state.** Because `_resolve_invocation_target()` selects *before* `_check_budget_before_invoke`, a `budget_exhausted` block consumes a round-robin slot even though no call fires (previously selection happened inside `ainvoke`, after the gate). Appears benign for load-balancing fairness (the blocked turn legitimately consumed capacity) and no existing test depends on the sequence, but it is a subtle routing-sequence change worth being aware of; a sentence in the ADR correction would document it. ### Summary A high-quality, well-documented fix that resolves the real #159 defect: per-invocation backend selection is surfaced (`SelectedBackend`), the pre-flight gate, pinned call, and cost accumulation now agree on the backend that actually serves each call, and the six duplicated check→invoke→extract→accumulate sites are consolidated behind `_invoke_and_track_cost()` without changing call-site semantics (verified: all seven sites — main, synthesis, synthesis_followup, stuck_model, stuck_model_followup, no-tools, stream — pass equivalent kwargs and labels; pruning builds its own model and is untouched; ADR-2038 pinning holds for retries and streams). Test additions are meaningful (distinct anchor/backend rates make mis-attribution numerically detectable; the unpriced-anchor assertion explicitly guards against a skip-accumulation partial fix; the mock's `chunk_position="last"` change is verified correct against langchain-core 1.8.5's astream sentinel behavior). Local verification matches the PR report: unit tests 3387/3387, typecheck 0 errors, lint clean. Two things block approval: the claimed-✅ AC3 has no test (Major), and the new `_accumulate_cost_after_invoke` docstring misstates the pruning path for pooled agents (Minor). Both are small, targeted follow-ups on an otherwise solid PR. Per the request, red-tape items (labels, commit footer, branch-name metadata) were excluded; the PR thread contains no prior reviewer comments and nothing was ruled out-of-scope there; the #159 gism0 memory journal was unavailable (no gism0 tools in this session), so the review relied on the ticket, PR description, ADRs, and `docs/index.md` (§4.4.7 documents only config surface/routing — no cost content, so no spec edit was required there).
CoreRasurae force-pushed bugfix/m1-virtual-provider-cost-attribution from f110605728
Some checks failed
CI / lint (pull_request) Successful in 48s
CI / typecheck (pull_request) Successful in 1m46s
CI / quality (pull_request) Successful in 1m47s
CI / security (pull_request) Successful in 2m10s
CI / build (pull_request) Successful in 1m35s
CI / integration_tests (pull_request) Successful in 3m7s
CI / unit_tests (pull_request) Successful in 7m5s
CI / coverage (pull_request) Failing after 13m57s
CI / benchmark (pull_request) Failing after 20m20s
CI / status-check (pull_request) Has been cancelled
to 68f2a2c8b8
Some checks failed
CI / security (pull_request) Successful in 1m18s
CI / lint (pull_request) Failing after 1m57s
CI / typecheck (pull_request) Successful in 2m32s
CI / build (pull_request) Successful in 49s
CI / quality (pull_request) Successful in 2m13s
CI / integration_tests (pull_request) Successful in 3m17s
CI / unit_tests (pull_request) Successful in 6m48s
CI / coverage (pull_request) Has been skipped
CI / status-check (pull_request) Failing after 1s
CI / benchmark (pull_request) Failing after 33m38s
2026-12-03 15:47:54 +00:00
Compare
Author
Member

@hurui200320 Thanks for the thorough review. Before making any change I re-checked each point against issue #159's acceptance criteria, docs/index.md §4.4.7, and docs/adr/ADR-2038-virtual-provider-load-balanced-backend-routing.md — all findings below were independently confirmed correct against those sources before being acted on. Pushed as an amendment to the same commit (f110605 → 68f2a2c), not a new commit, since this PR is still a single-commit TDD/bugfix pair with #202.

Major Issues

  1. Missing test for AC3 (zero-cost carve-out) — DONE. Confirmed AC3 in issue #159 explicitly requires "the zero-cost carve-out evaluates the selected backend's rates," and it genuinely had no test. Added two scenarios to features/virtual_provider.feature:
    • Pass case: selected backend priced at 0.0/0.0, agent-level anchor priced non-zero, accumulated cost already at the limit → the pooled run completes and accumulated cost stays unchanged (verifies _check_budget_before_invoke's carve-out reads target.provider/target.model, not self.provider/self.model).
    • Converse case (your "ideally" suggestion): selected backend priced non-zero, anchor zero-rated, accumulated cost at the limit → still raises budget_exhausted (verifies the carve-out can't be satisfied by a coincidentally zero-rated anchor when the backend that will actually serve the call is priced).
      Kept the PR description's ✅ on AC3 since it's now true, rather than walking it back.

Minor Issues

  1. Pruning docstring misattribution claim — DONE. Traced _run_pruning_pass → build_chat_model(config=self.config, ...) → confirmed it returns a fresh VirtualChatModel whenever a pooled agent's config["backends"] is present, exactly as you described. Corrected _accumulate_cost_after_invoke's docstring to state that pruning for pooled agents still bills the agent-level anchor pair, not the backend the pruning call actually invokes, and that this is pre-existing and out of #159's ACs — not something this PR fixes. I did not open a follow-up issue for the pruning-attribution gap itself (your recommendation offered it as one of two options, with "explicitly defer it on #159" as the alternative, which the corrected docstring now does); happy to file one if you'd prefer that over the docstring note.

Nits

  1. _resolve_invocation_target docstring — DONE. Confirmed: _ensure_chat_model() (called directly by this method) propagates ConfigurationError from construction before _check_budget_before_invoke runs, for every agent that goes through _invoke_and_track_cost/the streaming path — not only pooled ones, since _resolve_invocation_target is now called unconditionally first at every call site. Reworded the docstring to describe this correctly and scoped the note to "virtual and non-virtual agents alike" rather than pooled-only (my first draft had that wrong too before I traced all the call sites).
  2. Stale ADR-2038 implementation note — DONE. Confirmed by diffing llm_virtual_provider.py across this PR: pre-#159, VirtualChatModel._agenerate/_astream did their own internal select → call_with_retry, matching the old note. Post-#159, LLMAgent._retry_ainvoke/stream_message call target.backend.ainvoke()/.astream() directly through the existing ADR-2032 outer retry wrapper, bypassing VirtualChatModel's own entry points entirely. Rewrote the note to describe the new design, and kept VirtualChatModel._agenerate/_astream's internal retry logic in place (not dead code — it's required for VirtualChatModel to remain Liskov-substitutable for any BaseChatModel caller that invokes it directly rather than through LLMAgent). Also added your optional one-sentence note on the round-robin-position-advances-on-a-blocked-round observation, as documentation only — no code change, since you already flagged it as benign.
  3. _InvocationTarget.backend: Any — DONE. Changed to BaseChatModel | None; BaseChatModel was already imported under TYPE_CHECKING and used elsewhere in the file, so this was a pure typing tightening with no runtime impact (from __future__ import annotations keeps the dataclass annotation as a string).
  4. No length-consistency guard for backend_providers/backend_models — DONE, with a caveat. Added a pydantic @model_validator(mode="after") on VirtualChatModel rejecting any state other than "both empty" (opted out) or "both exactly len(backends)" (fully populated) — a partially-populated pair is now a construction-time ValidationError instead of a silent mismatch in select_backend(). Added a scenario covering the new error path so it isn't uncovered dead code. Caveat: I verified build_virtual_chat_model always populates all four parallel lists in lockstep in one loop, so this path is indeed unreachable through the normal config-driven construction path, exactly as you noted — the guard only protects direct/manual construction (test doubles, library use).
  5. Observation (blocked rounds advance selection state) — not code-changed, documented only, per the above (see nit 2). You yourself flagged it as benign with no test depending on the sequence, so I didn't add behavior or a test for it — only the ADR sentence.

Not acted on

  • "Submitting independent PRs": I didn't find any comment to that effect in this review thread (no inline comments, and this was the only review on the PR) — nothing to action here, but flagging in case it was meant for a different thread.
  • No new follow-up issue was filed for the pruning-pass attribution gap (Minor #1) or for re-plumbing VirtualChatModel's internal retry path — both are pre-existing, out of #159's scope, and documented as such; let me know if you'd like either filed separately rather than left as a documented gap.

Verification

nox -s unit_tests: 160 features / 3390 scenarios / 15611 steps, all green (3 new scenarios: 2 for AC3, 1 for the new validator). nox -s lint, nox -s typecheck (0 errors, the same 1 pre-existing unrelated warning), nox -s security_scan, nox -s dead_code: all clean. Coverage delta checked by scoping nox -s coverage_report to features/virtual_provider.feature alone (not the full suite): llm_virtual_provider.py at 99.57%, with only one pre-existing, unrelated line (llm_virtual_provider.py:510, an except ConfigurationError: raise) still uncovered in that scope — not part of this PR's diff.

@hurui200320 Thanks for the thorough review. Before making any change I re-checked each point against issue #159's acceptance criteria, `docs/index.md` §4.4.7, and `docs/adr/ADR-2038-virtual-provider-load-balanced-backend-routing.md` — all findings below were independently confirmed correct against those sources before being acted on. Pushed as an amendment to the same commit (`f110605` → `68f2a2c`), not a new commit, since this PR is still a single-commit TDD/bugfix pair with #202. ### Major Issues 1. **Missing test for AC3 (zero-cost carve-out) — DONE.** Confirmed AC3 in issue #159 explicitly requires "the zero-cost carve-out evaluates the selected backend's rates," and it genuinely had no test. Added two scenarios to `features/virtual_provider.feature`: - *Pass case*: selected backend priced at `0.0`/`0.0`, agent-level anchor priced non-zero, accumulated cost already at the limit → the pooled run completes and accumulated cost stays unchanged (verifies `_check_budget_before_invoke`'s carve-out reads `target.provider`/`target.model`, not `self.provider`/`self.model`). - *Converse case* (your "ideally" suggestion): selected backend priced non-zero, anchor zero-rated, accumulated cost at the limit → still raises `budget_exhausted` (verifies the carve-out can't be satisfied by a coincidentally zero-rated anchor when the backend that will actually serve the call is priced). Kept the PR description's ✅ on AC3 since it's now true, rather than walking it back. ### Minor Issues 1. **Pruning docstring misattribution claim — DONE.** Traced `_run_pruning_pass` → `build_chat_model(config=self.config, ...)` → confirmed it returns a fresh `VirtualChatModel` whenever a pooled agent's `config["backends"]` is present, exactly as you described. Corrected `_accumulate_cost_after_invoke`'s docstring to state that pruning for pooled agents still bills the agent-level anchor pair, not the backend the pruning call actually invokes, and that this is pre-existing and out of #159's ACs — not something this PR fixes. I did not open a follow-up issue for the pruning-attribution gap itself (your recommendation offered it as one of two options, with "explicitly defer it on #159" as the alternative, which the corrected docstring now does); happy to file one if you'd prefer that over the docstring note. ### Nits 1. **`_resolve_invocation_target` docstring — DONE.** Confirmed: `_ensure_chat_model()` (called directly by this method) propagates `ConfigurationError` from construction before `_check_budget_before_invoke` runs, for *every* agent that goes through `_invoke_and_track_cost`/the streaming path — not only pooled ones, since `_resolve_invocation_target` is now called unconditionally first at every call site. Reworded the docstring to describe this correctly and scoped the note to "virtual and non-virtual agents alike" rather than pooled-only (my first draft had that wrong too before I traced all the call sites). 2. **Stale ADR-2038 implementation note — DONE.** Confirmed by diffing `llm_virtual_provider.py` across this PR: pre-#159, `VirtualChatModel._agenerate`/`_astream` did their own internal `select → call_with_retry`, matching the old note. Post-#159, `LLMAgent._retry_ainvoke`/`stream_message` call `target.backend.ainvoke()`/`.astream()` directly through the *existing* ADR-2032 outer retry wrapper, bypassing `VirtualChatModel`'s own entry points entirely. Rewrote the note to describe the new design, and kept `VirtualChatModel._agenerate`/`_astream`'s internal retry logic in place (not dead code — it's required for `VirtualChatModel` to remain Liskov-substitutable for any `BaseChatModel` caller that invokes it directly rather than through `LLMAgent`). Also added your optional one-sentence note on the round-robin-position-advances-on-a-blocked-round observation, as documentation only — no code change, since you already flagged it as benign. 3. **`_InvocationTarget.backend: Any` — DONE.** Changed to `BaseChatModel | None`; `BaseChatModel` was already imported under `TYPE_CHECKING` and used elsewhere in the file, so this was a pure typing tightening with no runtime impact (`from __future__ import annotations` keeps the dataclass annotation as a string). 4. **No length-consistency guard for `backend_providers`/`backend_models` — DONE, with a caveat.** Added a pydantic `@model_validator(mode="after")` on `VirtualChatModel` rejecting any state other than "both empty" (opted out) or "both exactly `len(backends)`" (fully populated) — a partially-populated pair is now a construction-time `ValidationError` instead of a silent mismatch in `select_backend()`. Added a scenario covering the new error path so it isn't uncovered dead code. Caveat: I verified `build_virtual_chat_model` always populates all four parallel lists in lockstep in one loop, so this path is indeed unreachable through the normal config-driven construction path, exactly as you noted — the guard only protects direct/manual construction (test doubles, library use). 5. **Observation (blocked rounds advance selection state) — not code-changed, documented only**, per the above (see nit 2). You yourself flagged it as benign with no test depending on the sequence, so I didn't add behavior or a test for it — only the ADR sentence. ### Not acted on - **"Submitting independent PRs"**: I didn't find any comment to that effect in this review thread (no inline comments, and this was the only review on the PR) — nothing to action here, but flagging in case it was meant for a different thread. - No new follow-up issue was filed for the pruning-pass attribution gap (Minor #1) or for re-plumbing `VirtualChatModel`'s internal retry path — both are pre-existing, out of #159's scope, and documented as such; let me know if you'd like either filed separately rather than left as a documented gap. ### Verification `nox -s unit_tests`: 160 features / 3390 scenarios / 15611 steps, all green (3 new scenarios: 2 for AC3, 1 for the new validator). `nox -s lint`, `nox -s typecheck` (0 errors, the same 1 pre-existing unrelated warning), `nox -s security_scan`, `nox -s dead_code`: all clean. Coverage delta checked by scoping `nox -s coverage_report` to `features/virtual_provider.feature` alone (not the full suite): `llm_virtual_provider.py` at 99.57%, with only one pre-existing, unrelated line (`llm_virtual_provider.py:510`, an `except ConfigurationError: raise`) still uncovered in that scope — not part of this PR's diff.
hurui200320 left a comment

PR Review: !204 (Ticket #159)

Verdict: Approve

Re-review of the amended commit (68f2a2c) after the author's response to the previous review. All previously blocking findings were verifiably addressed, and a fresh pass over the full change surfaced no new critical or major issues. Verified locally on 68f2a2c: nox -s typecheck (0 errors, 1 pre-existing unrelated warning), nox -s lint (clean), nox -s coverage_report (97.3% full-suite, above the 97% standard — run unscoped this time, closing the only gap in the author's own verification), and nox -s unit_tests (160 features / 3390 scenarios / 15611 steps, all pass) — matching the author's reported results.

Per the review ground rules, items the author's response decided as out-of-scope or deferred were removed from this review (see Summary), as were process/red-tape items.

Critical Issues

None.

Major Issues

None.

Minor Issues

None.

Nits

  1. features/mocks/fake_backend_chat_model.py:117–131 — _build_stream_chunk silently ignores a partially-set token config where _build_response_message asserts. The non-streaming builder (lines 88–91) asserts prompt_tokens/completion_tokens are set together or both None; the streaming builder just skips usage_metadata when only one is set. Harmless today (every scenario sets both or neither), but a future misconfigured mock would silently produce usage-less streaming instead of failing fast. Recommend mirroring the assert (or factoring a shared guard).

  2. PR description test-plan numbers are stale for the amended commit. The body reports "3387 scenarios / 15601 steps" (the pre-amendment run); the pushed commit is 3390/15611 — as the author's thread comment states and this review re-verified locally. One-line PR-body update; cosmetic only.

Summary

All issues from the previous review are confirmed fixed in 68f2a2c, each verified against the code rather than the claims:

  • Major 1 (AC3 untested): two new scenarios in features/virtual_provider.feature drive the carve-out branch with a pooled agent in both directions — a provably-free selected backend passing an already-tripped gate while the anchor is priced (accumulated cost stays at the limit), and the converse where a priced selected backend still blocks even though the anchor is zero-rated (budget_exhausted asserted with kind='cost'/reason='budget_exhausted'). Distinct anchor/backend rates make mis-attribution numerically detectable, and both scenarios fail against the pre-fix anchor-resolved carve-out — AC3 is now genuinely pinned, and the PR body's ✅ is accurate.
  • Minor 1 (pruning docstring): _accumulate_cost_after_invoke's docstring now correctly states that pooled-agent pruning spend still bills the agent-level anchor pair, explicitly scoped as pre-existing and outside #159's ACs.
  • Nits 1–4: _resolve_invocation_target's docstring now accurately describes the error-precedence change (ConfigurationError raised there, for virtual and non-virtual agents alike); the ADR-2038 implementation note was rewritten to match the outer-retry pinned-call design while keeping VirtualChatModel Liskov-substitutable, plus the round-robin-advance note; _InvocationTarget.backend is now BaseChatModel | None; and a pydantic @model_validator rejects partially populated backend_providers/backend_models at construction time, with a scenario covering the new error path.

Removed from this review per the author's thread decisions: the pruning-pass attribution gap (explicitly deferred — documented as a pre-existing, out-of-scope gap in the docstring; the author offered to file a follow-up issue if preferred, which is a ticket-process decision, not a PR blocker); the blocked-rounds-advance-selection observation (documentation-only, agreed benign, now captured in the ADR); and the phantom "Submitting independent PRs" item (no such comment exists in this thread). The gism0 memory journal for #159 was unavailable in this session (no gism0 tools), so the review relied on the ticket, PR description, ADRs, and docs/index.md — no behavioral gaps found against them.

Spec/subtask check: the issue's subtasks are satisfied — attribution mechanism decided (backend-identity propagation via select_backend()/SelectedBackend), wired into both _check_budget_before_invoke and _accumulate_cost_after_invoke, and the full test matrix added (AC1 non-streaming + streaming, AC2 unpriced anchor, AC3 both directions, AC4 preserved by the non-virtual fallback plus the untouched pre-existing suite). docs/index.md §4.4.7 carries no cost-attribution content, so no spec edit was needed there (the corrections live in the two ADRs, both dated in their changelog tables). benchmarks/virtual_provider_benchmark.py still measures the same hot path (_select now delegates to select_backend), so it remains valid without changes. The commit first line matches the issue's Metadata Commit Message and the PR is a single atomic commit on a rebase-clean branch.

Ready to merge.

## PR Review: !204 (Ticket #159) ### Verdict: Approve Re-review of the amended commit (`68f2a2c`) after the author's response to the previous review. All previously blocking findings were verifiably addressed, and a fresh pass over the full change surfaced no new critical or major issues. Verified locally on `68f2a2c`: `nox -s typecheck` (0 errors, 1 pre-existing unrelated warning), `nox -s lint` (clean), `nox -s coverage_report` (97.3% full-suite, above the 97% standard — run unscoped this time, closing the only gap in the author's own verification), and `nox -s unit_tests` (160 features / 3390 scenarios / 15611 steps, all pass) — matching the author's reported results. Per the review ground rules, items the author's response decided as out-of-scope or deferred were removed from this review (see Summary), as were process/red-tape items. ### Critical Issues None. ### Major Issues None. ### Minor Issues None. ### Nits 1. **`features/mocks/fake_backend_chat_model.py:117–131` — `_build_stream_chunk` silently ignores a partially-set token config where `_build_response_message` asserts.** The non-streaming builder (lines 88–91) asserts `prompt_tokens`/`completion_tokens` are set together or both `None`; the streaming builder just skips `usage_metadata` when only one is set. Harmless today (every scenario sets both or neither), but a future misconfigured mock would silently produce usage-less streaming instead of failing fast. Recommend mirroring the assert (or factoring a shared guard). 2. **PR description test-plan numbers are stale for the amended commit.** The body reports "3387 scenarios / 15601 steps" (the pre-amendment run); the pushed commit is 3390/15611 — as the author's thread comment states and this review re-verified locally. One-line PR-body update; cosmetic only. ### Summary All issues from the previous review are confirmed fixed in `68f2a2c`, each verified against the code rather than the claims: - **Major 1 (AC3 untested):** two new scenarios in `features/virtual_provider.feature` drive the carve-out branch with a pooled agent in both directions — a provably-free selected backend passing an already-tripped gate while the anchor is priced (accumulated cost stays at the limit), and the converse where a priced selected backend still blocks even though the anchor is zero-rated (`budget_exhausted` asserted with `kind='cost'`/`reason='budget_exhausted'`). Distinct anchor/backend rates make mis-attribution numerically detectable, and both scenarios fail against the pre-fix anchor-resolved carve-out — AC3 is now genuinely pinned, and the PR body's ✅ is accurate. - **Minor 1 (pruning docstring):** `_accumulate_cost_after_invoke`'s docstring now correctly states that pooled-agent pruning spend still bills the agent-level anchor pair, explicitly scoped as pre-existing and outside #159's ACs. - **Nits 1–4:** `_resolve_invocation_target`'s docstring now accurately describes the error-precedence change (ConfigurationError raised there, for virtual and non-virtual agents alike); the ADR-2038 implementation note was rewritten to match the outer-retry pinned-call design while keeping `VirtualChatModel` Liskov-substitutable, plus the round-robin-advance note; `_InvocationTarget.backend` is now `BaseChatModel | None`; and a pydantic `@model_validator` rejects partially populated `backend_providers`/`backend_models` at construction time, with a scenario covering the new error path. **Removed from this review per the author's thread decisions:** the pruning-pass attribution gap (explicitly deferred — documented as a pre-existing, out-of-scope gap in the docstring; the author offered to file a follow-up issue if preferred, which is a ticket-process decision, not a PR blocker); the blocked-rounds-advance-selection observation (documentation-only, agreed benign, now captured in the ADR); and the phantom "Submitting independent PRs" item (no such comment exists in this thread). The gism0 memory journal for #159 was unavailable in this session (no gism0 tools), so the review relied on the ticket, PR description, ADRs, and `docs/index.md` — no behavioral gaps found against them. Spec/subtask check: the issue's subtasks are satisfied — attribution mechanism decided (backend-identity propagation via `select_backend()`/`SelectedBackend`), wired into both `_check_budget_before_invoke` and `_accumulate_cost_after_invoke`, and the full test matrix added (AC1 non-streaming + streaming, AC2 unpriced anchor, AC3 both directions, AC4 preserved by the non-virtual fallback plus the untouched pre-existing suite). `docs/index.md` §4.4.7 carries no cost-attribution content, so no spec edit was needed there (the corrections live in the two ADRs, both dated in their changelog tables). `benchmarks/virtual_provider_benchmark.py` still measures the same hot path (`_select` now delegates to `select_backend`), so it remains valid without changes. The commit first line matches the issue's Metadata Commit Message and the PR is a single atomic commit on a rebase-clean branch. Ready to merge.
CoreRasurae force-pushed bugfix/m1-virtual-provider-cost-attribution from 68f2a2c8b8
Some checks failed
CI / security (pull_request) Successful in 1m18s
CI / lint (pull_request) Failing after 1m57s
CI / typecheck (pull_request) Successful in 2m32s
CI / build (pull_request) Successful in 49s
CI / quality (pull_request) Successful in 2m13s
CI / integration_tests (pull_request) Successful in 3m17s
CI / unit_tests (pull_request) Successful in 6m48s
CI / coverage (pull_request) Has been skipped
CI / status-check (pull_request) Failing after 1s
CI / benchmark (pull_request) Failing after 33m38s
to 0163c37b25
Some checks failed
CI / lint (pull_request) Failing after 43s
CI / typecheck (pull_request) Successful in 1m53s
CI / unit_tests (pull_request) Has started running
CI / integration_tests (pull_request) Has started running
CI / build (pull_request) Has started running
CI / benchmark (pull_request) Has started running
CI / security (pull_request) Successful in 1m44s
CI / quality (pull_request) Successful in 1m47s
CI / coverage (pull_request) Has been cancelled
CI / status-check (pull_request) Has been cancelled
2026-12-03 16:32:48 +00:00
Compare
CoreRasurae force-pushed bugfix/m1-virtual-provider-cost-attribution from 0163c37b25
Some checks failed
CI / lint (pull_request) Failing after 43s
CI / typecheck (pull_request) Successful in 1m53s
CI / unit_tests (pull_request) Has started running
CI / integration_tests (pull_request) Has started running
CI / build (pull_request) Has started running
CI / benchmark (pull_request) Has started running
CI / security (pull_request) Successful in 1m44s
CI / quality (pull_request) Successful in 1m47s
CI / coverage (pull_request) Has been cancelled
CI / status-check (pull_request) Has been cancelled
to d4bb0d5e53
Some checks failed
CI / lint (pull_request) Successful in 53s
CI / benchmark (pull_request) Has started running
CI / security (pull_request) Successful in 1m49s
CI / build (pull_request) Successful in 52s
CI / quality (pull_request) Successful in 1m51s
CI / typecheck (pull_request) Successful in 2m25s
CI / integration_tests (pull_request) Successful in 3m51s
CI / unit_tests (pull_request) Successful in 7m11s
CI / coverage (pull_request) Has started running
CI / status-check (pull_request) Has been cancelled
2026-12-03 16:39:00 +00:00
Compare
CoreRasurae force-pushed bugfix/m1-virtual-provider-cost-attribution from d4bb0d5e53
Some checks failed
CI / lint (pull_request) Successful in 53s
CI / benchmark (pull_request) Has started running
CI / security (pull_request) Successful in 1m49s
CI / build (pull_request) Successful in 52s
CI / quality (pull_request) Successful in 1m51s
CI / typecheck (pull_request) Successful in 2m25s
CI / integration_tests (pull_request) Successful in 3m51s
CI / unit_tests (pull_request) Successful in 7m11s
CI / coverage (pull_request) Has started running
CI / status-check (pull_request) Has been cancelled
to 6f15fa48eb
Some checks failed
CI / lint (pull_request) Successful in 48s
CI / typecheck (pull_request) Successful in 1m24s
CI / security (pull_request) Successful in 1m9s
CI / quality (pull_request) Successful in 1m53s
CI / build (pull_request) Successful in 2m16s
CI / integration_tests (pull_request) Successful in 3m19s
CI / unit_tests (pull_request) Successful in 7m53s
CI / benchmark (pull_request) Has been cancelled
CI / coverage (pull_request) Successful in 6m27s
CI / status-check (pull_request) Successful in 2s
2026-12-03 16:50:44 +00:00
Compare
Author
Member

@hurui200320 Thanks for the re-review and approval. Before touching anything I re-checked both reviews against issue #159's acceptance criteria, docs/index.md §4.4.7, and both docs/adr/ADR-2038-* documents, then independently re-derived (not just trusted) that the Major/Minor items from the first review were genuinely present in the code — they were, matching your approval. This reply covers the two remaining Nits from your approving review, plus one housekeeping item.

Nits from the approving review

  1. _build_stream_chunk silently drops a partially-set token pair — DONE.
    Confirmed the asymmetry you flagged: _build_response_message (features/mocks/fake_backend_chat_model.py:88-91) already asserts prompt_tokens/completion_tokens are set together or both None, but _build_stream_chunk just fell through to the no-usage-metadata branch on a partial pair instead of failing fast. Added the identical assert to _build_stream_chunk, immediately before its is_last branch.
    No scenario currently constructs a partial pair, so this is a pure fail-fast tightening with no behavioral change today — it only prevents a future misconfigured mock from silently producing usage-less streaming. Re-verified scoped: nox -s unit_tests -- features/virtual_provider.feature → 1 feature, 49 scenarios, 153 steps, all passed. nox -s lint and nox -s typecheck both clean (the one typecheck warning is the same pre-existing, unrelated langchain_google_genai import warning noted in both your reviews). Coverage delta scoped to the same feature: llm_virtual_provider.py 99.57%, the same single pre-existing/unrelated uncovered line (llm_virtual_provider.py:510) as before — no regression.

  2. PR description test-plan counts are stale — NOT done (tooling restriction on my end, not a disagreement).
    You're right that the description still reports the pre-amendment 3387 scenarios / 15601 steps instead of 3390/15611. I attempted to patch the PR body via the Forgejo API to correct this, but my own tooling's auto-mode permission layer blocked that specific call as an unscoped external-system write (PR-description edits weren't explicitly requested by my operator for this pass). I'm flagging it here rather than silently skipping it: the accurate current counts are 160 features, 3390 scenarios, 15611 steps (unchanged by the nit-1 fix above, since it adds no new scenario — it only tightens an existing step's assertion), and three new scenarios now exist versus the stale description's "one": the streaming-path scenario, the two AC3 carve-out scenarios (counted as one bullet originally), and the backend-list construction-time validator scenario. If you'd like, I can have my operator explicitly authorize the description edit in a follow-up pass, or you/another maintainer can correct it directly — either way it's cosmetic only and doesn't affect mergeability.

Housekeeping

  • The commit was amended in place (not a new commit, per this project's single-commit-per-issue convention) from d4bb0d5 to 6f15fa4 and force-pushed to bugfix/m1-virtual-provider-cost-attribution. The commit message's trailing paragraph documents the nit-1 change and its scoped re-verification, consistent with how the earlier review-response paragraphs were recorded in the same commit.
  • Re: the "submitting independent PRs" item referenced in my own prior reply's "Not acted on" section — confirmed (again) that no such comment exists anywhere in this PR's review or comment thread. Nothing to action; noting it here only to close the loop on my own earlier aside.

No other outstanding items from either review remain unaddressed on my side. Let me know if the description edit should be done now or left as-is.

@hurui200320 Thanks for the re-review and approval. Before touching anything I re-checked both reviews against issue #159's acceptance criteria, `docs/index.md` §4.4.7, and both `docs/adr/ADR-2038-*` documents, then independently re-derived (not just trusted) that the Major/Minor items from the first review were genuinely present in the code — they were, matching your approval. This reply covers the two remaining **Nits** from your approving review, plus one housekeeping item. ### Nits from the approving review 1. **`_build_stream_chunk` silently drops a partially-set token pair — DONE.** Confirmed the asymmetry you flagged: `_build_response_message` (`features/mocks/fake_backend_chat_model.py:88-91`) already asserts `prompt_tokens`/`completion_tokens` are set together or both `None`, but `_build_stream_chunk` just fell through to the no-usage-metadata branch on a partial pair instead of failing fast. Added the identical assert to `_build_stream_chunk`, immediately before its `is_last` branch. No scenario currently constructs a partial pair, so this is a pure fail-fast tightening with no behavioral change today — it only prevents a future misconfigured mock from silently producing usage-less streaming. Re-verified scoped: `nox -s unit_tests -- features/virtual_provider.feature` → 1 feature, 49 scenarios, 153 steps, all passed. `nox -s lint` and `nox -s typecheck` both clean (the one typecheck warning is the same pre-existing, unrelated `langchain_google_genai` import warning noted in both your reviews). Coverage delta scoped to the same feature: `llm_virtual_provider.py` 99.57%, the same single pre-existing/unrelated uncovered line (`llm_virtual_provider.py:510`) as before — no regression. 2. **PR description test-plan counts are stale — NOT done (tooling restriction on my end, not a disagreement).** You're right that the description still reports the pre-amendment `3387 scenarios / 15601 steps` instead of `3390/15611`. I attempted to patch the PR body via the Forgejo API to correct this, but my own tooling's auto-mode permission layer blocked that specific call as an unscoped external-system write (PR-description edits weren't explicitly requested by my operator for this pass). I'm flagging it here rather than silently skipping it: the accurate current counts are **160 features, 3390 scenarios, 15611 steps** (unchanged by the nit-1 fix above, since it adds no new scenario — it only tightens an existing step's assertion), and three new scenarios now exist versus the stale description's "one": the streaming-path scenario, the two AC3 carve-out scenarios (counted as one bullet originally), and the backend-list construction-time validator scenario. If you'd like, I can have my operator explicitly authorize the description edit in a follow-up pass, or you/another maintainer can correct it directly — either way it's cosmetic only and doesn't affect mergeability. ### Housekeeping - The commit was **amended in place** (not a new commit, per this project's single-commit-per-issue convention) from `d4bb0d5` to `6f15fa4` and force-pushed to `bugfix/m1-virtual-provider-cost-attribution`. The commit message's trailing paragraph documents the nit-1 change and its scoped re-verification, consistent with how the earlier review-response paragraphs were recorded in the same commit. - Re: the "submitting independent PRs" item referenced in my own prior reply's "Not acted on" section — confirmed (again) that no such comment exists anywhere in this PR's review or comment thread. Nothing to action; noting it here only to close the loop on my own earlier aside. No other outstanding items from either review remain unaddressed on my side. Let me know if the description edit should be done now or left as-is.
CoreRasurae force-pushed bugfix/m1-virtual-provider-cost-attribution from 6f15fa48eb
Some checks failed
CI / lint (pull_request) Successful in 48s
CI / typecheck (pull_request) Successful in 1m24s
CI / security (pull_request) Successful in 1m9s
CI / quality (pull_request) Successful in 1m53s
CI / build (pull_request) Successful in 2m16s
CI / integration_tests (pull_request) Successful in 3m19s
CI / unit_tests (pull_request) Successful in 7m53s
CI / benchmark (pull_request) Has been cancelled
CI / coverage (pull_request) Successful in 6m27s
CI / status-check (pull_request) Successful in 2s
to 11af53405e
Some checks failed
CI / lint (pull_request) Successful in 1m14s
CI / typecheck (pull_request) Successful in 1m49s
CI / security (pull_request) Successful in 1m50s
CI / build (pull_request) Successful in 1m55s
CI / quality (pull_request) Successful in 2m19s
CI / benchmark (pull_request) Failing after 31m38s
CI / lint (push) Successful in 43s
CI / security (push) Successful in 1m3s
CI / quality (push) Successful in 1m13s
CI / build (push) Successful in 3m17s
CI / typecheck (push) Successful in 2m29s
CI / unit_tests (push) Successful in 6m55s
CI / integration_tests (push) Successful in 2m51s
CI / coverage (push) Successful in 6m33s
CI / status-check (push) Successful in 1s
CI / benchmark (push) Successful in 29m15s
CI / unit_tests (pull_request) Successful in 6m47s
CI / integration_tests (pull_request) Successful in 4m6s
CI / coverage (pull_request) Successful in 7m27s
CI / status-check (pull_request) Successful in 1s
2026-12-03 17:06:46 +00:00
Compare
CoreRasurae deleted branch bugfix/m1-virtual-provider-cost-attribution 2026-12-03 20:50:24 +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!204
No description provided.