Skip to content

fix(pr_agent/algo/utils.py): reporting an unreadable token budget instead of ignoring it - #2744

Merged
IsmaelMartinez merged 6 commits into
The-PR-Agent:mainfrom
dwin-gharibi:fix/clip-tokens-invalid-budget
Aug 22, 2026
Merged

IsmaelMartinez merged 6 commits into
The-PR-Agent:mainfrom
dwin-gharibi:fix/clip-tokens-invalid-budget

Conversation

@dwin-gharibi

Copy link
Copy Markdown
Contributor

Closes #2743.

Description

The whole body of clip_tokens is wrapped in except Exception: warning; return text, so a non-integer max_tokens returns the text unchanged.

Root cause

max_tokens is used inside the broad try, so a TypeError from the arithmetic is caught by the
same handler that exists to protect against encoder failures, and the warning it logs does not
name the budget as the cause.

The fix

Coerce max_tokens to int before the broad try. When it cannot be read as a number, log a warning that names the value and return the text — the previous outcome, but now with a signal.

Behaviour change

Before clip_tokens(text, "50") returns the text unclipped with a generic warning
After An unreadable budget is named in the warning; a numeric string budget is honoured and clips

Files changed

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

Testing

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

$ PYTHONPATH=. pytest tests/unittest/test_clip_tokens_invalid_budget.py
4 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
-> 1965 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

Numeric budgets are unaffected. The broad except is left in place for genuine encoder failures.

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:18

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

Report non-numeric token budgets in clip_tokens (instead of silently ignoring)

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Validate/coerce max_tokens before encoder try/except to avoid masking TypeError/ValueError
• Emit a targeted warning when max_tokens is unreadable and return text unchanged
• Add regression tests covering string budgets, invalid budgets, and unchanged behavior
Diagram

graph TD
  A[Caller] --> B["clip_tokens()"] --> C["int(max_tokens)"] --> D{Budget valid?}
  D -- "No" --> E["log warning"] --> F["return text"]
  D -- "Yes" --> G["TokenEncoder + clip"] --> H["return clipped/unchanged"]
  subgraph Legend
    direction LR
    _p["Process"] ~~~ _d{"Decision"}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Raise TypeError/ValueError for invalid max_tokens
  • ➕ Fails fast and forces callers to fix misuse immediately
  • ➕ Avoids silently exceeding context windows
  • ➖ Breaking behavior change for existing integrations passing bad types
  • ➖ Harder to use in best-effort/observability-first paths
2. Narrow the broad try/except to only encoder operations
  • ➕ Prevents non-encoder errors from being swallowed
  • ➕ Keeps failure mode explicit without extra pre-validation
  • ➖ More invasive refactor with higher risk of behavior drift
  • ➖ Still needs a policy decision for bad budgets (warn vs raise vs coerce)

Recommendation: Current approach is the best fit: it preserves prior behavior (returning text unchanged) while making the failure diagnosable and also accepting numeric strings. Raising would be a breaking change, and narrowing the broad try/except is a larger refactor than needed for this bug.

Files changed (2) +49 / -0

Bug fix (1) +8 / -0
utils.pyValidate/coerce max_tokens before encoder try/except and warn on invalid budget +8/-0

Validate/coerce max_tokens before encoder try/except and warn on invalid budget

• Adds an early int() coercion for max_tokens before the broad try/except that guards encoder failures. If conversion fails, logs a warning that explicitly names the non-numeric value and returns the original text unchanged.

pr_agent/algo/utils.py

Tests (1) +41 / -0
test_clip_tokens_invalid_budget.pyRegression tests for non-numeric and string token budgets in clip_tokens +41/-0

Regression tests for non-numeric and string token budgets in clip_tokens

• Introduces tests verifying that quoted numeric budgets clip, unreadable budgets emit a specific warning and return unchanged text, numeric budgets retain existing clipping behavior, and short text remains unchanged within a large budget.

tests/unittest/test_clip_tokens_invalid_budget.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. Catch infinite budget conversion ✓ Resolved 🐞 Bug ☼ Reliability
Description
The new int(max_tokens) conversion catches only TypeError and ValueError, so a budget such as
float("inf") raises OverflowError before the existing fallback handler can run. This changes
clip_tokens from returning the original text on processing failures to raising, and
CONFIG.MAX_DESCRIPTION_TOKENS is passed through without type validation by a production caller.
Code

pr_agent/algo/utils.py[R1106-1107]

+        max_tokens = int(max_tokens)
+    except (TypeError, ValueError):
Relevance

●●● Strong

Recent reliability reviews accept defensive validation for malformed configuration and reachable
runtime inputs.

PR-#2503
PR-#2387

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The changed conversion executes before the broad processing try, and its exception tuple excludes
OverflowError; the repository caller forwards the configuration value directly, so this input is
reachable in production. The prior fallback path explicitly returned the original text for
processing exceptions, demonstrating the behavior being lost for this conversion failure.

pr_agent/algo/utils.py[1105-1111]
pr_agent/algo/utils.py[1113-1130]
pr_agent/git_providers/git_provider.py[260-269]
pr_agent/algo/utils.py[1061-1067]

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

### Issue description
`int(max_tokens)` can raise `OverflowError` for values such as `float("inf")`, but the new handler catches only `TypeError` and `ValueError`. This lets `clip_tokens` raise before its established text-return fallback.

### Issue Context
Preserve the existing behavior for unreadable budgets: log a warning and return the original text. `CONFIG.MAX_DESCRIPTION_TOKENS` is passed directly by the GitProvider caller, so non-finite values can reach this function.

### Fix Focus Areas
- pr_agent/algo/utils.py[1106-1107]
- pr_agent/git_providers/git_provider.py[260-269]

Catch `OverflowError` as part of the invalid-budget path (and add a regression test for an infinite float budget).

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



Remediation recommended

2. Empty text bypasses budget warning ✓ Resolved 🐞 Bug ◔ Observability ⭐ New
Description
clip_tokens returns immediately for empty/falsy text before executing the new int(max_tokens)
validation, so clip_tokens("", "not-a-number") still silently ignores an unreadable budget. This
leaves the diagnostic fix incomplete for empty inputs and makes warning behavior depend on text
content rather than budget validity.
Code

pr_agent/algo/utils.py[R1106-1107]

+        max_tokens = int(max_tokens)
+    except (TypeError, ValueError, OverflowError):
Relevance

●●● Strong

Recent accepted precedent favors validating inputs early even when falsy/edge-case, matching PR
intent to surface unreadable budgets.

PR-#2610

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The PR branch places the new conversion after the function's if not text: return text guard, while
the regression tests exercise only LONG_TEXT; therefore an invalid budget paired with empty text
never reaches the added warning block.

pr_agent/algo/utils.py[1102-1111]
tests/unittest/test_clip_tokens_invalid_budget.py[28-34]

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

## Issue description
Invalid `max_tokens` values are not reported when `text` is empty because the existing early return precedes the new conversion.

## Issue Context
The PR's purpose is to warn whenever a budget cannot be read, while preserving the returned text. The current implementation only does so for truthy text.

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

Move the budget coercion/invalid-budget warning before the empty-text early return, or otherwise ensure empty inputs still validate and report an unreadable budget without changing valid empty-text behavior.

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



Informational

3. io import is nested ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The new test places the standard-library io import inside _capture instead of the file's
top-level standard-library import section, leaving imports split across scopes and violating the
required isort-style grouping.
Code

tests/unittest/test_clip_tokens_invalid_budget.py[R9-10]

+    import io
+    buffer = io.StringIO()
Relevance

● Weak

A close precedent accepted nested standard-library imports in tests, indicating this
import-placement nit is not enforced.

PR-#2467

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The changed test has top-level local imports at lines 2-3, while the added standard-library import
appears inside _capture at line 10. The checklist requires contiguous, correctly ordered import
sections in modified Python files.

Rule 2694656: Group Python imports according to isort sections and order
tests/unittest/test_clip_tokens_invalid_budget.py[2-10]

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 test imports the standard-library module `io` inside `_capture`, rather than keeping standard-library imports in the top-level import block.

## Issue Context
Imports in modified Python files must be grouped by isort section: standard library, third-party, then local imports, with each section contiguous.

## Fix Focus Areas
- tests/unittest/test_clip_tokens_invalid_budget.py[1-10]

ⓘ 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, low-risk fix that moves budget coercion ahead of the existing fallback and adds focused regression coverage, with no security, API, schema, or broad cross-cutting impact.

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

Previous reviews

Review updated until commit 7a0d880

Results up to commit 35e8416 🚀 Fast


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


Action required
1. Catch infinite budget conversion ✓ Resolved 🐞 Bug ☼ Reliability
Description
The new int(max_tokens) conversion catches only TypeError and ValueError, so a budget such as
float("inf") raises OverflowError before the existing fallback handler can run. This changes
clip_tokens from returning the original text on processing failures to raising, and
CONFIG.MAX_DESCRIPTION_TOKENS is passed through without type validation by a production caller.
Code

pr_agent/algo/utils.py[R1106-1107]

+        max_tokens = int(max_tokens)
+    except (TypeError, ValueError):
Relevance

●●● Strong

Recent reliability reviews accept defensive validation for malformed configuration and reachable
runtime inputs.

PR-#2503
PR-#2387

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The changed conversion executes before the broad processing try, and its exception tuple excludes
OverflowError; the repository caller forwards the configuration value directly, so this input is
reachable in production. The prior fallback path explicitly returned the original text for
processing exceptions, demonstrating the behavior being lost for this conversion failure.

pr_agent/algo/utils.py[1105-1111]
pr_agent/algo/utils.py[1113-1130]
pr_agent/git_providers/git_provider.py[260-269]
pr_agent/algo/utils.py[1061-1067]

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

### Issue description
`int(max_tokens)` can raise `OverflowError` for values such as `float("inf")`, but the new handler catches only `TypeError` and `ValueError`. This lets `clip_tokens` raise before its established text-return fallback.

### Issue Context
Preserve the existing behavior for unreadable budgets: log a warning and return the original text. `CONFIG.MAX_DESCRIPTION_TOKENS` is passed directly by the GitProvider caller, so non-finite values can reach this function.

### Fix Focus Areas
- pr_agent/algo/utils.py[1106-1107]
- pr_agent/git_providers/git_provider.py[260-269]

Catch `OverflowError` as part of the invalid-budget path (and add a regression test for an infinite float budget).

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



Informational
2. io import is nested ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The new test places the standard-library io import inside _capture instead of the file's
top-level standard-library import section, leaving imports split across scopes and violating the
required isort-style grouping.
Code

tests/unittest/test_clip_tokens_invalid_budget.py[R9-10]

+    import io
+    buffer = io.StringIO()
Relevance

● Weak

A close precedent accepted nested standard-library imports in tests, indicating this
import-placement nit is not enforced.

PR-#2467

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The changed test has top-level local imports at lines 2-3, while the added standard-library import
appears inside _capture at line 10. The checklist requires contiguous, correctly ordered import
sections in modified Python files.

Rule 2694656: Group Python imports according to isort sections and order
tests/unittest/test_clip_tokens_invalid_budget.py[2-10]

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 test imports the standard-library module `io` inside `_capture`, rather than keeping standard-library imports in the top-level import block.

## Issue Context
Imports in modified Python files must be grouped by isort section: standard library, third-party, then local imports, with each section contiguous.

## Fix Focus Areas
- tests/unittest/test_clip_tokens_invalid_budget.py[1-10]

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


Grey Divider

Qodo Logo

Comment thread pr_agent/algo/utils.py Resolved
@github-actions github-actions Bot added the bug label Aug 21, 2026
@qodo-code-review

Copy link
Copy Markdown
Contributor

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

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 7a0d880

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

Copy link
Copy Markdown
Collaborator

Merged, thanks. Much better to hear about a bad budget than have it swallowed.

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.

clip_tokens silently ignores a non-integer budget and returns the text unclipped

3 participants