Skip to content

[BUG] Unified query API fails with date types #5250

Open

Description

@lostella

What is the bug?
Unified query API fails when date type is involved in PPL, but query runs fine in OpenSearch

How can one reproduce the bug?
Run the following class:

package org.opensearch.sql.api.examples;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.calcite.DataContext;
import org.apache.calcite.config.CalciteConnectionConfig;
import org.apache.calcite.linq4j.Enumerable;
import org.apache.calcite.linq4j.Linq4j;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.schema.ScannableTable;
import org.apache.calcite.schema.Schema;
import org.apache.calcite.schema.Statistic;
import org.apache.calcite.schema.Statistics;
import org.apache.calcite.schema.Table;
import org.apache.calcite.schema.impl.AbstractSchema;
import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.type.SqlTypeName;
import org.opensearch.sql.api.UnifiedQueryContext;
import org.opensearch.sql.api.UnifiedQueryPlanner;
import org.opensearch.sql.api.compiler.UnifiedQueryCompiler;
import org.opensearch.sql.executor.QueryType;

/** MWE: DATE() function comparison fails - returns string instead of int (days since epoch). */
public class DateComparisonBugExample {

  public static void main(String[] args) throws Exception {
    Map<String, SqlTypeName> schema = new LinkedHashMap<>();
    schema.put("id", SqlTypeName.INTEGER);
    schema.put("date_hired", SqlTypeName.DATE);

    List<Object[]> rows = List.of(new Object[] {1, Date.valueOf("2020-03-15")}, new Object[] {2, Date.valueOf("2020-06-15")});

    AbstractSchema testSchema =
        new AbstractSchema() {
          @Override
          protected Map<String, Table> getTableMap() {
            return Map.of("employees", new SimpleTable(schema, rows));
          }
        };

    try (UnifiedQueryContext context =
        UnifiedQueryContext.builder()
            .language(QueryType.PPL)
            .catalog("test", testSchema)
            .defaultNamespace("test")
            .build()) {

      UnifiedQueryPlanner planner = new UnifiedQueryPlanner(context);
      UnifiedQueryCompiler compiler = new UnifiedQueryCompiler(context);

      String query = "source=employees | where date_hired > DATE('2020-06-01')";
      PreparedStatement stmt = compiler.compile(planner.plan(query));
      ResultSet rs = stmt.executeQuery();

      while (rs.next()) {
        System.out.println("id=" + rs.getInt(1) + ", date_hired=" + rs.getDate(2));
      }
    }
  }

  private static class SimpleTable implements ScannableTable {
    private final Map<String, SqlTypeName> schema;
    private final List<Object[]> rows;

    SimpleTable(Map<String, SqlTypeName> schema, List<Object[]> rows) {
      this.schema = schema;
      this.rows = rows;
    }

    @Override
    public RelDataType getRowType(RelDataTypeFactory typeFactory) {
      RelDataTypeFactory.Builder builder = typeFactory.builder();
      schema.forEach((name, type) -> builder.add(name, typeFactory.createSqlType(type)));
      return builder.build();
    }

    @Override
    public Enumerable<Object[]> scan(DataContext root) {
      return Linq4j.asEnumerable(rows);
    }

    @Override
    public Statistic getStatistic() {
      return Statistics.UNKNOWN;
    }

    @Override
    public Schema.TableType getJdbcTableType() {
      return Schema.TableType.TABLE;
    }

    @Override
    public boolean isRolledUp(String column) {
      return false;
    }

    @Override
    public boolean rolledUpColumnValidInsideAgg(
        String column, SqlCall call, SqlNode parent, CalciteConnectionConfig config) {
      return false;
    }
  }
}

What is the expected behavior?

The PPL query executed in the class should run fine, and return the second record in the table.

This expected behavior can be reproduced in OpenSearch:

PUT /employees
{
  "mappings": {
    "properties": {
      "id": { "type": "integer" },
      "date_hired": { "type": "date", "format": "yyyy-MM-dd" }
    }
  }
}

POST /employees/_bulk
{"index": {}}
{"id": 1, "date_hired": "2020-03-15"}
{"index": {}}
{"id": 2, "date_hired": "2020-06-15"}


POST /_plugins/_ppl
{
  "query": "source=employees | where date_hired > DATE('2020-06-01')"
}

Activity

  1. added
    bug
    on Mar 19, 2026
  2. changed the title [-][BUG][/-] [+][BUG] Unified query API fails with date types[/+] on Mar 19, 2026
  3. dai-chen commented on Mar 19, 2026

    @dai-chen
    Collaborator

    Will investigate and reproduce. Thanks!

  4. self-assigned this
    on Mar 23, 2026
  5. dai-chen commented on Mar 23, 2026

    @dai-chen
    Collaborator

    The potential root cause is that the unified query API accepts standard Calcite ScannableTable where users naturally declare SqlTypeName.DATE (standard Calcite convention, values are int). But the PPL engine's UDFs return String values designed for the EXPR_DATE UDT. The API doesn't bridge between these two type conventions. Confirming and figuring out a solution.

    Test

    # In UnifiedQueryCompilerTest:
      @Test
      public void testDateFunctionComparisonWithScannableTable() throws Exception {
        AbstractSchema schema =
            new AbstractSchema() {
              @Override
              protected Map<String, Table> getTableMap() {
                return Map.of(
                    "employees",
                    SimpleTable.builder()
                        .col("id", org.apache.calcite.sql.type.SqlTypeName.INTEGER)
                        .col("date_hired", DATE)
                        .row(new Object[] {1, 18336}) // 2020-03-15
                        .row(new Object[] {2, 18428}) // 2020-06-15
                        .build());
              }
            };
    
        try (UnifiedQueryContext ctx =
            UnifiedQueryContext.builder()
                .language(QueryType.PPL)
                .catalog("test", schema)
                .defaultNamespace("test")
                .build()) {
          UnifiedQueryPlanner p = new UnifiedQueryPlanner(ctx);
          UnifiedQueryCompiler c = new UnifiedQueryCompiler(ctx);
    
          IllegalStateException e =
              org.junit.Assert.assertThrows(
                  IllegalStateException.class,
                  () ->
                      c.compile(
                              p.plan("source=employees | where date_hired > DATE('2020-06-01')"))
                          .executeQuery());
          // DATE() UDF returns String via ExprDateValue.valueForCalcite(), but ScannableTable
          // provides DATE column values as int (days since epoch) per Calcite convention.
          org.junit.Assert.assertTrue(
              e.getMessage().contains("Failed to compile logical plan"));
    
          e.printStackTrace();
        }
      }
    

    Error stacktrace

    Caused by: java.sql.SQLException: Error while preparing plan [LogicalFilter(condition=[>($1, DATE('2020-06-01':VARCHAR))])
      BindableTableScan(table=[[test, employees]])
    ]
    	at org.apache.calcite.avatica.Helper.createException(Helper.java:56)
    	at org.apache.calcite.avatica.Helper.createException(Helper.java:41)
    	at org.apache.calcite.jdbc.CalciteConnectionImpl.prepareStatement_(CalciteConnectionImpl.java:236)
    	at org.apache.calcite.jdbc.CalciteConnectionImpl.lambda$unwrap$0(CalciteConnectionImpl.java:196)
    	at org.opensearch.sql.api.compiler.UnifiedQueryCompiler.compile(UnifiedQueryCompiler.java:66)
    	... 48 more
    Caused by: java.lang.RuntimeException: Error while compiling generated Java code:
    public org.apache.calcite.linq4j.Enumerable bind(final org.apache.calcite.DataContext root) {
      final org.apache.calcite.rel.RelNode v1stashed = (org.apache.calcite.rel.RelNode) root.get("v1stashed");
      final org.apache.calcite.interpreter.Interpreter interpreter = new org.apache.calcite.interpreter.Interpreter(
        root,
        v1stashed);
      return new org.apache.calcite.linq4j.AbstractEnumerable(){
          public org.apache.calcite.linq4j.Enumerator enumerator() {
            return new org.apache.calcite.linq4j.Enumerator(){
                public final org.apache.calcite.linq4j.Enumerator inputEnumerator = interpreter.enumerator();
                public void reset() {
                  inputEnumerator.reset();
                }
    
                public boolean moveNext() {
                  while (inputEnumerator.moveNext()) {
                    if (org.apache.calcite.runtime.SqlFunctions.toInt(((Object[]) inputEnumerator.current())[1]) > "2020-06-01") {
                      return true;
                    }
                  }
                  return false;
                }
    
                public void close() {
                  inputEnumerator.close();
                }
    
                public Object current() {
                  final Object[] current = (Object[]) inputEnumerator.current();
                  final Object input_value = current[0];
                  final Object input_value0 = current[1];
                  return new Object[] {
                      input_value,
                      input_value0};
                }
    
              };
          }
    
        };
    }
    
    public Class getElementType() {
      return java.lang.Object[].class;
    }
    
    	at org.apache.calcite.avatica.Helper.wrap(Helper.java:37)
    	at org.apache.calcite.adapter.enumerable.EnumerableInterpretable.toBindable(EnumerableInterpretable.java:129)
    	at org.apache.calcite.prepare.CalcitePrepareImpl$CalcitePreparingStmt.implement(CalcitePrepareImpl.java:1190)
    	at org.opensearch.sql.calcite.utils.CalciteToolsHelper$OpenSearchCalcitePreparingStmt.implement(CalciteToolsHelper.java:361)
    	at org.apache.calcite.prepare.CalcitePrepareImpl$CalcitePreparingStmt.prepare_(CalcitePrepareImpl.java:1087)
    	at org.apache.calcite.prepare.CalcitePrepareImpl$CalcitePreparingStmt.prepareRel(CalcitePrepareImpl.java:1042)
    	at org.apache.calcite.prepare.CalcitePrepareImpl.prepare2_(CalcitePrepareImpl.java:694)
    	at org.apache.calcite.prepare.CalcitePrepareImpl.prepare_(CalcitePrepareImpl.java:524)
    	at org.apache.calcite.prepare.CalcitePrepareImpl.prepareSql(CalcitePrepareImpl.java:492)
    	at org.apache.calcite.jdbc.CalciteConnectionImpl.parseQuery(CalciteConnectionImpl.java:246)
    	at org.apache.calcite.jdbc.CalciteConnectionImpl.prepareStatement_(CalciteConnectionImpl.java:226)
    	... 50 more
    Caused by: org.codehaus.commons.compiler.CompileException: Line 17, Column 112: Cannot compare types "int" and "java.lang.String"
    	at org.codehaus.janino.UnitCompiler.compileError(UnitCompiler.java:13228)
    	at org.codehaus.janino.UnitCompiler.compileBoolean2(UnitCompiler.java:4638)
    	at org.codehaus.janino.UnitCompiler.access$6800(UnitCompiler.java:240)
    	at org.codehaus.janino.UnitCompiler$14.visitBinaryOperation(UnitCompiler.java:4363)
    	at org.codehaus.janino.UnitCompiler$14.visitBinaryOperation(UnitCompiler.java:4344)
    	at org.codehaus.janino.Java$BinaryOperation.accept(Java.java:5249)
    	at org.codehaus.janino.UnitCompiler.compileBoolean(UnitCompiler.java:4344)
    	at org.codehaus.janino.UnitCompiler.compile2(UnitCompiler.java:2697)
    
  6. added
    PPL
    and removed on Mar 23, 2026
  7. dai-chen commented on Mar 23, 2026

    @dai-chen
    Collaborator

    @lostella Thanks for reporting this!

    Root Cause

    The root cause is a type system mismatch between standard Calcite types and the PPL engine's internal type representation. Specifically, the PPL engine's date functions (including DATE()) return a custom VARCHAR-based UDT, while your ScannableTable declares the column as standard Calcite SqlTypeName.DATE which uses int internally. I need more time to explore the best solution that doesn't require users to work around PPL engine internals.

    Workaround

    As a temporary workaround, you can either (1) declare date columns using the PPL engine's EXPR_DATE UDT with String values, or (2) simply use SqlTypeName.VARCHAR with String values in ISO format (yyyy-MM-dd). I've pushed a test demonstrating the bug reproduction and both workarounds here:

  8. dai-chen commented on Apr 7, 2026

    @dai-chen
    Collaborator

    Root Cause Details

    PPL datetime UDFs return VARCHAR-backed UDTs (EXPR_DATE/TIME/TIMESTAMP, stored as String). When the unified query API consumer (e.g., analytics-engine) provides a ScannableTable with standard Calcite DATE/TIME/TIMESTAMP columns, the RelNode contains type mismatches between the columns (int/long Java types) and the UDT values (String Java types).

    Example: source=events | eval d = DATE(ts) where ts is standard TIMESTAMP:

    LogicalProject(ts=[$0:TIMESTAMP], d=[DATE($0):EXPR_DATE])
      LogicalTableScan(table=[events])
    
      ts type:       TIMESTAMP (long, standard Calcite)
      DATE() type:   EXPR_DATE (String, VARCHAR-backed UDT) ← mismatch
    

    This causes:

    1. Janino compilation failure comparing long > String in conditions.
    2. fromObjectValue((String) longValue) → ClassCastException at runtime.
    3. Consumers can't pattern-match clean types for downstream pushdown.

    Examples

    Schema: hire_date is standard Calcite DATE (int), name is VARCHAR.

    # Case Example query What fails today
    1 Std datetime col fed into PPL UDT UDF source=t &#124; eval y = YEAR(hire_date) UDF receives int, fromObjectValue((String) intValue) → ClassCastException
    2 UDT result compared with std datetime col source=t &#124; where hire_date > DATE('2020-06-01') Janino rejects int > String — no valid code path
    3 UDT terminal in projection source=t &#124; eval d = LAST_DAY(hire_date) &#124; fields d UDF receives int operand; same ClassCastException as Case 1
    4 Bare std datetime col in projection source=t &#124; fields hire_date No runtime error, but ResultSet returns java.sql.Date instead of ISO string — violates PPL's wire-format contract

    Approaches Explored

    # Approach Where Complexity Case coverage Notes
    A Remove datetime UDTs entirely — PPL datetime UDFs return standard Calcite types; rewrite valueForCalcite() to return int/long; update OpenSearchIndexEnumerator and fromObjectValue() core/ + opensearch/ Extremely high 1, 2, 3, 4 Long-term correct direction. Multi-release refactor; requires OpenSearch plugin migration. Out of scope as a tactical #5250 fix.
    B Wrap user schema with UDT replacement at the unified API boundary — substitute DATE → EXPR_DATE etc. in the ScannableTable before Calcite sees it api/ schema adapter Unknown (likely High) 1, 2, 3, 4 Not PoC'd. Needs wrapping every caller-provided ScannableTable / Schema, row-value conversion, handling of derived schemas (views, CTEs). Transparent to PPL. Couples api/ to UDT knowledge.
    C Intercept function resolution / swap operator — replace the PPL datetime UDF at resolution time with a variant that handles standard operand types natively (via PPLFuncImpTable.registerExternalOperator or ExtendedRexBuilder.makeCall() override) core/ (ExtendedRexBuilder) or none Medium 1, 3 PPLFuncImpTable is a global singleton — risk of race conditions with the SQL plugin path. Doesn't cover Case 2 (comparison is not a PPL UDF) or Case 4 (no UDF at all).
    D Rebind function implementation via NotNullImplementor — walk RelNode, wrap each PPL datetime UDF with a delegating NotNullImplementor that intercepts translatedOperands as Linq4j Expression and converts long → String → impl → String → int inline core+api Medium 1, 2, 3, 4 PoC #5355, 7 tests pass. Clean RelNode — UDT types erased, no CAST nodes. Requires exposing NotNullImplementor on ImplementorUDF (named inner class with getter).
    E Replace UDFs with standard Calcite operators — map 17 PPL datetime UDFs with Calcite equivalents (YEAR → SqlStdOperatorTable.YEAR, etc.); CAST-wrap the remaining 23 api/ RelNode rewriter High 1, 2, 3, 4 (inconsistently) Only 17 of ~40 datetime UDFs have standard equivalents. Remaining 23 still need CAST wrapping. Behavioral divergence between replaced and non-replaced UDFs. Complex mapping to maintain.
    F Post-analysis RelNode rewrite with CASTs — walk the plan and insert CAST nodes to bridge type boundaries. Two variants tried: F1 wrap UDF operands to VARCHAR + wrap UDF results back to standard DATE (keeps enclosing Project output types unchanged); F2 wrap every standard datetime ref directly to UDT api/ PostAnalysisRule Medium F1: 1, 2, 3, 4 (with caveats); F2: ❌ does not work F1 works functionally but produces noisy plans like CAST(DATE(CAST($0 AS VARCHAR)):EXPR_DATE AS DATE) — downstream consumers can't pattern-match on bare UDF calls for pushdown; nested calls compound the CASTs. F2 changes RelNode output types and invalidates parent RelNodes' cached RexInputRef types, causing Project.isValid() assertions to fire during plan rebuild (GROUP BY, aggregates break).
    G Implicit coercion inside core/ function resolution — either fix ExprValueUtils.fromObjectValue() to accept Integer/Long + add standard↔UDT type coercion rules, OR add UDT-aware CAST insertion inside PPLFuncImpTable.resolveWithCoercion() core/ (ExprValueUtils or PPLFuncImpTable) Medium 1, 3 (partial 2) Covers UDF operand mismatches at the function-resolution layer. Case 2 (bare comparison col > DATE('...')) goes through SqlStdOperatorTable.GREATER_THAN — needs extra logic in the comparator path of resolveWithCoercion. Case 4 is unreachable — no UDF invocation, no resolver hook. Needs supplementary mechanism for full coverage. The fromObjectValue variant also adds conversion machinery that entrenches UDTs rather than reducing them.
    H Construction-time coercion in QualifiedNameResolver — implicitly cast standard datetime refs to PPL UDTs at field-ref resolution, before any RelNode is built core/ name resolver Low 1, 2, 3, 4 QualifiedNameResolver.resolve() is the single chokepoint for PPL expression-level field references (where, eval, fields, sort, stats, comparisons, UDF args, join conditions). A ~10-line addition handles all four cases. Construction-time coercion means each RelNode is built with consistent UDT types from the start — no parent-child type mismatches possible. Can be gated by a flag on CalcitePlanContext so V3 behavior is unchanged.

    Key Finding: Post-Analysis Type Rewrites Can't Solve This

    Approach F's F2 variant (wrapping refs to UDT) and any similar post-analysis rewrite that changes RelNode output column types has a fundamental flaw: any change to a RelNode's output column type must propagate to every ancestor that references that column by RexInputRef. Calcite's RexInputRef carries its own declared type, captured when the parent RelNode was built. Changing the child's output type after the parent is built leaves the parent's refs stale; Calcite's Project.isValid() / Filter.isValid() assertions fire on any plan rebuild.

    The approaches that avoid this are those that either (a) don't change RelNode output types in the first place, or (b) establish the intended type before it enters the RelNode tree:

    1. Remove UDTs at the source (A) — the long-term solution.
    2. Replace the UDT at the input boundary (B, D) — intercept before types are established.
    3. Coerce at field-ref resolution time (H) — insert CASTs at expression construction, so RelNodes are born with the intended types.
    4. Accept plan-level CAST pollution (F1) — wrap operands and re-cast results around UDF calls without changing enclosing Project output types. Works but clutters the plan.
  9. dai-chen commented on May 8, 2026

    @dai-chen
    Collaborator

    Follow-up: Datetime UDF Compilation Fixes (Low Priority)

    Branch: feature/ppl-udt-compilation-adapter

    The merged PR #5408 normalizes datetime UDT types in the RelNode plan, which is sufficient for the Analytics Engine (Substrait/DataFusion) path. Two additional fixes are needed only for the UnifiedQueryCompiler path (in-memory Enumerable execution):

    1. Function Implementation Adapter (DatetimeUdfCompilationAdapterRule)

    Problem: After normalization, UDF return types are standard DATE/TIME/TIMESTAMP (int/long at runtime), but PPL UDF implementors still expect and produce String values. Janino-generated code passes int/long to methods expecting String → ClassCastException.

    Fix: A preCompilationRule that inserts CAST bridges around datetime UDFs:

    Before: LAST_DAY($2:DATE) : DATE
    After:  CAST(LAST_DAY(CAST($2 AS VARCHAR)):VARCHAR AS DATE)
    

    The UDF receives String, produces String, and CASTs handle the int↔String conversion using Calcite's DateTimeUtils.

    2. Aggregate Type Propagation Fix (in DatetimeUdtNormalizeRule)

    Problem: When a datetime UDF result feeds into LogicalAggregate (e.g., stats max(DATE(...)) or stats count() by DATE(...)), the normalize rule changes the child's output type, causing Aggregate.copy() to fail with a type mismatch assertion. A parent LogicalProject above the Aggregate also fails due to stale RexInputRef types.

    Before normalize:
     LogicalProject(c=[$1], d=[$0])                    ← $0 type: EXPR_DATE
       LogicalAggregate(group=[{5}], c=[COUNT()])       ← AggregateCall type: EXPR_DATE
         LogicalProject(..., d=[DATE('...'):EXPR_DATE])
           LogicalTableScan
    
    After normalize (without fix → cascading type mismatch):
     LogicalProject(c=[$1], d=[$0])                    ← $0 type: EXPR_DATE (STALE!)
       LogicalAggregate(group=[{5}], c=[COUNT()])       ← AggregateCall type: EXPR_DATE (STALE!)
         LogicalProject(..., d=[DATE('...'):DATE])      ← changed to standard DATE
           LogicalTableScan
    

    Fix: Override the bottom-up traversal to manually handle each level when child types change:

    • Aggregate: Rebuild AggregateCall with null type to force re-inference from new input
    • Project: Refresh RexInputRef types from new child's row type

    This avoids cascading — each level only fixes its immediate references to the changed child (one level down), so the fix is bounded (not recursive).

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

Metadata

Metadata

Assignees

Labels

PPLbug

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions