← Back to Pull requests

[SPARK-60214][SQL] Rejecting non-folable lgNomEntries in analysis phase #59430

Open
SavicStefan opened this pull request with 2525 lines diff across 41 files
View on GitHub
SavicStefan SavicStefan commented on Oct 13, 2026 09:33 UTC
Author

<!--
Thanks for sending a pull request! Here are some tips for you:
1. If this is your first time, please read our contributor guidelines: https://spark.apache.org/contributing.html
2. Ensure you have added or run the appropriate tests for your PR: https://spark.apache.org/developer-tools.html
3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][SPARK-XXXX] Your PR title ...'.
4. Be sure to keep the PR description updated to reflect all changes.
5. Please write your PR title to summarize what this PR proposes.
6. If possible, provide a concise example to reproduce the issue for a faster review.
7. If you want to add a new configuration, please read the guideline first for naming configurations in
'common/utils/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
8. If you want to add or modify an error type or message, please read the guideline first in
'common/utils/src/main/resources/error/README.md'.
-->

What changes were proposed in this pull request?


<!--
Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue.
If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
2. If you fix some SQL features, you can provide some references of other DBMSes.
3. If there is design documentation, please add the link.
4. If there is a discussion in the mailing list, please add the link.
-->

This PR validates the configuration arguments of the HLL, Theta, and Tuple sketch functions during analysis instead of during execution. The arguments must be foldable, non-NULL, and within the valid range:

  • theta_union and its lgNomEntries

  • theta_sketch_agg and its lgNomEntries

  • theta_union_agg and its gNomEntries

  • hll_sketch_agg and its lgConfigK

  • hll_union_agg and its allowDifferentLgConfigK
  • The allowDifferentLgConfigK argument of hll_union_agg must be a foldable boolean expression. NULL continues to mean false, preserving the existing behavior. This handling is now explicit and documented.

    Violations are reported with the existing DATATYPE_MISMATCH subclasses:

  • NON_FOLDABLE_INPUT for row-varying arguments,

  • UNEXPECTED_NULL for NULL arguments,

  • VALUE_OUT_OF_RANGE for out-of-range values.
  • The Tuple functions already validated lgNomEntries during analysis, but reported out-of-range values as TYPE_CHECK_FAILURE_WITH_HINT wrapping SKETCH_INVALID_LG_NOM_ENTRIES. They now report VALUE_OUT_OF_RANGE, which is consistent with HLL and Theta.

    The size checks share a common helper. Constant RuntimeReplaceable expressions, such as nvl(CAST(NULL AS INT), 12) and try_add(10, 2), are replaced before validation.

    Why are the changes needed?


    <!--
    Please clarify why the changes are needed. For instance,
    1. If you propose a new API, clarify the use case for a new API.
    2. If you fix a bug, you can clarify why it is a bug.
    -->

    Previously, invalid HLL and Theta configuration arguments could pass analysis and fail during execution with a SparkRuntimeException. Validating during analysis reports these problems earlier using standard error conditions and query context. Scalar theta_union now follows the same constant, non-NULL size requirement as Tuple union functions.

    Does this PR introduce _any_ user-facing change?


    <!--
    Note that it means any user-facing change including all aspects such as new features, bug fixes, or other behavior changes. Documentation-only updates are not considered user-facing changes.

    If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
    If possible, please also clarify if this is a user-facing change compared to the released Spark versions or within the unreleased branches such as master.
    If no, write 'No'.
    -->

    Yes:
    • Invalid HLL and Theta configuration arguments now fail during analysis with an AnalysisException
    • Validation applies even when an aggregate never executes, such as a grouped aggregate over empty input
    • Scalar theta_union rejects row-varying lgNomEntries values
    • Scalar theta_union with NULL lgNomEntries raises UNEXPECTED_NULL instead of returning NULL
    • Tuple out-of-range errors change from TYPE_CHECK_FAILURE_WITH_HINT to VALUE_OUT_OF_RANGE
    • The existing NULL-to-false behavior of hll_union_agg, allowDifferentLgConfigK flag remains unchanged

    These compatibility changes are documented in the SQL migration guide.

    How was this patch tested?


    <!--
    If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
    If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
    If tests were not added, please describe why they were not added and/or why it was difficult to add.
    If benchmark tests were added, please run the benchmarks in GitHub Actions for the consistent environment, and the instructions could accord to: https://spark.apache.org/developer-tools.html#github-workflow-benchmarks.
    -->

    New and updated unit tests:
    - DatasketchesHllSketchSuite
    - ThetasketchesAggSuite
    - TupleSketchUtilsSuite
    - DataFrameAggregateSuite
    - SQL cases in hll.sql, thetasketch.sql and tuplesketch.sql
    - Connect plan-generation tests

    The latest regression cases cover constant RuntimeReplaceable arguments and NULL HLL union flags, including matching and differing sketch sizes.

    New and updated SQL golden-file cases in hll.sql and thetasketch.sql, plus regenerated tuplesketch.sql output
    and Regenerated Connect golden files with PlanGenerationTestSuite and ProtoToParsedPlanTestSuite.

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


    <!--
    If generative AI tooling has been used in the process of authoring this patch, please include the
    phrase: 'Generated-by: ' followed by the name of the tool and its version.
    If no, write 'No'.
    Please refer to the ASF Generative Tooling Guidance for details.
    -->

    Generated-by: Claude Code (Claude Opus 5.5)

    Diff: 2525 lines (+2159 / -366) across 41 files Reviewer: mihailoale-db Review duration: 53272m
    All Vouch review confidence checks passed
    Residual risk 0.27 = Change Risk (0.79) × (1 − Review Confidence (0.66)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.79 · 2525 lines diff across 41 files
    0.79
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.35 · 1 substantive comment(s)
    0.35
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    65%
    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.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    2 items
    mihailoale-db mihailoale-db commented on Oct 15, 2026 14:59 UTC
    Reviewer

    Leaving some AI proposed comments that I think that we should consider for addressing. PTAL when you find time. Thanks!
    1. sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/thetasketchesExpressions.scala, lines 116-123
    High: scalar theta_union should not require a foldable, non-NULL lgNomEntries. Since 4.1.0, theta_union has validated lgNomEntries per row in nullSafeEval (still at line 129) and returned
    NULL for a NULL value, and the Scala theta_union(c1, c2, lgNomEntries: Column) doc does not say it must be a constant (unlike theta_union_agg). With this check both cases fail analysis, so existing
    queries and views break on upgrade, even though a scalar union builds an independent union per row and has no buffer-wide invariant to protect. Please range-check at analysis only when third is foldable
    and non-NULL, keep the per-row check and NULL -> NULL behavior otherwise, and turn the new non-foldable golden case into a passing one; if the restriction is kept, it needs a migration-guide entry and a
    legacy conf, as with the options-foldability change at docs/sql-migration-guide.md:34.

    2. sql/core/src/test/resources/sql-tests/results/hll.sql.out, lines 249-252
    High: these user-visible changes need a migration-guide entry. hll_ (3.5), theta_ (4.1) and the tuple sketch functions (4.2) change for released users: invalid arguments now raise
    AnalysisException instead of SparkRuntimeException, the SQLSTATE moves from 22546 / 22003 / 42K0E to 42K09, tuple out-of-range errors change from TYPE_CHECK_FAILURE_WITH_HINT to
    VALUE_OUT_OF_RANGE, a query whose invalid sketch aggregate never ran (e.g. a grouped aggregate over empty input) now fails, and scalar theta_union rejects inputs it used to accept. Comparable changes
    are documented at docs/sql-migration-guide.md:34 (foldability) and :44 (an error-condition change for array_repeat). Please add an entry to the target version's section of
    docs/sql-migration-guide.md.

    3. sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/datasketchesAggregates.scala, line 36
    Medium: the same foldable / non-NULL / range check is now implemented three times. DatasketchesInputValidation.checkFoldableInput (a generic, curried helper with a single caller, placed above the
    public HllSketchAgg), ThetaSketchUtils.checkLgNomEntriesInput, and SketchSize.checkLgNomEntriesParameter in TupleSketchUtils.scala (rewritten in this PR to match) emit identical error parameters
    but use different guards: an unchecked asInstanceOf[Int] in the caller's lambda, an internalError on a non-Int value, and reliance on callers having type-checked first. Consider a single shared helper
    such as checkFoldableIntInRange(expr, name, min, max), called with (4, 21) for HLL and (4, 26) for Theta and Tuple, with SketchSize.checkLgNomEntriesParameter delegating to it.

    4. sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/datasketchesAggregates.scala, lines 114-120
    Medium: the runtime re-validation in the lazy vals is now unreachable. Once checkInputDataTypes guarantees a foldable, non-NULL, in-range value, the throws in this lazy val (including the
    hllInvalidLgK throw inlined here) and in ThetaSketchAgg.lgNomEntries / ThetaUnionAgg.lgNomEntries (thetasketchesAggregates.scala:118-125 and :375-382) cannot fire for an analyzed plan, so
    HLL_K_MUST_BE_CONSTANT and THETA_LG_NOM_ENTRIES_MUST_BE_CONSTANT look reachable but are not. Consider reducing these lazy vals to right.eval().asInstanceOf[Int], as CountMinSketchAgg and
    ApproximatePercentile do, and removing HLL_K_MUST_BE_CONSTANT and THETA_LG_NOM_ENTRIES_MUST_BE_CONSTANT.

    5. sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/datasketchesAggregates.scala, line 42
    Medium: constant RuntimeReplaceable arguments are now rejected as non-foldable. RuntimeReplaceable does not override foldable (Expression.scala:451-470), so arguments such as nvl(CAST(NULL AS
    INT), 12)
    or try_add(10, 2) now fail with NON_FOLDABLE_INPUT, while before this change the lazy val ran after ReplaceExpressions and constant folding and accepted them; the same applies to the
    HllUnionAgg check (line 376) and ThetaSketchUtils.checkLgNomEntriesInput. Consider checking foldability on ReplaceExpressions.replace(input), as ExprUtils.convertToMapData does
    (ExprUtils.scala:70-75), and adding a golden case with an nvl argument.

    6. sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/datasketchesAggregates.scala, line 376
    Medium: a NULL allowDifferentLgConfigK is silently treated as false. This check accepts a NULL flag, and the lazy val then turns it into false through null.asInstanceOf[Boolean] (line 335),
    which the new gridTest in DataFrameAggregateSuite locks in; meanwhile every other configuration argument in this PR rejects NULL, scalar hll_union returns NULL for a NULL flag, and the PR description
    says all arguments must be non-NULL. If NULL -> false is meant to stay (it has behaved this way since 3.5), please make it explicit (case null => false), document it in the ExpressionDescription and
    docs/sql-ref-sketch-aggregates.md, update the PR description, and cover it in hll.sql.

    7. sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/datasketchesAggregates.scala, line 288
    Medium: checkLgK now returns a Boolean but keeps a name that implies it throws. HllSketchAgg.checkLgK is public, so an existing caller that uses it as a statement still compiles but silently
    stops validating; for Theta, this PR instead keeps the throwing checkLgNomLongs and adds a separate isValidLgNomLongs predicate. Consider renaming this to isValidLgK so stale callers fail to compile
    and both sketch families follow the same convention.

    8. sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/ThetaSketchUtils.scala, lines 83-86
    *Medium: the new error parameters use raw strings instead of the toSQL helpers. inputName, inputType and inputExpr are passed as "lgNomEntries", "int" and lgNomEntries.sql, so the
    message renders CAST(tab.col AS INT) unquoted next to a quoted sqlExpr, whereas ApproximatePercentile and CountMinSketchAgg use toSQLId / toSQLType / toSQLExpr for NON_FOLDABLE_INPUT (the
    existing tuple sketch code also uses raw strings, but this PR sets these parameters for several released functions at once). Consider switching to toSQLId(...), toSQLType(...) and toSQLExpr(...)
    here and in the HLL and tuple helpers, which becomes a single edit if the helpers are merged.

    9. sql/core/src/test/resources/sql-tests/inputs/thetasketch.sql, lines 473-475
    Medium: several changed behaviors have no golden coverage. The new golden cases only cover non-foldable inputs, so theta_union with an out-of-range value (3 or 27) and with CAST(NULL AS INT)
    (which changes from returning NULL to an error and is only covered in ThetasketchesAggSuite), theta_union_agg with a NULL lgNomEntries, hll_union_agg with a NULL flag (only in a Scala gridTest), a
    foldable non-literal passing case such as hll_sketch_agg(col, 10 + 2), and an argument that throws when evaluated during analysis (e.g. CAST('x' AS INT) under ANSI) are not pinned at the SQL level.
    Please add these to thetasketch.sql and hll.sql and regenerate the golden files.

    10. sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/datasketchesAggregates.scala, lines 89-90
    Medium: the user docs don't describe the new requirements. docs/sql-ref-sketch-aggregates.md (lines 102, 143, 254, 295, 381) lists these arguments only as "INT (optional)" / "BOOLEAN (optional)"
    with a range, the ExpressionDescriptions say "foldable" but not non-NULL (and this one omits the [4, 21] range), and the Scala theta_union(c1, c2, lgNomEntries: Column) doc
    (functions.scala:9991-9993) does not mention the constant requirement. Please update these together; if the scalar theta_union restriction is dropped, its Scala doc can stay as is, but the reference
    doc and the aggregate descriptions still need updating.

    11. sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/TupleSketchUtils.scala, line 126
    Low: two nearby scaladocs in SketchSize don't match the code.** The doc on checkLgNomEntriesParameter (lines 111-113) omits the non-NULL check this method performs, and the doc on
    lgNomEntriesInput (lines 138-141) says it validates the value, although it only evaluates and casts it. Both predate this PR, but since this method is being rewritten, consider fixing them here.

    Reviewers
    Assignees
    SavicStefan SavicStefan
    Labels
    risk: low confidence: 65.5% 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: 78.5% (HIGH) · Higher = larger blast radius
    78.5%
    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: 65.5% · Lower = rushed or shallow review
    65.5%
    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: 27.1% · Safe to merge
    27.1%
    Repository