Skip to content

fix: /ask on outdated review comments crashes with TypeError - #2784

Merged
IsmaelMartinez merged 2 commits into
The-PR-Agent:mainfrom
rophy:fix/ask-outdated-comment-crash
Aug 24, 2026
Merged

IsmaelMartinez merged 2 commits into
The-PR-Agent:mainfrom
rophy:fix/ask-outdated-comment-crash

Conversation

@rophy

@rophy rophy commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

Description

Fixes #2783

github_app.py — handle_line_comments() now falls back to original_start_line / original_line when start_line / line are null.

git_patch_processing.py — extract_hunk_lines_from_patch() now converts line_start / line_end to int at entry, falling back to -1 for invalid values.

Type of change

  • Bug fix (non-breaking change)

Verification

$ PYTHONPATH=. python -m pytest tests/unittest/test_diff_pipeline_core.py::TestExtractHunkLinesFromPatch tests/unittest/test_github_app_timeout_core.py::TestHandleLineComments -q
21 passed in 2.60s

New tests:

  • test_non_numeric_line_params_do_not_crash (parametrized: "", None, "None")
  • test_string_line_params_are_coerced_to_int
  • test_outdated_comment_falls_back_to_original_line
  • test_outdated_comment_single_line_falls_back_to_original

Manually verified: /ask on an outdated review comment now responds instead of crashing silently.

Fall back to original_start_line/original_line when GitHub nulls
start_line/line on outdated comments. Defensively convert line params
to int in extract_hunk_lines_from_patch.

Fixes The-PR-Agent#2783
@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Fix /ask crash on outdated GitHub review comments

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Prevent TypeError when GitHub nulls line fields on outdated review comments.
• Coerce/guard diff line parameters to avoid crashes on invalid inputs.
• Add unit tests covering outdated comments and non-numeric line parameters.
Diagram

graph TD
  GH{{"GitHub review comment"}} --> APP["handle_line_comments"] --> PATCH["extract_hunk_lines_from_patch"] --> OUT["Hunk selection output"]
  APP --> T_APP["github_app tests"]
  PATCH --> T_DIFF["diff pipeline tests"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Validate/normalize GitHub payload via a schema layer
  • ➕ Centralizes payload quirks (e.g., outdated comment nulls) in one place
  • ➕ Makes downstream code assume a consistent, typed shape
  • ➖ Adds schema/typing overhead (and potentially a dependency) for a narrow fix
  • ➖ Still needs defensive handling for unexpected real-world payloads
2. Fail fast with a user-facing error on missing/invalid line bounds
  • ➕ Avoids silently producing empty selections when inputs are invalid
  • ➕ Makes debugging easier if upstream sends malformed values
  • ➖ Worse UX for edge cases where a best-effort response is preferable
  • ➖ Requires deciding and implementing an error-reporting path
3. Move int coercion to the CLI/command-arg builder only
  • ➕ Keeps core patch extraction function stricter and simpler
  • ➕ Single responsibility: parsing at the boundary
  • ➖ Other callers could still pass invalid values and reintroduce crashes
  • ➖ Spreads defensive checks across entry points over time

Recommendation: Keep the PR’s approach: it hardens two key boundaries where real GitHub payload/arg variability occurs, and it adds tests to prevent regressions. If invalid line bounds become a recurring issue, consider introducing a small normalization/schema layer for webhook payloads and adding lightweight logging when line bounds are coerced to a sentinel.

Files changed (4) +46 / -2

Bug fix (2) +10 / -2
git_patch_processing.pyCoerce line bounds to ints with safe fallback +8/-0

Coerce line bounds to ints with safe fallback

• Adds defensive conversion of line_start/line_end to integers at function entry. Invalid or non-numeric values are mapped to -1 to avoid TypeError/ValueError during hunk extraction.

pr_agent/algo/git_patch_processing.py

github_app.pyFallback to original line fields for outdated comments +2/-2

Fallback to original line fields for outdated comments

• Updates handle_line_comments() to use original_start_line/original_line when start_line/line are null (common for outdated GitHub review comments). Preserves existing behavior by defaulting start_line to end_line for single-line contexts.

pr_agent/servers/github_app.py

Tests (2) +36 / -0
test_diff_pipeline_core.pyAdd tests for invalid and string line parameters +24/-0

Add tests for invalid and string line parameters

• Introduces pytest-based tests ensuring extract_hunk_lines_from_patch() does not crash on non-numeric line bounds. Also verifies that string numeric inputs are coerced to the same results as integer inputs.

tests/unittest/test_diff_pipeline_core.py

test_github_app_timeout_core.pyTest outdated comment line fallback behavior +12/-0

Test outdated comment line fallback behavior

• Adds unit tests confirming /ask argument construction uses original_* line fields when start_line/line are missing. Covers both multi-line (start+end) and single-line fallback behavior.

tests/unittest/test_github_app_timeout_core.py

@qodo-code-review

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

Copy link
Copy Markdown
Contributor

Code Review by Qodo

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

Grey Divider


Remediation recommended

1. OverflowError still unhandled 🐞 Bug ☼ Reliability ⭐ New
Description
extract_hunk_lines_from_patch() catches ValueError/TypeError when coercing
line_start/line_end, but int(float('inf')) raises OverflowError, which falls into the outer
except and returns ("", ""), recreating a silent no-response failure mode for /ask-style flows.
Code

pr_agent/algo/git_patch_processing.py[R420-423]

+        try:
+            line_end = int(line_end)
+        except (ValueError, TypeError):
+            get_logger().warning(f"Ignoring invalid line_end {line_end!r} for '{file_name}'")
Relevance

●●● Strong

Recent PR #2744 accepted the identical OverflowError omission in defensive int conversion.

PR-#2744

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The PR change shows int() conversion guarded only by (ValueError, TypeError). The function-wide
outer handler returns empty strings on any other exception, so an OverflowError from int() would
take that path and drop output entirely. This is the same defensive-int-conversion pitfall already
fixed elsewhere in the codebase.

pr_agent/algo/git_patch_processing.py[413-424]
pr_agent/algo/git_patch_processing.py[469-472]
PR-#2744

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

### Issue description
`extract_hunk_lines_from_patch()` converts `line_start`/`line_end` to `int` but only catches `(ValueError, TypeError)`. `int()` can also raise `OverflowError` for non-finite numeric inputs (e.g., `float('inf')`). When that happens, the function falls into the outer `except` and returns `( "", "" )`, which can prevent downstream flows from responding.

### Issue Context
There is already a repo precedent to include `OverflowError` when doing defensive `int()` conversion.

### Fix Focus Areas
- pr_agent/algo/git_patch_processing.py[415-424]
- pr_agent/algo/git_patch_processing.py[469-472]

### Expected fix
- Extend both `except (ValueError, TypeError):` blocks to `except (ValueError, TypeError, OverflowError):`.
- Keep the current fallback behavior (`-1`) so the function returns a header/empty selection instead of `( "", "" )`.

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


2. Warning logs may spam 🐞 Bug ◔ Observability ⭐ New
Description
The new warning logs fire for common “missing” defaults (e.g., line_start='', line_end=''),
which are used by callers, so normal runs without line parameters can now emit warning-level noise
and drown out actionable warnings.
Code

pr_agent/algo/git_patch_processing.py[R418-419]

+            get_logger().warning(f"Ignoring invalid line_start {line_start!r} for '{file_name}'")
+            line_start = -1
Relevance

●● Moderate

Warning-noise concerns are plausible, but history lacks a close precedent specifically suppressing
expected invalid-parameter warnings.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The PR adds warning logs on int() conversion failure. A caller in-repo uses '' as the default
when the setting isn’t provided, which will always fail int('') and therefore always emit the new
warning when line params are absent.

pr_agent/algo/git_patch_processing.py[415-424]
pr_agent/tools/pr_line_questions.py[67-73]

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

### Issue description
`extract_hunk_lines_from_patch()` now logs `warning` when `line_start`/`line_end` are invalid. Some callers pass empty-string defaults when line parameters are absent, which will now reliably produce warning logs during otherwise normal operation.

### Issue Context
`PR_LineQuestions.run()` reads `line_start`/`line_end` from settings with `''` defaults; when those settings are not present, the new code will warn even though the absence of line ranges may be expected for some invocations.

### Fix Focus Areas
- pr_agent/algo/git_patch_processing.py[415-424]
- pr_agent/tools/pr_line_questions.py[67-73]

### Expected fix (pick one)
- Only warn when the value is not in a small “expected missing” set like `{None, "", "None"}` (log at `debug` for these cases), OR
- Downgrade these messages to `info`/`debug`, OR
- Add an explicit `if line_start in (...): line_start = -1` path without warning, keeping warnings for truly unexpected types/values.

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


3. Single-quoted sample path assertion 📘 Rule violation ⚙ Maintainability
Description
The new test uses a single-quoted string literal in assert "## File: 'src/sample.py'" in full,
contrary to the repository requirement that Python string literals use double quotes. This is a
style compliance violation in the submitted test code.
Code

tests/unittest/test_diff_pipeline_core.py[241]

+        assert "## File: 'src/sample.py'" in full
Relevance

●●● Strong

Recent test-style precedents accept converting single-quoted literals to double quotes; the
repository rule explicitly requires it.

PR-#2569
PR-#2526

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694657 requires all Python string literals in changed files to use double quotes.
The added assertion at the cited line is delimited with single quotes.

Rule 2694657: Use double quotes for all Python string literals
tests/unittest/test_diff_pipeline_core.py[241-241]

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 assertion contains a single-quoted Python string literal, violating the double-quote convention.

## Issue Context
Keep the expected embedded single quotes around `src/sample.py` while delimiting the Python literal with double quotes.

## Fix Focus Areas
- tests/unittest/test_diff_pipeline_core.py[241-241]

ⓘ 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: ⚖️ Balanced

Grey Divider

Tip of the day
💡 Did you know, you can switch off images and animations for a plain-text comment

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit cae68c5 ⚖️ Balanced

Results up to commit f51dbd1 🚀 Fast


🐞 Bugs (0) 📘 Rule violations (1) 📎 Requirement gaps (0) 🎨 UX issues (0) 📜 Skill insights (0)


Remediation recommended
1. Single-quoted sample path assertion 📘 Rule violation ⚙ Maintainability
Description
The new test uses a single-quoted string literal in assert "## File: 'src/sample.py'" in full,
contrary to the repository requirement that Python string literals use double quotes. This is a
style compliance violation in the submitted test code.
Code

tests/unittest/test_diff_pipeline_core.py[241]

+        assert "## File: 'src/sample.py'" in full
Relevance

●●● Strong

Recent test-style precedents accept converting single-quoted literals to double quotes; the
repository rule explicitly requires it.

PR-#2569
PR-#2526

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694657 requires all Python string literals in changed files to use double quotes.
The added assertion at the cited line is delimited with single quotes.

Rule 2694657: Use double quotes for all Python string literals
tests/unittest/test_diff_pipeline_core.py[241-241]

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 assertion contains a single-quoted Python string literal, violating the double-quote convention.

## Issue Context
Keep the expected embedded single quotes around `src/sample.py` while delimiting the Python literal with double quotes.

## Fix Focus Areas
- tests/unittest/test_diff_pipeline_core.py[241-241]

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


Grey Divider

Qodo Logo

@rophy

rophy commented Aug 23, 2026

Copy link
Copy Markdown
Contributor Author

The string literal is already double-quoted — the single quotes inside are part of the expected output (## File: 'src/sample.py'), not the Python delimiter. Same pattern as the existing tests at line 164.

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the report and for fixing it yourself the same day; the captured payload made this quick to confirm. Verified against three comment shapes, and there is one thing inline I would rather not lose before this merges.

Comment thread pr_agent/servers/github_app.py Resolved
Comment thread pr_agent/algo/git_patch_processing.py Resolved
Address review feedback: log a warning when line_start/line_end
are coerced from invalid values to -1, so the fallback isn't silent.
@qodo-code-review

Copy link
Copy Markdown
Contributor

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

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for adding the warnings, that is what I meant: the coercion is greppable now. Approving.

One optional extra. Qodo is right that OverflowError escapes the tuple, and it is reachable: the question text is appended last to the /ask_line command, so /ask ... --line_start=.inf overrides the payload value, and _fix_key_value yaml-parses .inf into a float. Nothing crashes, because the function's own except Exception catches it and returns ("", ""), but that is an error log and no answer rather than the warning and -1 you have just added. Adding OverflowError to both tuples makes it consistent, and token_handler.py:131 and utils.py:1173 already spell it that way.

@IsmaelMartinez
IsmaelMartinez merged commit 357c573 into The-PR-Agent:main Aug 24, 2026
5 checks passed
@rophy
rophy deleted the fix/ask-outdated-comment-crash branch August 24, 2026 23:28
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.

fix: /ask on outdated review comments crashes with TypeError

2 participants