Repository navigation
fix(trino): emit OFFSET before LIMIT for paginated queries - #42899
Conversation
Code Review Agent Run #42f9d6Actionable Suggestions - 0Filtered by Review RulesBito filtered these suggestions based on rules created automatically for your feedback. Manage rules.
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #42899 +/- ##
==========================================
+ Coverage 84.94% 85.00% +0.05%
==========================================
Files 3077 3079 +2
Lines 208282 209261 +979
Branches 49121 49234 +113
==========================================
+ Hits 176932 177884 +952
- Misses 27985 27998 +13
- Partials 3365 3379 +14
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
| # Presto and Trino require OFFSET to appear before LIMIT in the SQL grammar. | ||
| # Superset normalizes compiled SQL accordingly so pagination works even when | ||
| # the connection resolves to a driver whose dialect emits the ANSI | ||
| # ``LIMIT ... OFFSET`` ordering (e.g. PyHive). See | ||
| # ``BaseEngineSpec.apply_offset_before_limit``. | ||
| offset_before_limit = True |
There was a problem hiding this comment.
Suggestion: The flag is defined on PrestoBaseEngineSpec, but HiveEngineSpec inherits PrestoEngineSpec, and SparkEngineSpec and DatabricksHiveEngineSpec inherit HiveEngineSpec. Consequently, every compiled Hive, Spark, and Databricks Interactive Cluster query with LIMIT and OFFSET is reparsed and regenerated using that engine's sqlglot dialect, even though this change is intended only for Presto and Trino. This can rewrite valid engine-specific SQL or alter function semantics; define the flag only on PrestoEngineSpec and TrinoEngineSpec, or explicitly disable it on the Hive-family descendants. [api mismatch]
Severity Level: Major ⚠️
- ⚠️ Hive pagination queries receive unintended SQL reformatting.
- ⚠️ Spark pagination queries use the shared normalization path.
- ⚠️ Databricks interactive-cluster SQL is reparsed unnecessarily.(Use Cmd/Ctrl + Click for best experience)
Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** superset/db_engine_specs/presto.py
**Line:** 170:175
**Comment:**
*Api Mismatch: The flag is defined on `PrestoBaseEngineSpec`, but `HiveEngineSpec` inherits `PrestoEngineSpec`, and `SparkEngineSpec` and `DatabricksHiveEngineSpec` inherit `HiveEngineSpec`. Consequently, every compiled Hive, Spark, and Databricks Interactive Cluster query with `LIMIT` and `OFFSET` is reparsed and regenerated using that engine's sqlglot dialect, even though this change is intended only for Presto and Trino. This can rewrite valid engine-specific SQL or alter function semantics; define the flag only on `PrestoEngineSpec` and `TrinoEngineSpec`, or explicitly disable it on the Hive-family descendants.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix|
The flagged issue is correct. The To resolve this, you should move the flag definition from Proposed Fix
Would you like me to fetch all other comments on this PR to validate and implement fixes for them as well? superset/db_engine_specs/presto.py |
Pilot for real-container testing of db_engine_specs against actual databases (CockroachDB, CrateDB, Trino), via testcontainers-python. Existing unit tests mock the driver/dialect layer entirely, which cannot catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where Trino emitted OFFSET before LIMIT for paginated queries. Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every merge: container pulls and startup are slower and more flake-prone than the existing mocked unit tests, and this measures that cost/signal tradeoff before considering wider adoption. Building this surfaced two real bugs, fixed/documented separately: - The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due to a dead upstream package -- fixed in #43501. - testcontainers-python's TrinoContainer.get_connection_url() returns the container-internal port instead of the Docker-mapped host port; worked around locally, filed upstream.
Pilot for real-container testing of db_engine_specs against actual databases (CockroachDB, CrateDB, Trino), via testcontainers-python. Existing unit tests mock the driver/dialect layer entirely, which cannot catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where Trino emitted OFFSET before LIMIT for paginated queries. Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every merge: container pulls and startup are slower and more flake-prone than the existing mocked unit tests, and this measures that cost/signal tradeoff before considering wider adoption. Building this surfaced two real bugs, fixed/documented separately: - The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due to a dead upstream package -- fixed in #43501. - testcontainers-python's TrinoContainer.get_connection_url() returns the container-internal port instead of the Docker-mapped host port; worked around locally, filed upstream.
Pilot for real-container testing of db_engine_specs against actual databases (CockroachDB, CrateDB, Trino), via testcontainers-python. Existing unit tests mock the driver/dialect layer entirely, which cannot catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where Trino emitted OFFSET before LIMIT for paginated queries. Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every merge: container pulls and startup are slower and more flake-prone than the existing mocked unit tests, and this measures that cost/signal tradeoff before considering wider adoption. Building this surfaced two real bugs, fixed/documented separately: - The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due to a dead upstream package -- fixed in #43501. - testcontainers-python's TrinoContainer.get_connection_url() returns the container-internal port instead of the Docker-mapped host port; worked around locally, filed upstream.
Pilot for real-container testing of db_engine_specs against actual databases (CockroachDB, CrateDB, Trino), via testcontainers-python. Existing unit tests mock the driver/dialect layer entirely, which cannot catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where Trino emitted OFFSET before LIMIT for paginated queries. Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every merge: container pulls and startup are slower and more flake-prone than the existing mocked unit tests, and this measures that cost/signal tradeoff before considering wider adoption. Building this surfaced two real bugs, fixed/documented separately: - The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due to a dead upstream package -- fixed in #43501. - testcontainers-python's TrinoContainer.get_connection_url() returns the container-internal port instead of the Docker-mapped host port; worked around locally, filed upstream.
Pilot for real-container testing of db_engine_specs against actual databases (CockroachDB, CrateDB, Trino), via testcontainers-python. Existing unit tests mock the driver/dialect layer entirely, which cannot catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where Trino emitted OFFSET before LIMIT for paginated queries. Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every merge: container pulls and startup are slower and more flake-prone than the existing mocked unit tests, and this measures that cost/signal tradeoff before considering wider adoption. Building this surfaced two real bugs, fixed/documented separately: - The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due to a dead upstream package -- fixed in #43501. - testcontainers-python's TrinoContainer.get_connection_url() returns the container-internal port instead of the Docker-mapped host port; worked around locally, filed upstream.
Pilot for real-container testing of db_engine_specs against actual databases (CockroachDB, CrateDB, Trino), via testcontainers-python. Existing unit tests mock the driver/dialect layer entirely, which cannot catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where Trino emitted OFFSET before LIMIT for paginated queries. Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every merge: container pulls and startup are slower and more flake-prone than the existing mocked unit tests, and this measures that cost/signal tradeoff before considering wider adoption. Building this surfaced two real bugs, fixed/documented separately: - The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due to a dead upstream package -- fixed in #43501. - testcontainers-python's TrinoContainer.get_connection_url() returns the container-internal port instead of the Docker-mapped host port; worked around locally, filed upstream.
Pilot for real-container testing of db_engine_specs against actual databases (CockroachDB, CrateDB, Trino), via testcontainers-python. Existing unit tests mock the driver/dialect layer entirely, which cannot catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where Trino emitted OFFSET before LIMIT for paginated queries. Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every merge: container pulls and startup are slower and more flake-prone than the existing mocked unit tests, and this measures that cost/signal tradeoff before considering wider adoption. Building this surfaced two real bugs, fixed/documented separately: - The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due to a dead upstream package -- fixed in #43501. - testcontainers-python's TrinoContainer.get_connection_url() returns the container-internal port instead of the Docker-mapped host port; worked around locally, filed upstream.
Drill to Detail pagination (and any paginated query) fails on Trino/Presto with `mismatched input 'OFFSET'` on page 2+. Superset builds the query with SQLAlchemy `.limit()`/`.offset()`, and the compiled clause order is decided by the driver's dialect. The official `trino` package and `sqlalchemy-trino` override `limit_clause` to emit `OFFSET ... LIMIT`, but PyHive's Presto/Trino dialects inherit SQLAlchemy's ANSI `LIMIT ... OFFSET` ordering, which Presto and Trino reject. Connections that resolve to a PyHive dialect (and any vanilla `presto://` connection) therefore produce invalid SQL when an offset is applied. Guarantee the ordering in Superset instead of relying on the driver: add an `offset_before_limit` engine-spec flag (True for Presto/Trino) and normalize compiled SQL via sqlglot's dialect-aware generator in `compile_sqla_query`. The reorder only runs when the flag is set and the SQL is in the invalid order, so drivers that already emit OFFSET first are untouched. Reported when using Trino as the query engine. Co-Authored-By: Claude Opus 4.8 <[email protected]>
b3c2be0 to
e1517c0
Compare
rebenitez1802
left a comment
There was a problem hiding this comment.
Request changes: the fix works for PyHive presto://, but the new flag also leaks into Hive, Spark and Databricks Hive, and the required pre-commit (current) check fails. Details inline.
| # the connection resolves to a driver whose dialect emits the ANSI | ||
| # ``LIMIT ... OFFSET`` ordering (e.g. PyHive). See | ||
| # ``BaseEngineSpec.apply_offset_before_limit``. | ||
| offset_before_limit = True |
There was a problem hiding this comment.
🔴 High — offset_before_limit leaks into Hive, Spark and Databricks Hive
HiveEngineSpec subclasses PrestoEngineSpec (hive.py:104), so Hive, SparkEngineSpec and DatabricksHiveEngineSpec all inherit offset_before_limit = True from this line. PyHive's Hive dialect emits LIMIT x OFFSET y, so every page-2+ query on these engines gets fully re-rendered by sqlglot, and the clause order stays the same.
The SQL still changes, though. Through get_query_str on spark:// with a filter value C:\users\data:
- page 1:
`path` = 'C:\users\data' - page 2:
`path` = 'C:\\users\\data'
So two pages of the same Drill to Detail filter on different values. On Hive the re-render also drops /*+ MAPJOIN(...) */ hints (sqlglot logs "Hints are not supported").
Fix: opt out in HiveEngineSpec, next to its existing supports_grouping_sets = False override (hive.py isn't in the diff, so no applyable suggestion):
# Hive/Spark accept the ANSI ``LIMIT ... OFFSET`` order; don't inherit
# the Presto/Trino reordering (and the sqlglot re-render it triggers).
offset_before_limit = FalsePlus a test that paginated Hive/Spark SQL comes back unchanged.
There was a problem hiding this comment.
Still open after the master merge. A correction to my example above: with sqlglot 30.24 (#45704) the backslash value no longer changes. Page 2 now renders 'C:usersdata', which Spark reads the same as page 1's 'C:\users\data'.
The re-render still breaks page 2 on Hive, though:
named_struct('x', f.a, 'y', d.q).xbecomesSTRUCT(f.a, d.q).x. Hive names those fieldscol1/col2, so.xfails.- The
/*+ MAPJOIN(d) */hint is still dropped.
Hive and Spark already accept LIMIT … OFFSET, so they get the rewrite with no benefit. The fix is the same: offset_before_limit = False on HiveEngineSpec.
There was a problem hiding this comment.
Fixed in d6dc352: HiveEngineSpec now sets offset_before_limit = False (superset/db_engine_specs/hive.py), overriding the value inherited from PrestoBaseEngineSpec. SparkEngineSpec and DatabricksHiveEngineSpec subclass HiveEngineSpec, so they pick up the opt-out too. The non-Hive Databricks specs derive from BaseEngineSpec (default False), so they need no override. Added test_apply_offset_before_limit_not_applied_to_hive_family asserting Hive/Spark/Databricks-Hive leave ANSI LIMIT ... OFFSET SQL untouched. I also fixed the ruff 0.9.7 formatting and the where_in chart test fixture. The sqlglot literal re-rendering concern is not addressed here.
| assert upper.rfind("OFFSET") < upper.rfind( | ||
| "LIMIT" | ||
| ), f"OFFSET must precede LIMIT for Trino, got: {result!r}" |
There was a problem hiding this comment.
🔴 High — required pre-commit (current) check fails on ruff-format
ruff 0.9.7 (pinned in requirements/development.txt) reformats this assert, and pre-commit (current) is a required check in .asf.yaml.
| assert upper.rfind("OFFSET") < upper.rfind( | |
| "LIMIT" | |
| ), f"OFFSET must precede LIMIT for Trino, got: {result!r}" | |
| assert upper.rfind("OFFSET") < upper.rfind("LIMIT"), ( | |
| f"OFFSET must precede LIMIT for Trino, got: {result!r}" | |
| ) |
| assert upper.rfind("OFFSET") < upper.rfind( | ||
| "LIMIT" | ||
| ), f"OFFSET must precede LIMIT for Trino, got: {sql!r}" |
There was a problem hiding this comment.
🔴 High — same ruff-format failure as in test_trino.py
| assert upper.rfind("OFFSET") < upper.rfind( | |
| "LIMIT" | |
| ), f"OFFSET must precede LIMIT for Trino, got: {sql!r}" | |
| assert upper.rfind("OFFSET") < upper.rfind("LIMIT"), ( | |
| f"OFFSET must precede LIMIT for Trino, got: {sql!r}" | |
| ) |
| return sql | ||
|
|
||
| try: | ||
| return SQLScript(sql, engine=cls.engine).format() |
There was a problem hiding this comment.
🟡 Medium (non-blocking) — re-rendering the whole statement can silently change Presto SQL
When the gate fires on presto://, sqlglot regenerates the entire query, not just the trailing clause. A custom WHERE price >= DECIMAL '9.99' comes out on page 2 as price >= CAST('9.99' AS DECIMAL). Presto/Trino read a bare DECIMAL as decimal(38,0), so page 2 effectively filters >= 10 while page 1 filters >= 9.99. Master leaves user clauses as written for exactly this reason (sanitize_clause, #36113), and the gate comment's "never wrong SQL" doesn't hold.
A narrower option that avoids the round-trip: make PyHive's PrestoCompiler.limit_clause emit OFFSET then LIMIT (as the official trino dialect does), or rewrite only an anchored trailing LIMIT n OFFSET m. The compiler route also fixes the OFFSET-only LIMIT -1 OFFSET n case and leaves Hive/Spark untouched.
There was a problem hiding this comment.
Non-blocking follow-up: one more case where the page-2 re-render changes results on presto://. log(10, x) becomes LOG(x, 10), so on a Trino server page 1 and page 2 compute different values. Rewriting only an anchored trailing LIMIT n OFFSET m would avoid the round-trip, and the gate comment's "never wrong SQL" line could go.
There was a problem hiding this comment.
Thanks @rebenitez1802, good catch. Pushed 6f9be4c: apply_offset_before_limit now rewrites only an anchored trailing LIMIT n OFFSET m into OFFSET m LIMIT n with a regex, so the rest of the query is no longer re-rendered (no more log(10, x) → LOG(x, 10) between pages). The sqlglot round-trip and the "never wrong SQL" comment are gone, and I added tests for the trailing-only rewrite and for non-trailing LIMIT/OFFSET in subqueries being left alone.
rebenitez1802
left a comment
There was a problem hiding this comment.
The Hive leak is still open (see thread). CI is also blocked: tests/unit_tests/jinja_context_test.py::test_where_in_chart_compilation fails with this change, because its Database has no sqlalchemy_uri.
| # the connection resolves to a driver whose dialect emits the ANSI | ||
| # ``LIMIT ... OFFSET`` ordering (e.g. PyHive). See | ||
| # ``BaseEngineSpec.apply_offset_before_limit``. | ||
| offset_before_limit = True |
There was a problem hiding this comment.
Still open after the master merge. A correction to my example above: with sqlglot 30.24 (#45704) the backslash value no longer changes. Page 2 now renders 'C:usersdata', which Spark reads the same as page 1's 'C:\users\data'.
The re-render still breaks page 2 on Hive, though:
named_struct('x', f.a, 'y', d.q).xbecomesSTRUCT(f.a, d.q).x. Hive names those fieldscol1/col2, so.xfails.- The
/*+ MAPJOIN(d) */hint is still dropped.
Hive and Spark already accept LIMIT … OFFSET, so they get the rewrite with no benefit. The fix is the same: offset_before_limit = False on HiveEngineSpec.
…t and jinja test fixture - HiveEngineSpec (and Spark/Databricks Hive) opt out of offset_before_limit - reformat asserts for ruff 0.9.7 - give where_in chart test Database a sqlalchemy_uri Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ffset-pagination # Conflicts: # superset/db_engine_specs/hive.py
rebenitez1802
left a comment
There was a problem hiding this comment.
The Hive opt-out, formatting and test-fixture fixes look good, and CI is green. LGTM.
| return sql | ||
|
|
||
| try: | ||
| return SQLScript(sql, engine=cls.engine).format() |
There was a problem hiding this comment.
Non-blocking follow-up: one more case where the page-2 re-render changes results on presto://. log(10, x) becomes LOG(x, 10), so on a Trino server page 1 and page 2 compute different values. Rewriting only an anchored trailing LIMIT n OFFSET m would avoid the round-trip, and the gate comment's "never wrong SQL" line could go.
…ering the query Re-rendering the whole statement through sqlglot could change semantics on presto:// (e.g. log(10, x) -> LOG(x, 10)). Rewrite only an anchored trailing `LIMIT n OFFSET m` and leave the rest of the SQL untouched. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: Evan Rusackas <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: Evan Rusackas <[email protected]> (cherry picked from commit c01ffe6)
SUMMARY
Drill to Detail pagination fails on Trino/Presto: navigating to page 2 of the results produces a query that Trino rejects with a syntax error:
This was reported when using Trino as the query engine. The same query runs fine in SQL Lab, because SQL Lab never emits an
OFFSET— only the automated pagination path does.Problem
Superset builds paginated queries with SQLAlchemy's dialect-aware construction (
qry.limit(row_limit).offset(row_offset)inmodels/helpers.py) and compiles them inDatabase.compile_sqla_query. In SQLAlchemy the compiled clause order is decided entirely by the driver's dialect (limit_clause), not by the order the methods are called.Trino and Presto require
OFFSETto appear beforeLIMIT(unlike the ANSILIMIT ... OFFSETordering). Whether Superset emits valid SQL therefore depends on which driver the connection resolves to:trinopackage and the legacysqlalchemy-trinopackage both overridelimit_clauseto emitOFFSET ... LIMIT→ correct.PrestoCompiler/TrinoCompiler) do not overridelimit_clause; they inherit SQLAlchemy's ANSILIMIT ... OFFSET→ rejected by Presto/Trino.So any connection that resolves to a PyHive dialect — including any vanilla
presto://connection on stock Superset — produces invalid SQL as soon as an offset is applied (Drill to Detail page 2+, server-side pagination, etc.).Verified directly:
Fix
Guarantee the ordering in Superset rather than depending on the driver:
offset_before_limitengine-spec flag (defaultFalse, set toTrueonPrestoBaseEngineSpec, inherited by both Presto and Trino).BaseEngineSpec.apply_offset_before_limit(sql), which re-renders the statement through sqlglot's dialect-aware generator (which ordersOFFSETbeforeLIMITfor these dialects). A cheap textual gate means it only runs when the flag is set and the SQL is actually in the invalid order, so drivers that already emitOFFSETfirst are left byte-for-byte untouched.Database.compile_sqla_query, the single choke point where datasource queries are turned into SQL.This fixes every automated-offset path (Drill to Detail, samples, server pagination) for Presto and Trino, independent of the installed SQLAlchemy driver.
BEFORE/AFTER
This is a query-generation fix, so the meaningful before/after is the SQL Superset dispatches for Drill to Detail page 2 (
row_limit=50,row_offset=50) when the connection resolves to a driver that emits ANSI ordering (e.g. PyHive). Output below is the actual compiled SQL, reproduced end to end.Before — invalid for Trino/Presto (fails with
line N: mismatched input 'OFFSET'. Expecting: <EOF>):After — valid; page 2 loads:
UI screenshots aren't included because reproducing the failure in the browser requires a live Trino/Presto cluster connected via the PyHive dialect; the SQL above is the exact statement that changes.
TESTING INSTRUCTIONS
LIMIT ... OFFSET(e.g. PyHive).mismatched input 'OFFSET'; after it, the page loads.Automated coverage added:
tests/unit_tests/db_engine_specs/test_trino.py—apply_offset_before_limitreorders ANSI ordering, leaves already-correct/limit-only SQL untouched, and is a no-op for engines that don't set the flag.tests/unit_tests/models/core_test.py— end-to-end throughcompile_sqla_query, driving a TrinoDatabasebacked by a dialect that emits ANSI ordering and asserting the compiled SQL putsOFFSETbeforeLIMIT.ADDITIONAL INFORMATION
🤖 Generated with Claude Code