Skip to content

fix(explore): prevent full table scan when SQL expression is used as x-axis - #41339

Merged
sadpandajoe merged 10 commits into
masterfrom
fix-clickhouse-query
Nov 21, 2026
Merged

sadpandajoe merged 10 commits into
masterfrom
fix-clickhouse-query

Conversation

@betodealmeida

@betodealmeida betodealmeida commented Jun 23, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

On ClickHouse (and other engines with row-read limits like max_rows_to_read), using a SQL expression as the x-axis in a timeseries line chart triggers a full table scan and fails, while using a plain physical temporal column works fine.

Root cause: In _apply_granularity (query_context_factory.py), from_dttm/to_dttm are only applied as a WHERE clause when granularity (a physical time column) is explicitly configured. When a user sets the x-axis to an adhoc SQL expression like toStartOfDay(ts) or duration * 0.05, the frontend's isTemporalColumn() check returns false — so no TEMPORAL_RANGE filter is created for the expression, and no automatic WHERE clause is generated. The result is an unfiltered query that reads every row in the table.

Backend fix: Added an elif branch in _apply_granularity. When the x-axis is an adhoc SQL expression, a time range is set (from_dttm/to_dttm are not null), but no granularity is configured, the method falls back to datasource.main_dttm_col (if it exists and is temporal) and sets it as the granularity. This causes helpers.py to emit a WHERE main_dttm_col >= from_dttm AND main_dttm_col < to_dttm clause automatically. Any pre-existing TEMPORAL_RANGE filter for that column is also removed to prevent the condition from appearing twice.

Frontend fix: Added a useEffect in ControlPanelsContainer that shows a warning modal when the user sets the x-axis to a SQL expression, pointing them to add a time column filter in the Filters section.

Workaround for existing users (no upgrade required): Add a TEMPORAL_RANGE filter on the dataset's time column in the chart's Filters section. The backend fix then picks it up automatically.

This PR also fixes a pre-existing bug in DatetimeFormatDetector where get_df was called with schema in the catalog position, causing incorrect behavior on databases that use both catalogs and schemas.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Screenshot 2026-06-23 at 10 20 48 AM

TESTING INSTRUCTIONS

  1. Connect Superset to a ClickHouse database. Configure max_rows_to_read to a value smaller than the total row count of a test table (e.g. max_rows_to_read = 100000 on a 500K-row table ordered by a DateTime column ts).
  2. Create a Line Chart using that table.
  3. Set the X-axis to a SQL expression, e.g. toStartOfDay(ts). Leave the Filters section empty.
  4. Before: query fails with Code: 158. DB::Exception: Limit for rows (max_rows_to_read) exceeded.
  5. Add a TEMPORAL_RANGE filter on ts (e.g. "Last year") in the Filters section and run again.
  6. After: query succeeds. Check ··· → View Query — a single WHERE ts >= ... AND ts < ... clause should appear, with no duplication.
  7. Verify the warning modal appears when switching the X-axis from a physical temporal column to a SQL expression.
  8. Verify charts using a physical temporal column as X-axis are unaffected.

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags:
  • Changes UI (warning modal in Explore)
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

@netlify

netlify Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 53ae505
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6a3a96a00d4a9600087bb0eb
😎 Deploy Preview https://deploy-preview-41339--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@codecov

codecov Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 66.66667% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.87%. Comparing base (b44ea29) to head (023d990).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
.../src/explore/components/ControlPanelsContainer.tsx 55.55% 4 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master   #41339   +/-   ##
=======================================
  Coverage   85.86%   85.87%           
=======================================
  Files        3117     3117           
  Lines      216005   216015   +10     
  Branches    51231    51236    +5     
=======================================
+ Hits       185482   185499   +17     
+ Misses      27108    27101    -7     
  Partials     3415     3415           
Flag Coverage Δ
hive 33.94% <0.00%> (-0.01%) ⬇️
javascript 82.72% <55.55%> (+<0.01%) ⬆️
mysql 51.60% <66.66%> (+<0.01%) ⬆️
postgres 51.62% <66.66%> (-0.01%) ⬇️
presto 35.62% <66.66%> (+<0.01%) ⬆️
python 88.36% <100.00%> (+<0.01%) ⬆️
sqlite 51.30% <66.66%> (+<0.01%) ⬆️
unit 83.73% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@betodealmeida betodealmeida changed the title fix: enforce time filter on adhoc SQL fix(explore): prevent full table scan when SQL expression is used as x-axis Jun 23, 2026
@betodealmeida
betodealmeida force-pushed the fix-clickhouse-query branch from 43ad8c9 to 53ae505 Compare June 23, 2026 14:22
@betodealmeida
betodealmeida marked this pull request as ready for review June 23, 2026 14:28
@dosubot dosubot Bot added change:backend Requires changing the backend change:frontend Requires changing the frontend explore:filter Related to filters in Explore explore:performance Related to performance of Explore labels Jun 23, 2026
@betodealmeida
betodealmeida force-pushed the fix-clickhouse-query branch from 53ae505 to ace7a65 Compare June 23, 2026 15:51
@bito-code-review

bito-code-review Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #510666

Actionable Suggestions - 0
Filtered by Review Rules

Bito filtered these suggestions based on rules created automatically for your feedback. Manage rules.

  • tests/unit_tests/datasets/test_datetime_format_detector.py - 2
Review Details
  • Files reviewed - 5 · Commit Range: 0a40a94..05182f9
    • superset-frontend/src/explore/components/ControlPanelsContainer.tsx
    • superset/common/query_context_factory.py
    • superset/datasets/datetime_format_detector.py
    • tests/unit_tests/common/test_query_context_factory.py
    • tests/unit_tests/datasets/test_datetime_format_detector.py
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@eschutho
eschutho requested a review from kgabryje June 24, 2026 05:07
@rusackas

Copy link
Copy Markdown
Member

Code and tests lookin' good... say the word if you want help with the rebase.

@rusackas

Copy link
Copy Markdown
Member

Still looking good on my end. It's gone conflicting with master again since I last checked - say the word if you want a hand with the rebase, @betodealmeida.

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Sep 3, 2026
@rusackas

Copy link
Copy Markdown
Member

Nice diagnosis on the ClickHouse full-table-scan issue, and the main_dttm_col fallback plus the catalog/schema fix in datetime_format_detector.py look right to me. GitHub's showing conflicts with master though, so we can't merge as-is. I'll rebase it since it's not on a fork.

@rusackas rusackas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

As noted, the ClickHouse diagnosis and the main_dttm_col fallback (plus the catalog/schema fix in datetime_format_detector.py) look right to me, and the test coverage is solid. Approving to get this off the review-required list, just needs a rebase before it can merge since GitHub's showing conflicts with master again.

betodealmeida and others added 4 commits October 21, 2026 11:19
…dent fix

Master landed its own fix for the same ClickHouse full-table-scan bug
(#42052) after this PR was approved, via a differently-guarded
`should_infer_filter_granularity` check. This PR's own unguarded
`elif` branch would have regressed master's
`test_granularity_not_inferred_from_another_temporal_filter` by firing
in a case master's guard exists to prevent, so it's dropped in favor
of master's check. The one piece master's fix was still missing - a
dedupe of a pre-existing TEMPORAL_RANGE filter already on the inferred
main_dttm_col, to avoid a duplicate WHERE clause - is ported forward
into master's guarded branch instead.

Also restores the catalog/schema argument-order fix in
datetime_format_detector.py's get_df call, which master's own later
ClickHouse read-limit retry refactor had reintroduced.

Co-Authored-By: Evan Rusackas <[email protected]>
Co-Authored-By: Claude Sonnet 5 <[email protected]>
@rusackas
rusackas force-pushed the fix-clickhouse-query branch from 05182f9 to 970301c Compare October 21, 2026 19:43
# The inferred column supplies the time-filter subject. It must not be
# treated as an explicitly selected granularity, which would rewrite
# the x-axis or remove an independent temporal filter below.
query_object.granularity = main_dttm_col

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.

Suggestion: For timeseries charts, the query builder selects and groups by this inferred column, splitting expression-axis results by the physical timestamp.

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes · 🏷️ Api mismatch

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/common/query_context_factory.py
**Line:** 321:321
**Comment:**
	*Api Mismatch: For timeseries charts, the query builder selects and groups by this inferred column, splitting expression-axis results by the physical timestamp.

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
👍 | 👎

Comment on lines +326 to +333
query_object.filter = [
filter_
for filter_ in query_object.filter
if not (
filter_["op"] == "TEMPORAL_RANGE"
and filter_["col"] == main_dttm_col
)
]

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.

Suggestion: When time_range is absent but explicit bounds coexist with a different range filter on main_dttm_col, this drops that filter and can broaden results.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Logic error

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/common/query_context_factory.py
**Line:** 326:333
**Comment:**
	*Logic Error: When `time_range` is absent but explicit bounds coexist with a different range filter on `main_dttm_col`, this drops that filter and can broaden results.

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
👍 | 👎

@codeant-ai-for-open-source

codeant-ai-for-open-source Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

CodeAnt  CodeAnt PR Risk

🟡  Medium Risk

  • The PR needs attention before merging.
  • Setting the inferred timestamp as granularity may group expression-axis results by that timestamp and change chart output.
  • When explicit bounds coexist with a different range filter on the main timestamp, removing that filter may change or broaden results.

Assessed commit: 023d9903121b

@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Oct 21, 2026
@sadpandajoe

Copy link
Copy Markdown
Member

This PR has been quiet for a while. We'd like to help get it across the finish line, so we'll push updates here. Thanks for the contribution!

We merged master and added this PR's new warning string to the translation template (messages.pot) so the translation drift check passes.

@github-actions github-actions Bot added the i18n Namespace | Anything related to localization label Nov 20, 2026
@sadpandajoe
sadpandajoe merged commit 6d15dda into master Nov 21, 2026
85 checks passed
@sadpandajoe
sadpandajoe deleted the fix-clickhouse-query branch November 21, 2026 17:25
jprinet added a commit to jprinet/superset that referenced this pull request Nov 23, 2026
* origin/master: (393 commits)
  fix(a11y): name the semantic view description input (apache#46458)
  docs(semantic): explain datasource list modification eligibility (apache#46462)
  docs(semantic-layer): document NULL-preserving exclusion filters (apache#46447)
  fix(uploads): skip folder and system entries in columnar ZIP uploads (apache#45617)
  fix(i18n-es): promote 47 of the zero-context backfill entries (apache#45847)
  fix(mcp): return structured ChartError on SQLAlchemyError in get_chart_sql (apache#44351)
  fix(datasets): follow semantic view modification permissions (apache#46448)
  fix(docker): account for container memory limits in frontend-mem-nag.sh (apache#46373)
  fix(reports): carry the report's native filters in the email and Slack link (apache#46062)
  fix(explore): apply the dataset timezone to grained temporal filter values (apache#46175)
  fix(i18n): enforce the do-not-translate registry across the catalogs (apache#45974)
  chore(logging): log unparseable virtual dataset SQL at debug in the RLS lookup (apache#46139)
  fix(i18n): split parameter-suggestion plural into two messages (apache#46049)
  test(partition-mapping): cover Hive/Impala mirrored SQL, cache outage and migration (apache#46319)
  perf(dashboard): look up the dashboard once per filter_state read (apache#46314)
  fix(i18n): load the dayjs locale for every language with a catalog (apache#45982)
  test(semantic-layer): make date export parametrization deterministic (apache#46449)
  fix(oauth2): idempotent OAuth2 completion and resilient listener (apache#40292)
  fix(explore): prevent full table scan when SQL expression is used as x-axis (apache#41339)
  feat(mcp): radar chart type plugin (apache#43571)
  ...

# Conflicts:
#	.github/workflows/docker.yml
#	.github/workflows/superset-frontend.yml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

change:backend Requires changing the backend change:frontend Requires changing the frontend explore:filter Related to filters in Explore explore:performance Related to performance of Explore i18n Namespace | Anything related to localization preset-io size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants