← Back to Pull requests

fix: Enforce scalar subquery cardinality guard #27711

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on May 04, 2026 04:56 UTC
Author

Summary

Fixes prestodb/presto#27709.

Native execution could incorrectly suppress Scalar sub-query has returned multiple rows for correlated scalar subqueries when the scalar-subquery cardinality guard was combined with another filter predicate into a single AND expression, or when predicates were pushed below the guard allowing rows to be eliminated before the guard evaluates.

Bug

TransformCorrelatedScalarSubquery plans the scalar-subquery cardinality check as a filter directly above MarkDistinct. The filter predicate is a guard like:

SWITCH(
    is_distinct,
    WHEN true THEN true,
    CAST(fail(SUBQUERY_MULTIPLE_ROWS, 'Scalar sub-query has returned multiple rows') AS boolean)
)

This guard must run before any later predicate is allowed to discard the row. Otherwise, a row whose correlated scalar subquery produced multiple rows can disappear without raising the required error.

Multiple optimizer passes can fold this guard together with other predicates into a single AND:

guard AND predicate

That is unsafe for native execution. Native lowers the merged filter into Velox FilterProject expression evaluation. Velox applies top-level conjuncts stage-wise over SelectivityVectors: ConjunctExpr::evalSpecialForm evaluates each input over activeRows, ConjunctExpr::updateResult removes rows whose AND result is already false, and finalizeErrors clears errors for rows that are no longer active.

Additionally, PredicatePushDown.visitMarkDistinct can push predicates below MarkDistinct and the join, eliminating rows before they reach the guard. This prevents the guard from ever seeing the non-distinct rows it needs to reject.

For a query such as:

SELECT name
FROM nation n
WHERE 'AFRICA' = (
    SELECT name
    FROM region
    WHERE regionkey > n.regionkey
)

the comparison predicate can reject the duplicate rows before the scalar-subquery guard's fail(...) is preserved, so native returns an empty result instead of failing.

Fix

Three changes:

1. FilterNode.doNotMerge flag: New boolean field on FilterNode. The filter created by TransformCorrelatedScalarSubquery (the cardinality guard) sets this to true.

2. MergeFilters: Skips merging when the child filter has doNotMerge=true.

3. PredicatePushDown:
- visitFilter: When a FilterNode has doNotMerge=true, does not combine its predicate with inherited predicates. Instead, rewrites the source with TRUE and places any inherited predicates as a separate filter above.
- visitMarkDistinct (native execution only): When the non-pushable set contains the guard, does not push any predicates below MarkDistinct. Creates two separate FilterNodes above: the guard in its own filter (so Velox can't mask its error), and remaining predicates in another filter above it.

The doNotMerge flag is a generic fix (not gated on native execution) since Java can also exhibit incorrect behavior when the guard is combined with other predicates. The visitMarkDistinct change is native-specific since Velox requires the guard to be in its own filter operator to prevent error masking across operator boundaries.

This preserves:

Filter(predicate)
  Filter(guard, doNotMerge=true)
    MarkDistinct(is_distinct)
      Join (all rows — nothing pushed below)

instead of:

Filter(guard AND predicate)
  MarkDistinct(is_distinct)
    Join (with predicates pushed below, eliminating rows)

Validation

  • TestMergeFilters: verifies filters skip merging when child has doNotMerge=true, and merge normally otherwise.

  • TestPredicatePushdown, TestSubqueries, TestTransformCorrelatedScalarSubquery: all pass.

  • testCorrelatedScalarSubqueryMultipleRowsGuard in TestSubqueries: Java-side test verifying the error is raised.

  • testSubqueries in AbstractTestNativeGeneralQueries: native-side tests verifying the error is raised against the standalone Velox runner.
  • Release Notes

    == NO RELEASE NOTE ==
    

    Summary by Sourcery

    Ensure scalar subquery multiple-rows guards are preserved correctly during native Velox expression conversion for AND predicates.

    Bug Fixes:

  • Prevent scalar subquery cardinality guards from being short-circuited away when combined with other predicates in AND expressions during native execution.
  • Enhancements:

  • Detect scalar subquery multiple-rows guard patterns in converted expressions and rewrite AND conjunctions to enforce guard evaluation before other predicates.
  • Summary by Sourcery

    Prevent merging scalar subquery cardinality guard filters with other predicates when they depend on MarkDistinct marker variables, and add tests to cover the behavior in both planner rules and native execution.

    Bug Fixes:

  • Avoid merging filter predicates above MarkDistinct when the child filter references the MarkDistinct marker, preserving scalar subquery cardinality guard semantics during native execution.
  • Tests:

  • Add planner tests verifying filters over MarkDistinct are merged only when they do not reference the MarkDistinct marker variable.

  • Add native execution query tests ensuring correlated scalar subqueries correctly raise multiple-rows errors instead of being silently filtered out.
  • Summary by Sourcery

    Preserve scalar subquery cardinality guard behavior for native execution by preventing unsafe filter merging above MarkDistinct and adding coverage tests.

    Bug Fixes:

  • Avoid merging filters referencing MarkDistinct marker variables when native execution is enabled, preventing scalar subquery cardinality guards from being masked by other predicates.

  • Adjust predicate pushdown over MarkDistinct to keep scalar subquery cardinality guards as separate filters in native execution so multiple-rows errors are not suppressed.
  • Tests:

  • Extend MergeFilters rule tests to cover merging and skipping behavior over MarkDistinct for both native and Java execution paths.

  • Add native execution query tests ensuring correlated scalar subqueries correctly raise multiple-rows errors even when additional predicates could filter the row.
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: pramodsatya Review duration: 303413m
    All Vouch review confidence checks passed
    Residual risk 0.35 = Change Risk (0.59) × (1 − Review Confidence (0.41)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.59 · 650 lines diff across 8 files
    0.59
    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%
    40%
    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.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #27711"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 40.9% 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: 59% (MEDIUM) · Higher = larger blast radius
    59%
    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: 40.9% · Lower = rushed or shallow review
    40.9%
    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: 34.8% · Safe to merge
    34.8%