Skip to content

fix(pr_agent/algo/utils.py): skipping a malformed contribution time estimate - #2746

Merged
IsmaelMartinez merged 4 commits into
The-PR-Agent:mainfrom
dwin-gharibi:fix/contribution-time-estimate-shape
Aug 22, 2026
Merged

IsmaelMartinez merged 4 commits into
The-PR-Agent:mainfrom
dwin-gharibi:fix/contribution-time-estimate-shape

Conversation

@dwin-gharibi

Copy link
Copy Markdown
Contributor

Closes #2745.

Description

convert_to_markdown_v2 indexes value['best_case'] on the contribution-time estimate without checking that the model returned a dict.

Root cause

The renderer trusts the model to produce the exact {best_case, average_case, worst_case} shape, with no validation before subscripting.

The fix

Guard the branch with isinstance(value, dict) and a check for the keys it reads; anything else is skipped with continue, exactly as the renderer already does for other unusable values.

Behaviour change

Before One malformed field discards the whole review
After The malformed row is skipped; the rest of the review is published

Files changed

pr_agent/algo/utils.py | 4 ++++
 1 file changed, 4 insertions(+)

Testing

New regression coverage in tests/unittest/test_contribution_time_estimate_shape.py — 6 tests, each written to fail
without the fix:

$ PYTHONPATH=. pytest tests/unittest/test_contribution_time_estimate_shape.py
6 passed

Proven to be a genuine regression test: with every changed pr_agent/ file reverted to its
origin/main version and the new test file left in place, the suite fails. It only passes
with the fix applied.

Full pipeline, reproduced locally exactly as .github/workflows/build-and-test.yaml runs it:

docker build -f docker/Dockerfile --target test .
docker run --rm <image> pytest -v tests/unittest
-> 1967 passed, 1 skipped, 1 xfailed

on python:3.12.13-slim — no failures.

Also checked:

  • pytest tests/unittest — no new failures vs main
  • ruff — no new findings vs main; isort — clean on every file touched
  • No new code comments authored

Risk / compatibility

Well-formed estimates render exactly as before.

Checklist

  • Focused on a single fix
  • Existing tests pass
  • New regression tests added, proven to fail without the fix
  • No new dependencies
  • Reviewed by a maintainer

Copilot AI lite review requested due to automatic review settings August 21, 2026 12:20

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Skip malformed contribution-time estimates when rendering markdown

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Guard contribution-time estimate rendering against non-dict or missing-key values.
• Log and skip only the malformed row instead of aborting the whole review.
• Add regression tests covering multiple malformed shapes and ensuring other fields render.
Diagram

graph TD
  A(["LLM review JSON"]) --> B(["convert_to_markdown_v2"]) --> C{["Estimate shape ok?"]} --> D(["Render estimate row"]) --> E(["Markdown output"]) 
  C --> F(["Log warning + continue"]) --> E
  G(["pytest unit tests"]) --> B
  subgraph Legend
    direction LR
    _in(["Input"]) ~~~ _fn(["Function"]) ~~~ _dec{["Decision"]} ~~~ _out(["Output"])
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Schema-validate the full model output earlier
  • ➕ Centralizes validation instead of scattering guards across render branches
  • ➕ Can surface structured validation errors to callers/telemetry
  • ➖ Higher implementation surface area for a single-field robustness fix
  • ➖ May require broader refactors of how model output is represented/typed
2. Use a typed model (e.g., pydantic/dataclass) for the estimate field
  • ➕ Clear contract for {best, average, worst} values
  • ➕ Can provide defaults/coercions in one place
  • ➖ Adds runtime/maintenance overhead and potential dependency considerations
  • ➖ Still needs a fallback behavior for invalid model output

Recommendation: The chosen approach (local guard + logging + skip) is the best fit for this renderer: it matches existing behavior for unusable values, minimizes blast radius, and prevents a single malformed field from discarding the whole review. Consider broader schema validation only if malformed outputs become frequent across multiple fields.

Files changed (2) +36 / -0

Bug fix (1) +4 / -0
utils.pyValidate contribution-time estimate shape before rendering +4/-0

Validate contribution-time estimate shape before rendering

• Adds a defensive check ensuring the contribution time estimate is a dict containing best_case/average_case/worst_case before subscripting. Malformed values are logged and skipped so the rest of the review still renders.

pr_agent/algo/utils.py

Tests (1) +32 / -0
test_contribution_time_estimate_shape.pyRegression tests for malformed contribution-time estimate shapes +32/-0

Regression tests for malformed contribution-time estimate shapes

• Introduces unit tests covering non-dict values and missing keys to ensure the renderer does not raise and that other fields continue rendering. Confirms well-formed estimates still produce the expected output.

tests/unittest/test_contribution_time_estimate_shape.py

@qodo-code-review

qodo-code-review Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Validate estimate value types ✓ Resolved 🐞 Bug ☼ Reliability
Description
The guard checks only the container and key names, so a dict such as `{"best_case": None,
"average_case": "1h", "worst_case": "2h"} still reaches _expand_minute_suffix` and raises
TypeError from re.sub. This leaves the claimed malformed-row resilience incomplete for malformed
values and can still discard the whole review.
Code

pr_agent/algo/utils.py[R228-231]

+            if not isinstance(value, dict) or not {'best_case', 'average_case', 'worst_case'} <= set(value):
+                get_logger().warning("Skipping malformed contribution time estimate",
+                                     artifact={'value': value})
+                continue
Relevance

●●● Strong

Recent reviews accepted defensive validation preventing malformed values from reaching downstream
helpers and causing runtime failures.

PR-#2584
PR-#2503
PR-#2610

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The modified condition accepts any dict containing the three keys regardless of their values, while
the helper used immediately afterward requires a string because it supplies the value to re.sub as
the subject.

pr_agent/algo/utils.py[131-138]
pr_agent/algo/utils.py[228-244]

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 new shape guard accepts dictionaries whose `best_case`, `average_case`, or `worst_case` values are not strings. `_expand_minute_suffix` passes each value to `re.sub`, so `None`, integers, lists, and similar model outputs still raise and abort the renderer.

## Issue Context
Keep the existing behavior for well-formed estimates and skip malformed rows with the same warning/`continue` behavior. Validate all three values before indexing/expanding them.

## Fix Focus Areas
- pr_agent/algo/utils.py[228-244]
- tests/unittest/test_contribution_time_estimate_shape.py[9-32]

Add regression coverage for malformed values inside an otherwise keyed dictionary, including at least `None` and a non-string value, for both rendering modes if applicable.

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



Remediation recommended

2. Single-quoted estimate keys ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The new validation condition uses single-quoted string literals for best_case, average_case, and
worst_case, contrary to the repository’s double-quote convention. Replace them with double-quoted
literals.
Code

pr_agent/algo/utils.py[228]

+            if not isinstance(value, dict) or not {'best_case', 'average_case', 'worst_case'} <= set(value):
Relevance

●●● Strong

Recent repository reviews accepted identical double-quote convention findings, including in adjacent
utility and newly changed code.

PR-#2677
PR-#2693
PR-#2703

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694657 requires all non-exempt Python string literals in changed files to use
double quotes. The added validation expression contains three single-quoted literals on the pointed
line.

Rule 2694657: Use double quotes for all Python string literals
pr_agent/algo/utils.py[228-228]

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 added key-set validation uses single-quoted Python string literals, violating the project’s required double-quote convention.

## Issue Context
Keep the validation behavior unchanged while changing only the literal delimiters.

## Fix Focus Areas
- pr_agent/algo/utils.py[228-228]

ⓘ 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.

Grey Divider

Context sources
✅ Compliance rules (platform): 34 rules
Review mode: 🚀 Fast: This is a localized defensive validation change in one rendering path with focused regression tests and no security, API, schema, or cross-cutting risk.

Grey Divider

Tip of the day
💡 Did you know, you can commit Qodo's fix in one click with committable suggestions (GitHub & GitLab)

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread pr_agent/algo/utils.py Resolved
@qodo-code-review

Copy link
Copy Markdown
Contributor

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

@IsmaelMartinez
IsmaelMartinez merged commit 059a7f4 into The-PR-Agent:main Aug 22, 2026
5 checks passed
@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

Merged. Failing soft here is the right call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A malformed contribution-time estimate kills the entire review

3 participants