examples/test_app.py: LLM request/response logging wrapper re-wraps chat_model.ainvoke/astream on every chat_model access, duplicating LLM REQUEST/RESPONSE log lines #173

Closed
opened 2026-11-19 16:14:14 +00:00 by CoreRasurae · 2 comments
Member

Metadata

Commit Message: fix(examples): wrap chat_model ainvoke/astream logging exactly once per instance
Branch: bugfix/m1-llm-request-log-duplication

Background and context

examples/test_app.py's _setup_request_logging() installs an AOP intercept (_patched_ensure_chat_model) that monkey-patches LLMAgent._ensure_chat_model to log every LLM request/response to llm_requests.log, purely for observability while running the example CLI. The top-level patch install is documented and guarded as idempotent (_request_logging_configured prevents the monkey-patch itself from being applied twice), but the body of the patched method has no equivalent guard around the per-chat-model wrap it performs.

Current behavior

LLMAgent.chat_model is a property whose getter calls self._ensure_chat_model() on every access (src/cleveractors/agents/llm.py). This means _ensure_chat_model() runs once for every real LLM call made during a process's lifetime, across every actor/node in a run -- not just once per LLMAgent instance.

Inside _patched_ensure_chat_model (examples/test_app.py), each invocation does, roughly:

original_ainvoke = chat_model.ainvoke   # captures whatever is CURRENTLY installed
...
object.__setattr__(chat_model, "ainvoke", wrapped_ainvoke)   # installs a NEW layer

There is no check for "is ainvoke/astream already wrapped?" before wrapping again. _original_ensure_chat_model only skips re-creating the underlying BaseChatModel once self._chat_model is set -- it does not prevent the patched method from re-running its wrap logic. So every real _ensure_chat_model() call across the whole run installs one more logging layer on top of the previous one(s).

Result: the Nth real LLM call in a session gets logged N times -- once per stacked wrapper layer -- all synchronously, before/after the single real network round-trip underneath. Observed directly in a production run of the example CLI (python test_app.py test --llm-protocol http --llm-ip <host> --llm-port 8000 --local-store packages --unsafe --prompt "..." --graph 80487-fpu-actor-tools-graph.yaml): one real completion (provider id: chatcmpl-d129c30def4d4b6b963b04f4, usage_metadata.total_tokens: 88909) was logged as 40 near-identical LLM REQUEST: / LLM RESPONSE: line pairs in llm_requests.log. Grouping every logged response in that run by its provider id confirms the pattern is systemic, not a one-off: successive real calls in the same run duplicated 44, 44, 42, 42, 40, 40, 40, 38, 38, 38... times, growing by roughly one extra layer per real call made so far.

This does not duplicate the actual outbound API calls or token spend -- confirmed: one real HTTP round-trip per group, identical token counts and completion id across every duplicate line in the group. But it inflates llm_requests.log by a large, growing multiplier, makes the log actively misleading when diagnosing a run (a single real response reads as if the model retried dozens of times), and log volume grows roughly with the square of the number of LLM calls in a long-running session.

Expected behavior

chat_model.ainvoke and chat_model.astream are wrapped for logging exactly once per chat_model instance, regardless of how many times _ensure_chat_model() is subsequently called on the owning LLMAgent. Each real LLM call produces exactly one LLM REQUEST: line and exactly one LLM RESPONSE: line (or exactly one LLM STREAM REQUEST: / LLM STREAM RESPONSE: pair for streaming) in llm_requests.log.

Acceptance criteria

  • Running the example CLI for a session with N real LLM calls produces exactly N LLM REQUEST: lines and N LLM RESPONSE: lines in llm_requests.log (1:1 -- no growth multiplier).
  • Calling _ensure_chat_model() more than once on the same LLMAgent (e.g. once per turn in the interactive loop, or once per node execution across a graph run) does not add additional logging layers to an already-wrapped chat_model.
  • A Behave scenario proves the fix: invoking the patched _ensure_chat_model() twice on the same LLMAgent/chat_model instance and then calling ainvoke once results in exactly one logged request and one logged response.
  • No change to the actual number of outbound LLM API calls or token usage -- this is a logging-only defect.

Supporting information

  • Affected function: _setup_request_logging._patched_ensure_chat_model in examples/test_app.py.
  • Underlying property that triggers the repeated wrap on every real call: LLMAgent.chat_model / LLMAgent._ensure_chat_model in src/cleveractors/agents/llm.py (this part of the core library is correct and not implicated -- it only guards re-creation of self._chat_model, which is a separate, working concern).
  • Captured evidence: a local log excerpt (llm_requests_prematurely_eneded_the_execution.log) from a CleverActors CLI run that also hit an unrelated, separately-tracked failure (a file_write tool call receiving a corrupted path argument) -- that second issue is out of scope here and is not part of this ticket.
  • This defect lives entirely in example/tooling code (examples/), not in src/cleveractors/ runtime code.

Subtasks

  • Add an instance-level guard (e.g. getattr(chat_model, "_request_logging_wrapped", False) / object.__setattr__(chat_model, "_request_logging_wrapped", True)) in _patched_ensure_chat_model so ainvoke and astream are wrapped only once per chat_model object.
  • Tests (Behave): add a scenario in features/ that calls the patched _ensure_chat_model() twice on the same agent/chat-model instance and asserts exactly one logged request/response pair per real ainvoke call.
  • Verify coverage >=97% via nox -s coverage_report.
  • Run nox (all default sessions), fix any errors.

Definition of Done

This issue is complete when:

  • All subtasks above are completed and checked off.
  • A Git commit is created where the first line matches the Commit Message in Metadata exactly.
  • The commit is pushed to the branch matching the Branch in Metadata exactly.
  • The commit is submitted as a PR to master, reviewed, and merged.
  • A companion Type/Testing TDD issue exists, the TDD scenario (tagged @tdd_expected_fail) is merged first, and this issue's Forgejo dependency correctly shows it depends on that TDD issue.

Note for triage

No existing Epic cleanly covers example/tooling-harness defects (Epic #77 "LLM Agent Runtime Stabilization" explicitly scopes out logging-refactor-only work unless requested; #148 is the single, non-Epic issue that introduced examples/). Leaving parent-Epic assignment to maintainer triage rather than forcing a mismatched link.

## Metadata Commit Message: `fix(examples): wrap chat_model ainvoke/astream logging exactly once per instance` Branch: bugfix/m1-llm-request-log-duplication ## Background and context `examples/test_app.py`'s `_setup_request_logging()` installs an AOP intercept (`_patched_ensure_chat_model`) that monkey-patches `LLMAgent._ensure_chat_model` to log every LLM request/response to `llm_requests.log`, purely for observability while running the example CLI. The top-level patch install is documented and guarded as idempotent (`_request_logging_configured` prevents the monkey-patch itself from being applied twice), but the *body* of the patched method has no equivalent guard around the per-chat-model wrap it performs. ## Current behavior `LLMAgent.chat_model` is a property whose getter calls `self._ensure_chat_model()` on every access (`src/cleveractors/agents/llm.py`). This means `_ensure_chat_model()` runs once for every real LLM call made during a process's lifetime, across every actor/node in a run -- not just once per `LLMAgent` instance. Inside `_patched_ensure_chat_model` (`examples/test_app.py`), each invocation does, roughly: ```python original_ainvoke = chat_model.ainvoke # captures whatever is CURRENTLY installed ... object.__setattr__(chat_model, "ainvoke", wrapped_ainvoke) # installs a NEW layer ``` There is no check for "is `ainvoke`/`astream` already wrapped?" before wrapping again. `_original_ensure_chat_model` only skips re-creating the underlying `BaseChatModel` once `self._chat_model` is set -- it does not prevent the patched method from re-running its wrap logic. So every real `_ensure_chat_model()` call across the whole run installs one more logging layer on top of the previous one(s). Result: the Nth real LLM call in a session gets logged N times -- once per stacked wrapper layer -- all synchronously, before/after the single real network round-trip underneath. Observed directly in a production run of the example CLI (`python test_app.py test --llm-protocol http --llm-ip <host> --llm-port 8000 --local-store packages --unsafe --prompt "..." --graph 80487-fpu-actor-tools-graph.yaml`): one real completion (provider `id: chatcmpl-d129c30def4d4b6b963b04f4`, `usage_metadata.total_tokens: 88909`) was logged as 40 near-identical `LLM REQUEST:` / `LLM RESPONSE:` line pairs in `llm_requests.log`. Grouping every logged response in that run by its provider `id` confirms the pattern is systemic, not a one-off: successive real calls in the same run duplicated 44, 44, 42, 42, 40, 40, 40, 38, 38, 38... times, growing by roughly one extra layer per real call made so far. This does **not** duplicate the actual outbound API calls or token spend -- confirmed: one real HTTP round-trip per group, identical token counts and completion `id` across every duplicate line in the group. But it inflates `llm_requests.log` by a large, growing multiplier, makes the log actively misleading when diagnosing a run (a single real response reads as if the model retried dozens of times), and log volume grows roughly with the square of the number of LLM calls in a long-running session. ## Expected behavior `chat_model.ainvoke` and `chat_model.astream` are wrapped for logging exactly once per `chat_model` instance, regardless of how many times `_ensure_chat_model()` is subsequently called on the owning `LLMAgent`. Each real LLM call produces exactly one `LLM REQUEST:` line and exactly one `LLM RESPONSE:` line (or exactly one `LLM STREAM REQUEST:` / `LLM STREAM RESPONSE:` pair for streaming) in `llm_requests.log`. ## Acceptance criteria - Running the example CLI for a session with N real LLM calls produces exactly N `LLM REQUEST:` lines and N `LLM RESPONSE:` lines in `llm_requests.log` (1:1 -- no growth multiplier). - Calling `_ensure_chat_model()` more than once on the same `LLMAgent` (e.g. once per turn in the `interactive` loop, or once per node execution across a graph run) does not add additional logging layers to an already-wrapped `chat_model`. - A Behave scenario proves the fix: invoking the patched `_ensure_chat_model()` twice on the same `LLMAgent`/`chat_model` instance and then calling `ainvoke` once results in exactly one logged request and one logged response. - No change to the actual number of outbound LLM API calls or token usage -- this is a logging-only defect. ## Supporting information - Affected function: `_setup_request_logging._patched_ensure_chat_model` in `examples/test_app.py`. - Underlying property that triggers the repeated wrap on every real call: `LLMAgent.chat_model` / `LLMAgent._ensure_chat_model` in `src/cleveractors/agents/llm.py` (this part of the core library is correct and not implicated -- it only guards re-creation of `self._chat_model`, which is a separate, working concern). - Captured evidence: a local log excerpt (`llm_requests_prematurely_eneded_the_execution.log`) from a CleverActors CLI run that also hit an unrelated, separately-tracked failure (a `file_write` tool call receiving a corrupted path argument) -- that second issue is out of scope here and is not part of this ticket. - This defect lives entirely in example/tooling code (`examples/`), not in `src/cleveractors/` runtime code. ## Subtasks - [ ] Add an instance-level guard (e.g. `getattr(chat_model, "_request_logging_wrapped", False)` / `object.__setattr__(chat_model, "_request_logging_wrapped", True)`) in `_patched_ensure_chat_model` so `ainvoke` and `astream` are wrapped only once per `chat_model` object. - [ ] Tests (Behave): add a scenario in `features/` that calls the patched `_ensure_chat_model()` twice on the same agent/chat-model instance and asserts exactly one logged request/response pair per real `ainvoke` call. - [ ] Verify coverage >=97% via `nox -s coverage_report`. - [ ] Run `nox` (all default sessions), fix any errors. ## Definition of Done This issue is complete when: - All subtasks above are completed and checked off. - A Git commit is created where the first line matches the Commit Message in Metadata exactly. - The commit is pushed to the branch matching the Branch in Metadata exactly. - The commit is submitted as a PR to master, reviewed, and merged. - A companion `Type/Testing` TDD issue exists, the TDD scenario (tagged `@tdd_expected_fail`) is merged first, and this issue's Forgejo dependency correctly shows it depends on that TDD issue. ## Note for triage No existing Epic cleanly covers example/tooling-harness defects (Epic #77 "LLM Agent Runtime Stabilization" explicitly scopes out logging-refactor-only work unless requested; #148 is the single, non-Epic issue that introduced `examples/`). Leaving parent-Epic assignment to maintainer triage rather than forcing a mismatched link.
Author
Member

Blocked by #174 (TDD issue-capture test must be written and merged first, per the mandatory Bug Fix TDD Workflow).

Blocked by #174 (TDD issue-capture test must be written and merged first, per the mandatory Bug Fix TDD Workflow).
Author
Member

Fix submitted: PR #186 (bugfix/m1-llm-request-log-duplication -> develop). Moving to State/In Review.

Fix submitted: PR #186 (bugfix/m1-llm-request-log-duplication -> develop). Moving to State/In Review.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
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#173
No description provided.