Skip to content

fix(bigquery): coerce LIMIT before SQL interpolation - #2636

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

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

Conversation

@Bartok9

@Bartok9 Bartok9 commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Summary

BigQuery limit wrap used int(limit) only inside _apply_limit after a None check; add explicit coerce (negatives/injection) on query().

Test plan

  • cd core/wren && .venv/bin/python -m pytest tests/unit/test_bigquery_coerce_limit.py -q (4 passed)

Summary by CodeRabbit

  • Bug Fixes
    • Improved BigQuery query limit handling.
    • Rejects negative or invalid limit values before executing queries.
    • Safely normalizes optional limits and prevents unsafe SQL limit input.

Reject negative/non-numeric limit values before the subquery LIMIT wrap.
@github-actions github-actions Bot added python Pull requests that update Python code core labels Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The BigQuery connector now coerces optional limits to integers, rejects negative values, and validates limits before SQL interpolation. Unit tests cover null, invalid, injection-like, and valid integer inputs.

Changes

BigQuery limit validation

Layer / File(s) Summary
Limit coercion and query application
core/wren/src/wren/connector/bigquery.py, core/wren/tests/unit/test_bigquery_coerce_limit.py
_coerce_limit preserves None, converts values to integers, and rejects negative values. query validates the limit before applying SQL limiting. Tests cover invalid inputs and integer LIMIT rendering.

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

Possibly related PRs

  • Canner/WrenAI#2465: Both changes modify BigQuery limit handling in BigQueryConnector.query.
  • Canner/WrenAI#2624: Both changes implement equivalent BigQuery limit coercion and validation.
  • Canner/WrenAI#2625: Both changes validate limits before SQL interpolation and add connector tests.

Poem

A rabbit checks the limit line,
Turns odd inputs into integers fine.
Negative bounds are sent away,
Safe SQL hops into play.
BigQuery runs with limits bright,
And tests keep watch throughout the night.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description includes a summary and test command but omits the required failure reproduction, duplicate check, and explicit CI coverage. Add the actual failure and error output, state whether the test runs in CI, and document which open PRs were checked for duplicates.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: coercing BigQuery LIMIT values before SQL interpolation.
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/tests/unit/test_bigquery_coerce_limit.py (1)

16-18: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Extend tests to cover the runtime contract.

test_apply_limit_uses_int passes an already-integer 2, so it does not test coercion. It also bypasses BigQueryConnector.query, so it cannot detect a regression that executes SQL before validation. Add a numeric-string case, a -0.5 regression case, and a mocked query-path test that confirms invalid input does not call connection.query.

Also applies to: 26-27

🤖 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/tests/unit/test_bigquery_coerce_limit.py` around lines 16 - 18,
Extend the tests around _coerce_limit and BigQueryConnector.query to cover
numeric-string coercion, rejection of -0.5, and the query execution path. Mock
the connection and verify invalid limits raise before connection.query is
called, while retaining coverage that valid numeric strings are coerced
correctly.
🤖 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/bigquery.py`:
- Around line 14-15: Update _coerce_limit to validate the original limit for
negativity before applying int(limit), ensuring values such as -0.5 and
Decimal("-0.5") are rejected rather than converted to zero; preserve the
existing handling for valid integral limits.

---

Nitpick comments:
In `@core/wren/tests/unit/test_bigquery_coerce_limit.py`:
- Around line 16-18: Extend the tests around _coerce_limit and
BigQueryConnector.query to cover numeric-string coercion, rejection of -0.5, and
the query execution path. Mock the connection and verify invalid limits raise
before connection.query is called, while retaining coverage that valid numeric
strings are coerced correctly.
🪄 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: c511f411-1536-42bb-b3ab-e3cebf167029

📥 Commits

Reviewing files that changed from the base of the PR and between 74bf59e and 07dfc8f.

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

Comment on lines +14 to +15
coerced = int(limit)
if coerced < 0:

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n -C 3 'limit|BigQueryConnector|\.query\(' core/wren/src core/wren/tests

Repository: Canner/WrenAI

Length of output: 50372


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the relevant limit helper and query path.
sed -n '1,110p' core/wren/src/wren/connector/bigquery.py
printf '\n--- coere_limit usages ---\n'
rg -n -C 3 '_coerce_limit|def query|raw_cursor_sql' core/wren/src/wren/connector/bigquery.py

# Behavioral probe for Python conversion semantics across representative inputs.
python3 - <<'PY'
from decimal import Decimal
values = [-1, -0.5, -0.9; Decimal("-0.5"), Decimal("-0"), 0, 0.5, "1", None]
results = []
for limit in values:
    try:
        coerced = int(limit)
        ok = (limit is None) or (coerced >= 0)
        results.append((repr(limit), coerced, ok))
    except Exception as exc:
        results.append((repr(limit), "<exception>", type(exc).__name__))
for row in results:
    print(row)
PY

Repository: Canner/WrenAI

Length of output: 3943


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Behavioral probe for Python conversion semantics across representative inputs.
python3 - <<'PY'
from decimal import Decimal

values = [-1, -0.5, -0.9, Decimal("-0.5"), Decimal("-0"), 0, 0.5, "1", None]

def current(limit):
    coerced = int(limit)
    return (coerced is None or coerced >= 0), coerced

for limit in values:
    try:
        ok, coerced = current(limit)
        print(repr(limit), "=>", coerced, "accepted_by_current=", ok)
    except Exception as exc:
        print(repr(limit), "=> exception", type(exc).__name__)
PY

Repository: Canner/WrenAI

Length of output: 482


Validate the original limit before truncation.

int(limit) converts -0.5 and Decimal("-0.5") to 0, so _coerce_limit accepts those negative limits for BigQuery and passes LIMIT 0 through. Check negativity on the original value before converting, or reject non-integral values explicitly.

🤖 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/bigquery.py` around lines 14 - 15, Update
_coerce_limit to validate the original limit for negativity before applying
int(limit), ensuring values such as -0.5 and Decimal("-0.5") are rejected rather
than converted to zero; preserve the existing handling for valid integral
limits.

@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 specificallybigquery.py:21 already interpolates {int(limit)}; as above, the delta is the negativity check only.

@goldmedal goldmedal closed this Aug 3, 2026
@Bartok9

Bartok9 commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @goldmedal — fair close. Per-connector PRs were the wrong packaging; I'll fold the negativity check and shared coerce_limit wiring into #2624 as one consolidated refactor(connector) (strictest semantics, canner.py + mysql.py, single test module).

Noted that BigQuery already used {int(limit)} so the delta here was thin on its own.

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