FrankChen021 commented on code in PR #19353:
URL: https://github.com/apache/druid/pull/19353#discussion_r3129501176


##########
processing/src/main/java/org/apache/druid/query/topn/TopNQueryEngine.java:
##########
@@ -96,13 +98,34 @@ public Sequence<Result<TopNResultValue>> query(
       if (cursorHolder.isPreAggregated()) {
         query = 
query.withAggregatorSpecs(Preconditions.checkNotNull(cursorHolder.getAggregatorsForPreAggregated()));
       }
+
+      final TimeBoundaryInspector timeBoundaryInspector = 
segment.as(TimeBoundaryInspector.class);
+
+      final boolean canVectorize = cursorHolder.canVectorize()
+                                   && VectorTopNEngine.canVectorize(query, 
cursorFactory);
+      final boolean shouldVectorize = 
query.context().getVectorize().shouldVectorize(canVectorize);
+
+      if (shouldVectorize) {
+        final ResourceHolder<ByteBuffer> bufHolder = bufferPool.take();
+        try {
+          final Closer resourceCloser = Closer.create();
+          resourceCloser.register(bufHolder);
+          resourceCloser.register(cursorHolder);
+          return Sequences.filter(
+              VectorTopNEngine.process(query, timeBoundaryInspector, 
cursorHolder, bufHolder.get()),
+              Predicates.notNull()
+          ).withBaggage(resourceCloser);

Review Comment:
   [P2] Vectorized TopN bypasses existing query metrics reporting.
   
   The new early return into `VectorTopNEngine.process` skips the row-path 
bookkeeping that reports TopN metrics today. In the non-vector path this method 
records `queryMetrics.cursor(...)`, then `getMapFn` records 
`dimensionCardinality(...)` and algorithm selection, and `TopNMapFn` records 
selector and pass-size metrics. None of that runs when `shouldVectorize` is 
true, so enabling vectorization changes emitted TopN metrics and removes 
operational visibility into algorithm choice and cardinality. If that loss is 
intended it should be wired back explicitly; otherwise this is a regression.



##########
processing/src/main/java/org/apache/druid/query/topn/vector/VectorTopNEngine.java:
##########
@@ -0,0 +1,367 @@
+/*
+ * 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.druid.query.topn.vector;
+
+import com.google.common.base.Suppliers;
+import org.apache.datasketches.memory.WritableMemory;
+import org.apache.druid.java.util.common.guava.BaseSequence;
+import org.apache.druid.java.util.common.guava.Sequence;
+import org.apache.druid.java.util.common.parsers.CloseableIterator;
+import org.apache.druid.query.Order;
+import org.apache.druid.query.Result;
+import org.apache.druid.query.aggregation.AggregatorAdapters;
+import org.apache.druid.query.aggregation.AggregatorFactory;
+import org.apache.druid.query.dimension.DimensionSpec;
+import org.apache.druid.query.groupby.epinephelinae.BufferArrayGrouper;
+import org.apache.druid.query.groupby.epinephelinae.Grouper;
+import org.apache.druid.query.groupby.epinephelinae.HeapVectorGrouper;
+import org.apache.druid.query.groupby.epinephelinae.VectorGrouper;
+import org.apache.druid.query.groupby.epinephelinae.collection.MemoryPointer;
+import org.apache.druid.query.topn.TopNQuery;
+import org.apache.druid.query.topn.TopNResultBuilder;
+import org.apache.druid.query.topn.TopNResultValue;
+import org.apache.druid.query.vector.VectorCursorGranularizer;
+import org.apache.druid.segment.ColumnInspector;
+import org.apache.druid.segment.ColumnProcessors;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.TimeBoundaryInspector;
+import org.apache.druid.segment.column.ColumnCapabilities;
+import org.apache.druid.segment.column.Types;
+import org.apache.druid.segment.column.ValueType;
+import org.apache.druid.segment.vector.VectorColumnSelectorFactory;
+import org.apache.druid.segment.vector.VectorCursor;
+import org.apache.druid.segment.virtual.VirtualizedColumnInspector;
+import org.joda.time.DateTime;
+import org.joda.time.Interval;
+
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+/**
+ * Vectorized execution engine for {@link TopNQuery}, analogous to
+ * {@link 
org.apache.druid.query.groupby.epinephelinae.vector.VectorGroupByEngine} for 
groupBy.
+ *
+ * Uses a {@link VectorGrouper} for batch aggregation (with vectorized null 
handling via
+ * {@link 
org.apache.druid.segment.vector.VectorValueSelector#getNullVector()}) and then 
applies top-N
+ * ordering via {@link TopNResultBuilder} after each time-bucket is fully 
aggregated.
+ *
+ * @see org.apache.druid.query.topn.TopNQueryEngine for the entry point that 
selects this path
+ */
+public class VectorTopNEngine
+{
+  private VectorTopNEngine()
+  {
+    // No instantiation.
+  }
+
+  public static Sequence<Result<TopNResultValue>> process(
+      final TopNQuery query,
+      @Nullable final TimeBoundaryInspector timeBoundaryInspector,
+      final CursorHolder cursorHolder,
+      final ByteBuffer processingBuffer
+  )
+  {
+    return new BaseSequence<>(
+        new BaseSequence.IteratorMaker<Result<TopNResultValue>, 
CloseableIterator<Result<TopNResultValue>>>()
+        {
+          @Override
+          public CloseableIterator<Result<TopNResultValue>> make()
+          {
+            final VectorCursor cursor = cursorHolder.asVectorCursor();
+
+            if (cursor == null) {
+              return new CloseableIterator<>()
+              {
+                @Override
+                public boolean hasNext()
+                {
+                  return false;
+                }
+
+                @Override
+                public Result<TopNResultValue> next()
+                {
+                  throw new NoSuchElementException();
+                }
+
+                @Override
+                public void close()
+                {
+                  // Nothing to do.
+                }
+              };
+            }
+
+            final VectorColumnSelectorFactory columnSelectorFactory = 
cursor.getColumnSelectorFactory();
+            final TopNVectorColumnSelector selector = 
ColumnProcessors.makeVectorProcessor(
+                query.getDimensionSpec(),
+                TopNVectorColumnProcessorFactory.instance(),
+                columnSelectorFactory
+            );
+
+            return new VectorTopNEngineIterator(
+                query,
+                timeBoundaryInspector,
+                cursor,
+                cursorHolder.getTimeOrder(),
+                selector,
+                processingBuffer
+            );
+          }
+
+          @Override
+          public void cleanup(final CloseableIterator<Result<TopNResultValue>> 
iterFromMake)
+          {
+            try {
+              iterFromMake.close();
+            }
+            catch (IOException e) {
+              throw new RuntimeException(e);
+            }
+          }
+        }
+    );
+  }
+
+  /**
+   * Returns true if the given query is eligible for the vectorized topN path.
+   */
+  public static boolean canVectorize(final TopNQuery query, final 
ColumnInspector inspector)
+  {
+    final DimensionSpec dimensionSpec = query.getDimensionSpec();
+
+    if (!dimensionSpec.canVectorize()) {
+      return false;
+    }
+
+    // Decorated specs (e.g. extraction functions that are not one-to-one) 
change value semantics in ways that
+    // are incompatible with the vectorized grouper key approach.
+    if (dimensionSpec.mustDecorate()) {
+      return false;
+    }
+
+    if (dimensionSpec.getOutputType().isArray()) {
+      return false;
+    }
+
+    // Wrap with virtual columns so capabilities lookups for virtual column 
dimensions work correctly.
+    final ColumnInspector effectiveInspector =
+        new VirtualizedColumnInspector(inspector, query.getVirtualColumns());
+
+    final ColumnCapabilities capabilities = 
effectiveInspector.getColumnCapabilities(dimensionSpec.getDimension());
+    // null means column does not exist; nil columns can be vectorized
+    if (capabilities != null && 
capabilities.hasMultipleValues().isMaybeTrue()) {
+      return false;
+    }
+
+    // TODO(vectorized-topn): the non-vectorized path coerces raw values to 
the dimension's output type before
+    // grouping (see TopNColumnAggregatesProcessorFactory). This path groups 
on the raw column type, so mixed-type
+    // queries (e.g. DOUBLE column with LONG output) would produce distinct 
groups that coerce to the same output
+    // value. Falling back for now; a future change could coerce at writeKeys 
time to match non-vec semantics.
+    if (capabilities != null && dimensionSpec.getOutputType().getType() != 
capabilities.getType()) {
+      return false;
+    }
+
+    for (final AggregatorFactory agg : query.getAggregatorSpecs()) {
+      if (!agg.canVectorize(effectiveInspector)) {
+        return false;
+      }
+    }
+
+    return true;

Review Comment:
   [P1] `canVectorize` admits unsupported object/COMPLEX dimensions.
   
   `VectorTopNEngine.canVectorize` only filters out decorated specs, arrays, 
and multi-value columns, then returns true for any remaining type whose output 
type matches the column capabilities. But 
`TopNVectorColumnProcessorFactory.makeObjectProcessor` only handles STRING 
object selectors and throws for every other object/COMPLEX type. That means a 
query using a `DefaultDimensionSpec` over a nested/COMPLEX column can be marked 
vectorizable here and then fail at runtime in `makeObjectProcessor` instead of 
falling back to the row path. `canVectorize` should reject non-STRING 
object/COMPLEX dimensions up front so capability checks match actual factory 
support.



-- 
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