fix(examples): wrap chat_model ainvoke/astream logging exactly once per instance #186

Merged
CoreRasurae merged 1 commit from bugfix/m1-llm-request-log-duplication into develop 2026-11-25 11:20:58 +00:00
Member

Summary

Fixes #173: examples/test_app.py's _setup_request_logging() AOP patch re-wrapped chat_model.ainvoke/astream on every _ensure_chat_model() call instead of once per chat model instance. Because LLMAgent.chat_model re-invokes _ensure_chat_model() on every access (not just once per LLMAgent), each real LLM call in a session stacked another logging layer, so the Nth real call was logged N times in llm_requests.log -- a growing multiplier that made the log actively misleading, with no change to actual outbound API calls or token spend.

An instance-level guard (_request_logging_wrapped, set via object.__setattr__ the same way ainvoke/astream already are) ensures each chat_model instance is wrapped exactly once, regardless of how many times _ensure_chat_model() subsequently runs on the owning agent.

Companion TDD issue #174 (merged to develop in commit d7936cd) already added the failing-first Behave scenario tagged @tdd_issue @tdd_issue_173 @tdd_expected_fail. This PR removes @tdd_expected_fail now that the assertion passes normally, and updates the scenario/feature wording to describe the fixed behavior.

Test plan

  • nox -s lint / nox -s format -- --check -- green
  • nox -s typecheck -- green, zero suppressions
  • nox -s unit_tests -- green, including the now-passing @tdd_issue_173 scenario
  • nox -s coverage_report -- 97.3% (>= 96.5% threshold)
  • nox -s security_scan / nox -s dead_code -- green
  • nox -s complexity -- green
  • nox -s integration_tests (Robot Framework) -- green
  • nox -s build -- wheel builds successfully
  • nox -s docs -- MkDocs builds successfully
  • nox -s benchmark / nox -s benchmark_regression are informational-only (CI continue-on-error) and not exercised meaningfully by this change (touches only examples/ and features/, not src/cleveractors)

Closes #173

## Summary Fixes #173: `examples/test_app.py`'s `_setup_request_logging()` AOP patch re-wrapped `chat_model.ainvoke`/`astream` on every `_ensure_chat_model()` call instead of once per chat model instance. Because `LLMAgent.chat_model` re-invokes `_ensure_chat_model()` on every access (not just once per `LLMAgent`), each real LLM call in a session stacked another logging layer, so the Nth real call was logged N times in `llm_requests.log` -- a growing multiplier that made the log actively misleading, with no change to actual outbound API calls or token spend. An instance-level guard (`_request_logging_wrapped`, set via `object.__setattr__` the same way `ainvoke`/`astream` already are) ensures each `chat_model` instance is wrapped exactly once, regardless of how many times `_ensure_chat_model()` subsequently runs on the owning agent. Companion TDD issue #174 (merged to `develop` in commit d7936cd) already added the failing-first Behave scenario tagged `@tdd_issue @tdd_issue_173 @tdd_expected_fail`. This PR removes `@tdd_expected_fail` now that the assertion passes normally, and updates the scenario/feature wording to describe the fixed behavior. ## Test plan - [x] `nox -s lint` / `nox -s format -- --check` -- green - [x] `nox -s typecheck` -- green, zero suppressions - [x] `nox -s unit_tests` -- green, including the now-passing `@tdd_issue_173` scenario - [x] `nox -s coverage_report` -- 97.3% (>= 96.5% threshold) - [x] `nox -s security_scan` / `nox -s dead_code` -- green - [x] `nox -s complexity` -- green - [x] `nox -s integration_tests` (Robot Framework) -- green - [x] `nox -s build` -- wheel builds successfully - [x] `nox -s docs` -- MkDocs builds successfully - `nox -s benchmark` / `nox -s benchmark_regression` are informational-only (CI `continue-on-error`) and not exercised meaningfully by this change (touches only `examples/` and `features/`, not `src/cleveractors`) Closes #173
CoreRasurae added this to the v2.1.0 milestone 2026-11-21 20:34:15 +00:00
fix(examples): wrap chat_model ainvoke/astream logging exactly once per instance
Some checks failed
CI / lint (pull_request) Successful in 47s
CI / typecheck (pull_request) Successful in 1m59s
CI / security (pull_request) Successful in 1m46s
CI / build (pull_request) Successful in 1m33s
CI / quality (pull_request) Successful in 2m21s
CI / unit_tests (pull_request) Successful in 7m5s
CI / coverage (pull_request) Successful in 7m10s
CI / benchmark (pull_request) Failing after 31m56s
CI / integration_tests (pull_request) Successful in 3m31s
CI / status-check (pull_request) Successful in 2s
807cb28849
LLMAgent.chat_model re-invokes _ensure_chat_model() on every access, not
just once per LLMAgent instance, so examples/test_app.py's
_patched_ensure_chat_model AOP hook ran on every real LLM call made
during a process's lifetime. Each run re-wrapped chat_model.ainvoke/
astream unconditionally, stacking a fresh logging layer on top of any
previous one -- the Nth real LLM call in a session logged N nested
request/response pairs instead of one, inflating llm_requests.log with
a growing multiplier and making it actively misleading when diagnosing
a run.

Adds an instance-level guard (_request_logging_wrapped, set via
object.__setattr__ to survive Pydantic/frozen chat model instances) so
ainvoke/astream are wrapped exactly once per chat_model object,
regardless of how many times _ensure_chat_model() subsequently runs on
the owning LLMAgent. No change to the number of outbound LLM API calls
or token usage -- this was a logging-only defect.

Removes @tdd_expected_fail from the @tdd_issue_173 scenario in
features/request_logging_wrapper.feature now that the underlying
assertion passes normally, and updates the scenario/feature wording to
describe the fixed behavior.

ISSUES CLOSED: #173
hurui200320 left a comment

PR Review: !186 (Ticket #173)

Verdict: Approve

Verified locally on bugfix/m1-llm-request-log-duplication (commit 807cb28): nox -s lint, nox -s typecheck (0 errors), and the full Behave suite via nox -s coverage_report all pass, with coverage at 97.3% (threshold 96.5%) — matching the PR's claim. The @tdd_issue_173 scenario now passes genuinely (6/6 steps, no inversion) after the @tdd_expected_fail removal, which is exactly the step CONTRIBUTING's Bug Fix Workflow prescribes for the fix developer. Process bookkeeping (PR base develop vs the ticket DoD's "PR to master" wording, labels, dependency links) is consciously excluded from this review per reviewer instruction; the author's issue comment documents the develop target explicitly.

Critical Issues

None

Major Issues

None

Minor Issues

None

Nits

  1. features/request_logging_wrapper.feature:15 — The re-wrap guard is only exercised through ainvoke; no scenario drives astream after two _ensure_chat_model() invocations. Ticket #173's expected behavior also covers the streaming case ("exactly one LLM STREAM REQUEST: / LLM STREAM RESPONSE: pair"), even though its acceptance criteria only required the ainvoke scenario, so this is compliant. Both paths share the same early return, so this is purely an optional suite-strengthening suggestion (a mirrored streaming scenario asserting exactly one LLM STREAM REQUEST/LLM STREAM RESPONSE pair).

  2. examples/test_app.py:121-190 — The _request_logging_wrapped check-and-set is not synchronized: two OS threads reaching the chat_model property concurrently could both pass the guard and stack two wrapper layers (bounded at 2, versus unbounded before the fix). This is unreachable in practice for the single-event-loop example CLI because the wrap section contains no await points, so it cannot interleave within one event loop; noting only for completeness. If ever hardened, hold self._chat_model_lock around the check+set.

Summary

A small, well-scoped fix that implements exactly what ticket #173 prescribes. The instance-level marker handles every chat-model lifecycle path I traced: first access wraps once; every subsequent chat_model property access short-circuits on the marker; a model re-injected via the chat_model setter, or re-created after cleanup (self._chat_model = None in LLMAgent), lacks the marker and is wrapped exactly once; and a VirtualChatModel (the outer instance cached in _chat_model) is wrapped once regardless of backend rotation, so every routed call still logs exactly once. The guard correctly runs after _original_ensure_chat_model(self), so lazy creation is unaffected, and the docstring/feature-file wording accurately describe the fixed behavior.

The Behave scenario (from companion TDD PR, merged as d7936cd) is meaningful, not tautological: it invokes the real patched class-level hook twice, then a real Pydantic BaseChatModel fake once, and counts actual logging records — and the TDD-capture merge proves the assertion genuinely failed on unfixed code (the stale-tag policy would have failed CI otherwise). The @tdd_expected_fail removal leaves the required @tdd_issue/@tdd_issue_173 tags in place per the tag policy. The CHANGELOG entry is correctly placed under [Unreleased] > Fixed with the issue reference. Commit hygiene is clean: single atomic commit, first line matches the ticket Metadata's Commit Message verbatim, ISSUES CLOSED: #173 footer present, branch name matches Metadata, no merge commits, based on the current develop head. Robot integration tests do not reference the changed files. Robot/integration green status is taken from the author's reported run, per review policy.

Approved — the two nits above are non-blocking suggestions.

## PR Review: !186 (Ticket #173) ### Verdict: Approve Verified locally on `bugfix/m1-llm-request-log-duplication` (commit 807cb28): `nox -s lint`, `nox -s typecheck` (0 errors), and the full Behave suite via `nox -s coverage_report` all pass, with coverage at **97.3%** (threshold 96.5%) — matching the PR's claim. The `@tdd_issue_173` scenario now passes genuinely (6/6 steps, no inversion) after the `@tdd_expected_fail` removal, which is exactly the step CONTRIBUTING's Bug Fix Workflow prescribes for the fix developer. Process bookkeeping (PR base `develop` vs the ticket DoD's "PR to master" wording, labels, dependency links) is consciously excluded from this review per reviewer instruction; the author's issue comment documents the `develop` target explicitly. ### Critical Issues None ### Major Issues None ### Minor Issues None ### Nits 1. **`features/request_logging_wrapper.feature:15`** — The re-wrap guard is only exercised through `ainvoke`; no scenario drives `astream` after two `_ensure_chat_model()` invocations. Ticket #173's *expected behavior* also covers the streaming case ("exactly one `LLM STREAM REQUEST:` / `LLM STREAM RESPONSE:` pair"), even though its acceptance criteria only required the `ainvoke` scenario, so this is compliant. Both paths share the same early return, so this is purely an optional suite-strengthening suggestion (a mirrored streaming scenario asserting exactly one `LLM STREAM REQUEST`/`LLM STREAM RESPONSE` pair). 2. **`examples/test_app.py:121-190`** — The `_request_logging_wrapped` check-and-set is not synchronized: two OS threads reaching the `chat_model` property concurrently could both pass the guard and stack two wrapper layers (bounded at 2, versus unbounded before the fix). This is unreachable in practice for the single-event-loop example CLI because the wrap section contains no `await` points, so it cannot interleave within one event loop; noting only for completeness. If ever hardened, hold `self._chat_model_lock` around the check+set. ### Summary A small, well-scoped fix that implements exactly what ticket #173 prescribes. The instance-level marker handles every chat-model lifecycle path I traced: first access wraps once; every subsequent `chat_model` property access short-circuits on the marker; a model re-injected via the `chat_model` setter, or re-created after cleanup (`self._chat_model = None` in `LLMAgent`), lacks the marker and is wrapped exactly once; and a `VirtualChatModel` (the outer instance cached in `_chat_model`) is wrapped once regardless of backend rotation, so every routed call still logs exactly once. The guard correctly runs *after* `_original_ensure_chat_model(self)`, so lazy creation is unaffected, and the docstring/feature-file wording accurately describe the fixed behavior. The Behave scenario (from companion TDD PR, merged as d7936cd) is meaningful, not tautological: it invokes the real patched class-level hook twice, then a real Pydantic `BaseChatModel` fake once, and counts actual `logging` records — and the TDD-capture merge proves the assertion genuinely failed on unfixed code (the stale-tag policy would have failed CI otherwise). The `@tdd_expected_fail` removal leaves the required `@tdd_issue`/`@tdd_issue_173` tags in place per the tag policy. The CHANGELOG entry is correctly placed under `[Unreleased] > Fixed` with the issue reference. Commit hygiene is clean: single atomic commit, first line matches the ticket Metadata's Commit Message verbatim, `ISSUES CLOSED: #173` footer present, branch name matches Metadata, no merge commits, based on the current `develop` head. Robot integration tests do not reference the changed files. Robot/integration green status is taken from the author's reported run, per review policy. **Approved** — the two nits above are non-blocking suggestions.
CoreRasurae deleted branch bugfix/m1-llm-request-log-duplication 2026-11-25 11:20:59 +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!186
No description provided.