hello-stephen commented on code in PR #69032: URL: https://github.com/apache/doris/pull/69032#discussion_r4734483573
########## fe/fe-core/src/main/java/org/apache/doris/datasource/connector/converter/ConnectorSpatialWriteNormalizer.java: ########## @@ -0,0 +1,790 @@ +// 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.doris.datasource.connector.converter; + +import org.apache.doris.catalog.Column; +import org.apache.doris.nereids.CTEContext; +import org.apache.doris.nereids.analyzer.UnboundFunction; +import org.apache.doris.nereids.properties.OrderKey; +import org.apache.doris.nereids.rules.analysis.ExpressionAnalyzer; +import org.apache.doris.nereids.rules.rewrite.PushProjectThroughUnion; +import org.apache.doris.nereids.trees.expressions.Alias; +import org.apache.doris.nereids.trees.expressions.CTEId; +import org.apache.doris.nereids.trees.expressions.Cast; +import org.apache.doris.nereids.trees.expressions.ExprId; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.expressions.NamedExpression; +import org.apache.doris.nereids.trees.expressions.Slot; +import org.apache.doris.nereids.trees.expressions.SlotReference; +import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator; +import org.apache.doris.nereids.trees.expressions.functions.scalar.Array; +import org.apache.doris.nereids.trees.expressions.functions.scalar.Cardinality; +import org.apache.doris.nereids.trees.expressions.functions.scalar.CreateMap; +import org.apache.doris.nereids.trees.expressions.functions.scalar.CreateNamedStruct; +import org.apache.doris.nereids.trees.expressions.functions.scalar.CreateStruct; +import org.apache.doris.nereids.trees.expressions.functions.scalar.MapContainsKey; +import org.apache.doris.nereids.trees.expressions.functions.scalar.MapKeys; +import org.apache.doris.nereids.trees.expressions.functions.scalar.MapSize; +import org.apache.doris.nereids.trees.expressions.literal.ArrayLiteral; +import org.apache.doris.nereids.trees.expressions.literal.Literal; +import org.apache.doris.nereids.trees.expressions.literal.MapLiteral; +import org.apache.doris.nereids.trees.expressions.literal.NullLiteral; +import org.apache.doris.nereids.trees.expressions.literal.StringLikeLiteral; +import org.apache.doris.nereids.trees.expressions.literal.StructLiteral; +import org.apache.doris.nereids.trees.plans.Plan; +import org.apache.doris.nereids.trees.plans.algebra.SetOperation.Qualifier; +import org.apache.doris.nereids.trees.plans.logical.LogicalCTE; +import org.apache.doris.nereids.trees.plans.logical.LogicalCTEAnchor; +import org.apache.doris.nereids.trees.plans.logical.LogicalCTEConsumer; +import org.apache.doris.nereids.trees.plans.logical.LogicalCTEProducer; +import org.apache.doris.nereids.trees.plans.logical.LogicalFilter; +import org.apache.doris.nereids.trees.plans.logical.LogicalLimit; +import org.apache.doris.nereids.trees.plans.logical.LogicalOneRowRelation; +import org.apache.doris.nereids.trees.plans.logical.LogicalPlan; +import org.apache.doris.nereids.trees.plans.logical.LogicalProject; +import org.apache.doris.nereids.trees.plans.logical.LogicalSetOperation; +import org.apache.doris.nereids.trees.plans.logical.LogicalSort; +import org.apache.doris.nereids.trees.plans.logical.LogicalSubQueryAlias; +import org.apache.doris.nereids.trees.plans.logical.LogicalUnion; +import org.apache.doris.nereids.trees.plans.logical.ProjectProcessor; +import org.apache.doris.nereids.types.ArrayType; +import org.apache.doris.nereids.types.DataType; +import org.apache.doris.nereids.types.GeographyType; +import org.apache.doris.nereids.types.GeometryType; +import org.apache.doris.nereids.types.MapType; +import org.apache.doris.nereids.types.StructType; +import org.apache.doris.nereids.util.ExpressionUtils; +import org.apache.doris.nereids.util.TypeCoercionUtils; + +import com.google.common.collect.ImmutableList; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.IntStream; + +/** Restores proven NULL producer values before spatial sink coercion. */ +public final class ConnectorSpatialWriteNormalizer { + private ConnectorSpatialWriteNormalizer() { + } + + public static LogicalPlan normalize(List<Column> targets, LogicalPlan source, CTEContext cteContext) { + return normalize(targets, source, IntStream.range(0, targets.size()).boxed() + .collect(ImmutableList.toImmutableList()), cteContext); + } + + /** Aligns data targets with source positions when a row-level sink also carries routing columns. */ + public static LogicalPlan normalize(List<Column> targets, LogicalPlan source, + List<Integer> sourceOrdinals, CTEContext cteContext) { + if (targets.stream().noneMatch(column -> column.getType().typeContainsSpatialType())) { + return source; + } + if (source instanceof LogicalUnion && ((LogicalUnion) source).getQualifier() == Qualifier.ALL) { + return normalizeUnionAll(targets, (LogicalUnion) source, sourceOrdinals, cteContext); + } + if (source instanceof LogicalSubQueryAlias) { + LogicalPlan child = (LogicalPlan) source.child(0); + LogicalPlan normalized = normalize(targets, child, sourceOrdinals, cteContext); + return normalized == child ? source : (LogicalPlan) source.withChildren(ImmutableList.of(normalized)); + } + if (source instanceof LogicalProject && isForwardingProject((LogicalProject<?>) source)) { + Plan input = source.child(0); + while (input instanceof LogicalSubQueryAlias) { + input = input.child(0); + } + Plan boundary = input; + while (boundary instanceof LogicalSubQueryAlias + || (boundary instanceof LogicalProject && isForwardingProject((LogicalProject<?>) boundary))) { + boundary = boundary.child(0); + } + if (boundary instanceof LogicalUnion && ((LogicalUnion) boundary).getQualifier() == Qualifier.ALL) { + // Reuse the existing safe forwarding/cast projection rule, including its ExprId handling. + Optional<Plan> pushed = ProjectProcessor.tryProcessProject( + ((LogicalProject<?>) source).getProjects(), input); + // Forwarding aliases can also repeat or prune outputs without moving calculations. + if (!pushed.isPresent() && input instanceof LogicalUnion + && ((LogicalProject<?>) source).getProjects().stream() + .allMatch(project -> project instanceof Slot + || (project instanceof Alias && project.child(0) instanceof Slot))) { + pushed = Optional.of(PushProjectThroughUnion.doPushProject( + ((LogicalProject<?>) source).getProjects(), (LogicalUnion) input)); + } + if (pushed.isPresent()) { + return normalize(targets, (LogicalPlan) pushed.get(), sourceOrdinals, cteContext); + } + } + } + Resolver resolver = new Resolver(source, cteContext); + List<NamedExpression> outputs = new ArrayList<>(source.getOutput()); + List<LogicalPlan> wrappers = new ArrayList<>(); + Set<ExprId> sortInputs = new HashSet<>(); + LogicalPlan producerInput = source; + while (producerInput instanceof LogicalSort || producerInput instanceof LogicalLimit) { + wrappers.add(producerInput); + for (Expression expression : producerInput.getExpressions()) { + collectSortInputs(expression, sortInputs); + } + producerInput = (LogicalPlan) producerInput.child(0); + } + LogicalProject<?> producer = producerInput instanceof LogicalProject + && !((LogicalProject<?>) producerInput).isDistinct() ? (LogicalProject<?>) producerInput : null; + List<NamedExpression> producerOutputs = null; + Map<ExprId, Slot> replacedSlots = new HashMap<>(); + boolean changed = false; + for (int i = 0; i < targets.size(); i++) { + Column target = targets.get(i); + if (!target.getType().typeContainsSpatialType()) { + continue; + } + int sourceOrdinal = sourceOrdinals.get(i); + Slot slot = source.getOutput().get(sourceOrdinal); + Expression value = resolver.resolve(slot, source); + DataType targetType = DataType.fromCatalogType(target.getType()); + boolean literal = isLiteralConstruction(value) || canRetargetSpatialNulls(value, targetType); + // SELECT/UPDATE reach the bound sink with CAST(ARRAY(NULL) AS ARRAY<INT>). + // Reuse MERGE's NULL-only proof before validation, without lifting arbitrary producers. + if (literal) { + value = normalizeSpatialNullsBeforeBinding(value, targetType); + } + if (!literal && producer != null && !sortInputs.contains(slot.getExprId()) + && sourceOrdinals.indexOf(sourceOrdinal) == sourceOrdinals.lastIndexOf(sourceOrdinal)) { + // Retag a constructor where it is computed, so its dynamic ordinary siblings + // still use the same inputs and are evaluated only once. Do not follow slots + // through joins, other producers, or a DISTINCT projection. + NamedExpression project = producer.getProjects().get(sourceOrdinal); + if (project instanceof Alias && canRetargetSpatialNulls(project.child(0), targetType, true)) { + Expression normalized = normalizeSpatialNullsBeforeBinding(project.child(0), targetType, true); + if (!normalized.getDataType().equals(slot.getDataType())) { + value = normalized; + if (producerOutputs == null) { + producerOutputs = new ArrayList<>(producer.getProjects()); + } + Alias replacement = new Alias(normalized, slot.getName()); + producerOutputs.set(sourceOrdinal, replacement); + Slot replacementSlot = replacement.toSlot(); + outputs.set(sourceOrdinal, replacementSlot); + replacedSlots.put(slot.getExprId(), replacementSlot); + } + } + } + ConnectorSpatialWriteValidator.validate(target, value); + // Never lift arbitrary producer expressions above their input scope, or + // replace outer-join NULL padding with a non-NULL container constant. + if (literal) { + Expression normalized = normalizeSpatialNulls(value, targetType); + if (!normalized.getDataType().equals(slot.getDataType())) { + // SELECT v,v can feed an ordinary BIGINT and a spatial NULL. Sharing + // v's ExprId would let project merging replace the ordinary cast's input. + outputs.set(sourceOrdinal, new Alias(normalized, slot.getName())); + changed = true; + } + } + } + LogicalPlan normalizedSource = source; + if (producerOutputs != null) { + normalizedSource = producer.withProjects(producerOutputs); + for (int i = wrappers.size() - 1; i >= 0; i--) { + LogicalPlan wrapper = wrappers.get(i); + if (wrapper instanceof LogicalSort) { + LogicalSort<?> sort = (LogicalSort<?>) wrapper; + List<OrderKey> keys = sort.getOrderKeys().stream().map(key -> { + // Rebind inside ordinary ancestors too, e.g. CARDINALITY(m)+1. + // Analysis rebuilds the function signature with the retagged MAP argument. + Expression rebound = key.getExpr().rewriteDownShortCircuit(expression -> { + if (expression instanceof Slot) { + Slot replacement = replacedSlots.get(((Slot) expression).getExprId()); + return replacement == null ? expression : replacement; + } + return expression; + }); + return rebound == key.getExpr() ? key : key.withExpression(rebound); + }).collect(ImmutableList.toImmutableList()); + normalizedSource = sort.withOrderKeysAndChild(keys, normalizedSource); + } else { + normalizedSource = (LogicalPlan) wrapper.withChildren(ImmutableList.of(normalizedSource)); + } + } + } + return changed ? new LogicalProject<>(outputs, normalizedSource) : normalizedSource; + } + + private static void collectSortInputs(Expression expression, Set<ExprId> inputs) { + if (expression instanceof Slot) { + inputs.add(((Slot) expression).getExprId()); + return; + } + // Retagging NULL values preserves keys and entry counts. Recognize these observations + // inside ordinary expressions as well as at the root. Other MAP observations still block. + boolean keysOrCount = (expression instanceof Cardinality || expression instanceof MapSize + || expression instanceof MapKeys || expression instanceof MapContainsKey) + && expression.child(0) instanceof Slot && expression.child(0).getDataType() instanceof MapType; + // MAP_CONTAINS_KEY's lookup can have its own MAP dependency; only its first input is safe. + for (int i = keysOrCount ? 1 : 0; i < expression.arity(); i++) { + collectSortInputs(expression.child(i), inputs); + } + } + + private static boolean isForwardingProject(LogicalProject<?> project) { + return !project.isDistinct() && project.getProjects().stream().allMatch(output -> output instanceof Slot + || (output instanceof Alias && ExpressionUtils.getExpressionCoveredByCast(output.child(0)) + instanceof Slot)); + } + + private static LogicalPlan normalizeUnionAll(List<Column> targets, LogicalUnion source, + List<Integer> sourceOrdinals, CTEContext context) { + List<Plan> children = new ArrayList<>(); + List<List<SlotReference>> childOutputs = new ArrayList<>(); + boolean changed = !source.getConstantExprsList().isEmpty(); + for (int i = 0; i < source.arity(); i++) { + LogicalPlan child = (LogicalPlan) source.child(i); + List<SlotReference> outputs = source.getRegularChildOutput(i); + LogicalPlan input = child.getOutput().equals(outputs) + ? child : new LogicalProject<>(ImmutableList.<NamedExpression>copyOf(outputs), child); + LogicalPlan normalized = normalize(targets, input, sourceOrdinals, context); + children.add(normalized); + childOutputs.add(normalized.getOutput().stream().map(SlotReference.class::cast) + .collect(ImmutableList.toImmutableList())); + changed |= normalized != child; + } + // Constant rows use the same proof and CAST validation as ordinary branches. + // Keep them as separate rows; never replace an entire UNION output with one constant. + for (List<NamedExpression> row : source.getConstantExprsList()) { + LogicalPlan normalized = normalize(targets, + new LogicalOneRowRelation(StatementScopeIdGenerator.newRelationId(), row), + sourceOrdinals, context); + children.add(normalized); + childOutputs.add(normalized.getOutput().stream().map(SlotReference.class::cast) + .collect(ImmutableList.toImmutableList())); + } + if (!changed) { + return source; + } + // A whole STRUCT NULL can adopt the sink's ordinary field types while a constructed + // STRUCT only retags its spatial leaves. Reconcile the branches before exposing UNION outputs. + List<DataType> commonTypes = new ArrayList<>(); + for (int i = 0; i < source.getOutput().size(); i++) { + DataType common = childOutputs.get(0).get(i).getDataType(); + for (int j = 1; j < childOutputs.size(); j++) { + common = LogicalSetOperation.getAssignmentCompatibleType( + common, childOutputs.get(j).get(i).getDataType()); + } + commonTypes.add(common); + } + for (int i = 0; i < children.size(); i++) { + List<SlotReference> slots = childOutputs.get(i); + List<NamedExpression> projects = new ArrayList<>(); + boolean castNeeded = false; + for (int j = 0; j < slots.size(); j++) { + SlotReference slot = slots.get(j); + Expression cast = TypeCoercionUtils.castForCommonTypeWithExactTarget(slot, commonTypes.get(j)); + projects.add(cast == slot ? slot : new Alias(cast, slot.getName())); + castNeeded |= cast != slot; + } + if (castNeeded) { + LogicalProject<?> project = new LogicalProject<>(projects, children.get(i)); + children.set(i, project); + childOutputs.set(i, project.getOutput().stream().map(SlotReference.class::cast) + .collect(ImmutableList.toImmutableList())); + } + } + + List<NamedExpression> outputs = new ArrayList<>(); + for (int i = 0; i < source.getOutput().size(); i++) { + SlotReference slot = (SlotReference) source.getOutput().get(i); + DataType type = commonTypes.get(i); + int ordinal = i; + boolean nullable = slot.nullable() || childOutputs.stream().anyMatch(row -> row.get(ordinal).nullable()); + // A forwarding project can repeat one slot for ordinary and spatial targets. + // Retagged outputs need distinct identities, just like the scalar projection path. + outputs.add(slot.getDataType().equals(type) ? slot.withNullable(nullable) : slot + .withExprId(StatementScopeIdGenerator.newExprId()).withNullableAndDataType(nullable, type)); + } + return source.withNewOutputsChildrenAndConstExprsList(outputs, children, childOutputs, ImmutableList.of()); + } + + private static boolean isLiteralConstruction(Expression value) { + // Only proven NULL-only casts can be retargeted; actual values and invalid source + // array-depth conversions must retain their original identity and errors. + return value instanceof Literal || (value.getClass() == Cast.class && nullArrayDepth(value) >= 0) + || ((value instanceof Array || value instanceof CreateMap + || value instanceof CreateStruct || value instanceof CreateNamedStruct) + && value.children().stream().allMatch(ConnectorSpatialWriteNormalizer::isLiteralConstruction)); + } + + private static final class Resolver { + private final CTEContext context; + private final Map<CTEId, Plan> producers = new HashMap<>(); + private final Set<CTEId> activeCtes = new HashSet<>(); + private final Map<Plan, Map<ExprId, Expression>> resolvedSlots = new IdentityHashMap<>(); + + private Resolver(Plan source, CTEContext context) { + this.context = context; + collectProducers(source); + } + + private void collectProducers(Plan source) { + if (source instanceof LogicalCTEProducer) { + LogicalCTEProducer<?> producer = (LogicalCTEProducer<?>) source; + producers.put(producer.getCteId(), producer.child()); + } + source.children().forEach(this::collectProducers); + } + + private Expression resolve(Expression value, Plan source) { + if (value instanceof Alias) { + return resolve(value.child(0), source); + } + if (value instanceof Slot) { + return resolveSlot((Slot) value, source); + } + // Only restore constant NULL construction. Expanding arbitrary IF(g, g) + // producer chains duplicates shared CTE lineage exponentially. + if (!(value instanceof Cast || value instanceof Array || value instanceof CreateMap + || value instanceof CreateStruct || value instanceof CreateNamedStruct)) { + return value; + } + List<Expression> children = value.children().stream() + .map(child -> resolve(child, source)) + .collect(ImmutableList.toImmutableList()); + // SELECT reaches sink binding before constant folding: CAST(NULL AS INT) + // and CAST(NULL AS GEOMETRY('EPSG:3857')) are still value-independent NULLs. + if (value instanceof Cast && children.get(0).isNullLiteral()) { + // A bound SELECT/UPDATE can still contain GEOGRAPHY -> INT. Retain its + // analysis error before NULL retagging and project merging erase the cast. + validateNullCastChain(value); + return new NullLiteral(value.getDataType()); + } + return children.equals(value.children()) ? value : value.withChildren(children); + } + + private Expression resolveSlot(Slot slot, Plan source) { + Map<ExprId, Expression> cached = resolvedSlots.computeIfAbsent(source, ignored -> new HashMap<>()); + Expression result = cached.get(slot.getExprId()); + if (result == null) { + result = traceSlot(slot, source); + cached.put(slot.getExprId(), result); + } + return result; + } + + private Expression traceSlot(Slot slot, Plan source) { + if (source instanceof LogicalProject || source instanceof LogicalOneRowRelation) { + List<NamedExpression> projects = source instanceof LogicalProject + ? ((LogicalProject<?>) source).getProjects() : ((LogicalOneRowRelation) source).getProjects(); + for (NamedExpression project : projects) { + if (project.getExprId().equals(slot.getExprId())) { + Plan input = source instanceof LogicalProject ? source.child(0) : source; + // A one-row correlated slot has no producer definition here. + return project instanceof Slot && input == source + ? slot : resolve(project, input); + } + } + } else if (source instanceof LogicalCTEConsumer) { + LogicalCTEConsumer consumer = (LogicalCTEConsumer) source; + Optional<Plan> producer = Optional.ofNullable(producers.get(consumer.getCteId())); + if (!producer.isPresent()) { + producer = context.findCTEContext(consumer.getName()) + .filter(cte -> cte.getCteId().equals(consumer.getCteId())) + .flatMap(cte -> cte.getAnalyzedCTEPlan(consumer.getName())).map(Plan.class::cast); + } + // Recursive CTEs do not prove constant provenance through their cycle. + if (producer.isPresent() && activeCtes.add(consumer.getCteId())) { + try { + // An analyzed outer CTE can own an inner WITH whose producers + // are absent from the sink's context and initial source tree. + collectProducers(producer.get()); + return resolve(consumer.getProducerSlot(slot), producer.get()); + } finally { + activeCtes.remove(consumer.getCteId()); + } + } + } else if (source instanceof LogicalCTEAnchor) { + return resolveSlot(slot, source.child(1)); + } else if (source instanceof LogicalSubQueryAlias || source instanceof LogicalFilter + || source instanceof LogicalLimit || source instanceof LogicalSort + || source instanceof LogicalCTE) { + return resolveSlot(slot, source.child(0)); + } + // Joins, grouping sets and set operations may add NULLs or combine values; + // their output type alone is not evidence of a constant value. + return slot; + } + } + + public static Expression normalizeSpatialNullsBeforeBinding(Expression input, DataType target) { + return normalizeSpatialNullsBeforeBinding(input, target, false); + } + + /** Retags proven NULLs in a bound write value while retaining its ordinary children. */ + public static Expression normalizeBoundSpatialNulls(Expression input, DataType target) { + return canRetargetSpatialNulls(input, target, true) + ? normalizeSpatialNullsBeforeBinding(input, target, true) : input; + } + + /** Casts a MERGE branch in place so only the selected branch is evaluated. */ + public static Expression castSpatialMergeBranch(Expression input, DataType target) { + Expression normalized = normalizeSpatialNullsBeforeBinding(input, target); + if (normalized == input && input.getClass() == Cast.class + && isMapOrStructCast(input.getDataType(), target) && !input.getDataType().equals(target) Review Comment: [P2] Defer ARRAY branch casts with runtime ordinary siblings For an Iceberg V3 Parquet MOR target `payload ARRAY<STRUCT<k:INT,shape:GEOMETRY>>`, a MERGE branch assigning `CAST(ARRAY(named_struct('k',s.id,'shape',CAST(NULL AS INT))) AS ARRAY<STRUCT<k:INT,shape:INT>>)` fails before binding. The reduced synthesis path is `MergeSink -> Project(IF(branch, target_cast(user_array_cast), NULL)) -> Join(t,s)`. `nullArrayDepth` cannot handle the STRUCT element, and the generic pre-binding proof stops at runtime `s.id`. This guard then excludes ARRAY, so `generateFinalProjections` falls through to `castUnbound`, which rejects INT -> GEOMETRY before the bound proof can retag the NULL. The original user cast is legal; removing just that identity ARRAY cast lets constructor normalization retain `s.id` and retag `shape`. Extend the existing delayed binding to compatible ARRAY containers while preserving original-cast validation, and cover matched/not-matched branches. Unlike the prior NULL-only-array cases, this array contains a non-NULL STRUCT with a run time ordinary field. Static call-path evidence; SQL was not executed. ########## be/src/exprs/function/geo/geography_calculation.cpp: ########## @@ -0,0 +1,2280 @@ +// 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. + +#include "exprs/function/geo/geography_calculation.h" + +#include <glog/logging.h> +#include <s2/mutable_s2shape_index.h> +#include <s2/s2boolean_operation.h> +#include <s2/s2closest_edge_query.h> +#include <s2/s2closest_point_query.h> +#include <s2/s2contains_point_query.h> +#include <s2/s2crossing_edge_query.h> +#include <s2/s2earth.h> +#include <s2/s2edge_crossings.h> +#include <s2/s2edge_distances.h> +#include <s2/s2edge_vector_shape.h> +#include <s2/s2lax_polygon_shape.h> +#include <s2/s2loop.h> +#include <s2/s2loop_measures.h> +#include <s2/s2point.h> +#include <s2/s2point_index.h> +#include <s2/s2point_vector_shape.h> +#include <s2/s2pointutil.h> +#include <s2/s2polygon.h> +#include <s2/s2polyline.h> +#include <s2/s2predicates.h> +#include <s2/s2shape_measures.h> + +#include <algorithm> +#include <array> +#include <bit> +#include <boost/iterator/iterator_facade.hpp> +// Integer proofs and software-wide arithmetic need no quadmath wrappers. Boost's float128 +// numeric_limits specialization conflicts with libstdc++ 15 in the GCC performance build. +#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 15 +#define BOOST_CSTDFLOAT_NO_LIBQUADMATH_SUPPORT +#endif +#include <boost/multiprecision/cpp_bin_float.hpp> +#include <boost/multiprecision/cpp_int.hpp> +#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 15 +#undef BOOST_CSTDFLOAT_NO_LIBQUADMATH_SUPPORT +#endif +#include <cmath> +#include <cstdint> +#include <limits> +#include <map> +#include <numbers> +#include <optional> +#include <set> +#include <type_traits> +#include <utility> + +#include "core/assert_cast.h" +#include "core/custom_allocator.h" +#include "exprs/function/geo/geo_types.h" +#include "exprs/function/geo/wkb_parse.h" + +namespace doris { + +// Apple ARM64 long double has binary64 precision/range. Keep native wide arithmetic +// where available; software quad preserves the tiny residual products on narrower ABIs. +using GeographyFloat = + std::conditional_t<std::numeric_limits<long double>::digits >= 64 && + std::numeric_limits<long double>::min_exponent <= -4096, + long double, boost::multiprecision::cpp_bin_float_quad>; +static_assert(std::numeric_limits<GeographyFloat>::digits >= 64 && + std::numeric_limits<GeographyFloat>::min_exponent <= -4096); + +template <typename Float> +static Float geography_pi() { + if constexpr (std::is_same_v<Float, long double>) { + return std::numbers::pi_v<long double>; + } else { + // Public software acos avoids float128 constant conversions/libquadmath on GCC. + static const Float pi = boost::multiprecision::acos(Float(-1)); + return pi; + } +} + +// Error-free TwoSum preserves tiny differences from a half-turn (e.g. -1e-15 + 180). +static std::pair<double, double> geography_degree_sum(double a, double b) { + const double high = a + b; + const double offset = high - a; + return {high, (a - (high - offset)) + (b - offset)}; +} + +// Reduce the exact degree sum before converting to radians. In particular, +// 180 + (-1e-300) must retain its small sine instead of becoming sin(pi). +template <typename Float = GeographyFloat> +static std::pair<Float, Float> geography_degree_sincos(double a, double b = 0, bool half = false) { + const auto [high, low] = geography_degree_sum(a, b); + int quadrant; + const Float reduced = [&] { + if constexpr (std::is_same_v<Float, long double>) { + return std::remquo(static_cast<Float>(high), half ? 180.0L : 90.0L, &quadrant) + + static_cast<Float>(low); + } else { + // high is binary64 and the periods are exact integers: its reduced remainder + // is representable in binary64. Add TwoSum's low residual only after widening. + return Float(std::remquo(high, half ? 180.0 : 90.0, &quadrant)) + Float(low); + } + }(); + const Float radians = reduced * (geography_pi<Float>() / 180) / (half ? 2 : 1); + using std::cos; + using std::sin; + const Float sine = sin(radians); + const Float cosine = cos(radians); + switch ((quadrant % 4 + 4) % 4) { + case 0: + return {sine, cosine}; + case 1: + return {cosine, -sine}; + case 2: + return {-sine, -cosine}; + default: + return {-cosine, sine}; + } +} + +// In longitude-midpoint coordinates, the raw normal retains the low bits of both +// endpoint differences. A Cartesian cross product would subtract rounded products. +template <typename Float> +static std::array<Float, 3> geography_raw_normal(const GeoCoordinate& a, const GeoCoordinate& b, + const Float& sin_half, const Float& cos_half) { + return {-sin_half * geography_degree_sincos<Float>(a.y, b.y).first, + cos_half * geography_degree_sincos<Float>(a.y, -b.y).first, + geography_degree_sincos<Float>(a.y).second * + geography_degree_sincos<Float>(b.y).second * + geography_degree_sincos<Float>(b.x, -a.x).first}; +} + +template <typename Float = GeographyFloat> +struct GeographyRawArc { + S2Point normal; + S2Point midpoint; + + GeographyRawArc(const GeoCoordinate& a, const GeoCoordinate& b) { + const auto [sd, cd] = geography_degree_sincos<Float>(b.x, -a.x, true); + const auto [sm, cm] = geography_degree_sincos<Float>(a.x, b.x, true); + const auto rotate_unit = [&](Float x, Float y, Float z) { + using std::sqrt; + const Float norm = sqrt(x * x + y * y + z * z); + DCHECK_GT(norm, 0); + return S2Point(static_cast<double>((cm * x - sm * y) / norm), + static_cast<double>((sm * x + cm * y) / norm), + static_cast<double>(z / norm)); + }; + const auto [nx, ny, nz] = geography_raw_normal(a, b, sd, cd); + normal = rotate_unit(nx, ny, nz); + const auto [sl, cl] = geography_degree_sincos<Float>(a.y, b.y, true); + const auto [st, ct] = geography_degree_sincos<Float>(b.y, -a.y, true); + midpoint = rotate_unit(cd * cl * ct, -sd * sl * st, sl * ct); + } +}; + +// Raw identity must survive ToPoint rounding: 58 and 58.00000000000001 degrees +// produce the same S2Point, but only one is an endpoint of the original edge. +struct GeographyVertex { + GeoCoordinate coordinate; + S2Point point; + + GeographyVertex() : GeographyVertex({.x = 0, .y = 0}) {} + explicit GeographyVertex(GeoCoordinate value) : coordinate(value) { + if (std::abs(coordinate.y) == 90) { + coordinate.x = 0; + point = {0, 0, coordinate.y > 0 ? 1.0 : -1.0}; + } else { + if (coordinate.x == 180) { + coordinate.x = -180; + } + point = S2LatLng::FromDegrees(coordinate.y, coordinate.x).ToPoint(); + } + } + bool operator==(const GeographyVertex& other) const { + return coordinate.x == other.coordinate.x && coordinate.y == other.coordinate.y; + } + bool operator<(const GeographyVertex& other) const { + return std::pair {coordinate.x, coordinate.y} < + std::pair {other.coordinate.x, other.coordinate.y}; + } +}; + +static bool geography_antipodal(const GeographyVertex& a, const GeographyVertex& b) { + return a.coordinate.y == -b.coordinate.y && + (std::abs(a.coordinate.y) == 90 || + geography_degree_sum(std::max(a.coordinate.x, b.coordinate.x), + -std::min(a.coordinate.x, b.coordinate.x)) == + std::pair {180.0, 0.0}); +} + +struct GeographyCoordinates { + GeoShapeType type = GeoShapeType::GEO_SHAPE_ANY; + DorisVector<DorisVector<GeographyVertex>> sequences; + GeoParseStatus status; + + explicit GeographyCoordinates(StringRef wkb) { + GeoCoordinateListList raw; + status = WkbParse::calculation_coordinates(wkb.data, wkb.size, &raw, &type); + if (status != GeoParseStatus::GEO_PARSE_OK) { + return; + } + for (const auto& sequence : raw.list) { + auto& vertices = sequences.emplace_back(); + for (const auto& coordinate : sequence->list) { + vertices.emplace_back(coordinate); + } + } + } +}; + +static bool geography_stable_points(const DorisVector<GeographyVertex>& sequence, + std::vector<S2Point>* points) { + for (size_t i = 0; i + 1 < sequence.size(); ++i) { + const auto& a = sequence[i]; + const auto& b = sequence[i + 1]; + // (0,0)->(180,0) has no unique arc and would normalize a zero raw normal. + if (geography_antipodal(a, b)) { + return false; + } + points->push_back(a.point); + // Stabilize before S2 admission: rounded (30,58)->(-150,-58-e) can be + // exactly antipodal despite its unique raw arc passing through the south pole. + if (a.point.DotProd(b.point) < 0) { + points->push_back(GeographyRawArc(a.coordinate, b.coordinate).midpoint); + } + } + // A line's final vertex is real, including its closing edge; only rings remove it. + points->push_back(sequence.back().point); + points->erase(std::ranges::unique(*points).begin(), points->end()); + return true; +} + +static std::unique_ptr<GeoShape> decode_geography_line(const GeographyCoordinates& raw, + StringRef value) { + std::vector<S2Point> points; + if (!geography_stable_points(raw.sequences.front(), &points)) { + return nullptr; + } + if (points.size() < 2) { + // Canonical pole aliases such as (0,90),(90,90) collapse to one calculation + // point. Preserve their prior admission; the old parser still rejects a + // truly duplicate-only line such as (1,1),(1,1). + GeoParseStatus status; + return GeoShape::from_wkb_bytes(value.data, value.size, status); + } + auto polyline = std::make_unique<S2Polyline>(points, S2Debug::DISABLE); + if (!polyline->IsValid()) { + return nullptr; + } + return GeoLine::create_unique(std::move(polyline)); +} + +std::unique_ptr<GeoShape> decode_geography_calculation_shape(StringRef value) { + GeographyCoordinates raw(value); + if (raw.status != GeoParseStatus::GEO_PARSE_OK) { + return nullptr; + } + if (raw.type == GeoShapeType::GEO_SHAPE_POINT) { + GeoParseStatus status; + return GeoShape::from_wkb_bytes(value.data, value.size, status); + } + if (raw.type == GeoShapeType::GEO_SHAPE_LINE_STRING) { + return decode_geography_line(raw, value); + } + std::vector<std::unique_ptr<S2Loop>> loops; + std::vector<const S2Loop*> input_loops; + for (const auto& ring : raw.sequences) { + std::vector<S2Point> points; + // Validate holes against stable raw arcs, as with typed line admission. + if (!geography_stable_points(ring, &points)) { + return nullptr; + } + // Validated WKB rings are closed; only polygon admission removes that endpoint. + DCHECK(points.front() == points.back()); + points.pop_back(); + if (points.size() < 3) { + return nullptr; + } + auto loop = std::make_unique<S2Loop>(points, S2Debug::DISABLE); + if (!loop->IsValid()) { + return nullptr; + } + loop->Normalize(); + if (!loops.empty() && !loops.front()->Contains(*loop)) { + return nullptr; + } + input_loops.push_back(loop.get()); + loops.push_back(std::move(loop)); + } + auto polygon = std::make_unique<S2Polygon>(std::move(loops), S2Debug::DISABLE); + if (!polygon->IsValid()) { + return nullptr; + } + std::vector<int> depths; + for (const auto* loop : input_loops) { + depths.push_back(loop->depth()); + } + return GeoPolygon::create_unique(std::move(polygon), std::move(depths)); +} + +#ifdef BE_TEST +static thread_local size_t geography_exact_proofs = 0; +static thread_local size_t geography_candidate_visits = 0; +static thread_local size_t geography_polygon_crossing_checks = 0; +static thread_local size_t geography_polygon_admission_checks = 0; +static thread_local size_t geography_point_polygon_preparations = 0; +static thread_local size_t geography_distance_evaluations = 0; +static thread_local size_t geography_distance_pair_nodings = 0; +#endif + +// Test coplanarity of the original degree ordinates, not independently rounded S2 vectors. +// For example (45,-45), (90,0), (135,45) share an arc although ToPoint's determinant is nonzero. +// Keep the dyadic conversion and polynomial reduction together for the exact-zero proof. +// NOLINTNEXTLINE(readability-function-size) +static bool geography_common_great_circle(const GeoCoordinate& a, const GeoCoordinate& b, + const GeoCoordinate& c) { +#ifdef BE_TEST + ++geography_exact_proofs; +#endif + using boost::multiprecision::cpp_int; + const std::array<double, 6> ordinates {a.y, a.x, b.y, b.x, c.y, c.x}; + constexpr int significand_bits = std::numeric_limits<double>::digits; + std::array<uint64_t, 6> significands {}; + std::array<int, 6> exponents {}; + int denominator_bits = 0; + for (size_t i = 0; i < ordinates.size(); ++i) { + if (ordinates[i] == 0) { + continue; + } + int exponent; + const double fraction = std::frexp(std::abs(ordinates[i]), &exponent); + // Recover the exact integer significand, including for subnormal ordinates. + const auto significand = static_cast<uint64_t>(std::ldexp(fraction, significand_bits)); + const int trailing_zeros = std::countr_zero(significand); + significands[i] = significand >> trailing_zeros; + exponents[i] = exponent - significand_bits + trailing_zeros; + denominator_bits = std::max(denominator_bits, -exponents[i]); + } + std::array<cpp_int, 6> angles; + for (size_t i = 0; i < angles.size(); ++i) { + angles[i] = cpp_int(significands[i]) << (denominator_bits + exponents[i]); + if (std::signbit(ordinates[i])) { + angles[i] = -angles[i]; + } + } + // For degree denominator 2^q, let z be the primitive root of order 360*2^q + // and D = 2^(q+2). The minimal polynomial of z is Phi_90(X^D). + // Expand cos(lat_i)cos(lat_j)sin(lat_k)sin(lon_j-lon_i), cyclically, into + // 48 integer-coefficient powers of z. Group the powers by residue modulo D + // and reduce each group by Phi_90. The remainders occupy distinct exponent + // residues in X, so they must vanish independently for the determinant to be zero. + const int shift = denominator_bits + 2; + const cpp_int basis = cpp_int(1) << shift; + const cpp_int period = 90 * basis; + std::map<cpp_int, std::array<int, 90>> polynomials; + for (int i = 0; i < 3; ++i) { + const int j = (i + 1) % 3; + const int k = (i + 2) % 3; + for (int mask = 0; mask < 16; ++mask) { + std::array<int, 4> signs; + for (int bit = 0; bit < 4; ++bit) { + signs[bit] = (mask & (1 << bit)) ? 1 : -1; + } + cpp_int power = signs[0] * angles[2 * i] + signs[1] * angles[2 * j] + + signs[2] * angles[2 * k] + + signs[3] * (angles[2 * j + 1] - angles[2 * i + 1]); + power %= period; + if (power < 0) { + power += period; + } + const int quotient = (power >> shift).convert_to<int>(); + const cpp_int residue = power - (cpp_int(quotient) << shift); + polynomials[residue][quotient] += signs[2] * signs[3]; + } + } + // Phi_90 is monic. Its lower terms are listed as (degree, coefficient). + constexpr int phi90_degree = 24; + static constexpr std::array<std::pair<int, int>, 6> phi90_lower_terms { + {{21, 1}, {15, -1}, {12, -1}, {9, -1}, {3, 1}, {0, 1}}}; + for (auto& [residue, coefficients] : polynomials) { + for (int i = 89; i >= phi90_degree; --i) { + const int coefficient = coefficients[i]; + coefficients[i] = 0; + for (const auto& [degree, factor] : phi90_lower_terms) { + coefficients[i - phi90_degree + degree] -= coefficient * factor; + } + } + if (std::ranges::any_of(coefficients, [](int value) { return value != 0; })) { + return false; + } + } + return true; +} + +// Keep each atomic segment in its own shape. Pinned S2 ProcessEdge1 uses a chain's +// global start as a local offset in one endpoint path, so multiple chains per line +// shape are unsafe. Closed AA shapes restore internal vertices in the OPEN model. +class GeographyLineShape final : public S2Shape { +public: + GeographyLineShape(const S2Point& a, const S2Point& b) : _edge(a, b) {} + // Inline Edge replaces a tracked vector buffer. Account the complete owning + // shape so removing that allocation does not hide its bytes from the query. + static void* operator new(size_t size) { + return Allocator<false>().alloc(size, alignof(GeographyLineShape)); + } + static void operator delete(void* ptr) noexcept { + Allocator<false>().free(ptr, sizeof(GeographyLineShape)); + } + int num_edges() const override { return 1; } + Edge edge(int i) const override { + DCHECK_EQ(i, 0); + return _edge; + } + int dimension() const override { return 1; } + ReferencePoint GetReferencePoint() const override { return ReferencePoint::Contained(false); } + int num_chains() const override { return 1; } + Chain chain(int i) const override { + DCHECK_EQ(i, 0); + return {0, 1}; + } + Edge chain_edge(int i, int j) const override { + DCHECK_EQ(i, 0); + return edge(j); + } + ChainPosition chain_position(int i) const override { + DCHECK_EQ(i, 0); + return {0, 0}; + } + +private: + Edge _edge; +}; + +#ifdef BE_TEST +std::unique_ptr<S2Shape> geography_line_shape_for_test() { + return std::make_unique<GeographyLineShape>(S2Point(1, 0, 0), S2Point(0, 1, 0)); +} +#endif + +class GeographyEdgeNodes { +public: + using LineEdge = std::pair<GeographyVertex, GeographyVertex>; + using LineEdges = std::set<LineEdge, std::less<>, CustomStdAllocator<LineEdge>>; + using PolygonEdges = std::array<LineEdges, 2>; + + struct RawEdges { + LineEdges line; + PolygonEdges polygon; + + auto vertices(const GeographyCoordinates& raw) const { + std::set<GeographyVertex, std::less<>, CustomStdAllocator<GeographyVertex>> result; + // A pole-alias line can have no edges but still denotes one canonical position. + result.insert(raw.sequences.front().front()); + const auto append = [&](const LineEdges& edges) { + for (const auto& [a, b] : edges) { + result.insert(a); + result.insert(b); + } + }; + append(line); + for (const auto& ring_edges : polygon) { + append(ring_edges); + } + return result; + } + }; + + GeographyCoordinates left; + GeographyCoordinates right; + + GeographyEdgeNodes(StringRef left_wkb, StringRef right_wkb) : left(left_wkb), right(right_wkb) { + DCHECK_EQ(left.status, GeoParseStatus::GEO_PARSE_OK); + DCHECK_EQ(right.status, GeoParseStatus::GEO_PARSE_OK); + DorisMap<double, DorisVector<GeographyVertex>> longitude_vertices; + std::set<GeographyVertex, std::less<>, CustomStdAllocator<GeographyVertex>> coordinates; + for (const auto* shape : {&left, &right}) { + for (const auto& sequence : shape->sequences) { + for (const auto& point : sequence) { + if (!coordinates.insert(point).second) { + continue; + } + const auto& coordinate = point.coordinate; + longitude_vertices[coordinate.x].push_back(point); + if (std::abs(coordinate.y) != 90) { + _meridians[meridian(coordinate.x)][coordinate.x < 0].push_back( + {coordinate.y, point}); + } + } + } + } + // Polygon rings retain directed edges, unlike the merged line intervals. Raw + // coordinate bands avoid recalling a whole tiny zigzag ring for every edge. + if (left.type == GeoShapeType::GEO_SHAPE_POLYGON || + right.type == GeoShapeType::GEO_SHAPE_POLYGON) { + _longitude_order.assign(coordinates.begin(), coordinates.end()); + _latitude_order = _longitude_order; + std::ranges::sort(_latitude_order, {}, + [](const auto& vertex) { return vertex.coordinate.y; }); + } + // Keep dense longitude groups separately so a circle can skip its known + // endpoint longitudes before enumerating nearby points. At sqrt(N) points + // per group there are at most sqrt(N) extra indexes, even with unrelated + // vertices padding a near-antipodal spoke input. + const auto dense_size = + std::max(size_t {2}, static_cast<size_t>(std::ceil(std::sqrt(coordinates.size())))); + for (const auto& [longitude, points] : longitude_vertices) { + auto& index = + points.size() >= dense_size ? _dense_longitudes[longitude] : _vertex_index; + for (const auto& point : points) { + index.Add(point.point, point); + } + } + for (auto& entry : _meridians) { + for (auto& side : entry.second) { + side.push_back({-90, GeographyVertex({.x = 0, .y = -90})}); + side.push_back({90, GeographyVertex({.x = 0, .y = 90})}); + std::ranges::sort(side, {}, &Vertex::latitude); + } + } + } + + bool contains_point(const GeographyVertex& start, const GeographyVertex& end, + const GeographyVertex& point) const { + // Preserve exact endpoints, including date-line and pole aliases. + if (point == start || point == end) { + return true; + } + if (start == end) { + return false; + } + const auto& a = start.coordinate; + const auto& b = end.coordinate; + const auto& c = point.coordinate; + const auto key = meridian(std::abs(a.y) == 90 ? b.x : a.x); + bool member = false; + if (meridian_edge(start, end, [&](const auto& vertices, double from, double to) { + // Opposite-longitude edges can pass through a pole; the pole belongs + // to both legs, whereas other positions must be on the selected side. + const bool same_side = + std::abs(c.y) == 90 || + (meridian(c.x) == key && &_meridians.at(key)[c.x < 0] == &vertices); + member |= same_side && c.y >= std::min(from, to) && c.y <= std::max(from, to); + })) { + return member; + } + const bool wraps = geography_degree_sum(std::max(a.x, b.x), -std::min(a.x, b.x)) > + std::pair {180.0, 0.0}; + const bool within = wraps ? (c.x < std::min(a.x, b.x) || c.x > std::max(a.x, b.x)) + : (c.x > std::min(a.x, b.x) && c.x < std::max(a.x, b.x)); + // Near-antipodal endpoint conversion can rotate the S2 plane substantially. + // POINT(45 0) is on (-44.99999999999997 -45,134.99999999999997 45); + // decide from raw degrees rather than accepting a larger distance tolerance. + return within && geography_common_great_circle(a, b, c); + } + + bool line_contains_point(const GeographyCoordinates& shape, + const GeographyVertex& point) const { + const auto& line = shape.sequences.front(); + for (size_t i = 0; i + 1 < line.size(); ++i) { Review Comment: [P2] Index Point/Line candidates before exact coplanarity For `ST_Intersects(L,p)` with constant spherical Geography line vertices `v_i=((i%2==0 ? -1 : 1), i/(N-1))` and M scanned points `p_j=(0,-20+j/(M-1))`, every point is far from the line, but this loop calls `geography_common_great_circle()` for every edge: the longitude test passes and there is no nearby-edge filter. At N=M=10000 that is 99,990,000 arbitrary-precision coplanarity proofs for a 160,009-byte constant line, plus repeated raw-line preparation. `StRelationFunction` caches the decoded shape but prepares an index only for polygons; the Point/Line dispatch returns before the nonpoint indexes. Both operand orders of Intersects/Disjoint and the corresponding containment calls are affected. Reuse prepared line state and conservatively select nearby edges before exact proofs, with increasing-size work-count coverage. This is separate from the existing Point/Polygon and distance-cache threads. Counts are source-derived; no benchmark ran. -- 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]
