xiangfu0 commented on code in PR #20303: URL: https://github.com/apache/pinot/pull/20303#discussion_r4646696553
########## pinot-query-planner/src/main/java/org/apache/pinot/query/type/OpenStructSqlType.java: ########## @@ -0,0 +1,77 @@ +/** + * 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.type; + +import java.util.Collections; +import java.util.Map; +import java.util.TreeMap; +import javax.annotation.Nullable; +import org.apache.calcite.rel.type.RelDataType; +import org.apache.calcite.sql.type.MapSqlType; + + +/// Calcite type of an OPEN_STRUCT column. +/// +/// It is a `MAP<VARCHAR, VARCHAR>` so that `col['key']` validates as a map lookup, and it carries the column's +/// declared child field specs as Calcite types. [PinotItemOperator] uses them to type a key read: a declared key has +/// its declared type, an undeclared key is VARCHAR (the single-stage engine reads it as STRING). Selecting the whole +/// column returns JSON text, as in the single-stage engine. +/// +/// The declared types are part of the digest, so two OPEN_STRUCT columns with different declarations are different +/// types after canonicalization. Instances are immutable. +public class OpenStructSqlType extends MapSqlType { + private final Map<String, RelDataType> _declaredKeyTypes; + + public OpenStructSqlType(RelDataType keyType, RelDataType valueType, boolean isNullable, + Map<String, RelDataType> declaredKeyTypes) { + super(keyType, valueType, isNullable); + _declaredKeyTypes = Collections.unmodifiableMap(new TreeMap<>(declaredKeyTypes)); + // MapSqlType computed the digest before the declared types were set; include them now. + computeDigest(); + } + + /// Declared type of `key`, or null when the key is not declared. + @Nullable + public RelDataType getDeclaredKeyType(String key) { + return _declaredKeyTypes.get(key); + } + + public Map<String, RelDataType> getDeclaredKeyTypes() { + return _declaredKeyTypes; + } + + @Override + protected void generateTypeString(StringBuilder sb, boolean withDetail) { + sb.append("OPEN_STRUCT"); + // Null while the super constructor computes its first digest. + if (_declaredKeyTypes != null && !_declaredKeyTypes.isEmpty()) { + sb.append('('); + boolean first = true; + for (Map.Entry<String, RelDataType> entry : _declaredKeyTypes.entrySet()) { + if (!first) { + sb.append(", "); + } + first = false; + sb.append(entry.getKey()).append(' ') Review Comment: The raw key name makes the type digest ambiguous. With nullable children, two fields `a` (INT) and `b` (LONG) produce the same `OPEN_STRUCT(a INTEGER, b BIGINT)` digest as one LONG field named `a INTEGER, b`. Both schemas validate. I reproduced `TypeFactory` returning the same instance for both, so the second schema loses its declared LONG key and can infer VARCHAR for that lookup. Please encode key boundaries unambiguously and include the declarations in structural equality and hashing for Calcite’s digest-disabled mode. ########## 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: This assertion checks the result schema, but the CASE query above can fail while fetching its first block. The planner pushes the CASE projection to the leaf. `CaseTransformFunction` reports OPEN_STRUCT for its `THEN v` branch, and `RowBasedBlockValueFetcher` has no single-value fetcher for OPEN_STRUCT. Only a bare column projection gets the JSON-text block value set. Could we make the CASE projection read the document as JSON and execute this query on rows taking both branches, asserting the document and SQL NULL? ########## 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)) { Review Comment: The leaf also requires the left operand of `ITEM` to be a column identifier. With two OPEN_STRUCT columns, `(CASE WHEN id = 0 THEN v ELSE w END)['k']` validates here and plans as `ITEM(CASE(...), 'k')` directly over a table scan. On the server, `ItemTransformFunction.init` rejects the CASE with `Map Item: Left operand must be an identifier`. Could we push the key read into the CASE branches, or reject this unsupported operand during validation with a clear error? ########## pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/operator/utils/TypeUtils.java: ########## @@ -18,16 +18,51 @@ */ package org.apache.pinot.query.runtime.operator.utils; +import com.fasterxml.jackson.core.JsonProcessingException; import java.lang.reflect.Array; import java.math.BigDecimal; import org.apache.pinot.common.utils.DataSchema.ColumnDataType; import org.apache.pinot.spi.utils.ByteArray; +import org.apache.pinot.spi.utils.JsonUtils; +import org.apache.pinot.spi.utils.PinotDataType; public class TypeUtils { private TypeUtils() { } + /// Converts a value whose logical type is `inputType` to `outputStoredType`. Same as [#convert(Object, + /// ColumnDataType)], except where the stored value alone does not say how to convert it: + /// - To STRING, a BOOLEAN reads as `true`/`false` and a TIMESTAMP as its timestamp text, as `CAST(x AS VARCHAR)` + /// does, rather than as the stored `1`/`0` or epoch millis; an array reads as JSON text. + /// - Text to a numeric type is converted the way ingestion converts it ([PinotDataType]). A segment can serve a key + /// as STRING while the plan types it from the table's declaration, for example an OPEN_STRUCT key declared after + /// older segments were built. Text that does not convert (`"abc"`, `"1.9"` or an out-of-range value for INT/LONG) + /// fails with an [IllegalStateException] naming both types, rather than reading as a value it does not hold. + public static Object convert(Object value, ColumnDataType inputType, ColumnDataType outputStoredType) { + if (outputStoredType == ColumnDataType.STRING && !(value instanceof String)) { + if (inputType == ColumnDataType.BOOLEAN || inputType == ColumnDataType.TIMESTAMP) { + return inputType.convertAndFormat(value).toString(); + } + if (inputType.isArray()) { + try { + return JsonUtils.objectToString(inputType.convertAndFormat(value)); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Cannot convert " + inputType + " to STRING", e); + } + } + } + if (value instanceof String && outputStoredType.isNumber()) { + try { + return outputStoredType.toPinotDataType().convert(value, PinotDataType.STRING); Review Comment: A previously built dense segment can return the STRING `"true"` after `flag` is declared BOOLEAN. `SELECT v['flag']` reaches this branch with `outputStoredType == INT`, so `PinotDataType.STRING.toInt` calls `Integer.parseInt("true")` and the query fails. A timestamp string such as `"2024-01-01 00:00:00"` likewise reaches `Long.parseLong` for a TIMESTAMP declaration. Please pass the planned logical output type into the conversion so these values use Pinot’s boolean or timestamp parser before being written in their stored representation. ########## 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: An undeclared `n` can be physically stored as INT. For a row containing `10`, `WHERE v['n'] > '2'` should exclude it under the VARCHAR type inferred here. The plan pushes `>(ITEM(v, 'n'), '2')` to the server without a cast. `MapFilterOperator` then builds the predicate from the segment’s INT data source and includes the row. The same type mismatch affects a pushed `ORDER BY v['n'] LIMIT 1`, where the segment can discard the correct row before `LeafOperator` converts the result. Could we apply the inferred type before pushing comparisons and top-N into the segment, or keep those operations above the typed projection? An undeclared INT key containing `2` and `10` would exercise both cases. -- 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]
