test(examples): capture duplicate LLM request/response log entries bug (#173) #179

Merged
CoreRasurae merged 1 commit from tdd/m1-llm-request-log-duplication into develop 2026-11-20 12:19:46 +00:00
Member

Summary

TDD issue-capture test for bug #173: examples/test_app.py's _setup_request_logging() monkey-patches LLMAgent._ensure_chat_model with _patched_ensure_chat_model, which re-wraps chat_model.ainvoke/astream on every call with no per-instance guard. Each call to _ensure_chat_model() stacks a fresh logging layer on top of any previous one, so the Nth call on the same chat model produces N nested wrappers and one real LLM call ends up logged N times in llm_requests.log.

Adds features/request_logging_wrapper.feature / features/steps/request_logging_wrapper_steps.py, a new pair (no existing step file covers examples/test_app.py's logging patch). The scenario is tagged @tdd_issue @tdd_issue_173 @tdd_expected_fail: it installs the real patch against an LLMAgent wired to a FakeBackendChatModel (no real network call), invokes the patched _ensure_chat_model() twice on the same instance, calls ainvoke() once, and asserts exactly one LLM REQUEST/LLM RESPONSE log line pair is recorded. The assertion fails on the current (unfixed) code — two layers produce two of each — so CI passes only via the @tdd_expected_fail inversion until the real fix (#173) lands.

Per the project's mandatory Bug Fix TDD Workflow, this TDD test must merge before the fix PR for #173.

Test plan

  • nox -s unit_tests — 160 features, 3327 scenarios, 0 failed (new scenario included, passes via @tdd_expected_fail inversion)
  • nox -s coverage_report — COVERAGE OK: 97.2% (threshold: 96.5%)
  • nox -s lint — clean
  • nox -s format -- --check — clean
  • nox -s typecheck — 0 errors
  • nox -s security_scan — no issues
  • nox -s dead_code — no issues

Closes #174

## Summary TDD issue-capture test for bug #173: `examples/test_app.py`'s `_setup_request_logging()` monkey-patches `LLMAgent._ensure_chat_model` with `_patched_ensure_chat_model`, which re-wraps `chat_model.ainvoke`/`astream` on every call with no per-instance guard. Each call to `_ensure_chat_model()` stacks a fresh logging layer on top of any previous one, so the Nth call on the same chat model produces N nested wrappers and one real LLM call ends up logged N times in `llm_requests.log`. Adds `features/request_logging_wrapper.feature` / `features/steps/request_logging_wrapper_steps.py`, a new pair (no existing step file covers `examples/test_app.py`'s logging patch). The scenario is tagged `@tdd_issue @tdd_issue_173 @tdd_expected_fail`: it installs the real patch against an `LLMAgent` wired to a `FakeBackendChatModel` (no real network call), invokes the patched `_ensure_chat_model()` twice on the same instance, calls `ainvoke()` once, and asserts exactly one `LLM REQUEST`/`LLM RESPONSE` log line pair is recorded. The assertion fails on the current (unfixed) code — two layers produce two of each — so CI passes only via the `@tdd_expected_fail` inversion until the real fix (#173) lands. Per the project's mandatory Bug Fix TDD Workflow, this TDD test must merge before the fix PR for #173. ## Test plan - [x] `nox -s unit_tests` — 160 features, 3327 scenarios, 0 failed (new scenario included, passes via `@tdd_expected_fail` inversion) - [x] `nox -s coverage_report` — COVERAGE OK: 97.2% (threshold: 96.5%) - [x] `nox -s lint` — clean - [x] `nox -s format -- --check` — clean - [x] `nox -s typecheck` — 0 errors - [x] `nox -s security_scan` — no issues - [x] `nox -s dead_code` — no issues Closes #174
test(examples): capture duplicate LLM request/response log entries bug (#173)
Some checks failed
CI / lint (pull_request) Successful in 34s
CI / typecheck (pull_request) Successful in 1m2s
CI / security (pull_request) Successful in 1m49s
CI / build (pull_request) Successful in 1m42s
CI / quality (pull_request) Successful in 2m31s
CI / integration_tests (pull_request) Successful in 3m39s
CI / unit_tests (pull_request) Successful in 5m3s
CI / coverage (pull_request) Successful in 6m1s
CI / status-check (pull_request) Successful in 1s
CI / benchmark (pull_request) Failing after 20m57s
dbcea1025a
Adds a failing-first Behave regression test proving issue #173:
examples/test_app.py's _setup_request_logging() installs
_patched_ensure_chat_model, an AOP intercept that re-wraps
chat_model.ainvoke/astream on every LLMAgent._ensure_chat_model() call.
The wrap logic has no per-instance guard, so each call stacks a fresh
logging layer on top of any previous one -- the Nth call on the same
chat model produces N nested wrappers, and one real LLM call ends up
logged N times in llm_requests.log.

New features/request_logging_wrapper.feature /
features/steps/request_logging_wrapper_steps.py pair (no existing
step file covers examples/test_app.py's logging patch, per the
project's step-file rules) adds a scenario tagged
@tdd_issue @tdd_issue_173 @tdd_expected_fail: it installs the real
patch against an LLMAgent wired to a FakeBackendChatModel (no real
network call), invokes the patched _ensure_chat_model() twice on the
same instance, calls ainvoke() once, and asserts exactly one LLM
REQUEST/RESPONSE log line pair is recorded. The assertion fails on
the current (unfixed) code -- two layers produce two of each -- so the
suite passes CI only via the @tdd_expected_fail inversion until the
real fix (#173) lands. Log records are captured with a dedicated
logging.Handler attached to the cleveractors.requests logger (rather
than reading llm_requests.log from disk), and every mutation this
Given step makes to global state (LLMAgent._ensure_chat_model, the
module's _request_logging_configured flag, and the logger's handlers)
is reverted via the existing context._active_patches cleanup hook so
nothing leaks into later scenarios in the same Behave process.

ISSUES CLOSED: #174
hurui200320 left a comment

PR Review: !179 (Ticket #174)

Verdict: Approve

This is a test-only TDD capture PR for bug #173, and it fully satisfies ticket #174's acceptance criteria. The bug reproduction was verified locally: the Then step's assertion fails on unfixed code with exactly the expected evidence (got 2 log pairs for one ainvoke call), and the @tdd_expected_fail inversion flips it to a pass. A full local nox -s unit_tests run is green (3327 scenarios, 0 failed — matching the PR's claim exactly), and nox -s lint / nox -s typecheck pass. No critical or major issues found.

Critical Issues

None

Major Issues

None

Minor Issues

  1. Incomplete global-state restore in _restore — features/steps/request_logging_wrapper_steps.py:75-81
    _setup_request_logging() (examples/test_app.py:182, 208, 223, 97) mutates five pieces of global state, but _restore only undoes three: it restores LLMAgent._ensure_chat_model, the _request_logging_configured flag, and logger handlers — but not LLMAgent._run_pruning_pass, not ToolAgent.process_message (both stay logging-wrapped for the rest of the Behave process), and not the cleveractors.requests logger level (stays at DEBUG). The PR description's claim that "nothing leaks into later scenarios" is therefore overstated.
    Impact today: zero — the leaked wrappers are pass-throughs that only log, and after cleanup the logger has no handlers so INFO records go nowhere; the full suite (including all scenarios alphabetically after this one) runs green. It remains a latent hygiene hazard for future tests that assert on that logger or on method identity, and the PR body shouldn't claim complete cleanup.
    Recommendation: capture and restore LLMAgent._run_pruning_pass, ToolAgent.process_message, and the logger's original level in _restore (ideally in the same commit or a fast-follow before merge).

Nits

  1. context.invocation_response captured but never asserted — features/steps/request_logging_wrapper_steps.py:113
    The captured response is unused. Asserting e.g. context.invocation_response.content == "duplicate-logging-fake" in the Then step would explicitly prove the wrapper chain is a pass-through returning the real fake result (currently only implied by the RESPONSE log lines being emitted).

Summary

Spec compliance / ticket coverage — all acceptance criteria of ticket #174 are met: scenario tagged @tdd_issue @tdd_issue_173 @tdd_expected_fail ✓; assertions use bare assert/AssertionError only ✓; the scenario fails on unfixed code and passes CI only via inversion ✓ (verified live); nox -s unit_tests green ✓; no new mocks outside features/mocks/ ✓ (reuses FakeBackendChatModel, so the "add a fake if new" subtask was correctly unnecessary). The bug-issue dependency required by the DoD exists (#173 is blocked-by #174) ✓. Commit message first line matches the issue's Metadata exactly and the footer references #174; branch name matches Metadata; single atomic commit, no merge commits.

Correctness — the scenario faithfully reproduces the reported mechanism: patch installed → chat_model injected via the property setter → patched _ensure_chat_model() invoked twice stacks wrapper₂(wrapper₁(real)) → one ainvoke yields 2 REQUEST + 2 RESPONSE records → == 1 assertions fail. Substring counting is safe ("LLM STREAM REQUEST" does not contain "LLM REQUEST"), and only ainvoke is exercised so no STREAM lines exist anyway. No step-text collisions with existing step files; context.scenario_temp is always created in before_scenario; context._active_patches cleanup calls .stop(), compatible with the SimpleNamespace(stop=_restore) registration. The temporary os.chdir is correctly restored in finally, and the FileHandler created inside scenario_temp is removed and closed, so no llm_requests.log leaks into the repo root.

Tests — the new feature/step pair follows the step-file naming rule (foo.feature ↔ foo_steps.py) and is the first coverage of examples/test_app.py's logging patch, as claimed. Coverage is unaffected by construction ([tool.coverage] source is src only); the PR's reported 97.2% ≥ 96.5% threshold stands. The AsyncMock RuntimeWarning visible at the end of the full-suite run also occurs with pre-existing scenarios and did not appear in an isolated run of the new feature, so it is not attributable to this PR.

PR-discussion check — the PR has no comments, reviews, or review threads yet, and neither #174 nor #173 records any decision marking an item out-of-scope or deferred, so nothing was excluded on those grounds. Per reviewer instructions, red-tape items (labels, base-branch workflow choice — develop is where recent PRs #172/#169 merged) were excluded from this review.

Verification performed locally: nox -s unit_tests (full suite: 3327 scenarios, 0 failed), isolated run of features/request_logging_wrapper.feature (assertion correctly fails with got 2, inverted to pass), nox -s lint (clean), nox -s typecheck (0 errors).

## PR Review: !179 (Ticket #174) ### Verdict: Approve This is a test-only TDD capture PR for bug #173, and it fully satisfies ticket #174's acceptance criteria. The bug reproduction was **verified locally**: the `Then` step's assertion fails on unfixed code with exactly the expected evidence (`got 2` log pairs for one `ainvoke` call), and the `@tdd_expected_fail` inversion flips it to a pass. A full local `nox -s unit_tests` run is green (**3327 scenarios, 0 failed** — matching the PR's claim exactly), and `nox -s lint` / `nox -s typecheck` pass. No critical or major issues found. ### Critical Issues None ### Major Issues None ### Minor Issues 1. **Incomplete global-state restore in `_restore`** — `features/steps/request_logging_wrapper_steps.py:75-81` `_setup_request_logging()` (examples/test_app.py:182, 208, 223, 97) mutates **five** pieces of global state, but `_restore` only undoes three: it restores `LLMAgent._ensure_chat_model`, the `_request_logging_configured` flag, and logger handlers — but **not** `LLMAgent._run_pruning_pass`, **not** `ToolAgent.process_message` (both stay logging-wrapped for the rest of the Behave process), and **not** the `cleveractors.requests` logger level (stays at `DEBUG`). The PR description's claim that "nothing leaks into later scenarios" is therefore overstated. *Impact today: zero* — the leaked wrappers are pass-throughs that only log, and after cleanup the logger has no handlers so INFO records go nowhere; the full suite (including all scenarios alphabetically after this one) runs green. It remains a latent hygiene hazard for future tests that assert on that logger or on method identity, and the PR body shouldn't claim complete cleanup. *Recommendation:* capture and restore `LLMAgent._run_pruning_pass`, `ToolAgent.process_message`, and the logger's original level in `_restore` (ideally in the same commit or a fast-follow before merge). ### Nits 1. **`context.invocation_response` captured but never asserted** — `features/steps/request_logging_wrapper_steps.py:113` The captured response is unused. Asserting e.g. `context.invocation_response.content == "duplicate-logging-fake"` in the `Then` step would explicitly prove the wrapper chain is a pass-through returning the real fake result (currently only implied by the RESPONSE log lines being emitted). ### Summary **Spec compliance / ticket coverage** — all acceptance criteria of ticket #174 are met: scenario tagged `@tdd_issue @tdd_issue_173 @tdd_expected_fail` ✓; assertions use bare `assert`/`AssertionError` only ✓; the scenario fails on unfixed code and passes CI only via inversion ✓ (verified live); `nox -s unit_tests` green ✓; no new mocks outside `features/mocks/` ✓ (reuses `FakeBackendChatModel`, so the "add a fake if new" subtask was correctly unnecessary). The bug-issue dependency required by the DoD exists (#173 is blocked-by #174) ✓. Commit message first line matches the issue's Metadata exactly and the footer references #174; branch name matches Metadata; single atomic commit, no merge commits. **Correctness** — the scenario faithfully reproduces the reported mechanism: patch installed → `chat_model` injected via the property setter → patched `_ensure_chat_model()` invoked twice stacks wrapper₂(wrapper₁(real)) → one `ainvoke` yields 2 REQUEST + 2 RESPONSE records → `== 1` assertions fail. Substring counting is safe (`"LLM STREAM REQUEST"` does not contain `"LLM REQUEST"`), and only `ainvoke` is exercised so no STREAM lines exist anyway. No step-text collisions with existing step files; `context.scenario_temp` is always created in `before_scenario`; `context._active_patches` cleanup calls `.stop()`, compatible with the `SimpleNamespace(stop=_restore)` registration. The temporary `os.chdir` is correctly restored in `finally`, and the FileHandler created inside `scenario_temp` is removed and closed, so no `llm_requests.log` leaks into the repo root. **Tests** — the new feature/step pair follows the step-file naming rule (`foo.feature` ↔ `foo_steps.py`) and is the first coverage of `examples/test_app.py`'s logging patch, as claimed. Coverage is unaffected by construction ([tool.coverage] source is `src` only); the PR's reported 97.2% ≥ 96.5% threshold stands. The `AsyncMock` RuntimeWarning visible at the end of the full-suite run also occurs with pre-existing scenarios and did not appear in an isolated run of the new feature, so it is not attributable to this PR. **PR-discussion check** — the PR has no comments, reviews, or review threads yet, and neither #174 nor #173 records any decision marking an item out-of-scope or deferred, so nothing was excluded on those grounds. Per reviewer instructions, red-tape items (labels, base-branch workflow choice — `develop` is where recent PRs #172/#169 merged) were excluded from this review. **Verification performed locally:** `nox -s unit_tests` (full suite: 3327 scenarios, 0 failed), isolated run of `features/request_logging_wrapper.feature` (assertion correctly fails with `got 2`, inverted to pass), `nox -s lint` (clean), `nox -s typecheck` (0 errors).
@ -0,0 +72,4 @@
and handler not in pre_existing_file_handlers
]
def _restore() -> None:
Member

Minor: _setup_request_logging() also patches LLMAgent._run_pruning_pass and ToolAgent.process_message (test_app.py:208/223) and sets the cleveractors.requests logger to DEBUG (line 97), none of which are restored here. Impact today is zero (pass-through wrappers, no handlers after cleanup — full suite verified green), but they leak for the rest of the Behave process and the PR body's "nothing leaks into later scenarios" claim is overstated. Suggest restoring these too.

Minor: `_setup_request_logging()` also patches `LLMAgent._run_pruning_pass` and `ToolAgent.process_message` (test_app.py:208/223) and sets the `cleveractors.requests` logger to DEBUG (line 97), none of which are restored here. Impact today is zero (pass-through wrappers, no handlers after cleanup — full suite verified green), but they leak for the rest of the Behave process and the PR body's "nothing leaks into later scenarios" claim is overstated. Suggest restoring these too.
@ -0,0 +110,4 @@
async def _run() -> Any:
return await context.fake_chat_model.ainvoke([HumanMessage(content="hi")])
context.invocation_response = asyncio.run(_run())
Member

Nit: context.invocation_response is captured but never asserted. Asserting context.invocation_response.content == "duplicate-logging-fake" in the Then step would explicitly prove the stacked wrapper chain is a pass-through returning the real fake result.

Nit: `context.invocation_response` is captured but never asserted. Asserting `context.invocation_response.content == "duplicate-logging-fake"` in the Then step would explicitly prove the stacked wrapper chain is a pass-through returning the real fake result.
CoreRasurae force-pushed tdd/m1-llm-request-log-duplication from dbcea1025a
Some checks failed
CI / lint (pull_request) Successful in 34s
CI / typecheck (pull_request) Successful in 1m2s
CI / security (pull_request) Successful in 1m49s
CI / build (pull_request) Successful in 1m42s
CI / quality (pull_request) Successful in 2m31s
CI / integration_tests (pull_request) Successful in 3m39s
CI / unit_tests (pull_request) Successful in 5m3s
CI / coverage (pull_request) Successful in 6m1s
CI / status-check (pull_request) Successful in 1s
CI / benchmark (pull_request) Failing after 20m57s
to d7936cdd84
Some checks failed
CI / lint (pull_request) Successful in 1m26s
CI / typecheck (pull_request) Successful in 2m13s
CI / build (pull_request) Successful in 1m44s
CI / quality (pull_request) Successful in 2m1s
CI / security (pull_request) Successful in 2m34s
CI / integration_tests (pull_request) Successful in 3m15s
CI / benchmark (pull_request) Failing after 19m57s
CI / unit_tests (pull_request) Successful in 6m48s
CI / coverage (pull_request) Successful in 6m51s
CI / status-check (pull_request) Successful in 1s
CI / quality (push) Successful in 43s
CI / lint (push) Successful in 55s
CI / build (push) Successful in 56s
CI / security (push) Successful in 1m42s
CI / typecheck (push) Successful in 2m17s
CI / integration_tests (push) Successful in 2m38s
CI / unit_tests (push) Successful in 6m20s
CI / coverage (push) Successful in 6m53s
CI / status-check (push) Successful in 6s
CI / benchmark (push) Failing after 20m31s
2026-11-20 11:43:57 +00:00
Compare
CoreRasurae left a comment

@hurui200320 Thanks for the review (#9876) — both findings checked out and are addressed in the latest push (d7936cd). Before applying anything, I cross-checked both against docs/index.md, the docs/adr/* ADRs, and issues #173/#174: none of them cover examples/test_app.py or this test harness (it's example/tooling code, explicitly out of core-spec scope per #173's own "Supporting information" section), so there was no specification conflict to resolve either way — both were purely test-hygiene findings and both are correct as written.

Minor — incomplete global-state restore (addressed)

Confirmed by reading _setup_request_logging() directly: it mutates five pieces of global state, and _restore() only undid three. Fixed in features/steps/request_logging_wrapper_steps.py's step_install_request_logging_patch — _restore() now also captures and restores:

  • LLMAgent._run_pruning_pass (back to the pre-patch original)
  • ToolAgent.process_message (back to the pre-patch original)
  • the cleveractors.requests logger's level (back to whatever it was before setLevel(logging.DEBUG))

alongside the three it already handled (LLMAgent._ensure_chat_model, _request_logging_configured, the added FileHandlers). The PR body's "nothing leaks into later scenarios" claim is now actually true rather than overstated.

Nit — unasserted invocation_response (addressed)

Added a new Then step, the agent's chat model invocation should return the fake backend's response, asserting context.invocation_response.content == "duplicate-logging-fake" — wired into the scenario in features/request_logging_wrapper.feature right after the existing log-count assertion, exactly as suggested. One transparency note: in the current (unfixed) state this new step doesn't actually execute yet, because the preceding log-count assertion still fails first and Behave skips the remaining steps in the scenario — the suite still passes overall only via the @tdd_expected_fail inversion. The assertion is correctly wired and will exercise for real once the actual fix lands on bugfix/m1-llm-request-log-duplication and the preceding step starts passing.

Not changed

Nothing from this review was skipped or rejected — both findings were accepted as-is, with no spec objection raised against either.

Verification

  • nox -s lint — clean
  • nox -s typecheck — 0 errors
  • nox -s unit_tests — 160 features / 3351 scenarios / 15424 steps passed, 0 failed. The TDD scenario still fails its underlying assertion pre-fix (got 2) exactly as before, confirming the fix didn't accidentally paper over the bug it's supposed to prove.
  • Coverage: not re-run — both changes are test-only (features/steps/request_logging_wrapper_steps.py + the .feature file), and [tool.coverage] scopes Slipcover to src only, so there is no production coverage delta from this change.
  • No CHANGELOG.md entry added — this is a test-only commit and the project's changelog rule exempts tests.

The local commit was amended in place (no new commit; this branch carries a single atomic commit) and force-pushed. PR head is now d7936cd.

@hurui200320 Thanks for the review (#9876) — both findings checked out and are addressed in the latest push (`d7936cd`). Before applying anything, I cross-checked both against `docs/index.md`, the `docs/adr/*` ADRs, and issues #173/#174: none of them cover `examples/test_app.py` or this test harness (it's example/tooling code, explicitly out of core-spec scope per #173's own "Supporting information" section), so there was no specification conflict to resolve either way — both were purely test-hygiene findings and both are correct as written. ### Minor — incomplete global-state restore (addressed) Confirmed by reading `_setup_request_logging()` directly: it mutates five pieces of global state, and `_restore()` only undid three. Fixed in `features/steps/request_logging_wrapper_steps.py`'s `step_install_request_logging_patch` — `_restore()` now also captures and restores: - `LLMAgent._run_pruning_pass` (back to the pre-patch original) - `ToolAgent.process_message` (back to the pre-patch original) - the `cleveractors.requests` logger's level (back to whatever it was before `setLevel(logging.DEBUG)`) alongside the three it already handled (`LLMAgent._ensure_chat_model`, `_request_logging_configured`, the added `FileHandler`s). The PR body's "nothing leaks into later scenarios" claim is now actually true rather than overstated. ### Nit — unasserted `invocation_response` (addressed) Added a new `Then` step, `the agent's chat model invocation should return the fake backend's response`, asserting `context.invocation_response.content == "duplicate-logging-fake"` — wired into the scenario in `features/request_logging_wrapper.feature` right after the existing log-count assertion, exactly as suggested. One transparency note: in the current (unfixed) state this new step doesn't actually execute yet, because the preceding log-count assertion still fails first and Behave skips the remaining steps in the scenario — the suite still passes overall only via the `@tdd_expected_fail` inversion. The assertion is correctly wired and will exercise for real once the actual fix lands on `bugfix/m1-llm-request-log-duplication` and the preceding step starts passing. ### Not changed Nothing from this review was skipped or rejected — both findings were accepted as-is, with no spec objection raised against either. ### Verification - `nox -s lint` — clean - `nox -s typecheck` — 0 errors - `nox -s unit_tests` — 160 features / 3351 scenarios / 15424 steps passed, 0 failed. The TDD scenario still fails its underlying assertion pre-fix (`got 2`) exactly as before, confirming the fix didn't accidentally paper over the bug it's supposed to prove. - Coverage: not re-run — both changes are test-only (`features/steps/request_logging_wrapper_steps.py` + the `.feature` file), and `[tool.coverage]` scopes Slipcover to `src` only, so there is no production coverage delta from this change. - No `CHANGELOG.md` entry added — this is a test-only commit and the project's changelog rule exempts tests. The local commit was amended in place (no new commit; this branch carries a single atomic commit) and force-pushed. PR head is now `d7936cd`.
CoreRasurae deleted branch tdd/m1-llm-request-log-duplication 2026-11-20 12:19:47 +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!179
No description provided.