Repository navigation
Open
Description
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')"
}
Metadata
Metadata
Assignees
Type
Projects
- StatusShow more project fieldsNot Started
Activity
[-][BUG][/-][+][BUG] Unified query API fails with date types[/+]dai-chen commentedon Mar 19, 2026
Will investigate and reproduce. Thanks!
dai-chen commentedon Mar 23, 2026
The potential root cause is that the unified query API accepts standard Calcite
ScannableTablewhere users naturally declareSqlTypeName.DATE(standard Calcite convention, values are int). But the PPL engine's UDFs return String values designed for theEXPR_DATEUDT. The API doesn't bridge between these two type conventions. Confirming and figuring out a solution.Test
Error stacktrace
[Test] Add reproduction and workarounds for date type comparison bug (o…
dai-chen commentedon Mar 23, 2026
@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_DATEUDT with String values, or (2) simply useSqlTypeName.VARCHARwith String values in ISO format (yyyy-MM-dd). I've pushed a test demonstrating the bug reproduction and both workarounds here:feat(api): Add post-planning datetime UDT rewriter for clean RelNode
dai-chen commentedon Apr 7, 2026
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)wheretsis standardTIMESTAMP:This causes:
long > Stringin conditions.fromObjectValue((String) longValue)→ ClassCastException at runtime.Examples
Schema:
hire_dateis standard CalciteDATE(int),nameisVARCHAR.source=t | eval y = YEAR(hire_date)int,fromObjectValue((String) intValue)→ ClassCastExceptionsource=t | where hire_date > DATE('2020-06-01')int > String— no valid code pathsource=t | eval d = LAST_DAY(hire_date) | fields dintoperand; same ClassCastException as Case 1source=t | fields hire_datejava.sql.Dateinstead of ISO string — violates PPL's wire-format contractApproaches Explored
valueForCalcite()to return int/long; updateOpenSearchIndexEnumeratorandfromObjectValue()DATE→EXPR_DATEetc. in the ScannableTable before Calcite sees itScannableTable/Schema, row-value conversion, handling of derived schemas (views, CTEs). Transparent to PPL. Couples api/ to UDT knowledge.PPLFuncImpTable.registerExternalOperatororExtendedRexBuilder.makeCall()override)NotNullImplementor— walk RelNode, wrap each PPL datetime UDF with a delegatingNotNullImplementorthat interceptstranslatedOperandsas Linq4jExpressionand converts long → String → impl → String → int inlineNotNullImplementoronImplementorUDF(named inner class with getter).YEAR→SqlStdOperatorTable.YEAR, etc.); CAST-wrap the remaining 23CAST(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' cachedRexInputReftypes, causingProject.isValid()assertions to fire during plan rebuild (GROUP BY, aggregates break).ExprValueUtils.fromObjectValue()to accept Integer/Long + add standard↔UDT type coercion rules, OR add UDT-aware CAST insertion insidePPLFuncImpTable.resolveWithCoercion()col > DATE('...')) goes throughSqlStdOperatorTable.GREATER_THAN— needs extra logic in the comparator path ofresolveWithCoercion. Case 4 is unreachable — no UDF invocation, no resolver hook. Needs supplementary mechanism for full coverage. ThefromObjectValuevariant also adds conversion machinery that entrenches UDTs rather than reducing them.QualifiedNameResolver— implicitly cast standard datetime refs to PPL UDTs at field-ref resolution, before any RelNode is builtQualifiedNameResolver.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 onCalcitePlanContextso 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'sRexInputRefcarries 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'sProject.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:
feat(api): Add UDT normalizer for unified query API (opensearch-proje…
feat(api): Add UDT normalizer for unified query API (opensearch-proje…
feat(api): Add UDT normalizer for unified query API (opensearch-proje…
dai-chen commentedon May 8, 2026
Follow-up: Datetime UDF Compilation Fixes (Low Priority)
Branch:
feature/ppl-udt-compilation-adapterThe 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
UnifiedQueryCompilerpath (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
preCompilationRulethat inserts CAST bridges around datetime UDFs: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(...))orstats count() by DATE(...)), the normalize rule changes the child's output type, causingAggregate.copy()to fail with a type mismatch assertion. A parentLogicalProjectabove the Aggregate also fails due to staleRexInputReftypes.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 LogicalTableScanFix: Override the bottom-up traversal to manually handle each level when child types change:
AggregateCallwithnulltype to force re-inference from new inputRexInputReftypes from new child's row typeThis avoids cascading — each level only fixes its immediate references to the changed child (one level down), so the fix is bounded (not recursive).