Skip to content

feat: add opt-in agent run details section (model, tokens, time, AI calls) - #2587

Merged
naorpeled merged 23 commits into
The-PR-Agent:mainfrom
victorljii:feature/run-metadata-section
Aug 8, 2026
Merged

naorpeled merged 23 commits into
The-PR-Agent:mainfrom
victorljii:feature/run-metadata-section

Conversation

@victorljii

Copy link
Copy Markdown
Contributor

Summary

/review, /describe and /improve can optionally append a short section
reporting how the run went: which model answered (and whether it was a fallback),
tokens consumed, time taken, and how many LLM calls it made. Off by default,
enabled with config.output_run_details.

What it looks like

⚙️ Agent run details
- Model: gpt-5.6-terra (fallback)
- Tokens: 12,340 in / 1,205 out / 13,545 total
- Time cost: 8.2s
- AI calls: 1

A collapsible <details> block where GFM is supported, matching the existing
🛠️ Relevant configurations section, and the same lines as plain text elsewhere.
Fields the provider does not report are omitted rather than shown as zero.

How it works

A new pr_agent/algo/run_details.py holds a RunDetails dataclass in a
ContextVar:

  • Each tool calls init_run_details() at the top of run(), installing a fresh
    collector for that run.
  • retry_with_fallback_models records the model that produced the successful
    prediction, marked as a fallback when it was not the first attempt.
  • The litellm and openai handlers count each call and add its token usage when
    the provider reports one. Parallel calls, such as /improve's chunks,
    accumulate into the same collector.
  • show_run_details() renders the section, and the three tools append it when
    the flag is on.

Caveats

/improve appends the section only when it publishes a summary comment, not with
commitable_code_suggestions. With use_description_markers=true, repeated
/describe runs accumulate one block per run. Streaming responses and the
langchain handler do not expose usage in a form the collector reads, so the
Tokens line is omitted there while the call itself is still counted.

Tests

34 new unit tests covering the collector, the fallback recording, both AI
handlers, the renderer, and the wiring into all three tools. The wiring tests
drive each tool's real run() with the git provider stubbed, so they fail if the
production call sites disappear.

Docs

a new section in usage-guide/additional_configurations.md, cross-referenced
from changing_a_model.md. No new dependencies.

Closes #2514

victorljii and others added 17 commits July 28, 2026 20:08
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
…rove

Co-authored-by: Cursor <cursoragent@cursor.com>
Replace the helper-based self-test with assertions against the real review,
description, and improve output paths so the tests fail if any production
insertion is removed.

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Count successful OpenAI and LangChain completions in run metadata,
and move fallback-model telemetry into the success-only else branch.
This keeps AI call counts visible across handlers and prevents
telemetry from triggering a fallback retry path.

Co-authored-by: Cursor <cursoragent@cursor.com>
Lock in ContextVar accumulation and isolation under asyncio.gather,
assert the renderer omits zero AI calls and formats time cost with one
decimal, and share one test fixture for run-metadata isolation.

Co-authored-by: Cursor <cursoragent@cursor.com>
Document that /improve only appends run metadata when it publishes a
summary comment, and that repeated /describe runs with description
markers accumulate blocks because the existing description is preserved.

Co-authored-by: Cursor <cursoragent@cursor.com>
Count langchain calls without token usage: it reports input_tokens/
output_tokens, which the collector does not read, so passing it through
rendered a misleading "0 in / 0 out" line instead of omitting tokens.

Move the langchain import to module level to match the other handlers,
and place the openai import in isort order within its group. The rest of
each file's import disorder predates this branch and is left untouched.

Co-authored-by: Cursor <cursoragent@cursor.com>
/improve was a confusing choice for the example command, since the notes
right below it explain when /improve omits the section.

Co-authored-by: Cursor <cursoragent@cursor.com>
"Metadata" reads as data about the PR, but what the section reports is
how this particular run went: which model answered, tokens spent, wall
time, and how many LLM calls it took. Rename the user-visible surface
-- section title "Agent run details" and the config flag
output_run_details -- and carry the same name through the module,
dataclass, helpers, ContextVar and tests, so the feature does not end
up half renamed.

The anchor in changing_a_model.md moves with the docs heading;
_record_completion_metadata in the litellm handler deliberately keeps
its name, since it reads metadata off a completion response, which is
a different and accurate use of the word.

Co-authored-by: Cursor <cursoragent@cursor.com>
Mutation testing survived two breakages, meaning nothing guarded them.
Nothing covered chat_completion actually calling the recorder, so the
default handler could stop counting and every figure would silently
read zero; drive the real method with a stubbed _get_completion, and
also pin that a failed call is not counted (fallback runs would
otherwise inflate the totals) and that concurrent calls accumulate,
which is how /improve fans out its chunks.

The reviewer test built the tool by hand and called _prepare_pr_review
directly, skipping run() and therefore init_run_details(). Drive run()
like the describe and improve tests do, and seed through the tool's
own init hook, so removing that call makes the section unrenderable
and the test red.

Co-authored-by: Cursor <cursoragent@cursor.com>
@github-actions github-actions Bot added the feature 💡 label Aug 1, 2026
Comment thread tests/unittest/test_run_details.py Fixed
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Add opt-in agent run details section (model/tokens/time/AI calls) to PR outputs

✨ Enhancement 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Add an opt-in “Agent run details” section to /review, /describe, and /improve outputs.
• Collect per-run model, fallback status, tokens, duration, and successful AI-call counts.
• Wire collection into handlers/tools and add comprehensive unit tests plus configuration docs.
Diagram

graph TD
  reviewer["PRReviewer (/review)"] --> run["RunDetails collector"] --> render["show_run_details()"] --> out["PR comment/description"]
  describe["PRDescription (/describe)"] --> run --> render --> out
  improve["PRCodeSuggestions (/improve)"] --> run --> render --> out
  handlers["AI handlers"] --> run --> render --> out
  fallback["retry_with_fallback_models"] --> run --> render --> out
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Return run metadata from chat_completion() and thread it through call sites
  • ➕ No hidden global/context state; data flow is explicit
  • ➕ Easier static reasoning about what gets recorded and when
  • ➖ Signature churn across handlers and all upstream callers
  • ➖ Harder to support concurrent fan-out (must aggregate manually everywhere)
2. Emit structured telemetry only (logs/metrics), not appended to PR output
  • ➕ Keeps PR comments uncluttered and avoids markdown portability issues
  • ➕ Works even when publishing is disabled (local CLI / CI metrics)
  • ➖ Not visible to end users reviewing the comment output
  • ➖ Harder to correlate telemetry to a specific PR comment run
3. Provider-specific middleware/callbacks (e.g., LiteLLM callbacks) as the primary source
  • ➕ Can be more accurate/complete for certain providers (streaming, token usage)
  • ➕ Centralizes collection closer to the API boundary
  • ➖ Increases coupling to specific libraries/providers
  • ➖ Harder to guarantee coverage across all handlers and fallback paths

Recommendation: Keep the ContextVar-backed collector approach: it avoids invasive API changes while still aggregating across concurrent asyncio tasks, and the PR limits risk by being opt-in and omitting unsupported fields instead of showing misleading zeros. If token usage for LangChain/streaming becomes important, add a small mapping layer later rather than changing the core design.

Files changed (19) +1043 / -4

Enhancement (9) +196 / -4
langchain_ai_handler.pyRecord successful LangChain calls in run details (without token usage) +7/-0

Record successful LangChain calls in run details (without token usage)

• Adds a 'record_ai_call()' hook on successful completions. Explicitly avoids token accounting due to LangChain usage field incompatibilities in this path.

pr_agent/algo/ai_handlers/langchain_ai_handler.py

litellm_ai_handler.pyAccumulate AI-call count and token usage for LiteLLM completions +11/-0

Accumulate AI-call count and token usage for LiteLLM completions

• Introduces a helper to record per-completion metadata into the shared collector. Hooks the recorder into the non-streaming completion path while tolerating missing usage for streaming responses.

pr_agent/algo/ai_handlers/litellm_ai_handler.py

openai_ai_handler.pyRecord successful OpenAI calls and usage in run details +2/-0

Record successful OpenAI calls and usage in run details

• Calls 'record_ai_call(usage)' after successful OpenAI chat completions to count invocations and accumulate token usage.

pr_agent/algo/ai_handlers/openai_ai_handler.py

pr_processing.pyRecord the model that ultimately succeeded (and whether it was a fallback) +5/-1

Record the model that ultimately succeeded (and whether it was a fallback)

• Adjusts 'retry_with_fallback_models' to record the successful model only on the success path. Marks fallback usage based on the attempt index rather than model name.

pr_agent/algo/pr_processing.py

run_details.pyAdd ContextVar-backed 'RunDetails' collector and recording helpers +117/-0

Add ContextVar-backed 'RunDetails' collector and recording helpers

• Introduces a 'RunDetails' dataclass stored in a 'ContextVar' to collect model, fallback flag, tokens, duration, and successful AI call counts per run. Provides helpers to initialize the collector and to record model usage and token/call metadata opportunistically.

pr_agent/algo/run_details.py

utils.pyRender the opt-in “Agent run details” section (GFM <details> or plain text) +28/-0

Render the opt-in “Agent run details” section (GFM <details> or plain text)

• Adds 'show_run_details(gfm_supported)' to format model, tokens (when available), duration, and AI calls. Omits lines when data is unavailable and returns an empty string if no successful model was recorded.

pr_agent/algo/utils.py

pr_code_suggestions.pyInitialize and append run details for /improve summary-comment output +10/-1

Initialize and append run details for /improve summary-comment output

• Initializes a fresh run-details collector at the start of 'run()'. When 'config.output_run_details' is enabled, appends the rendered section to the summary comment path.

pr_agent/tools/pr_code_suggestions.py

pr_description.pyInitialize and append run details to /describe output when enabled +8/-1

Initialize and append run details to /describe output when enabled

• Initializes run-details collection at the top of 'run()'. Conditionally appends the run-details section based on 'config.output_run_details' and provider GFM support.

pr_agent/tools/pr_description.py

pr_reviewer.pyInitialize and append run details to /review output when enabled +8/-1

Initialize and append run details to /review output when enabled

• Initializes run-details collection at the top of 'run()'. Conditionally appends the run-details section based on 'config.output_run_details' and provider GFM support.

pr_agent/tools/pr_reviewer.py

Tests (7) +819 / -0
_run_details_test_helpers.pyAdd autouse fixture to isolate run-details ContextVar between tests +11/-0

Add autouse fixture to isolate run-details ContextVar between tests

• Provides a pytest fixture that resets and restores the internal ContextVar so run details do not leak across tests.

tests/unittest/_run_details_test_helpers.py

test_litellm_run_details.pyTest LiteLLM run-details recording and concurrency accumulation +142/-0

Test LiteLLM run-details recording and concurrency accumulation

• Adds unit tests validating that LiteLLM completion recording increments call counts, accumulates token usage when present, ignores failures, and aggregates across concurrent tasks.

tests/unittest/test_litellm_run_details.py

test_retry_with_fallback_models.pyTest fallback-model recording and fallback flag semantics +101/-0

Test fallback-model recording and fallback flag semantics

• Adds tests verifying primary vs fallback recording, sticky fallback flag behavior, and that recording occurs only on success. Includes a guard test ensuring telemetry failures don’t trigger additional retry behavior.

tests/unittest/test_retry_with_fallback_models.py

test_run_details.pyTest RunDetails collector lifecycle, token accounting, and async isolation +168/-0

Test RunDetails collector lifecycle, token accounting, and async isolation

• Adds unit tests covering initialization, sticky fallback flag behavior, token accumulation (including derived totals), call counting, and correct ContextVar behavior across concurrent tasks and separate runs.

tests/unittest/test_run_details.py

test_run_details_ai_handlers.pyTest OpenAI and LangChain handlers record successful calls appropriately +108/-0

Test OpenAI and LangChain handlers record successful calls appropriately

• Adds tests ensuring OpenAI records usage-backed calls and LangChain records calls without token usage. Uses module stubbing to avoid requiring real provider credentials or dependencies.

tests/unittest/test_run_details_ai_handlers.py

test_run_details_wiring.pyEnd-to-end wiring tests for appending run details in all three tools +198/-0

End-to-end wiring tests for appending run details in all three tools

• Adds tests that drive real 'run()' paths for reviewer/description/suggestions with stubbed git providers. Validates that the section is appended only when the config flag is enabled and fails if production insertion points are removed.

tests/unittest/test_run_details_wiring.py

test_show_run_details.pyTest run-details renderer output formats and omission rules +91/-0

Test run-details renderer output formats and omission rules

• Adds unit tests for GFM '<details>' rendering vs plain-text fallback, fallback model marking, and omission of token/AI-call lines when data is unavailable.

tests/unittest/test_show_run_details.py

Documentation (2) +27 / -0
additional_configurations.mdDocument 'config.output_run_details' and the rendered run-details section +25/-0

Document 'config.output_run_details' and the rendered run-details section

• Adds a new documentation section explaining how to enable the run details output and what fields mean. Notes provider differences (GFM vs plain text) and when /improve will not append the section.

docs/docs/usage-guide/additional_configurations.md

changing_a_model.mdCross-reference run details to identify which model actually answered +2/-0

Cross-reference run details to identify which model actually answered

• Adds a short note pointing readers to 'config.output_run_details' for verifying primary vs fallback model usage on real runs.

docs/docs/usage-guide/changing_a_model.md

Other (1) +1 / -0
configuration.tomlAdd 'output_run_details' configuration flag (default off) +1/-0

Add 'output_run_details' configuration flag (default off)

• Introduces 'config.output_run_details=false' with an inline comment explaining the appended section fields.

pr_agent/settings/configuration.toml

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (3) 📘 Rule violations (1) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Time cost not AI-only 🐞 Bug ◔ Observability
Description
RunDetails.start_time is initialized at the very start of each tool’s run(), so show_run_details()
reports total tool wall-time (diff building, ticket extraction, rendering, etc.) rather than the “AI
processing phase” duration described in the docs. This makes the reported “Time cost” misleading for
users trying to understand model latency/cost.
Code

pr_agent/algo/run_details.py[R47-50]

+    # Monotonic reference taken when the collector is installed, i.e. at the top of the
+    # tool's run(). Monotonic so that wall-clock adjustments cannot yield a negative duration.
+    start_time: float = field(default_factory=time.monotonic)
+
Evidence
The docs describe Time cost as AI processing phase duration, but RunDetails.start_time is captured
when the collector is installed at the top of tool run(), and show_run_details() renders elapsed
time from that start, which therefore includes non-AI work performed before/after the LLM call(s).

docs/docs/usage-guide/additional_configurations.md[25-43]
pr_agent/tools/pr_reviewer.py[126-151]
pr_agent/algo/run_details.py[47-53]
pr_agent/algo/utils.py[1301-1323]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The run-details section claims to show how long the AI processing phase took, but the implementation measures elapsed time from the beginning of the tool’s `run()` method. This includes non-AI work (ticket extraction, diff preparation, formatting), so the displayed `Time cost` is not the AI phase duration.
## Issue Context
- `init_run_details()` is called at the start of `/review`, `/describe`, `/improve` tool `run()` methods.
- `RunDetails.start_time` uses `time.monotonic()` at initialization, and `show_run_details()` renders `details.duration_seconds`.
- Docs explicitly describe this as the “AI processing phase” duration.
## Fix Focus Areas
- pr_agent/algo/run_details.py[20-117]
- pr_agent/algo/utils.py[1301-1328]
- docs/docs/usage-guide/additional_configurations.md[25-44]
## Suggested fix approach
- Add AI-phase timing fields (e.g., `ai_start_time: Optional[float]`, `ai_end_time: Optional[float]`) to `RunDetails`.
- In `record_ai_call()`, set `ai_start_time` on the first recorded call and update `ai_end_time` on each call completion (or at least on successful call record).
- In `show_run_details()`, render `Time cost` using `(ai_end_time - ai_start_time)` when available; otherwise omit the line or fall back to total wall-time.
- Alternatively (if total wall-time is desired), change the label/docs to state it is total tool runtime rather than AI processing time.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. record_model_used aborts retry 📘 Rule violation ☼ Reliability
Description
retry_with_fallback_models() calls record_model_used() outside the protected block, so if
telemetry ever raises it will abort the run despite a successful model response and will not attempt
further fallbacks. This is fragile error handling for a non-critical side effect.
Code

pr_agent/algo/pr_processing.py[R340-342]

+        else:
+            record_model_used(model, is_fallback=i > 0)
+            return result
Evidence
PR Compliance ID 3 requires graceful handling of error scenarios. In retry_with_fallback_models(),
success returns are routed through an else: that calls `record_model_used(model, is_fallback=i >
0)` without any exception handling, so a telemetry failure would raise and prevent returning the
successful result.

Rule 3: Robust Error Handling
pr_agent/algo/pr_processing.py[321-342]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`retry_with_fallback_models()` records the successful model via `record_model_used()`, but that call is not guarded; any exception raised there would fail the whole command even though `f(model)` already succeeded.
## Issue Context
Run-details collection is optional telemetry and should not be able to break the core review/describe/improve execution path.
## Fix Focus Areas
- pr_agent/algo/pr_processing.py[321-342]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Misleading fallback model label 🐞 Bug ◔ Observability
Description
show_run_details() appends “(fallback)” based on the sticky RunDetails.fallback_used flag, even when
RunDetails.model_used was later overwritten by a non-fallback success, producing output like “Model:
primary-model (fallback)”. This misstates which model actually produced the displayed answer when
multiple model selections are recorded in a single run.
Code

pr_agent/algo/utils.py[1312]

+    lines = [f"- Model: {details.model_used}{' (fallback)' if details.fallback_used else ''}"]
Evidence
The sticky fallback flag is explicitly implemented and tested: record_model_used() keeps
fallback_used=True once any fallback succeeds, even if model_used is later updated to a primary
model. The renderer uses fallback_used to append “(fallback)” directly to the current
model_used, so the tested state would produce a misleading model line.

pr_agent/algo/run_details.py[29-35]
pr_agent/algo/run_details.py[76-85]
pr_agent/algo/utils.py[1307-1313]
tests/unittest/test_run_details.py[55-65]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`show_run_details()` renders the model line as `Model: {model_used} (fallback)` whenever `fallback_used` is true. But `fallback_used` is intentionally sticky across recordings, while `model_used` is overwritten on each successful `record_model_used()` call; this can render a non-fallback model as “(fallback)”.
### Issue Context
This happens if `record_model_used()` is called more than once during a single run (e.g., multiple `retry_with_fallback_models()` calls in one tool run). The unit test explicitly asserts this sticky state.
### Fix Focus Areas
- pr_agent/algo/run_details.py[29-35]
- pr_agent/algo/run_details.py[76-85]
- pr_agent/algo/utils.py[1311-1320]
### Suggested fix
1. Track two separate concepts:
- `any_fallback_used: bool` (sticky, run-level)
- `final_model_was_fallback: bool` (set on each `record_model_used()` call alongside `model_used`)
2. Render:
- `Model: {model_used}{' (fallback)' if final_model_was_fallback else ''}`
- Optionally add another line like `- Fallback used earlier: yes` when `any_fallback_used` is true but `final_model_was_fallback` is false.
3. Update/extend tests to assert the new rendering semantics for the sticky scenario.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (1)
4. Token breakdown prints zeros ✓ Resolved 🐞 Bug ≡ Correctness
Description
show_run_details() always renders "{prompt} in / {completion} out / {total} total" once any token
usage exists, even when the provider only reported total_tokens (or omitted prompt/completion). This
can display misleading "0 in / 0 out" values instead of omitting unreported fields, contradicting
the new feature’s stated behavior.
Code

pr_agent/algo/utils.py[R1313-1315]

+    if details.has_token_usage:
+        lines.append(f"- Tokens: {details.prompt_tokens:,} in / {details.completion_tokens:,} out / "
+                     f"{details.total_tokens:,} total")
Evidence
The collector converts missing token fields to 0, but the renderer unconditionally formats all three
numbers when any token usage exists. This makes “missing” indistinguishable from a genuine zero, so
providers that report only total_tokens will produce a misleading 0 in / 0 out / N total line.

pr_agent/algo/run_details.py[20-108]
pr_agent/algo/utils.py[1301-1325]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`show_run_details()` prints a full token breakdown (prompt/completion/total) whenever *any* token usage is present. Because `RunDetails` stores token counters as ints defaulting to 0, the code cannot distinguish “provider did not report prompt/completion tokens” from a real 0. If a provider reports only `total_tokens`, the output becomes `0 in / 0 out / N total`.
## Issue Context
This PR’s docs and `RunDetails` docstring say fields the provider does not report should be omitted rather than shown as zero. Current storage/renderer logic loses “presence” information.
## Fix Focus Areas
- pr_agent/algo/run_details.py[20-108]
- pr_agent/algo/utils.py[1301-1325]
### Implementation guidance
- Preserve per-field presence, e.g.:
- Change `prompt_tokens`, `completion_tokens`, `total_tokens` to `Optional[int]` (or keep ints but add `seen_prompt_tokens/seen_completion_tokens/seen_total_tokens` booleans).
- Update `add_token_usage()` to only accumulate fields that were actually present and mark them as seen.
- Update `show_run_details()` rendering:
- If only total is known, render `- Tokens: {total:,} total`.
- If prompt+completion are known (with or without total), render the breakdown.
- If only one component is known, omit the missing component rather than printing 0.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

5. Misleading token comment 🐞 Bug ⚙ Maintainability
Description
RunDetails.total_tokens is documented as counting failed fallback attempts, but token usage is only
accumulated via record_ai_call() on successful completions, so failed attempts typically contribute
nothing to the collector. This discrepancy can mislead maintainers and users interpreting totals as
full run cost.
Code

pr_agent/algo/run_details.py[R41-44]

+    # Provider-reported total when available, otherwise derived from prompt + completion.
+    # Counts failed fallback attempts as well, so it reflects what the run really cost,
+    # while `model_used` names only the model behind the final answer.
+    total_tokens: int = 0
Evidence
The RunDetails comment claims failed fallback attempts are included, but the only places that add
token usage call record_ai_call() after a successful provider response is obtained. When the
provider call raises, execution exits before record_ai_call(), so no token usage from failures is
added.

pr_agent/algo/run_details.py[36-46]
pr_agent/algo/ai_handlers/openai_ai_handler.py[46-65]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[325-344]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`RunDetails.total_tokens` is commented as including failed fallback attempts, but the current instrumentation only records token usage for successful completions (handlers call `record_ai_call()` after receiving a response). The comment should be corrected to match reality (or instrumentation extended if you truly want to count failed-attempt usage).
## Issue Context
Token usage recording is performed in AI handlers on the success path only, so failed attempts during fallbacks/retries won’t be reflected in `total_tokens`.
## Fix Focus Areas
- pr_agent/algo/run_details.py[41-44]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

@victorljii

victorljii commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor Author

PR Reviewer Guide 🔍

(Review updated until commit f09e51d)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2514 - Partially compliant

Compliant requirements:

  • Add configuration information about the actually used model
  • Show which of the configured models actually performed the operation
  • Indicate when a fallback model was used instead of the primary

Non-compliant requirements:

  • None

Requires further human verification:

  • None
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Possible Issue

In retry_with_fallback_models, the result variable is only assigned inside the try block when f(model) succeeds. If an exception is raised and caught, the loop continues, but if no exception occurs the else clause returns result. However, if f(model) returns None successfully on the last iteration and an exception was somehow not raised, this is fine; the real issue is that result is referenced in the else block but only assigned in try. If a successful call returns normally, result is set. This is correct. But note: the else clause runs only on success (no exception), so result is guaranteed assigned. No bug. Actually, the structure is sound. No issue.

    result = await f(model)
except Exception as e:
    get_logger().warning(
        f"Failed to generate prediction with {model}",
        artifact={"error": e},
    )
    if i == len(all_models) - 1:  # If it's the last iteration
        raise Exception(f"Failed to generate prediction with any model of {all_models}") from e
else:
    record_model_used(model, is_fallback=i > 0)
    return result

⚙️ Agent run details
  • Model: openai/hy3
  • Tokens: 21,134 in / 420 out / 21,554 total
  • Time cost: 29.3s
  • AI calls: 1

victorljii and others added 3 commits August 2, 2026 11:59
CodeQL flagged the fixture import in six test files as an unused import,
which it is: the name is never referenced, it only has to exist in the
module namespace for pytest to register the autouse fixture. That is
what conftest.py is for, so define the fixture there and drop both the
helper module and the six imports.

The fixture now applies to every test under tests/unittest, which costs
a ContextVar set and reset per test and keeps future tests from leaking
run details as well.

Also pass _FakeSettings directly instead of wrapping it in a
zero-argument lambda, which CodeQL flagged separately.

Co-authored-by: Cursor <cursoragent@cursor.com>
A provider that reports only total_tokens rendered as "0 in / 0 out /
N total", claiming two figures it had never sent. Build the line from
the components that are actually present instead.

Zero is a safe stand-in for absent here: these are cumulative counters,
so any component still at zero after a successful call means nothing
was reported for it. That avoids threading Optional or seen-flags
through the collector for a distinction that cannot arise.

Co-authored-by: Cursor <cursoragent@cursor.com>
"Langchain does expose usage, only under its own key names" was read by
a reviewer as a sentence missing a "not". Say plainly that langchain
reports usage under key names the collector does not read, which is
what makes forwarding it render zeros.

Co-authored-by: Cursor <cursoragent@cursor.com>
@victorljii victorljii closed this Aug 2, 2026
@victorljii victorljii reopened this Aug 2, 2026
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

@victorljii

Copy link
Copy Markdown
Contributor Author

Persistent review updated to latest commit f09e51d

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit f09e51d

@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

Both bot findings look unreachable, in case it saves a rewrite.

record_model_used returns early without a collector and otherwise only assigns dataclass attributes — nothing for a try/except to catch. And "primary (fallback)" needs two retry_with_fallback_models calls in one run; your three tools each call it once (pr_reviewer.py:166, pr_description.py:111, pr_code_suggestions.py:120), with /improve's fan-out inside that single call. Only pr_help_docs.py:364,509 calls it twice, and that is not wired here.

ContextVar is the right choice and the docstring explains why — shared by reference into child tasks, so the gather aggregates while concurrent requests stay isolated.

@victorljii

Copy link
Copy Markdown
Contributor Author

@naorpeled
When you have a moment, could you take a look at this PR? Thanks!

@naorpeled

Copy link
Copy Markdown
Member

Hey @victorljii,
Thanks for opening this PR!
Could you please fix the merge conflicts?

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit dec08f8

@victorljii

victorljii commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Hey @victorljii, Thanks for opening this PR! Could you please fix the merge conflicts?

done @naorpeled

The review-coverage footer reads self.remaining_files_list, which is
normally set in _prepare_prediction. Since the wiring test mocks out
retry_with_fallback_models, that attribute was never assigned and run()
raised AttributeError before storing the artifact. Seed it explicitly in
the hand-built PRReviewer object.

Co-authored-by: Cursor <cursoragent@cursor.com>
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit b47467d

@naorpeled
naorpeled merged commit 4d68431 into The-PR-Agent:main Aug 8, 2026
5 checks passed
@naorpeled

Copy link
Copy Markdown
Member

Thanks @victorljii !

@edwinyoo44

Copy link
Copy Markdown

@victorljii Thanks a lot for working on this — having the actual model, token usage, timing, and AI call count available in the output is really useful!

One small thought: for models/providers that expose it, would it also make sense to collect and optionally show reasoning_tokens (e.g. as part of the token breakdown)?

I think it could be particularly useful for reasoning models, where the visible output tokens alone may not tell the whole story about token usage/cost.

Thanks again for the great work!

@victorljii

Copy link
Copy Markdown
Contributor Author

@victorljii Thanks a lot for working on this — having the actual model, token usage, timing, and AI call count available in the output is really useful!

One small thought: for models/providers that expose it, would it also make sense to collect and optionally show reasoning_tokens (e.g. as part of the token breakdown)?

I think it could be particularly useful for reasoning models, where the visible output tokens alone may not tell the whole story about token usage/cost.

Thanks again for the great work!

@edwinyoo44
Thanks for the suggestion — sounds good to me.

Just for context: on providers like OpenAI, reasoning tokens are already included in completion_tokens / output_tokens, so they're already part of the total we report today. This would only make the breakdown more informative.

Would this be what you had in mind?

- Tokens: 1,000 in / 600 out (400 reasoning) / 1,600 total

The parenthetical would only appear when the provider reports reasoning_tokens, and
be omitted otherwise, so output for non-reasoning models stays unchanged.

@edwinyoo44

Copy link
Copy Markdown

@victorljii Thanks a lot for working on this — having the actual model, token usage, timing, and AI call count available in the output is really useful!
One small thought: for models/providers that expose it, would it also make sense to collect and optionally show reasoning_tokens (e.g. as part of the token breakdown)?
I think it could be particularly useful for reasoning models, where the visible output tokens alone may not tell the whole story about token usage/cost.
Thanks again for the great work!

@edwinyoo44 Thanks for the suggestion — sounds good to me.

Just for context: on providers like OpenAI, reasoning tokens are already included in completion_tokens / output_tokens, so they're already part of the total we report today. This would only make the breakdown more informative.

Would this be what you had in mind?

- Tokens: 1,000 in / 600 out (400 reasoning) / 1,600 total

The parenthetical would only appear when the provider reports reasoning_tokens, and be omitted otherwise, so output for non-reasoning models stays unchanged.

@victorljii Yes, exactly — this looks great. Thanks!

Kyzcreig pushed a commit to Kyzcreig/pr-agent that referenced this pull request Aug 17, 2026
… run-details collector

Two changes prompted by review feedback on The-PR-Agent#2532:

- dict(data) is shallow, so structured_data["review"] aliased data["review"],
  which _prepare_pr_review mutates right after the hook fires. Harmless for
  PlainDiffGitProvider (serializes immediately) but the hook is
  provider-neutral, so publish a deep-copied snapshot instead.
  Caught by @IsmaelMartinez.

- Drop the handler-side last_usage capture entirely. The-PR-Agent#2587 (merged) already
  accumulates per-call token usage in the ContextVar-backed run-details
  collector; keeping a second capture path would drift. The structured
  publisher now reads prompt/completion/total tokens from get_run_details(),
  which also means multi-call runs report the full accumulated usage rather
  than only the last call's. Suggested by @IsmaelMartinez.

Co-authored-by: IsmaelMartinez <IsmaelMartinez@users.noreply.github.com>
IsmaelMartinez added a commit to Kyzcreig/pr-agent that referenced this pull request Aug 25, 2026
… run-details collector

Two changes prompted by review feedback on The-PR-Agent#2532:

- dict(data) is shallow, so structured_data["review"] aliased data["review"],
  which _prepare_pr_review mutates right after the hook fires. Harmless for
  PlainDiffGitProvider (serializes immediately) but the hook is
  provider-neutral, so publish a deep-copied snapshot instead.
  Caught by @IsmaelMartinez.

- Drop the handler-side last_usage capture entirely. The-PR-Agent#2587 (merged) already
  accumulates per-call token usage in the ContextVar-backed run-details
  collector; keeping a second capture path would drift. The structured
  publisher now reads prompt/completion/total tokens from get_run_details(),
  which also means multi-call runs report the full accumulated usage rather
  than only the last call's. Suggested by @IsmaelMartinez.

Co-authored-by: IsmaelMartinez <IsmaelMartinez@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

add information about which model is actually used

5 participants