Skip to content

fix(trino): coerce LIMIT before SQL interpolation - #2626

Closed
Bartok9 wants to merge 1 commit into
Canner:mainfrom
Bartok9:fix/trino-coerce-limit
Closed

fix(trino): coerce LIMIT before SQL interpolation#2626
Bartok9 wants to merge 1 commit into
Canner:mainfrom
Bartok9:fix/trino-coerce-limit

Conversation

@Bartok9

@Bartok9 Bartok9 commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Summary

Coerce limit to a non-negative int before Trino LIMIT subquery wrapping.

Motivation

Same injection/negative-limit hole as other connectors that interpolate {limit}.

Verification

cd core/wren && .venv/bin/python -m pytest tests/unit/test_trino_coerce_limit.py -q
3 passed

Summary by CodeRabbit

  • Bug Fixes
    • Improved query limit handling by accepting valid numeric values and rejecting negative or invalid input.
    • Prevented injection-like content from being included in generated SQL.
    • Added validation to ensure SQL limits are safely formatted before execution.

Reject negative and non-numeric limits before building the Trino LIMIT wrapper.
@github-actions github-actions Bot added python Pull requests that update Python code core labels Jul 30, 2026
@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Trino query limits are now coerced to non-negative integers before SQL interpolation. Unit tests cover negative, injection-like, and numeric-string limit inputs.

Changes

Trino LIMIT validation

Layer / File(s) Summary
Limit coercion and query integration
core/wren/src/wren/connector/trino.py
Adds _coerce_limit and invokes it before applying SQL LIMIT clauses.
Limit validation tests
core/wren/tests/unit/test_trino_coerce_limit.py
Tests rejection of negative and injection-like values, plus acceptance of numeric strings without injected SQL content.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested reviewers: goldmedal

Poem

I’m a rabbit guarding the query gate,
Numbers pass; bad strings wait.
No dangling drops can hop inside,
Safe LIMITs now run with pride.
Test by test, the burrow’s bright!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description has summary, motivation, and verification, but it omits the required failure reproduction/actual error and duplicate-check details. Add a 'What failure does this repair?' section with repro steps and the observed error, plus a duplicate-check note listing related open PRs.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main behavioral change to Trino LIMIT handling.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
core/wren/src/wren/connector/trino.py (1)

499-499: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Align the type hints with the accepted limit inputs.

The tests intentionally pass "4", but both _coerce_limit and TrinoConnector.query declare int | None. If numeric strings are supported, update both annotations to include str (or use a shared alias) so static callers are not told this valid input is invalid.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@core/wren/src/wren/connector/trino.py` at line 499, Update the type
annotations for both _coerce_limit and TrinoConnector.query to accept str
alongside int and None, preferably through a shared limit type alias if one
exists or is appropriate. Keep the existing coercion behavior unchanged so
numeric string inputs such as "4" remain supported.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@core/wren/src/wren/connector/trino.py`:
- Around line 459-470: Update _coerce_limit to reject negative fractional
numeric inputs before int coercion, while preserving acceptance of valid
non-negative integral limits and existing rejection of negative integers. Add a
regression test confirming limit=-0.5 raises ValueError rather than becoming
LIMIT 0.

---

Nitpick comments:
In `@core/wren/src/wren/connector/trino.py`:
- Line 499: Update the type annotations for both _coerce_limit and
TrinoConnector.query to accept str alongside int and None, preferably through a
shared limit type alias if one exists or is appropriate. Keep the existing
coercion behavior unchanged so numeric string inputs such as "4" remain
supported.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3118ae98-ffaf-450d-9a5d-fdd79d8b7db5

📥 Commits

Reviewing files that changed from the base of the PR and between 32d76bf and bc63c89.

📒 Files selected for processing (2)
  • core/wren/src/wren/connector/trino.py
  • core/wren/tests/unit/test_trino_coerce_limit.py

Comment on lines +459 to +470
def _coerce_limit(limit: int | None) -> int | None:
"""Validate and coerce a user-supplied ``limit`` to a non-negative ``int``.

``int(limit)`` rejects strings like ``"5 OR 1=1"`` so the value can be
safely interpolated into SQL. Negative limits are also rejected.
"""
if limit is None:
return None
coerced = int(limit)
if coerced < 0:
raise ValueError(f"limit must be non-negative, got {coerced}")
return coerced

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reject fractional negative limits before coercion.

int(-0.5) becomes 0, so the check at Line 468 accepts an originally negative limit and executes LIMIT 0. Validate the original numeric value before truncation, or reject non-integral numeric inputs; add a regression test for limit=-0.5.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@core/wren/src/wren/connector/trino.py` around lines 459 - 470, Update
_coerce_limit to reject negative fractional numeric inputs before int coercion,
while preserving acceptance of valid non-negative integral limits and existing
rejection of negative integers. Add a regression test confirming limit=-0.5
raises ValueError rather than becoming LIMIT 0.

@goldmedal

Copy link
Copy Markdown
Collaborator

Closing in favour of a single consolidated change — thanks for the work, the underlying tidy-up is worth doing, just not as one PR per connector.

Why this is being closed rather than reviewed:

  1. This is one mechanical change spread across eight PRs. The contribution bar added in docs: set an explicit contribution bar for agent-authored PRs #2602 asks for exactly this to be a single diff: "A mechanical change repeated across several files or connectors belongs in one PR, not one PR per file. Reviewers need to see the resulting convention in a single diff."

  2. A shared helper already exists in this same batch, and none of these PRs use it. refactor(connector): centralize LIMIT coercion #2624 adds coerce_limit() to connector/base.py. Every other PR in the series re-declares a private _coerce_limit in its own module instead of importing it. Merged as-is the repo would carry nine copies of the same function (the eight here plus the existing one at connector/mysql.py:44).

  3. The copies have already diverged before merge. base.py (refactor(connector): centralize LIMIT coercion #2624), postgres, trino, oracle, redshift and bigquery use int(limit) then a negativity check; fix(clickhouse): coerce LIMIT before SQL interpolation #2627 (clickhouse) additionally rejects fractional negatives such as -0.5 via numbers.Number; fix(duckdb): coerce LIMIT before SQL interpolation #2637 (duckdb) additionally rejects bool and non-integral float. Three different semantics for one contract is the specific outcome a shared helper prevents.

  4. Coverage is inconsistent. connector/canner.py:255 interpolates a bare {limit} and is not covered by any PR in the series, while bigquery, duckdb and redshift already interpolate {int(limit)} today — for those three the only behavioural delta is the negativity check.

On the fix: label and the stated failure. The reproduction in the description calls connector.query(sql, limit="1; DROP TABLE users") directly. Tracing the call paths:

  • run_sql in mcp_server.py declares limit: int | None, so a non-numeric string is rejected by tool-argument validation, and mcp_server.py:84 already rejects negatives and clamps to MAX_ROW_LIMIT.
  • The CLI declares --limit/-l as Optional[int], so a non-integer is rejected at parse time.
  • That leaves Engine.query(sql, limit) as a Python API. At that boundary the caller already supplies sql verbatim — anyone able to pass limit="1; DROP TABLE t" can pass that as sql instead. limit is not a lower-trust channel than sql there, so this is not an injection path.

What remains is genuine but smaller: a negative limit currently surfaces as a driver-level error instead of a clear ValueError, and the coercion contract is inconsistent across connectors. That is refactor:, per "fix: requires a reproducible failure that the change repairs."

What we would take instead — a single PR, refactor(connector): centralize LIMIT coercion, that:

  • keeps one coerce_limit() in connector/base.py, with the strictest semantics of the three variants above (reject bool, non-integral values, and negatives);
  • routes every interpolating connector through it — including canner.py, and replacing the private copy in mysql.py;
  • leaves ConnectorABC.query's signature as int | None (see the per-PR note on fix(duckdb): coerce LIMIT before SQL interpolation #2637 below);
  • tests the helper once in tests/unit/test_coerce_limit.py, with at most a smoke test per connector proving it is wired in, rather than repeating the same six cases eight times.

#2624 is the natural home for that; it is being kept open with a note to that effect.


On this PR specificallytrino.py:489 is a bare-{limit} site, so it does belong in the consolidated change.

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

Labels

core python Pull requests that update Python code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants