Skip to content

fix(sql): allow constant and grouped-column Custom SQL metrics under GROUP BY - #46648

Closed
MikolajBalcerek wants to merge 6 commits into
apache:masterfrom
MikolajBalcerek:fix-nonagg-metric-check-false-positives
Closed

MikolajBalcerek wants to merge 6 commits into
apache:masterfrom
MikolajBalcerek:fix-nonagg-metric-check-false-positives

Conversation

@MikolajBalcerek

Copy link
Copy Markdown
Contributor

SUMMARY

#42199 rejects a Custom SQL metric using a GROUP BY when has_aggregate() is False.
Issue: #46641 with description

That is stricter than SQL and 6.1.0, and breaks charts that worked before, using legitimate SQL.

Example of bug behaviour

This blocks legit SQLs from being charted that worked on 6.1.0, like:

SELECT channel, COUNT(*) AS orders,
       'WIP' AS sessions          
FROM orders
GROUP BY channel

using constants as temporary values

SELECT franchise, this_week, last_week,
       (this_week - last_week) / last_week AS wow    -- metric
FROM top_10_weekly_franchise
GROUP BY franchise, this_week, last_week

or expressions over grouped columns

Charts like these worked in 6.x and break after upgrading.
There's no setting to turn the check off, and there's no automatic migration for the issue

Screenshots/recordings

image

Working on Superset 6.1.0

image

Broken on Superset 7.0 rc3

SELECT COALESCE(marketing_channel, 'Not Attributed')    AS marketing_channel,
       COALESCE(marketing_subchannel, 'Not Attributed') AS marketing_subchannel,
       'WIP'                                            AS "Sessions",      -- metric: 'WIP'
       'WIP'                                            AS "Session CVR",   -- metric: 'WIP'
       COUNT(DISTINCT user_id)                          AS "Users",
       'WIP'                                            AS "User CVR",      -- metric: 'WIP'
       COUNT(DISTINCT iid)                              AS "Units",
       SUM(revenue_ex_tax) / 100                        AS "Revenue",
       SUM(margin) / 100                                AS "Margin",
       CASE WHEN SUM(margin) <> 0 AND SUM(revenue_ex_tax) <> 0
            THEN SUM(margin) / SUM(revenue_ex_tax) ELSE 0 END           AS "Margin %",
       COUNT(DISTINCT order_id)                         AS "Orders",
       CASE WHEN COUNT(DISTINCT order_id) > 0
            THEN (SUM(revenue_ex_tax) / 100) / COUNT(DISTINCT order_id)
            ELSE 0 END                                  AS "AOV",
       COUNT(DISTINCT CASE WHEN is_new_customer IS TRUE THEN user_id ELSE NULL END) AS "New Customers",
       COUNT(DISTINCT iid)                              AS "Units %"
FROM marts.daily_orders
WHERE (NOT is_gift IS TRUE) AND (NOT is_redeem IS TRUE)
GROUP BY COALESCE(marketing_channel, 'Not Attributed'),
         COALESCE(marketing_subchannel, 'Not Attributed')
ORDER BY "Revenue" DESC
LIMIT 10000

example query used

Chart types:

  • table, aggregate mode
  • bubble chart (bubble_v2)

The fix

The check now raises only when the expression references a column that isn't itself one of the GROUP BY expressions.

Compares the metric's columns with the GROUP BY expressions that are bare column references.
Plain dataset columns and adhoc SQL columns like strings WIP count as grouped.

TESTING INSTRUCTIONS

  1. pytest tests/unit_tests/sql/parse_tests.py tests/unit_tests/models/helpers_test.py
  2. Create a table aggregate chart with SQL with constant or or expressions over grouped columns
  3. Before the fix, it will not render
  4. After, it will render

ADDITIONAL INFORMATION

…GROUP BY

The non-aggregate Custom SQL metric check from apache#42199 rejected metrics that
are valid SQL under a GROUP BY: constants ('WIP', NULL, 1) and expressions
whose columns are all grouped. Only raise when the expression references a
column that is not itself one of the GROUP BY expressions; calculated columns
and time-grain buckets don't count as grouped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Comment thread superset/sql/parse.py
dialect = SQLGLOT_DIALECTS.get(engine)
try:
parsed = sqlglot.parse_one(f"SELECT {expression}", dialect=dialect)
grouped = [sqlglot.parse_one(str(sql), dialect=dialect) for sql in group_by]

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: On MySQL, SQLAlchemy may render a reserved grouped column with double quotes, which this dialect reads as a string literal, causing a valid metric to be rejected.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ 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/sql/parse.py
**Line:** 301:301
**Comment:**
	*Api Mismatch: On MySQL, SQLAlchemy may render a reserved grouped column with double quotes, which this dialect reads as a string literal, causing a valid metric to be rejected.

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

@MikolajBalcerek MikolajBalcerek Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I am flagging this as Known Issue in PR description.


You could render the GROUP BY columns in the database's own SQL style instead of with a plain str(), i.e. col.compile(dialect=self.database.get_dialect()) to get this-DB-style-comparison, more complex

So getting at least partial fix in

I could try it if we want


To fix all the subcases perhaps just reverting #42199 and trying a different way to fix that issue would be preferable

Comment thread superset/sql/parse.py
return True
# case-insensitive, erring toward letting the database decide
names = {col.name.lower() for col in grouped if isinstance(col, exp.Column)}
return all(col.name.lower() in names for col in parsed.find_all(exp.Column))

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: This also finds columns inside scalar subqueries, so an independent subquery metric is mistaken for an ungrouped outer reference and rejected.

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/sql/parse.py
**Line:** 306:306
**Comment:**
	*Logic Error: This also finds columns inside scalar subqueries, so an independent subquery metric is mistaken for an ungrouped outer reference and rejected.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yea, true.

Telling the two kinds of subquery apart would require sqlglot's scope analysis.
Making the fix more thorough but more complex.

To fix all the subcases perhaps just reverting #42199 and trying a different way to fix that issue would be preferable

@codeant-ai-for-open-source

codeant-ai-for-open-source Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

CodeAnt  CodeAnt PR Risk

🟡  Medium Risk

  • The PR needs attention before merging because valid custom metrics may be rejected.
  • On MySQL, double-quoted grouped identifiers can be parsed as string literals, so valid metrics over reserved column names may fail validation.
  • Column references inside scalar subqueries are treated as outer references, which can reject otherwise valid independent subquery metrics.

Assessed commit: 0e5705f8098d

MikolajBalcerek and others added 5 commits November 27, 2026 20:26
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 20.00000% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.73%. Comparing base (7a1a056) to head (3c52ef1).
⚠️ Report is 83 commits behind head on master.

Files with missing lines Patch % Lines
superset/sql/parse.py 20.00% 8 Missing ⚠️

❗ There is a different number of reports uploaded between BASE (7a1a056) and HEAD (3c52ef1). Click for more details.

HEAD has 3 uploads less than BASE
Flag BASE (7a1a056) HEAD (3c52ef1)
python 7 5
postgres 2 1
Additional details and impacted files
@@             Coverage Diff             @@
##           master   #46648       +/-   ##
===========================================
- Coverage   85.98%   65.73%   -20.26%     
===========================================
  Files        3129     3143       +14     
  Lines      217840   219768     +1928     
  Branches    51648    51962      +314     
===========================================
- Hits       187320   144467    -42853     
- Misses      27096    71869    +44773     
- Partials     3424     3432        +8     
Flag Coverage Δ
hive 33.63% <20.00%> (-0.18%) ⬇️
mysql 51.82% <20.00%> (+0.20%) ⬆️
postgres 51.85% <20.00%> (+0.20%) ⬆️
presto 35.32% <20.00%> (-0.19%) ⬇️
python 52.15% <20.00%> (-36.34%) ⬇️
sqlite 51.55% <20.00%> (+0.22%) ⬆️
unit ?

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.

@MikolajBalcerek

Copy link
Copy Markdown
Contributor Author

Closing in favour of just revert #46650 to avoid unsolved cases of blocked charts when not needed

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Superset 7.0 rc] SQL metric check blocks previously valid queries using groupby

1 participant