Skip to content

[BugFix] Support cast of boolean to double and float in Calcite (#5987) - #5993

Merged
Swiddis merged 1 commit into
opensearch-project:mainfrom
shuseng8:issue-5987-cast-boolean-double
Nov 30, 2026
Merged

Swiddis merged 1 commit into
opensearch-project:mainfrom
shuseng8:issue-5987-cast-boolean-double

Conversation

@shuseng8

Copy link
Copy Markdown
Contributor

Description

cast(<boolean> as double) and cast(<boolean> as float) failed with a 500 (No applicable constructor/method found for actual parameters "boolean"; candidates are: "public java.lang.Object org.apache.calcite.linq4j.tree.Primitive.numberValueRoundDown(java.lang.Number)"), while cast(<boolean> as int) and cast(<boolean> as long) worked.

Root cause: Calcite's RexBuilder.makeCast rewrites a BOOLEAN → exact numeric cast (INTEGER/BIGINT) into CASE(b, 1, 0), which is why the int/long casts work. There is no such rewrite for approximate numeric targets, so a BOOLEAN → DOUBLE/REAL cast reaches RexToLixTranslator, which emits Primitive.of(double.class).numberValueRoundDown(<boolean>) and the generated code does not compile.

Fix: ExtendedRexBuilder.makeCast now rewrites BOOLEAN → approximate numeric (DOUBLE, FLOAT/REAL) casts the same way Calcite does for exact numerics: CASE(b, 1.0, 0.0), wrapped in CASE(IS NOT NULL(b), ..., null) when the input is nullable. So true → 1.0, false → 0.0, and null stays null. This matches the int/long casts, the v2 engine (TypeCastOperators maps boolean to 1D/0D and 1f/0f), and the documented v?1:0 rule in docs/user/ppl/functions/conversion.md, so no doc change is needed.

Related Issues

Resolves #5987

Check List

  • New functionality includes testing.
    • Unit tests in ExtendedRexBuilderTest for the rewritten expression (nullable and non-null boolean, DOUBLE and REAL).
    • Unit tests in CalcitePPLCastFunctionTest that execute cast(... as int/double/float) on true, false and null booleans and on boolean literals. Both fail on main with the codegen error from the issue.
    • Re-enabled the FLOAT and DOUBLE assertions in CalcitePPLCastFunctionIT.testCastBOOLEAN, which were commented out with a TODO for this codegen error.
    • YAML REST test issues/5987.yml with true, false and missing values.
  • New functionality has been documented.
    • New functionality has javadoc added.
    • New functionality has a user manual doc added.
  • New PPL command checklist all confirmed.
  • API changes companion pull request created.
  • Commits are signed per the DCO using --signoff or -s.
  • Public documentation issue/PR created.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.

…search-project#5987)

Calcite rewrites BOOLEAN to exact numeric casts into CASE expressions,
but not BOOLEAN to approximate numeric casts, so the generated code
passed a boolean to Primitive.numberValueRoundDown(Number) and failed
to compile, returning a 500. Rewrite these casts in ExtendedRexBuilder
so true becomes 1.0, false becomes 0.0 and null stays null, matching
the integer casts and the v2 engine.

Signed-off-by: Shubham <87247136+shuseng8@users.noreply.github.com>
@github-actions

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🧪 PR contains tests
🔒 No security concerns identified
✅ No TODO sections
🔀 No multiple PR themes
⚡ No major issues detected

@github-actions

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Simplify NULL propagation in boolean cast

The inner CASE(exp, 1.0, 0.0) treats a NULL boolean as FALSE and would return 0.0
instead of NULL. The outer IS_NOT_NULL guard only works if exp is actually nullable;
however, exp.getType().isNullable() reflects the declared type, not whether the
runtime value can be null in all contexts. Consider using a three-branch CASE
CASE(exp, 1.0, NOT(exp), 0.0, NULL) to correctly propagate NULL without relying on
the outer wrapper, simplifying the logic.

core/src/main/java/org/opensearch/sql/calcite/ExtendedRexBuilder.java [207-223]

 private RexNode makeCastBooleanToApproximateNumeric(RelDataType toType, RexNode exp) {
     final RelDataType literalType = typeFactory.createTypeWithNullability(toType, false);
-    final RexNode casted =
-        makeCall(
-            toType,
-            SqlStdOperatorTable.CASE,
-            ImmutableList.of(
-                exp, makeApproxLiteral(BigDecimal.ONE, literalType), makeZeroLiteral(literalType)));
     if (!exp.getType().isNullable()) {
-      return casted;
+      return makeCall(
+          toType,
+          SqlStdOperatorTable.CASE,
+          ImmutableList.of(
+              exp, makeApproxLiteral(BigDecimal.ONE, literalType), makeZeroLiteral(literalType)));
     }
     return makeCall(
         toType,
         SqlStdOperatorTable.CASE,
         ImmutableList.of(
-            makeCall(SqlStdOperatorTable.IS_NOT_NULL, exp), casted, makeNullLiteral(toType)));
+            exp,
+            makeApproxLiteral(BigDecimal.ONE, literalType),
+            makeCall(SqlStdOperatorTable.NOT, exp),
+            makeZeroLiteral(literalType),
+            makeNullLiteral(toType)));
   }
Suggestion importance[1-10]: 4

__

Why: The existing code correctly wraps the CASE with an IS_NOT_NULL guard when the input is nullable, so NULL is properly propagated. The suggestion offers a stylistic alternative (three-branch CASE) but does not fix a real bug; the claim that the outer wrapper is unreliable is not substantiated.

Low

@Swiddis Swiddis added PPL Piped processing language bugFix labels Nov 29, 2026

@Swiddis Swiddis left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

lgtm assuming actions pass (link checker and analytics engine ok) -- will check tomorrow that they did

@codecov

codecov Bot commented Nov 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.47%. Comparing base (c7e2cea) to head (ea9ece6).

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #5993      +/-   ##
============================================
+ Coverage     89.46%   89.47%   +0.01%     
- Complexity    12251    12255       +4     
============================================
  Files           980      980              
  Lines         41967    41979      +12     
  Branches       4829     4831       +2     
============================================
+ Hits          37545    37561      +16     
+ Misses         2945     2942       -3     
+ Partials       1477     1476       -1     
Flag Coverage Δ
integration 69.91% <83.33%> (+<0.01%) ⬆️
unit 76.84% <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.

@shuseng8

Copy link
Copy Markdown
Contributor Author

Hi @Swiddis, thanks for the approval! The remaining red checks look unrelated to this change (analytics-engine security IT / async PPL lifecycle IT failures, and codecov/project). Could you re-run the failed jobs when you get a chance? Happy to look at anything that still fails.

@Swiddis
Swiddis merged commit c154e40 into opensearch-project:main Nov 30, 2026
80 of 89 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bugFix PPL Piped processing language

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] cast(<boolean> as double) returns 500

2 participants