xiangfu0 commented on code in PR #20303:
URL: https://github.com/apache/pinot/pull/20303#discussion_r4646989236


##########
pinot-query-planner/src/main/java/org/apache/pinot/calcite/sql/fun/PinotItemOperator.java:
##########
@@ -0,0 +1,72 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.calcite.sql.fun;
+
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rel.type.RelDataTypeFactory;
+import org.apache.calcite.sql.SqlCallBinding;
+import org.apache.calcite.sql.SqlOperatorBinding;
+import org.apache.calcite.sql.fun.SqlItemOperator;
+import org.apache.calcite.sql.fun.SqlStdOperatorTable;
+import org.apache.calcite.sql.type.SqlSingleOperandTypeChecker;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.util.Static;
+import org.apache.pinot.query.type.OpenStructSqlType;
+
+
+/// The SQL `ITEM` operator (`x[i]`, `m['k']`), typed for OPEN_STRUCT columns.
+///
+/// Every operand type behaves as Calcite's standard ITEM. When the operand is 
an [OpenStructSqlType] and the key is a
+/// literal, the result is the key's declared type, so `v['n'] > 50` and 
`SUM(v['n'])` are numeric when `n` is
+/// declared numeric; an undeclared key is VARCHAR. Either way the result is 
nullable, since any row may lack the key.
+/// This matches the single-stage engine, which reads a declared key with its 
declared type and an undeclared key as
+/// STRING. The key must be a literal: the leaf stage resolves it once per 
segment, so `col[otherCol]` is rejected at
+/// validation. Stateless and thread-safe.
+public class PinotItemOperator extends SqlItemOperator {
+  public static final PinotItemOperator INSTANCE = new PinotItemOperator();
+
+  private PinotItemOperator() {
+    // Calcite's ITEM is built with a single-operand checker (the operand-type 
rules for MAP, ARRAY and ROW).
+    super("ITEM", (SqlSingleOperandTypeChecker) 
SqlStdOperatorTable.ITEM.getOperandTypeChecker(), 0, false);
+  }
+
+  @Override
+  public boolean checkOperandTypes(SqlCallBinding callBinding, boolean 
throwOnFailure) {
+    if (callBinding.getOperandType(0) instanceof OpenStructSqlType && 
!callBinding.isOperandLiteral(1, false)) {
+      if (throwOnFailure) {
+        throw 
callBinding.getValidator().newValidationError(callBinding.operand(1),
+            Static.RESOURCE.argumentMustBeLiteral(getName()));
+      }
+      return false;
+    }
+    return super.checkOperandTypes(callBinding, throwOnFailure);
+  }
+
+  @Override
+  public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
+    if (opBinding.getOperandType(0) instanceof OpenStructSqlType openStruct) {
+      RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+      String key = opBinding.isOperandLiteral(1, false) ? 
opBinding.getOperandLiteralValue(1, String.class) : null;
+      RelDataType declared = key == null ? null : 
openStruct.getDeclaredKeyType(key);
+      RelDataType type = declared != null ? declared : 
typeFactory.createSqlType(SqlTypeName.VARCHAR);

Review Comment:
   I reproduced this on `4f936bfe22` with one offline segment containing 1,000 
rows. `views` held the strings `0` through `999`, and the table declared it 
LONG. `WHERE metrics['views'] > 2` returned **887** rows (expected **997**), 
and ascending `ORDER BY metrics['views'] LIMIT 3` returned **[0, 1, 10]** 
(expected **[0, 1, 2]**). The reverse mismatch also reproduced: an undeclared 
DOUBLE key projected as STRING, but `WHERE metrics['cpu'] > '2'` counted 
**995** rows (expected **776** under string ordering). All three queries 
returned without exceptions.



##########
pinot-query-planner/src/test/java/org/apache/pinot/query/OpenStructMultiStagePlanningTest.java:
##########
@@ -0,0 +1,189 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.query;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
+import org.apache.pinot.query.planner.physical.DispatchableSubPlan;
+import org.apache.pinot.query.type.OpenStructSqlType;
+import org.apache.pinot.spi.data.ComplexFieldSpec;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
+
+
+/// OPEN_STRUCT columns in the multi-stage engine: a key read (`v['n']`) is 
typed by the key's declared child field
+/// spec and falls back to VARCHAR for an undeclared key, matching what the 
leaf stage returns for it; selecting the
+/// whole column is JSON text, as in the single-stage engine; and queries that 
never touch the column still plan.
+public class OpenStructMultiStagePlanningTest extends QueryEnvironmentTestBase 
{
+  private QueryEnvironment _env;
+
+  @BeforeClass
+  public void setUpOpenStructTable() {
+    Map<String, Schema> schemas = new HashMap<>(TABLE_SCHEMAS);
+    Schema schema = getSchemaBuilder("d").build();
+    Map<String, FieldSpec> declared = Map.of("n", new DimensionFieldSpec("n", 
DataType.LONG, true),
+        "price", new DimensionFieldSpec("price", DataType.DOUBLE, true),
+        "inner", new ComplexFieldSpec("inner", DataType.OPEN_STRUCT, true, 
Map.of()));
+    schema.addField(new ComplexFieldSpec("v", DataType.OPEN_STRUCT, true, 
declared));
+    schemas.put("d", schema);
+    // Same column, declaring `n` with the same type and `price` with another.
+    Schema other = getSchemaBuilder("d2").build();
+    other.addField(new ComplexFieldSpec("v", DataType.OPEN_STRUCT, true,
+        Map.of("n", new DimensionFieldSpec("n", DataType.LONG, true),
+            "price", new DimensionFieldSpec("price", DataType.STRING, true))));
+    schemas.put("d2", other);
+    _env = getQueryEnvironment(3, 1, 2, schemas, SERVER1_SEGMENTS, 
SERVER2_SEGMENTS, PARTITIONED_SEGMENTS_MAP);
+  }
+
+  private RelDataType validatedRowType(String sql) {
+    try (QueryEnvironment.CompiledQuery query = _env.compile(sql)) {
+      return query.getRelRoot().validatedRowType;
+    }
+  }
+
+  @Test
+  public void testDeclaredKeyIsTypedByItsChildFieldSpec() {
+    RelDataType rowType = validatedRowType("SELECT v['n'], v['price'] FROM d");
+    assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(), 
SqlTypeName.BIGINT);
+    assertEquals(rowType.getFieldList().get(1).getType().getSqlTypeName(), 
SqlTypeName.DOUBLE);
+    assertTrue(rowType.getFieldList().get(0).getType().isNullable());
+  }
+
+  @Test
+  public void testUndeclaredKeyAndNestedPathAreVarchar() {
+    RelDataType rowType = validatedRowType("SELECT v['name'], v['o.z'] FROM 
d");
+    assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(), 
SqlTypeName.VARCHAR);
+    assertEquals(rowType.getFieldList().get(1).getType().getSqlTypeName(), 
SqlTypeName.VARCHAR);
+  }
+
+  @Test
+  public void testNumericFilterAndAggregationOnDeclaredKeyPlan() {
+    RelDataType rowType = validatedRowType("SELECT SUM(v['n']), COUNT(*) FROM 
d WHERE v['n'] > 50");
+    assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(), 
SqlTypeName.BIGINT);
+    assertNotNull(_env.planQuery("SELECT SUM(v['n']), COUNT(*) FROM d WHERE 
v['n'] > 50"));
+    assertNotNull(_env.planQuery("SELECT CAST(v['name'] AS BIGINT) FROM d"));
+  }
+
+  @Test
+  public void testWholeColumnIsJsonText() {
+    DispatchableSubPlan plan = _env.planQuery("SELECT col1, v FROM d");
+    DataSchema schema = 
plan.getQueryStageMap().get(0).getPlanFragment().getFragmentRoot().getDataSchema();
+    assertEquals(schema.getColumnDataTypes()[1], ColumnDataType.JSON);
+  }
+
+  @Test
+  public void testComplexDeclaredChildIsVarchar() {
+    RelDataType rowType = validatedRowType("SELECT v['inner'] FROM d");
+    assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(), 
SqlTypeName.VARCHAR);
+  }
+
+  /// A UNION ALL of two OPEN_STRUCT columns stays OPEN_STRUCT: the whole 
column is still JSON, and a key both sides
+  /// declare with the same type keeps it while a key they declare differently 
is VARCHAR.
+  @Test
+  public void testUnionAllKeepsOpenStruct() {
+    DispatchableSubPlan plan = _env.planQuery("SELECT v FROM d UNION ALL 
SELECT v FROM d WHERE col3 > 0");
+    DataSchema schema = 
plan.getQueryStageMap().get(0).getPlanFragment().getFragmentRoot().getDataSchema();
+    assertEquals(schema.getColumnDataTypes()[0], ColumnDataType.JSON);
+    // d2 has no segments, so only validate across the two declarations.
+    String union = "(SELECT v FROM d UNION ALL SELECT v FROM d2)";
+    assertTrue(validatedRowType("SELECT v FROM " + 
union).getFieldList().get(0).getType()
+        instanceof OpenStructSqlType);
+    RelDataType rowType = validatedRowType("SELECT u.v['n'], u.v['price'] FROM 
" + union + " AS u");
+    assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(), 
SqlTypeName.BIGINT);
+    assertEquals(rowType.getFieldList().get(1).getType().getSqlTypeName(), 
SqlTypeName.VARCHAR);
+  }
+
+  @Test
+  public void testCaseAndCoalesceWithNullKeepJson() {
+    for (String sql : List.of("SELECT CASE WHEN col3 > 0 THEN v ELSE NULL END 
FROM d",
+        "SELECT COALESCE(v, NULL) FROM d")) {
+      DataSchema schema =
+          
_env.planQuery(sql).getQueryStageMap().get(0).getPlanFragment().getFragmentRoot().getDataSchema();
+      assertEquals(schema.getColumnDataTypes()[0], ColumnDataType.JSON, sql);

Review Comment:
   I reproduced the leaf failure on `4f936bfe22` with an offline segment. 
`SELECT CASE WHEN metrics['latencyMs'] = 0 THEN metrics ELSE NULL END FROM t 
ORDER BY ts LIMIT 2` returned query error 200, `Unsupported SV stored type: 
OPEN_STRUCT`, from `RowBasedBlockValueFetcher`. The first two rows take 
different CASE branches.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to