Skip to content

fix(snowflake): push LIMIT into SQL and strip trailing semicolon on wrap - #2456

Merged
goldmedal merged 3 commits into
Canner:mainfrom
Bartok9:fix/snowflake-pushdown-limit
Jul 13, 2026
Merged

goldmedal merged 3 commits into
Canner:mainfrom
Bartok9:fix/snowflake-pushdown-limit

Conversation

@Bartok9

@Bartok9 Bartok9 commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Push query(..., limit=N) into Snowflake SQL via SELECT * FROM (<sql>) AS _wren_sub LIMIT N.
  • Strip a trailing semicolon before wrapping so ;-terminated user SQL cannot break composition.
  • Lazy-import snowflake.connector so unit tests do not require the optional extra.

Motivation

The previous path ran the full statement and used arrow_table.slice(0, limit). Large queries paid full scan + transfer cost on the client even when Aster only needed a sample/page. Other connectors (postgres/redshift/clickhouse/trino) already apply LIMIT server-side; Snowflake was the outlier. Trailing-semicolon strip matches the established wrap helpers.

Verification

  • PYTHONPATH=src pytest tests/unit/test_snowflake_limit_pushdown.py → 3 passed
  • Asserted executed SQL for SELECT 1 AS x; + limit=5 is
    SELECT * FROM (SELECT 1 AS x) AS _wren_sub LIMIT 5
  • Without limit, original SQL is executed unchanged.

License

core/wren/** only (Apache-2.0).

Summary by CodeRabbit

  • Bug Fixes
    • Improved Snowflake query execution with limit by pushing the LIMIT into the SQL run on Snowflake rather than slicing results in Python.
    • More reliable SQL wrapping by stripping only a trailing semicolon/whitespace (while keeping semicolons inside quoted strings and respecting line-comment boundaries).
    • Updated Snowflake diagnostics so reported SQL reflects the actual composed query that was executed (including for dry_run).
  • Tests
    • Added unit coverage for trailing-semicolon cleanup, LIMIT pushdown SQL rewriting, and the no-limit execution path.

query(limit=N) previously executed the full statement and sliced the
Arrow table in Python, so large results were fully downloaded even when
the caller only needed N rows. Wrap user SQL as a subquery with LIMIT and
strip a trailing semicolon so composition stays valid. Lazy-import the
snowflake driver so unit tests can run without the optional extra.
@github-actions github-actions Bot added python Pull requests that update Python code core labels Jul 9, 2026
@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 455b4b39-eb3e-4472-97d3-82729a0f9fab

📥 Commits

Reviewing files that changed from the base of the PR and between 46d63ac and 5501e94.

📒 Files selected for processing (2)
  • core/wren/src/wren/connector/snowflake.py
  • core/wren/tests/unit/test_snowflake_limit_pushdown.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • core/wren/tests/unit/test_snowflake_limit_pushdown.py
  • core/wren/src/wren/connector/snowflake.py

Walkthrough

Modifies the Snowflake connector to defer the Snowflake import, strip only trailing semicolons before subquery wrapping, push LIMIT into executed SQL, and centralize ProgrammingError handling. Adds unit tests for semicolon handling and SQL rewrite behavior.

Changes

Snowflake LIMIT pushdown

Layer / File(s) Summary
Semicolon-stripping helper and deferred import
core/wren/src/wren/connector/snowflake.py
Adds _strip_trailing_semicolon(sql) and defers snowflake.connector import to connection/error lookup time.
Query LIMIT pushdown and error handling
core/wren/src/wren/connector/snowflake.py
query wraps semicolon-stripped SQL in SELECT * FROM (...) ... LIMIT ... when limit is set, executes the composed SQL directly, and reports composed SQL in invalid-query metadata; dry_run reuses centralized ProgrammingError handling.
Unit tests for stripping and LIMIT wrapping
core/wren/tests/unit/test_snowflake_limit_pushdown.py
Tests cover trailing-semicolon stripping, pushed-down LIMIT execution, trailing-comment wrapping, and unchanged SQL execution when limit is omitted.

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

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant SnowflakeConnector
  participant Cursor

  Caller->>SnowflakeConnector: query(sql, limit=5)
  SnowflakeConnector->>SnowflakeConnector: _strip_trailing_semicolon(sql)
  SnowflakeConnector->>Cursor: execute SELECT * FROM (cleaned sql) LIMIT 5
  Cursor-->>SnowflakeConnector: Arrow table result
  SnowflakeConnector-->>Caller: query result
Loading

Possibly related PRs

  • Canner/WrenAI#2268: Both PRs modify the native Snowflake connector path, including query and dry_run handling.
  • Canner/WrenAI#2407: Both PRs add trailing-semicolon stripping before wrapping user SQL in a subquery.
  • Canner/WrenAI#2420: Both PRs use _strip_trailing_semicolon(sql) when composing wrapped SQL for Snowflake-style execution.

Suggested reviewers: goldmedal

Poem

I’m a bunny with SQL in my paws,
I trimmed the last semicolon with applause.
Then LIMIT hopped inside the nest,
And Snowflake ran the query best.
🐰

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main Snowflake change: pushing LIMIT into SQL and stripping a trailing semicolon when wrapping.
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: 2

🤖 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/snowflake.py`:
- Around line 81-84: The Snowflake query wrapper in the code that builds
executed SQL should isolate the user-provided SQL from the trailing wrapper text
so a final `--` comment cannot swallow the closing alias and LIMIT clause.
Update the logic in the SQL construction path that uses
`_strip_trailing_semicolon(sql)` to place the inner SQL on its own lines inside
the `SELECT * FROM (...) AS _wren_sub LIMIT ...` wrapper, ensuring the suffix
remains outside any user comment and the wrapped query stays balanced.
- Around line 80-84: The LIMIT wrapper in SnowflakeQuery execution can both
change ordered preview results and be broken by trailing line comments. Update
the logic that builds the wrapped SQL in the limit-handling branch so it
preserves the original ORDER BY/LIMIT semantics (matching the current
Python-slice behavior) and ensures any trailing -- comment in
_strip_trailing_semicolon(sql) cannot swallow the closing wrapper, e.g. by
terminating the comment before appending the outer query. Use the existing
Snowflake query execution path and the _strip_trailing_semicolon helper as the
main points to adjust.
🪄 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

Run ID: f5ccc4df-8e0d-471a-9afa-4ee8def9e83a

📥 Commits

Reviewing files that changed from the base of the PR and between c4de8ac and b23df32.

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

@Bartok9

Bartok9 commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

Fixed both CodeRabbit findings in 5501e94: the user SQL now sits on its own line inside the wrapper — SELECT * FROM (\n<sql>\n) AS _wren_sub LIMIT N — so a trailing -- comment in the inner SQL is terminated by the newline and can no longer swallow the closing paren, alias, or LIMIT clause. ORDER BY semantics are preserved (the outer LIMIT wraps the fully-ordered subquery, matching the prior Python-slice behavior). Added test_query_limit_survives_trailing_line_comment covering the comment case.

@goldmedal

Copy link
Copy Markdown
Collaborator

LGTM overall — Snowflake was the last outlier fetching a full result set to slice in Python, so pushing LIMIT into the SQL is a good fix, and the newline-delimited wrap + trailing-line-comment test are a nice touch. The lazy snowflake.connector import (and _programming_error()) to keep the unit tests free of the optional extra is reasonable.

One nit on the ORDER BY comment:

statements that already contain an ORDER BY keep their ordering under the outer LIMIT

Per Snowflake's docs, an ORDER BY inside a subquery isn't guaranteed to survive to the outer query, so ORDER BY … LIMIT N previews can now return a different set of rows than the old Python-slice path (which ran the full ordered query, then took the first N). The behavior change itself is fine — it matches all the other pushdown connectors — but the comment asserts an ordering guarantee Snowflake doesn't make. Suggest softening it to note the outer LIMIT yields an arbitrary N rows unless ORDER BY and LIMIT sit at the same level.

Non-blocking follow-up thought: _strip_trailing_semicolon + the wrap expression are now duplicated across ~8 connectors with small differences (alias name, single-line vs newline, {limit} vs {int(limit)}). A shared wrap_with_limit(sql, limit) in connector/base.py would unify all of that — including the comment-safety this PR adds — in one place.

@goldmedal
goldmedal merged commit 4348f7a into Canner:main Jul 13, 2026
9 checks passed
@Bartok9

Bartok9 commented Jul 13, 2026

Copy link
Copy Markdown
Contributor Author

Good catch — you're right, that comment overstates the guarantee. Snowflake doesn't guarantee a subquery's ORDER BY survives to the outer query, so ORDER BY … LIMIT N previews can now return a different N rows than the old full-query-then-Python-slice path. The behavior is consistent with how the other connectors already push LIMIT down, so the change is fine, but the code comment is misleading. I'll follow up with a one-line PR to reword it to something like "the outer LIMIT bounds the row count; inner ORDER BY is best-effort and not guaranteed to be preserved per Snowflake semantics." Thanks for the precise reference.

Bartok9 added a commit to Bartok9/WrenAI that referenced this pull request Jul 13, 2026
goldmedal review on Canner#2457 — same newline guard as Snowflake Canner#2456 so
query("SELECT 1 -- pick", limit=n) does not comment out the closing wrap.
Bartok9 added a commit to Bartok9/WrenAI that referenced this pull request Jul 14, 2026
Drop the incorrect Snowflake Canner#2456 cross-reference (snowflake.py has no
subquery-LIMIT wrap / semicolon guard) and the review-thread residue
(PR numbers, reviewer handle). Keep only the substantive justification:
multiline wrap so a trailing line comment can't swallow the closing wrap.
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