← Back to Pull requests

[SPARK-60861][SQL] Preserve grouping-column precedence in HAVING with window functions #60076

Open
unknown opened this pull request with 561 lines diff across 7 files
View on GitHub
unknown unknown commented on Nov 04, 2026 01:42 UTC
Author

What changes were proposed in this pull request?

Preserve grouping-column precedence when window extraction turns HAVING into a Filter. Complete grouping keys remain available for correlated references, while helper columns stay out of SELECT-alias lookup, QUALIFY, and error suggestions. Finalize correlated dependencies during aggregate resolution, before SQL UDF or QUALIFY rewrites can separate the filter from its aggregate.

Depends on #60090 (SPARK-60873), which should land first. This branch includes that prerequisite unchanged. Its recursive window extraction and generator placement remain controlled by its independent legacy configuration; grouping precedence does not re-gate them. Grouping-set lowering retains the original input and complete-key mapping in HAVING scope: aggregate arguments use original rows, including nongrouping inputs that collide with SELECT aliases, while nonaggregate keys use nullable grouping outputs. This preserves grouping()/grouping_id(), correlated keys, and unselected ORDER BY dependencies.

A detached probe recognizes complete stock lower/lcase, upper/ucase, substr/substring and numeric/cast grouping keys. It uses existing expression coercion and accepts only a complete semantic grouping match. A miss discards tentative bindings and casts. UDFs, custom builders, higher-order functions, and uncertain function-path ownership retain the existing fallback; the probe never invokes a nested Analyzer.

spark.sql.analyzer.havingWithWindowResolvesGroupingColumnFirst.enabled remains internal, SESSION-bound, and false by default in production and tests. This deliberately stages the compatibility-sensitive name-binding change: existing queries can depend on SELECT-alias precedence. SPARK-60861 tracks the correction; changing the default requires a separate compatibility decision. This PR does not enable a rollout.

Why are the changes needed?

Adding a window function can change which groups survive HAVING when a grouping input shares its name with a SELECT alias. SQL UDF and QUALIFY rewrites can also leave correlated grouping references pointing to inputs the aggregate no longer outputs.

Does this PR introduce _any_ user-facing change?

Yes, when the grouping-scope configuration is enabled. For SELECT k + 10 AS k, count(*) OVER () AS n FROM VALUES (1), (2) AS t(k) GROUP BY k HAVING k >= 2, the result changes from (11, 2), (12, 2) to (12, 1). Non-grouped alias fallback retains its binding and types. The default remains unchanged relative to the prerequisite.

How was this patch tested?

Fresh local run: 26 SQL execution/analyzer checks, 495 Catalyst analysis tests, 59 DataFrame window tests, 3 config-binding tests, and 8 focused reproduction checks passed (591 total). Four optional Pandas UDF variants were ignored because their dependencies are unavailable. Catalyst scalastyle passed with zero errors or warnings.

Repository checks:

build/sbt -Phive \
  'sql/testOnly *SQLQueryTestSuite -- -z having.sql -z having-window-grouping-scope.sql -z qualify.sql -z window-resolution-edge-cases.sql -z generators-resolution-edge-cases.sql -z window-with-aggregates.sql' \
  'catalyst/testOnly *AnalysisSuite' \
  'sql/testOnly *DataFrameWindowFunctionsSuite' \
  'hive/testOnly *SparkConfigBindingPolicySuite' \
  'catalyst/scalastyle'

Small deterministic VALUES regressions cover SQL UDF placements, correlated computed/function keys with QUALIFY, stock function and cast keys, grouping sets, grouping()/grouping_id(), generators, alias fallback, both grouping-scope values, and independent window-order rollback. SQLQueryTestSuite regenerates execution and analyzer goldens: corrected groups change rows/window counts, and correlated outer attributes now reference aggregate outputs. Synthetic helper columns remain absent from final output. Existing expanded grouping-key names keep their ORDER BY bindings. Disabled controls intentionally retain legacy results and analysis errors. The existing disabled nested-window analyzer golden moves HAVING below the inner Window to reflect #60090; existing execution rows are unchanged. No fixture data is added.

The public single-pass analyzer guard excludes window expressions, so these cases exercise the fixed-point analyzer.

Was this patch authored or co-authored using generative AI tooling?

Generated-by: OpenAI Codex (GPT-6)

Diff: 561 lines (+420 / -141) across 7 files Reviewer: uros-b Review duration: 4625m
All Vouch review confidence checks passed
Residual risk 0.28 = Change Risk (0.50) × (1 − Review Confidence (0.43)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.50 · 561 lines diff across 7 files
0.50
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.02 · 1 substantive comment(s)
0.02
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
42%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.379
Shallow Review Depth shallow_review_depth
0.344
Real PR Conversation Timeline
1 comments
"Review active on #60076"
general weight: 0.35
Reviewers
Assignees
Unassigned
Labels
risk: low confidence: 43.0% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 49.7% (MEDIUM) · Higher = larger blast radius
49.7%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 43.0% · Lower = rushed or shallow review
43.0%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 28.3% · Safe to merge
28.3%
Repository