You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by "abhishekrb19 (via GitHub)" <gi...@apache.org> on 2026/04/27 05:12:33 UTC

[PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

abhishekrb19 opened a new pull request, #19379:
URL: https://github.com/apache/druid/pull/19379

    This PR adds a new `scan` transform type to Druid's transformSpec that unnests array-valued columns into individual rows during streaming ingestion. This is similar to the UNNEST support in SQL with MSQ batch ingestion,  but with realtime ingestion.
   
     - New ScanTransform (`type: "scan"`) - a multi-row transform that reuses the existing `UnnestCursorFactory` / cursor machinery to explode arrays at ingest time
     - Supports multiple scan transforms which can be chained together
     - Works with string arrays, object arrays, and nested arrays - objects are preserved through unnest and queryable via `JSON_VALUE at query time
   
   This would simplify queries by avoiding `UNNEST` and improve query performance since the unnesting is done once at ingest time rather than repeatedly at query time.
   
   ### Release note
   
   Scan transform for ingestion-time array unnesting. Added a new "scan" transform type in transformSpec that unnests array-valued columns into individual rows during streaming ingestion (similar to existing UNNEST functionality with Druid SQL with MSQ engine). Multiple scan transforms can be chained to unnest several array columns.
   
   This PR has:
   
   - [x] been self-reviewed.
   - [x] added documentation for new or modified features or behaviors.
   - [x] a release note entry in the PR description.
   - [x] added Javadocs for most classes and all non-trivial methods. Linked related entities via Javadoc links.
   - [x] added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
   - [x] added unit tests or modified existing tests to cover new code paths, ensuring the threshold for [code coverage](https://github.com/apache/druid/blob/master/dev/code-review/code-coverage.md) is met.
   - [x] added integration tests.
   - [x] been tested in a test Druid cluster.


-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "FrankChen021 (via GitHub) via commits" <co...@druid.apache.org>.
FrankChen021 commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r4811086193


##########
processing/src/main/java/org/apache/druid/segment/transform/SettableRowCursorFactory.java:
##########
@@ -0,0 +1,155 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.query.filter.Filter;
+import org.apache.druid.query.filter.ValueMatcher;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.RowAdapters;
+import org.apache.druid.segment.RowBasedColumnSelectorFactory;
+import org.apache.druid.segment.RowIdSupplier;
+import org.apache.druid.segment.column.ColumnCapabilities;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.ValueMatchers;
+
+import javax.annotation.Nullable;
+
+/**
+ * A {@link CursorFactory} backed by a mutable {@link InputRow} holder. Each call to
+ * {@link #makeCursorHolder(CursorBuildSpec)} returns a cursor that applies the spec's virtual columns
+ * on top of the current row. The underlying row holder is shared — call {@link #set(InputRow)} to
+ * swap the current row, then {@link Cursor#reset()} on the returned cursor.
+ */
+class SettableRowCursorFactory implements CursorFactory
+{
+  private final RowSignature rowSignature;
+  private final ColumnSelectorFactory baseSelectorFactory;
+  private InputRow currentRow;
+  private long rowId = RowIdSupplier.INIT;
+
+  SettableRowCursorFactory(final RowSignature rowSignature)
+  {
+    this.rowSignature = rowSignature;
+    this.baseSelectorFactory = new RowBasedColumnSelectorFactory<>(
+        this::getCurrentRow,
+        this::getRowId,
+        RowAdapters.standardRow(),
+        rowSignature,
+        false
+    );
+  }
+
+  void set(final InputRow row)
+  {
+    this.currentRow = row;
+    this.rowId++;
+  }
+
+  @Override
+  public CursorHolder makeCursorHolder(final CursorBuildSpec spec)
+  {
+    final ColumnSelectorFactory selectorFactory = spec.getVirtualColumns().wrap(baseSelectorFactory);
+    final Filter filter = spec.getFilter();
+    final ValueMatcher filterMatcher = filter == null
+                                       ? ValueMatchers.allTrue()
+                                       : filter.makeMatcher(selectorFactory);
+
+    return new CursorHolder()
+    {
+      @Override
+      public Cursor asCursor()
+      {
+        return new Cursor()
+        {
+          private boolean done = currentRow == null || !filterMatcher.matches(false);

Review Comment:
   [P2] Honor or reject the scan interval
   
   **Finding:** The scan transformer constructs a CursorBuildSpec with query.getSingleInterval(), but this cursor's initial and reset completion checks ignore spec.getInterval() and only evaluate currentRow and filterMatcher. With a bounded scan interval, input rows whose timestamps fall outside that interval still produce scan outputs and can be ingested. The documentation recommends eternity, but bounded intervals are not rejected.
   
   **Suggestion:** Either reject non-eternity intervals in ScanTransformSpec, or enforce spec.getInterval() in the cursor's initial and reset checks, with a bounded-interval regression test.



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r4067178912


##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,337 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.ListBasedInputRow;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.error.DruidException;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.ColumnValueSelector;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row is dropped. This matches native Druid UNNEST / CROSS JOIN semantics where
+ * null or empty arrays produce zero rows.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  // Field names that must never be promoted to a dimension, regardless of whether they show up in this
+  // scan query's result columns. See resolveDimensionColumns() for why this can't be derived locally.
+  private final Set<String> dimensionExclusions;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery, final Set<String> dimensionExclusions)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+    this.dimensionExclusions = dimensionExclusions;
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()
+                                                           .setInterval(query.getSingleInterval())
+                                                           .setFilter(Filters.toFilter(query.getFilter()))
+                                                           .setVirtualColumns(query.getVirtualColumns())
+                                                           .build();
+
+    this.baseCursorFactory = new SettableRowCursorFactory(broadSignature);
+    final SegmentMapFunction segmentMapFunction = query.getDataSource().createSegmentMapFunction(query);
+    final Segment mappedSegment = segmentMapFunction.apply(Optional.of(new CursorFactorySegment(baseCursorFactory)))
+                                                    .orElseThrow(() -> new ISE("SegmentMapFunction returned empty"));
+    final CursorFactory mappedCursorFactory = mappedSegment.as(CursorFactory.class);
+    this.cursorHolder = mappedCursorFactory.makeCursorHolder(cursorBuildSpec);
+  }
+
+  @Override
+  public boolean hasMultiRowTransform()
+  {
+    return true;
+  }
+
+  @Override
+  @Nullable
+  public InputRow transform(@Nullable final InputRow row)
+  {
+    throw new UnsupportedOperationException(
+        "ScanTransformer does not support single-row transform; use transformToList()"
+    );
+  }
+
+  @Override
+  public List<InputRow> transformToList(@Nullable final InputRow row)
+  {
+    if (row == null) {
+      return List.of();
+    }
+
+    return process(row);
+  }
+
+  @Override
+  @Nullable
+  public InputRowListPlusRawValues transform(@Nullable final InputRowListPlusRawValues row)
+  {
+    if (row == null || row.getInputRows() == null) {
+      return row;
+    }
+
+    final List<InputRow> inputRows = row.getInputRows();
+    final List<Map<String, Object>> inputRawValues = row.getRawValuesList();
+    final List<InputRow> outputRows = new ArrayList<>();
+    final List<Map<String, Object>> outputRawValues = inputRawValues == null ? null : new ArrayList<>();
+
+    for (int i = 0; i < inputRows.size(); i++) {
+      final List<InputRow> expandedRows = transformToList(inputRows.get(i));
+      outputRows.addAll(expandedRows);
+      if (outputRawValues != null) {
+        for (int j = 0; j < expandedRows.size(); j++) {
+          outputRawValues.add(inputRawValues.get(i));
+        }
+      }
+    }
+
+    return InputRowListPlusRawValues.ofList(outputRawValues, outputRows, row.getParseException());
+  }
+
+  @Override
+  public void close() throws IOException
+  {
+    cursorHolder.close();
+  }
+
+  private List<InputRow> process(final InputRow inputRow)
+  {
+    baseCursorFactory.set(inputRow);
+
+    if (cursor == null) {
+      cursor = cursorHolder.asCursor();
+    } else {
+      cursor.reset();
+    }
+
+    if (cursor == null || cursor.isDone()) {
+      return List.of();
+    }
+
+    final Set<String> nonDimensionEventFields = resolveNonDimensionEventFields(inputRow);
+    final List<String> columns = resolveColumnsForRow(inputRow, nonDimensionEventFields);
+    final List<String> dimensionColumns = resolveDimensionColumns(inputRow, columns, nonDimensionEventFields);
+    final ColumnSelectorFactory selectorFactory = cursor.getColumnSelectorFactory();
+
+    // Selectors are lazy views over the cursor's current position — create them once per column
+    // here, then re-read via getObject() as the cursor advances, rather than reallocating a selector
+    // for every (output-row x column) pair.
+    final ColumnValueSelector<?>[] selectors = new ColumnValueSelector<?>[columns.size()];
+    for (int i = 0; i < columns.size(); i++) {
+      selectors[i] = selectorFactory.makeColumnValueSelector(columns.get(i));
+    }
+
+    // The query re-executes fresh for each input row (cursor reset above), so this row's own unnested
+    // expansion is the query's entire result set for this execution — offset/limit bound that set,
+    // the same way they'd bound any other scan query's result set. This is necessarily per input row
+    // rather than global across the ingestion job: there is no single ordered stream spanning rows
+    // (let alone across the parallel/rolling readers of a real ingestion job) for them to paginate.
+    final long offset = query.getScanRowsOffset();
+    final long limit = query.getScanRowsLimit();
+    long skipped = 0;
+
+    final List<InputRow> result = new ArrayList<>();
+    while (!cursor.isDone() && result.size() < limit) {

Review Comment:
   ## CodeQL / Comparison of narrow type with wide type in loop condition
   
   Comparison between [expression](1) of type int and [expression](2) of wider type long.
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/11998)



##########
processing/src/test/java/org/apache/druid/segment/transform/ScanTransformTest.java:
##########
@@ -0,0 +1,717 @@
+/*
+ * 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.segment.transform;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Preconditions;
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.ListBasedInputRow;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.error.DruidExceptionMatcher;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.Druids;
+import org.apache.druid.query.TableDataSource;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.filter.SelectorDimFilter;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.TestHelper;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.virtual.ExpressionVirtualColumn;
+import org.apache.druid.testing.InitializedNullHandlingTest;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class ScanTransformTest extends InitializedNullHandlingTest
+{
+  private static final long TIMESTAMP = DateTimes.of("2024-01-01").getMillis();
+
+  private static InputRow makeRow(Object... kvPairs)
+  {
+    Preconditions.checkArgument(kvPairs.length % 2 == 0, "kvPairs must have even length");
+    final LinkedHashMap<String, Object> event = new LinkedHashMap<>();
+    final List<String> dimensions = new ArrayList<>();
+    for (int i = 0; i < kvPairs.length; i += 2) {
+      final String key = (String) kvPairs[i];
+      event.put(key, kvPairs[i + 1]);
+      if (!ColumnHolder.TIME_COLUMN_NAME.equals(key)) {
+        dimensions.add(key);
+      }
+    }
+    return new MapBasedInputRow(TIMESTAMP, dimensions, event);
+  }
+
+  private static ScanQuery makeUnnestQuery(String inputColumn, String outputName)
+  {
+    return makeUnnestQuery(inputColumn, outputName, ColumnType.STRING, null);
+  }
+
+  private static ScanQuery makeUnnestQuery(
+      String inputColumn,
+      String outputName,
+      ColumnType outputType,
+      SelectorDimFilter unnestFilter
+  )
+  {
+    return Druids.newScanQueryBuilder()
+                 .dataSource(UnnestDataSource.create(
+                     new TableDataSource("__input__"),
+                     new ExpressionVirtualColumn(outputName, "\"" + inputColumn + "\"", outputType, ExprMacroTable.nil()),
+                     unnestFilter
+                 ))
+                 .eternityInterval()
+                 .columns((List<String>) null)
+                 .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+                 .build();
+  }
+
+  private static BaseTransformer makeTransformer(ScanQuery query)
+  {
+    return new ScanTransformSpec(query).toTransformer();
+  }
+
+  @Test
+  public void testBasicUnnest()
+  {
+    final BaseTransformer transformer = makeTransformer(makeUnnestQuery("tags", "tag"));
+    final InputRow input = makeRow("user", "alice", "tags", List.of("a", "b", "c"));
+
+    final List<InputRow> result = transformer.transformToList(input);
+    Assertions.assertEquals(3, result.size());
+
+    Assertions.assertEquals("a", result.get(0).getRaw("tag"));
+    Assertions.assertEquals("alice", result.get(0).getRaw("user"));
+    Assertions.assertEquals(TIMESTAMP, result.get(0).getTimestampFromEpoch());
+
+    Assertions.assertEquals("b", result.get(1).getRaw("tag"));
+    Assertions.assertEquals("c", result.get(2).getRaw("tag"));
+  }
+
+  @Test
+  public void testUnnestEmptyArray()
+  {
+    final BaseTransformer transformer = makeTransformer(makeUnnestQuery("tags", "tag"));
+    final InputRow input = makeRow("user", "alice", "tags", List.of());
+
+    final List<InputRow> result = transformer.transformToList(input);
+    // Empty array produces 0 rows, matching native CROSS JOIN UNNEST semantics
+    Assertions.assertEquals(0, result.size());
+  }
+
+  @Test
+  public void testUnnestMissingColumn()
+  {
+    final BaseTransformer transformer = makeTransformer(makeUnnestQuery("services", "svc"));
+    final InputRow input = makeRow("user", "alice", "host", "web-01");
+
+    final List<InputRow> result = transformer.transformToList(input);
+    // Missing column produces 0 rows, matching native CROSS JOIN UNNEST semantics
+    Assertions.assertEquals(0, result.size());
+  }
+
+  @Test
+  public void testUnnestSingleElement()
+  {
+    final BaseTransformer transformer = makeTransformer(makeUnnestQuery("tags", "tag"));
+    final InputRow input = makeRow("user", "alice", "tags", List.of("only"));
+
+    final List<InputRow> result = transformer.transformToList(input);
+    Assertions.assertEquals(1, result.size());
+    Assertions.assertEquals("only", result.get(0).getRaw("tag"));
+  }
+
+  @Test
+  public void testUnnestScalarValue()
+  {
+    final BaseTransformer transformer = makeTransformer(makeUnnestQuery("tags", "tag"));
+    final InputRow input = makeRow("user", "alice", "tags", "scalar");
+
+    final List<InputRow> result = transformer.transformToList(input);
+    Assertions.assertEquals(1, result.size());
+    Assertions.assertEquals("scalar", result.get(0).getRaw("tag"));
+  }
+
+  @Test
+  public void testUnnestArrayOfJsonObjects()
+  {
+    final BaseTransformer transformer = makeTransformer(
+        makeUnnestQuery("items", "item", ColumnType.NESTED_DATA, null)
+    );
+    final InputRow input = makeRow("user", "alice", "items", List.of(
+        Map.of("product", "shirt", "price", 25),
+        Map.of("product", "pants", "price", 40),
+        Map.of("product", "hat", "price", 15)
+    ));
+
+    final List<InputRow> result = transformer.transformToList(input);
+    Assertions.assertEquals(3, result.size());
+
+    final Object item0 = result.get(0).getRaw("item");
+    Assertions.assertNotNull(item0);
+    Assertions.assertTrue(item0 instanceof Map, "Expected a Map, got " + item0.getClass());
+    Assertions.assertEquals("shirt", ((Map<?, ?>) item0).get("product"));
+
+    final Object item2 = result.get(2).getRaw("item");
+    Assertions.assertTrue(item2 instanceof Map);
+    Assertions.assertEquals("hat", ((Map<?, ?>) item2).get("product"));
+  }
+
+  @Test
+  public void testUnnestNestedArrays()
+  {
+    final BaseTransformer transformer = makeTransformer(
+        makeUnnestQuery("data", "element", ColumnType.NESTED_DATA, null)
+    );
+    final InputRow input = makeRow(
+        "user", "alice",
+        "data", List.of(List.of(1, 2), List.of(3))
+    );
+
+    final List<InputRow> result = transformer.transformToList(input);
+    Assertions.assertEquals(2, result.size());
+
+    final Object elem0 = result.get(0).getRaw("element");
+    Assertions.assertNotNull(elem0);
+    Assertions.assertArrayEquals(new Object[]{1L, 2L}, (Object[]) elem0);
+
+    final Object elem1 = result.get(1).getRaw("element");
+    Assertions.assertNotNull(elem1);
+    Assertions.assertArrayEquals(new Object[]{3L}, (Object[]) elem1);
+
+    Assertions.assertEquals("alice", result.get(0).getRaw("user"));
+    Assertions.assertEquals("alice", result.get(1).getRaw("user"));
+  }
+
+  @Test
+  public void testTimestampPreservation()
+  {
+    final BaseTransformer transformer = makeTransformer(makeUnnestQuery("tags", "tag"));
+    final InputRow input = makeRow("tags", List.of("a", "b"));
+
+    final List<InputRow> result = transformer.transformToList(input);
+    for (final InputRow row : result) {
+      Assertions.assertEquals(TIMESTAMP, row.getTimestampFromEpoch());
+    }
+  }
+
+  @Test
+  public void testWithUnnestFilter()
+  {
+    final BaseTransformer transformer = makeTransformer(
+        makeUnnestQuery("tags", "tag", ColumnType.STRING, new SelectorDimFilter("tag", "b", null))
+    );
+    final InputRow input = makeRow("user", "alice", "tags", List.of("a", "b", "c"));
+
+    final List<InputRow> result = transformer.transformToList(input);
+    Assertions.assertEquals(1, result.size());
+    Assertions.assertEquals("b", result.get(0).getRaw("tag"));
+  }
+
+  @Test
+  public void testScanQueryLimitCapsPerRowExpansion()
+  {
+    // The query re-executes fresh for each input row, so this row's own unnested elements are the
+    // query's entire result set for that execution — limit:1 caps it to the first unnested element.
+    final ScanQuery query = Druids.newScanQueryBuilder()
+                                   .dataSource(UnnestDataSource.create(
+                                       new TableDataSource("__input__"),
+                                       new ExpressionVirtualColumn("tag", "\"tags\"", ColumnType.STRING, ExprMacroTable.nil()),
+                                       null
+                                   ))
+                                   .eternityInterval()
+                                   .columns((List<String>) null)
+                                   .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+                                   .limit(1)
+                                   .build();
+
+    final BaseTransformer transformer = new ScanTransformSpec(query).toTransformer();
+    final InputRow input = makeRow("user", "alice", "tags", List.of("a", "b", "c"));
+
+    final List<InputRow> result = transformer.transformToList(input);
+    Assertions.assertEquals(1, result.size());
+    Assertions.assertEquals("a", result.get(0).getRaw("tag"));
+  }
+
+  @Test
+  public void testScanQueryOffsetSkipsPerRowExpansion()
+  {
+    final ScanQuery query = Druids.newScanQueryBuilder()
+                                   .dataSource(UnnestDataSource.create(
+                                       new TableDataSource("__input__"),
+                                       new ExpressionVirtualColumn("tag", "\"tags\"", ColumnType.STRING, ExprMacroTable.nil()),
+                                       null
+                                   ))
+                                   .eternityInterval()
+                                   .columns((List<String>) null)
+                                   .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+                                   .offset(1)
+                                   .limit(1)
+                                   .build();
+
+    final BaseTransformer transformer = new ScanTransformSpec(query).toTransformer();
+    final InputRow input = makeRow("user", "alice", "tags", List.of("a", "b", "c"));
+
+    final List<InputRow> result = transformer.transformToList(input);
+    Assertions.assertEquals(1, result.size());
+    Assertions.assertEquals("b", result.get(0).getRaw("tag"));
+  }
+
+  @Test
+  public void testScanQueryLimitAppliesIndependentlyPerInputRow()
+  {
+    // limit is bound to each execution of the query, i.e. each input row's own expansion — not a
+    // running total across the multiple input rows a reader processes over its lifetime.
+    final ScanQuery query = Druids.newScanQueryBuilder()
+                                   .dataSource(UnnestDataSource.create(
+                                       new TableDataSource("__input__"),
+                                       new ExpressionVirtualColumn("tag", "\"tags\"", ColumnType.STRING, ExprMacroTable.nil()),
+                                       null
+                                   ))
+                                   .eternityInterval()
+                                   .columns((List<String>) null)
+                                   .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+                                   .limit(1)
+                                   .build();
+
+    final BaseTransformer transformer = new ScanTransformSpec(query).toTransformer();
+
+    final List<InputRow> firstResult = transformer.transformToList(
+        makeRow("user", "alice", "tags", List.of("a", "b"))
+    );
+    final List<InputRow> secondResult = transformer.transformToList(
+        makeRow("user", "bob", "tags", List.of("x", "y"))
+    );
+
+    Assertions.assertEquals(1, firstResult.size());
+    Assertions.assertEquals("a", firstResult.get(0).getRaw("tag"));
+    Assertions.assertEquals(1, secondResult.size());
+    Assertions.assertEquals("x", secondResult.get(0).getRaw("tag"));
+  }
+
+  @Test
+  public void testTransformerWithSingleScanTransform()
+  {
+    final ScanTransformSpec spec = new ScanTransformSpec(
+        makeUnnestQuery("tags", "tag")
+    );
+
+    final BaseTransformer transformer = spec.toTransformer();
+    Assertions.assertTrue(transformer.hasMultiRowTransform());
+    Assertions.assertTrue(transformer instanceof ScanTransformer);
+
+    final InputRow input = makeRow("user", "alice", "tags", List.of("x", "y"));
+    final List<InputRow> result = transformer.transformToList(input);
+
+    Assertions.assertEquals(2, result.size());
+    Assertions.assertEquals("x", result.get(0).getRaw("tag"));
+    Assertions.assertEquals("y", result.get(1).getRaw("tag"));
+  }
+
+  @Test
+  public void testNestedUnnestCrossJoin()
+  {
+    final BaseTransformer transformer = new ScanTransformSpec(
+        Druids.newScanQueryBuilder()
+              .dataSource(UnnestDataSource.create(
+                  UnnestDataSource.create(
+                      new TableDataSource("__input__"),
+                      new ExpressionVirtualColumn("tag", "\"tags\"", ColumnType.STRING, ExprMacroTable.nil()),
+                      null
+                  ),
+                  new ExpressionVirtualColumn("color", "\"colors\"", ColumnType.STRING, ExprMacroTable.nil()),
+                  null
+              ))
+              .eternityInterval()
+              .columns((List<String>) null)
+              .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+              .build()
+    ).toTransformer();
+    Assertions.assertTrue(transformer.hasMultiRowTransform());
+
+    final InputRow input = makeRow(
+        "user", "alice",
+        "tags", List.of("a", "b"),
+        "colors", List.of("red", "blue", "green")
+    );
+    final List<InputRow> result = transformer.transformToList(input);
+
+    // 2 tags x 3 colors = 6 rows (cross join)
+    Assertions.assertEquals(6, result.size());
+  }
+
+  @Test
+  public void testNestedUnnestWithMissingOuterColumn()
+  {
+    final BaseTransformer transformer = new ScanTransformSpec(
+        Druids.newScanQueryBuilder()
+              .dataSource(UnnestDataSource.create(
+                  UnnestDataSource.create(
+                      new TableDataSource("__input__"),
+                      new ExpressionVirtualColumn("tag", "\"tags\"", ColumnType.STRING, ExprMacroTable.nil()),
+                      null
+                  ),
+                  new ExpressionVirtualColumn("svc", "\"services\"", ColumnType.NESTED_DATA, ExprMacroTable.nil()),
+                  null
+              ))
+              .eternityInterval()
+              .columns((List<String>) null)
+              .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+              .build()
+    ).toTransformer();
+
+    // tags present (2 elements), services missing
+    final InputRow input = makeRow("trace_id", "abc", "tags", List.of("music", "blll"));
+    final List<InputRow> result = transformer.transformToList(input);
+
+    // Nested unnest is a cross join: tags x services. With services missing, the cross join
+    // produces 0 rows — matching native CROSS JOIN UNNEST semantics.
+    Assertions.assertEquals(0, result.size());
+  }
+
+  @Test
+  public void testNestedUnnestFlattensNestedArrays()
+  {
+    final BaseTransformer transformer = new ScanTransformSpec(
+        Druids.newScanQueryBuilder()
+              .dataSource(UnnestDataSource.create(
+                  UnnestDataSource.create(
+                      new TableDataSource("__input__"),
+                      new ExpressionVirtualColumn("inner", "\"data\"", ColumnType.NESTED_DATA, ExprMacroTable.nil()),
+                      null
+                  ),
+                  new ExpressionVirtualColumn("val", "\"inner\"", ColumnType.LONG, ExprMacroTable.nil()),
+                  null
+              ))
+              .eternityInterval()
+              .columns((List<String>) null)
+              .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+              .build()
+    ).toTransformer();
+
+    final InputRow input = makeRow(
+        "user", "alice",
+        "data", List.of(List.of(1, 2), List.of(3))
+    );
+    final List<InputRow> result = transformer.transformToList(input);
+
+    // First unnest: [[1,2],[3]] -> [1,2], [3] (2 rows)
+    // Second unnest: [1,2] -> 1, 2 and [3] -> 3 (3 rows total)
+    Assertions.assertEquals(3, result.size());
+
+    final List<Object> values = new ArrayList<>();
+    for (final InputRow row : result) {
+      values.add(row.getRaw("val"));
+      Assertions.assertEquals("alice", row.getRaw("user"));
+    }
+    Assertions.assertEquals(3, values.size());
+    Assertions.assertEquals(1, ((Number) values.get(0)).intValue());
+    Assertions.assertEquals(2, ((Number) values.get(1)).intValue());
+    Assertions.assertEquals(3, ((Number) values.get(2)).intValue());
+  }
+
+  @Test
+  public void testScanTransformWithQueryFilter()
+  {
+    final BaseTransformer transformer = new ScanTransformSpec(
+        Druids.newScanQueryBuilder()
+              .dataSource(UnnestDataSource.create(
+                  new TableDataSource("__input__"),
+                  new ExpressionVirtualColumn("tag", "\"tags\"", ColumnType.STRING, ExprMacroTable.nil()),
+                  null
+              ))
+              .eternityInterval()
+              .filters(new SelectorDimFilter("user", "not_alice", null))
+              .columns((List<String>) null)
+              .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+              .build()
+    ).toTransformer();
+    final InputRow input = makeRow("user", "alice", "tags", List.of("a", "b"));
+    final List<InputRow> result = transformer.transformToList(input);
+    // Filter rejects the row (user != "not_alice"), so 0 rows — matching native scan query semantics
+    Assertions.assertEquals(0, result.size());
+  }
+
+  @Test
+  public void testTransformerWithoutScanTransform()
+  {
+    final TransformSpec spec = new TransformSpec(null, null);
+    final BaseTransformer transformer = spec.toTransformer();
+    Assertions.assertFalse(transformer.hasMultiRowTransform());
+    Assertions.assertTrue(transformer instanceof Transformer);
+
+    final InputRow input = makeRow("user", "alice");
+    final List<InputRow> result = transformer.transformToList(input);
+    Assertions.assertEquals(1, result.size());
+  }
+
+  @Test
+  public void testTransformerTransformToListWithNull()
+  {
+    final TransformSpec spec = new TransformSpec(null, null);
+    final BaseTransformer transformer = spec.toTransformer();
+    Assertions.assertTrue(transformer.transformToList(null).isEmpty());
+  }
+
+  // --- Serde tests ---
+
+  @Test
+  public void testScanTransformSpecSerde() throws Exception
+  {
+    final ScanTransformSpec spec = new ScanTransformSpec(
+        makeUnnestQuery("tags", "tag", ColumnType.STRING, new SelectorDimFilter("tag", "a", null))
+    );
+
+    final ObjectMapper jsonMapper = TestHelper.makeJsonMapper();
+    final String json = jsonMapper.writeValueAsString(spec);
+    final BaseTransformSpec deserialized = jsonMapper.readValue(json, BaseTransformSpec.class);
+    Assertions.assertTrue(deserialized instanceof ScanTransformSpec);
+    Assertions.assertEquals(spec, deserialized);
+  }
+
+  @Test
+  public void testUnnestPreservesNonDimensionEventFields()
+  {
+    // Simulates a fixed-dimensions ingestion with a metric: `bytes_sent` is in the raw event map
+    // but excluded from getDimensions() because DataSchema added it to dimensionExclusions.
+    // The expanded rows must still carry `bytes_sent` so downstream aggregators can read it, but must
+    // NOT promote it to a dimension — IncrementalIndex treats getDimensions() as authoritative and
+    // would otherwise auto-discover/store the metric source field as a dimension.
+    final LinkedHashMap<String, Object> event = new LinkedHashMap<>();
+    event.put("user", "alice");
+    event.put("tags", List.of("a", "b"));
+    event.put("bytes_sent", 1024L);
+    final InputRow input = new MapBasedInputRow(TIMESTAMP, List.of("user", "tags"), event);
+
+    final BaseTransformer transformer = makeTransformer(makeUnnestQuery("tags", "tag"));
+    final List<InputRow> result = transformer.transformToList(input);
+
+    Assertions.assertEquals(2, result.size());
+    for (final InputRow row : result) {
+      Assertions.assertEquals(1024L, row.getRaw("bytes_sent"));
+      Assertions.assertEquals("alice", row.getRaw("user"));
+      Assertions.assertFalse(
+          row.getDimensions().contains("bytes_sent"),
+          "metric source field must not be promoted to a dimension"
+      );
+      Assertions.assertTrue(row.getDimensions().contains("user"));
+      Assertions.assertTrue(row.getDimensions().contains("tag"));
+    }
+    Assertions.assertEquals("a", result.get(0).getRaw("tag"));
+    Assertions.assertEquals("b", result.get(1).getRaw("tag"));
+  }
+
+  @Test
+  public void testUnnestDoesNotDiscoverMetricSourceFieldAsDimension()
+  {
+    // Same scenario as above, but with multiple metric source fields (bytes_sent, latency_ms) that
+    // are never referenced by dimensions, virtual columns, or unnest output. None of them should
+    // appear in the expanded rows' dimensions.
+    final LinkedHashMap<String, Object> event = new LinkedHashMap<>();
+    event.put("host", "web-01");
+    event.put("tags", List.of("x", "y", "z"));
+    event.put("bytes_sent", 2048L);
+    event.put("latency_ms", 42L);
+    final InputRow input = new MapBasedInputRow(TIMESTAMP, List.of("host", "tags"), event);
+
+    final BaseTransformer transformer = makeTransformer(makeUnnestQuery("tags", "tag"));
+    final List<InputRow> result = transformer.transformToList(input);
+
+    Assertions.assertEquals(3, result.size());
+    for (final InputRow row : result) {
+      Assertions.assertEquals(2048L, row.getRaw("bytes_sent"));
+      Assertions.assertEquals(42L, row.getRaw("latency_ms"));
+      Assertions.assertEquals(List.of("host", "tags", "tag"), row.getDimensions());
+      Assertions.assertFalse(row.getDimensions().contains("bytes_sent"));
+      Assertions.assertFalse(row.getDimensions().contains("latency_ms"));
+    }
+  }
+
+  @Test
+  public void testGeneratedVirtualColumnOutputExcludedFromDimensions()
+  {
+    // "rate" is a virtual column consumed only by an aggregator, so DataSchema would put it in
+    // dimensionExclusions. Since it's generated by the scan query (not a raw event field), it can only
+    // be kept out of the dimension list if ScanTransformer is told about the exclusion explicitly.
+    final ScanQuery query = Druids.newScanQueryBuilder()
+                                   .dataSource(new TableDataSource("__input__"))
+                                   .virtualColumns(new ExpressionVirtualColumn(
+                                       "rate",
+                                       "\"total\" / 2",
+                                       ColumnType.LONG,
+                                       ExprMacroTable.nil()
+                                   ))
+                                   .eternityInterval()
+                                   .columns((List<String>) null)
+                                   .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+                                   .build();
+
+    final BaseTransformer transformer = new ScanTransformSpec(query).toTransformer(Set.of("rate"));
+    final InputRow input = makeRow("user", "alice", "total", 10L);
+
+    final List<InputRow> result = transformer.transformToList(input);
+    Assertions.assertEquals(1, result.size());
+    Assertions.assertEquals(5L, result.get(0).getRaw("rate"));
+    Assertions.assertFalse(
+        result.get(0).getDimensions().contains("rate"),
+        "metric-only virtual column output must not be promoted to a dimension"
+    );
+    Assertions.assertTrue(result.get(0).getDimensions().contains("user"));
+    Assertions.assertTrue(result.get(0).getDimensions().contains("total"));
+  }
+
+  @Test
+  public void testGeneratedVirtualColumnOutputPromotedToDimensionWithoutExclusions()
+  {
+    // Same query as above, but via the no-arg toTransformer() (no dimensionExclusions supplied).
+    // Without exclusion info, "rate" is promoted to a dimension — this documents the pre-existing behavior.
+    final ScanQuery query = Druids.newScanQueryBuilder()
+                                   .dataSource(new TableDataSource("__input__"))
+                                   .virtualColumns(new ExpressionVirtualColumn(
+                                       "rate",
+                                       "\"total\" / 2",
+                                       ColumnType.LONG,
+                                       ExprMacroTable.nil()
+                                   ))
+                                   .eternityInterval()
+                                   .columns((List<String>) null)
+                                   .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+                                   .build();
+
+    final BaseTransformer transformer = new ScanTransformSpec(query).toTransformer();
+    final InputRow input = makeRow("user", "alice", "total", 10L);
+
+    final List<InputRow> result = transformer.transformToList(input);
+    Assertions.assertEquals(1, result.size());
+    Assertions.assertTrue(result.get(0).getDimensions().contains("rate"));
+  }
+
+  @Test
+  public void testListBasedInputRowPreservesNonDimensionFieldsThroughUnnest()
+  {
+    // CSV/TSV/delimited ingestion produces ListBasedInputRow, not MapBasedInputRow. A metric-only field
+    // (bytes_sent) must still be carried into the expanded rows' event maps, same as for MapBasedInputRow.
+    final RowSignature signature = RowSignature.builder()
+                                                .add("user", ColumnType.STRING)
+                                                .add("tags", ColumnType.STRING_ARRAY)
+                                                .add("bytes_sent", ColumnType.LONG)
+                                                .build();
+    final InputRow input = new ListBasedInputRow(
+        signature,
+        DateTimes.utc(TIMESTAMP),
+        List.of("user", "tags"),
+        List.of("alice", List.of("a", "b"), 1024L)
+    );
+
+    final BaseTransformer transformer = makeTransformer(makeUnnestQuery("tags", "tag"));
+    final List<InputRow> result = transformer.transformToList(input);
+
+    Assertions.assertEquals(2, result.size());
+    for (final InputRow row : result) {
+      Assertions.assertEquals(1024L, row.getRaw("bytes_sent"));
+      Assertions.assertEquals("alice", row.getRaw("user"));
+      Assertions.assertFalse(
+          row.getDimensions().contains("bytes_sent"),
+          "metric source field must not be promoted to a dimension for list-backed rows either"
+      );
+    }
+    Assertions.assertEquals("a", result.get(0).getRaw("tag"));
+    Assertions.assertEquals("b", result.get(1).getRaw("tag"));
+  }
+
+  @Test
+  public void testUnsupportedInputRowTypeThrowsDefensiveException()
+  {
+    // Extension InputRow implementations (e.g. DeltaInputRow from druid-deltalake-extensions) implement
+    // InputRow directly rather than extending MapBasedInputRow/ListBasedInputRow, and have no generic
+    // Map-shaped view of their raw fields. ScanTransformer has no way to preserve non-dimension event
+    // fields (e.g. metrics) for such rows, so it must fail loudly instead of silently dropping them.
+    final InputRow input = new OpaqueInputRow(makeRow("user", "alice", "tags", List.of("a", "b")));
+    final BaseTransformer transformer = makeTransformer(makeUnnestQuery("tags", "tag"));
+
+    DruidExceptionMatcher.defensive().expectMessageContains(
+        "ScanTransformer does not support input rows of type"
+    ).assertThrowsAndMatches(() -> transformer.transformToList(input));
+  }
+
+  /**
+   * A minimal {@link InputRow} that delegates to another row without extending
+   * {@link MapBasedInputRow} or {@link ListBasedInputRow} — simulates an extension-provided row type
+   * such as {@code DeltaInputRow}, which has no generic Map-shaped view of its raw fields.
+   */
+  private static class OpaqueInputRow implements InputRow

Review Comment:
   ## CodeQL / Inconsistent compareTo
   
   This class declares [compareTo](1) but inherits equals; the two could be inconsistent.
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/11999)



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "FrankChen021 (via GitHub)" <gi...@apache.org>.
FrankChen021 commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r4071755616


##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,339 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.ListBasedInputRow;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.error.DruidException;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.ColumnValueSelector;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row is dropped. This matches native Druid UNNEST / CROSS JOIN semantics where
+ * null or empty arrays produce zero rows.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  // Field names that must never be promoted to a dimension, regardless of whether they show up in this
+  // scan query's result columns. See resolveDimensionColumns() for why this can't be derived locally.
+  private final Set<String> dimensionExclusions;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery, final Set<String> dimensionExclusions)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+    this.dimensionExclusions = dimensionExclusions;
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()
+                                                           .setInterval(query.getSingleInterval())
+                                                           .setFilter(Filters.toFilter(query.getFilter()))
+                                                           .setVirtualColumns(query.getVirtualColumns())
+                                                           .build();
+
+    this.baseCursorFactory = new SettableRowCursorFactory(broadSignature);
+    final SegmentMapFunction segmentMapFunction = query.getDataSource().createSegmentMapFunction(query);
+    final Segment mappedSegment = segmentMapFunction.apply(Optional.of(new CursorFactorySegment(baseCursorFactory)))
+                                                    .orElseThrow(() -> new ISE("SegmentMapFunction returned empty"));
+    final CursorFactory mappedCursorFactory = mappedSegment.as(CursorFactory.class);
+    this.cursorHolder = mappedCursorFactory.makeCursorHolder(cursorBuildSpec);
+  }
+
+  @Override
+  public boolean hasMultiRowTransform()
+  {
+    return true;
+  }
+
+  @Override
+  @Nullable
+  public InputRow transform(@Nullable final InputRow row)
+  {
+    throw new UnsupportedOperationException(
+        "ScanTransformer does not support single-row transform; use transformToList()"
+    );
+  }
+
+  @Override
+  public List<InputRow> transformToList(@Nullable final InputRow row)
+  {
+    if (row == null) {
+      return List.of();
+    }
+
+    return process(row);
+  }
+
+  @Override
+  @Nullable
+  public InputRowListPlusRawValues transform(@Nullable final InputRowListPlusRawValues row)
+  {
+    if (row == null || row.getInputRows() == null) {
+      return row;
+    }
+
+    final List<InputRow> inputRows = row.getInputRows();
+    final List<Map<String, Object>> inputRawValues = row.getRawValuesList();
+    final List<InputRow> outputRows = new ArrayList<>();
+    final List<Map<String, Object>> outputRawValues = inputRawValues == null ? null : new ArrayList<>();
+
+    for (int i = 0; i < inputRows.size(); i++) {
+      final List<InputRow> expandedRows = transformToList(inputRows.get(i));
+      outputRows.addAll(expandedRows);
+      if (outputRawValues != null) {
+        for (int j = 0; j < expandedRows.size(); j++) {
+          outputRawValues.add(inputRawValues.get(i));
+        }
+      }
+    }
+
+    return InputRowListPlusRawValues.ofList(outputRawValues, outputRows, row.getParseException());
+  }
+
+  @Override
+  public void close() throws IOException
+  {
+    cursorHolder.close();
+  }
+
+  private List<InputRow> process(final InputRow inputRow)
+  {
+    baseCursorFactory.set(inputRow);
+
+    if (cursor == null) {
+      cursor = cursorHolder.asCursor();
+    } else {
+      cursor.reset();
+    }
+
+    if (cursor == null || cursor.isDone()) {
+      return List.of();
+    }
+
+    final Set<String> nonDimensionEventFields = resolveNonDimensionEventFields(inputRow);
+    final List<String> columns = resolveColumnsForRow(inputRow, nonDimensionEventFields);
+    final List<String> dimensionColumns = resolveDimensionColumns(inputRow, columns, nonDimensionEventFields);
+    final ColumnSelectorFactory selectorFactory = cursor.getColumnSelectorFactory();
+
+    // Selectors are lazy views over the cursor's current position — create them once per column
+    // here, then re-read via getObject() as the cursor advances, rather than reallocating a selector
+    // for every (output-row x column) pair.
+    final ColumnValueSelector<?>[] selectors = new ColumnValueSelector<?>[columns.size()];
+    for (int i = 0; i < columns.size(); i++) {
+      selectors[i] = selectorFactory.makeColumnValueSelector(columns.get(i));
+    }
+
+    // The query re-executes fresh for each input row (cursor reset above), so this row's own unnested
+    // expansion is the query's entire result set for this execution — offset/limit bound that set,
+    // the same way they'd bound any other scan query's result set. This is necessarily per input row
+    // rather than global across the ingestion job: there is no single ordered stream spanning rows
+    // (let alone across the parallel/rolling readers of a real ingestion job) for them to paginate.
+    final long offset = query.getScanRowsOffset();
+    final long limit = query.getScanRowsLimit();
+    long skipped = 0;
+    long emitted = 0;
+
+    final List<InputRow> result = new ArrayList<>();
+    while (!cursor.isDone() && emitted < limit) {
+      if (skipped < offset) {
+        skipped++;
+        cursor.advance();
+        continue;
+      }
+      final Map<String, Object> event = new LinkedHashMap<>();
+      for (int i = 0; i < columns.size(); i++) {
+        event.put(columns.get(i), selectors[i].getObject());
+      }
+      result.add(new MapBasedInputRow(inputRow.getTimestampFromEpoch(), dimensionColumns, event));
+      emitted++;
+      cursor.advance();
+    }
+
+    return result;
+  }
+
+  /**
+   * Returns the raw fields present on {@code inputRow} that are not in {@link InputRow#getDimensions()}
+   * — e.g. metric inputs that {@code DataSchema} added to dimensionExclusions. These must still be read
+   * into the expanded rows' event maps (for aggregators), but must not be promoted to dimensions.
+   *
+   * <p>Handles both {@link MapBasedInputRow} (JSON/Kafka-style ingestion) and {@link ListBasedInputRow}
+   * (CSV/TSV/delimited ingestion, via {@code DelimitedValueReader}) — both expose their raw field names
+   * via a {@code Map}-shaped view ({@code getEvent()} / {@code asMap()}). Any other {@link InputRow}
+   * implementation has no generic way to enumerate its raw fields; rather than silently dropping metric
+   * values for such rows, this throws so the gap is caught instead of surfacing as null/0 aggregations.
+   */
+  private static Set<String> resolveNonDimensionEventFields(final InputRow inputRow)
+  {
+    final Set<String> allFields;
+    if (inputRow instanceof MapBasedInputRow) {
+      allFields = ((MapBasedInputRow) inputRow).getEvent().keySet();
+    } else if (inputRow instanceof ListBasedInputRow) {
+      allFields = ((ListBasedInputRow) inputRow).asMap().keySet();
+    } else {
+      throw DruidException.defensive(
+          "ScanTransformer does not support input rows of type[%s]; only MapBasedInputRow and "
+          + "ListBasedInputRow are supported",
+          inputRow.getClass().getName()
+      );
+    }
+    final Set<String> nonDimensionFields = new LinkedHashSet<>(allFields);
+    nonDimensionFields.removeAll(inputRow.getDimensions());
+    return nonDimensionFields;
+  }
+
+  private List<String> resolveColumnsForRow(final InputRow inputRow, final Set<String> nonDimensionEventFields)
+  {
+    final Set<String> columns = new LinkedHashSet<>();

Review Comment:
   P2 [P2] Honor ScanQuery.columns projection
   
   **Finding:** ScanTransformSpec accepts an embedded ScanQuery, whose columns property is the documented projection, but resolveColumnsForRow unconditionally adds every input dimension, every non-dimension event field, every query virtual column, and every unnest output. A query with columns: ["tag"] therefore still emits fields such as user, tags, and unrelated metrics, silently diverging from ScanQuery semantics and potentially storing fields the query explicitly excluded.
   
   **Suggestion:** Apply query.getColumns() when constructing the output column set, while explicitly retaining any raw fields that ingestion still requires for filters or aggregators, or reject non-empty projections until that distinction is implemented. Add coverage for a non-empty columns list.



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "FrankChen021 (via GitHub)" <gi...@apache.org>.
FrankChen021 commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r3979511840


##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,317 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.ListBasedInputRow;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.ColumnValueSelector;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row is dropped. This matches native Druid UNNEST / CROSS JOIN semantics where
+ * null or empty arrays produce zero rows.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  // Field names that must never be promoted to a dimension, regardless of whether they show up in this
+  // scan query's result columns. See resolveDimensionColumns() for why this can't be derived locally.
+  private final Set<String> dimensionExclusions;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery, final Set<String> dimensionExclusions)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+    this.dimensionExclusions = dimensionExclusions;
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()
+                                                           .setInterval(query.getSingleInterval())
+                                                           .setFilter(Filters.toFilter(query.getFilter()))
+                                                           .setVirtualColumns(query.getVirtualColumns())
+                                                           .build();
+
+    this.baseCursorFactory = new SettableRowCursorFactory(broadSignature);
+    final SegmentMapFunction segmentMapFunction = query.getDataSource().createSegmentMapFunction(query);
+    final Segment mappedSegment = segmentMapFunction.apply(Optional.of(new CursorFactorySegment(baseCursorFactory)))
+                                                    .orElseThrow(() -> new ISE("SegmentMapFunction returned empty"));
+    final CursorFactory mappedCursorFactory = mappedSegment.as(CursorFactory.class);
+    this.cursorHolder = mappedCursorFactory.makeCursorHolder(cursorBuildSpec);
+  }
+
+  @Override
+  public boolean hasMultiRowTransform()
+  {
+    return true;
+  }
+
+  @Override
+  @Nullable
+  public InputRow transform(@Nullable final InputRow row)
+  {
+    throw new UnsupportedOperationException(
+        "ScanTransformer does not support single-row transform; use transformToList()"
+    );
+  }
+
+  @Override
+  public List<InputRow> transformToList(@Nullable final InputRow row)
+  {
+    if (row == null) {
+      return List.of();
+    }
+
+    return process(row);
+  }
+
+  @Override
+  @Nullable
+  public InputRowListPlusRawValues transform(@Nullable final InputRowListPlusRawValues row)
+  {
+    if (row == null || row.getInputRows() == null) {
+      return row;
+    }
+
+    final List<InputRow> inputRows = row.getInputRows();
+    final List<Map<String, Object>> inputRawValues = row.getRawValuesList();
+    final List<InputRow> outputRows = new ArrayList<>();
+    final List<Map<String, Object>> outputRawValues = inputRawValues == null ? null : new ArrayList<>();
+
+    for (int i = 0; i < inputRows.size(); i++) {
+      final List<InputRow> expandedRows = transformToList(inputRows.get(i));
+      outputRows.addAll(expandedRows);
+      if (outputRawValues != null) {
+        for (int j = 0; j < expandedRows.size(); j++) {
+          outputRawValues.add(inputRawValues.get(i));
+        }
+      }
+    }
+
+    return InputRowListPlusRawValues.ofList(outputRawValues, outputRows, row.getParseException());
+  }
+
+  @Override
+  public void close() throws IOException
+  {
+    cursorHolder.close();
+  }
+
+  private List<InputRow> process(final InputRow inputRow)
+  {
+    baseCursorFactory.set(inputRow);
+
+    if (cursor == null) {
+      cursor = cursorHolder.asCursor();
+    } else {
+      cursor.reset();
+    }
+
+    if (cursor == null || cursor.isDone()) {
+      return List.of();
+    }
+
+    final Set<String> nonDimensionEventFields = resolveNonDimensionEventFields(inputRow);
+    final List<String> columns = resolveColumnsForRow(inputRow, nonDimensionEventFields);
+    final List<String> dimensionColumns = resolveDimensionColumns(inputRow, columns, nonDimensionEventFields);
+    final ColumnSelectorFactory selectorFactory = cursor.getColumnSelectorFactory();
+
+    // Selectors are lazy views over the cursor's current position — create them once per column
+    // here, then re-read via getObject() as the cursor advances, rather than reallocating a selector
+    // for every (output-row x column) pair.
+    final ColumnValueSelector<?>[] selectors = new ColumnValueSelector<?>[columns.size()];
+    for (int i = 0; i < columns.size(); i++) {
+      selectors[i] = selectorFactory.makeColumnValueSelector(columns.get(i));
+    }
+
+    final List<InputRow> result = new ArrayList<>();
+    while (!cursor.isDone()) {
+      final Map<String, Object> event = new LinkedHashMap<>();
+      for (int i = 0; i < columns.size(); i++) {
+        event.put(columns.get(i), selectors[i].getObject());
+      }
+      result.add(new MapBasedInputRow(inputRow.getTimestampFromEpoch(), dimensionColumns, event));
+      cursor.advance();
+    }
+
+    return result;
+  }
+
+  /**
+   * Returns the raw fields present on {@code inputRow} that are not in {@link InputRow#getDimensions()}
+   * — e.g. metric inputs that {@code DataSchema} added to dimensionExclusions. These must still be read
+   * into the expanded rows' event maps (for aggregators), but must not be promoted to dimensions.
+   *
+   * <p>Handles both {@link MapBasedInputRow} (JSON/Kafka-style ingestion) and {@link ListBasedInputRow}
+   * (CSV/TSV/delimited ingestion, via {@code DelimitedValueReader}) — both expose their raw field names
+   * via a {@code Map}-shaped view ({@code getEvent()} / {@code asMap()}). Any other {@link InputRow}
+   * implementation has no generic way to enumerate its raw fields, so it falls back to an empty set.
+   */
+  private static Set<String> resolveNonDimensionEventFields(final InputRow inputRow)
+  {
+    final Set<String> allFields;
+    if (inputRow instanceof MapBasedInputRow) {
+      allFields = ((MapBasedInputRow) inputRow).getEvent().keySet();
+    } else if (inputRow instanceof ListBasedInputRow) {
+      allFields = ((ListBasedInputRow) inputRow).asMap().keySet();
+    } else {
+      return Set.of();

Review Comment:
   P2 Preserve metric fields for non-map input rows
   
   The new batch integration applies `ScanTransformSpec` to every `InputSourceReader`, but this fallback drops every raw field not listed in `getDimensions()` for any non-`MapBasedInputRow`/`ListBasedInputRow`. `DeltaInputSource` emits `DeltaInputRow`; with a metric source such as `bytes`, `ScanTransformer` therefore omits `bytes` from each expanded event and the aggregator reads null/0. Enumerate the required non-dimension fields (or reject unsupported row types) so batch inputs retain metric values.



##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,317 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.ListBasedInputRow;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.ColumnValueSelector;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row is dropped. This matches native Druid UNNEST / CROSS JOIN semantics where
+ * null or empty arrays produce zero rows.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  // Field names that must never be promoted to a dimension, regardless of whether they show up in this
+  // scan query's result columns. See resolveDimensionColumns() for why this can't be derived locally.
+  private final Set<String> dimensionExclusions;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery, final Set<String> dimensionExclusions)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+    this.dimensionExclusions = dimensionExclusions;
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()
+                                                           .setInterval(query.getSingleInterval())
+                                                           .setFilter(Filters.toFilter(query.getFilter()))
+                                                           .setVirtualColumns(query.getVirtualColumns())
+                                                           .build();
+
+    this.baseCursorFactory = new SettableRowCursorFactory(broadSignature);
+    final SegmentMapFunction segmentMapFunction = query.getDataSource().createSegmentMapFunction(query);
+    final Segment mappedSegment = segmentMapFunction.apply(Optional.of(new CursorFactorySegment(baseCursorFactory)))
+                                                    .orElseThrow(() -> new ISE("SegmentMapFunction returned empty"));
+    final CursorFactory mappedCursorFactory = mappedSegment.as(CursorFactory.class);
+    this.cursorHolder = mappedCursorFactory.makeCursorHolder(cursorBuildSpec);
+  }
+
+  @Override
+  public boolean hasMultiRowTransform()
+  {
+    return true;
+  }
+
+  @Override
+  @Nullable
+  public InputRow transform(@Nullable final InputRow row)
+  {
+    throw new UnsupportedOperationException(
+        "ScanTransformer does not support single-row transform; use transformToList()"
+    );
+  }
+
+  @Override
+  public List<InputRow> transformToList(@Nullable final InputRow row)
+  {
+    if (row == null) {
+      return List.of();
+    }
+
+    return process(row);
+  }
+
+  @Override
+  @Nullable
+  public InputRowListPlusRawValues transform(@Nullable final InputRowListPlusRawValues row)
+  {
+    if (row == null || row.getInputRows() == null) {
+      return row;
+    }
+
+    final List<InputRow> inputRows = row.getInputRows();
+    final List<Map<String, Object>> inputRawValues = row.getRawValuesList();
+    final List<InputRow> outputRows = new ArrayList<>();
+    final List<Map<String, Object>> outputRawValues = inputRawValues == null ? null : new ArrayList<>();
+
+    for (int i = 0; i < inputRows.size(); i++) {
+      final List<InputRow> expandedRows = transformToList(inputRows.get(i));
+      outputRows.addAll(expandedRows);
+      if (outputRawValues != null) {
+        for (int j = 0; j < expandedRows.size(); j++) {
+          outputRawValues.add(inputRawValues.get(i));
+        }
+      }
+    }
+
+    return InputRowListPlusRawValues.ofList(outputRawValues, outputRows, row.getParseException());
+  }
+
+  @Override
+  public void close() throws IOException
+  {
+    cursorHolder.close();
+  }
+
+  private List<InputRow> process(final InputRow inputRow)
+  {
+    baseCursorFactory.set(inputRow);
+
+    if (cursor == null) {
+      cursor = cursorHolder.asCursor();
+    } else {
+      cursor.reset();
+    }
+
+    if (cursor == null || cursor.isDone()) {
+      return List.of();
+    }
+
+    final Set<String> nonDimensionEventFields = resolveNonDimensionEventFields(inputRow);
+    final List<String> columns = resolveColumnsForRow(inputRow, nonDimensionEventFields);
+    final List<String> dimensionColumns = resolveDimensionColumns(inputRow, columns, nonDimensionEventFields);
+    final ColumnSelectorFactory selectorFactory = cursor.getColumnSelectorFactory();
+
+    // Selectors are lazy views over the cursor's current position — create them once per column
+    // here, then re-read via getObject() as the cursor advances, rather than reallocating a selector
+    // for every (output-row x column) pair.
+    final ColumnValueSelector<?>[] selectors = new ColumnValueSelector<?>[columns.size()];
+    for (int i = 0; i < columns.size(); i++) {
+      selectors[i] = selectorFactory.makeColumnValueSelector(columns.get(i));
+    }
+
+    final List<InputRow> result = new ArrayList<>();
+    while (!cursor.isDone()) {

Review Comment:
   P2 Apply ScanQuery pagination during expansion
   
   `ScanTransformSpec` accepts a full `ScanQuery`, but this loop (and `SettableRowCursorFactory`) never uses `getScanRowsOffset()` or `getScanRowsLimit()`. Since the normal scan query toolchest applies those outside `ScanQueryEngine`, an embedded query such as `limit: 1` on a row with three unnested elements still emits all three rows into ingestion. Apply the query's offset/limit here, or reject non-default pagination so valid scan-query fields cannot silently change meaning.



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "abhishekrb19 (via GitHub)" <gi...@apache.org>.
abhishekrb19 commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r4084471300


##########
benchmarks/src/test/java/org/apache/druid/benchmark/TransformSpecBenchmark.java:
##########
@@ -0,0 +1,229 @@
+/*
+ * 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.benchmark;
+
+import com.google.common.collect.ImmutableList;
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.Druids;
+import org.apache.druid.query.TableDataSource;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.expression.TestExprMacroTable;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.transform.BaseTransformer;
+import org.apache.druid.segment.transform.ExpressionTransform;
+import org.apache.druid.segment.transform.ScanTransformSpec;
+import org.apache.druid.segment.transform.TransformSpec;
+import org.apache.druid.segment.virtual.ExpressionVirtualColumn;
+import org.apache.druid.testing.InitializedNullHandlingTest;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OperationsPerInvocation;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Warmup;
+import org.openjdk.jmh.infra.Blackhole;
+import org.openjdk.jmh.runner.Runner;
+import org.openjdk.jmh.runner.RunnerException;
+import org.openjdk.jmh.runner.options.Options;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Measures per-row throughput of the ingestion-time transform pipeline for the three shapes
+ * streaming ingestion actually hits:
+ *   NONE              — TransformSpec.NONE, baseline overhead of the transform wrapper.
+ *   EXPRESSION        — TransformSpec with a single expression transform (upper(user)).
+ *   SCAN_PASSTHROUGH  — ScanTransformSpec with no unnest (scan-query baseline over a 1-row cursor).
+ *   SCAN_VC           — ScanTransformSpec with one scan-query virtual column (upper(user)), equivalent
+ *                       work to EXPRESSION but via the scan pipeline.
+ *   SCAN_UNNEST       — ScanTransformSpec that unnests an array of {@code unnestArraySize} elements.
+ *
+ * Output is nanoseconds per input row. For SCAN_UNNEST, use {@link #totalOutputRowsPerInput()} to
+ * translate to ns/output-row.
+ *
+ * The input row is a {@link MapBasedInputRow} matching what Kafka JSON ingestion produces.
+ */
+@State(Scope.Benchmark)
+@BenchmarkMode(Mode.AverageTime)

Review Comment:
   >Finding: The class imports JMH's org.openjdk.jmh.annotations.Mode but also declares a nested enum named Mode. In @BenchmarkMode(Mode.AverageTime), the nested enum wins name resolution and has no AverageTime constant, so this new benchmark source does not compile and blocks the benchmarks module/build.
   
   I just ran the benchmark locally and CI succeeded, so the code actually compiles fine. The LLM probably got tripped up by a shadowing rule.



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r3145112307


##########
processing/src/test/java/org/apache/druid/segment/transform/ScanTransformTest.java:
##########
@@ -0,0 +1,460 @@
+/*
+ * 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.segment.transform;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.expression.TestExprMacroTable;
+import org.apache.druid.query.filter.SelectorDimFilter;
+import org.apache.druid.segment.TestHelper;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.virtual.ExpressionVirtualColumn;
+import org.apache.druid.testing.InitializedNullHandlingTest;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public class ScanTransformTest extends InitializedNullHandlingTest
+{
+  private static final long TIMESTAMP = DateTimes.of("2024-01-01").getMillis();
+
+  private static InputRow makeRow(Object... kvPairs)
+  {
+    final java.util.LinkedHashMap<String, Object> event = new java.util.LinkedHashMap<>();
+    final List<String> dimensions = new ArrayList<>();
+    for (int i = 0; i < kvPairs.length; i += 2) {
+      final String key = (String) kvPairs[i];
+      event.put(key, kvPairs[i + 1]);

Review Comment:
   ## CodeQL / Array index out of bounds
   
   This array access might be out of bounds, as the index might be equal to the array length.
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/11140)



##########
embedded-tests/src/test/java/org/apache/druid/testing/embedded/indexing/KafkaScanTransformTest.java:
##########
@@ -0,0 +1,358 @@
+/*
+ * 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.testing.embedded.indexing;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.collect.ImmutableList;
+import org.apache.druid.data.input.impl.DimensionsSpec;
+import org.apache.druid.data.input.impl.TimestampSpec;
+import org.apache.druid.indexer.granularity.UniformGranularitySpec;
+import org.apache.druid.indexing.kafka.KafkaIndexTaskModule;
+import org.apache.druid.indexing.kafka.simulate.KafkaResource;
+import org.apache.druid.indexing.kafka.supervisor.KafkaSupervisorSpec;
+import org.apache.druid.indexing.kafka.supervisor.KafkaSupervisorSpecBuilder;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.common.granularity.Granularities;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.DruidMetrics;
+import org.apache.druid.segment.TestHelper;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.transform.ScanTransform;
+import org.apache.druid.segment.transform.TransformSpec;
+import org.apache.druid.segment.virtual.ExpressionVirtualColumn;
+import org.apache.druid.testing.embedded.EmbeddedBroker;
+import org.apache.druid.testing.embedded.EmbeddedClusterApis;
+import org.apache.druid.testing.embedded.EmbeddedCoordinator;
+import org.apache.druid.testing.embedded.EmbeddedDruidCluster;
+import org.apache.druid.testing.embedded.EmbeddedIndexer;
+import org.apache.druid.testing.embedded.EmbeddedOverlord;
+import org.apache.druid.testing.embedded.junit5.EmbeddedClusterTestBase;
+import org.joda.time.Period;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+/**
+ * Verifies ScanTransform unnests array columns during Kafka ingestion.
+ * Uses two scan transforms to unnest both "tags" (string array) and "services" (object array)
+ * into a single datasource, producing a cross join of tag x service for each input row.
+ */
+public class KafkaScanTransformTest extends EmbeddedClusterTestBase
+{
+  // alice: 2 tags x 2 services = 4, bob: 1 tag x 3 services = 3 = 7 unnested rows
+  // carol (null arrays) and dave (missing columns) each produce 1 passthrough row = 2
+  // total: 9
+  private static final int EXPECTED_ROWS = 9;
+
+  private final KafkaResource kafka = new KafkaResource();
+  private final EmbeddedBroker broker = new EmbeddedBroker();
+  private final EmbeddedIndexer indexer = new EmbeddedIndexer();
+  private final EmbeddedOverlord overlord = new EmbeddedOverlord();
+  private final EmbeddedCoordinator coordinator = new EmbeddedCoordinator();
+
+  private String topic;
+
+  @Override
+  public EmbeddedDruidCluster createCluster()
+  {
+    coordinator.addProperty("druid.manager.segments.useIncrementalCache", "always");
+
+    indexer.setServerMemory(300_000_000)
+           .addProperty("druid.segment.handoff.pollDuration", "PT0.1s")
+           .addProperty("druid.processing.numThreads", "2")
+           .addProperty("druid.worker.capacity", "2");
+
+    return EmbeddedDruidCluster
+        .withEmbeddedDerbyAndZookeeper()
+        .addExtension(KafkaIndexTaskModule.class)
+        .addResource(kafka)
+        .addCommonProperty("druid.monitoring.emissionPeriod", "PT0.1s")
+        .useLatchableEmitter()
+        .useDefaultTimeoutForLatchableEmitter(30)
+        .addServer(coordinator)
+        .addServer(overlord)
+        .addServer(broker)
+        .addServer(indexer);
+  }
+
+  @Override
+  protected void refreshDatasourceName()
+  {
+    // Do not refresh — datasource is set once in setupAll
+  }
+
+  @BeforeAll
+  void setupAll() throws JsonProcessingException
+  {
+    topic = EmbeddedClusterApis.createTestDatasourceName();
+    kafka.createTopicWithPartitions(topic, 1);
+
+    super.refreshDatasourceName();
+    submitSupervisor();
+    publishTestData();
+
+    indexer.latchableEmitter().waitForEventAggregate(
+        event -> event.hasMetricName("ingest/events/processed")
+                      .hasDimension(DruidMetrics.DATASOURCE, dataSource),
+        agg -> agg.hasSumAtLeast(EXPECTED_ROWS)
+    );
+  }
+
+  private void submitSupervisor()
+  {
+    final TransformSpec transformSpec = new TransformSpec(
+        null,
+        ImmutableList.of(
+            new ScanTransform(
+                "tag",
+                new ExpressionVirtualColumn("tag", "\"tags\"", ColumnType.STRING, ExprMacroTable.nil()),
+                null
+            ),
+            new ScanTransform(
+                "svc",
+                new ExpressionVirtualColumn("svc", "\"services\"", ColumnType.NESTED_DATA, ExprMacroTable.nil()),
+                null
+            )
+        )
+    );
+
+    final KafkaSupervisorSpec spec = new KafkaSupervisorSpecBuilder()
+        .withDataSchema(
+            schema -> schema
+                .withTimestamp(new TimestampSpec("__time", "auto", null))
+                .withGranularity(new UniformGranularitySpec(Granularities.DAY, null, null))
+                .withDimensions(DimensionsSpec.builder().useSchemaDiscovery(true).build())
+                .withTransform(transformSpec)
+        )
+        .withIoConfig(
+            ioConfig -> ioConfig
+                .withJsonInputFormat()
+                .withTaskCount(1)
+                .withTaskDuration(Period.hours(1))
+                .withConsumerProperties(kafka.consumerProperties())
+                .withStartDelay(Period.millis(10))
+                .withSupervisorRunPeriod(Period.millis(500))
+                .withUseEarliestSequenceNumber(true)
+                .withCompletionTimeout(Period.seconds(5))
+        )
+        .build(dataSource, topic);
+
+    Assertions.assertEquals(
+        dataSource,
+        cluster.callApi().postSupervisor(spec)
+    );
+  }
+
+  private void publishTestData() throws JsonProcessingException
+  {
+    // alice: 2 tags x 2 services = 4 rows
+    // bob: 1 tag x 3 services = 3 rows
+    // carol: null tags x null services => 1 passthrough row
+    // dave: missing tags & services columns => 1 passthrough row
+    // total: 9 rows
+    final List<Map<String, Object>> records = new ArrayList<>();
+    records.add(Map.of(
+        "__time", "2024-01-01T00:00:00Z",
+        "user", "alice",
+        "tags", List.of("sports", "news"),
+        "services", List.of(
+            Map.of("type", "web", "dc", "us-east1"),
+            Map.of("type", "api", "dc", "us-west2")
+        )
+    ));
+    records.add(Map.of(
+        "__time", "2024-01-01T00:01:00Z",
+        "user", "bob",
+        "tags", List.of("music"),
+        "services", List.of(
+            Map.of("type", "cdn", "dc", "eu-west1"),
+            Map.of("type", "cache", "dc", "eu-west1"),
+            Map.of("type", "db", "dc", "us-east1")
+        )
+    ));
+
+    // carol: explicit null values for both array columns
+    final HashMap<String, Object> carolRecord = new HashMap<>();
+    carolRecord.put("__time", "2024-01-01T00:02:00Z");
+    carolRecord.put("user", "carol");
+    carolRecord.put("tags", null);
+    carolRecord.put("services", null);
+    records.add(carolRecord);
+
+    // dave: columns not present at all
+    records.add(Map.of(
+        "__time", "2024-01-01T00:03:00Z",
+        "user", "dave"
+    ));
+
+    final List<byte[]> recordBytes = new ArrayList<>();
+    for (Map<String, Object> record : records) {
+      recordBytes.add(TestHelper.JSON_MAPPER.writeValueAsBytes(record));
+    }
+    kafka.publishRecordsToTopic(topic, recordBytes);
+  }
+
+  @Test
+  @Timeout(60)
+  public void test_countRows()
+  {
+    final long count = Long.parseLong(cluster.runSql(
+        StringUtils.format("SELECT COUNT(*) FROM \"%s\"", dataSource)
+    ).trim());

Review Comment:
   ## CodeQL / Missing catch of NumberFormatException
   
   Potential uncaught 'java.lang.NumberFormatException'.
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/11141)



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "abhishekrb19 (via GitHub)" <gi...@apache.org>.
abhishekrb19 commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r3962722313


##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row is dropped. This matches native Druid UNNEST / CROSS JOIN semantics where
+ * null or empty arrays produce zero rows.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()
+                                                           .setInterval(query.getSingleInterval())
+                                                           .setFilter(Filters.toFilter(query.getFilter()))
+                                                           .setVirtualColumns(query.getVirtualColumns())
+                                                           .build();
+
+    this.baseCursorFactory = new SettableRowCursorFactory(broadSignature);
+    final SegmentMapFunction segmentMapFunction = query.getDataSource().createSegmentMapFunction(query);
+    final Segment mappedSegment = segmentMapFunction.apply(Optional.of(new CursorFactorySegment(baseCursorFactory)))
+                                                    .orElseThrow(() -> new ISE("SegmentMapFunction returned empty"));
+    final CursorFactory mappedCursorFactory = mappedSegment.as(CursorFactory.class);
+    this.cursorHolder = mappedCursorFactory.makeCursorHolder(cursorBuildSpec);
+  }
+
+  @Override
+  public boolean hasMultiRowTransform()
+  {
+    return true;
+  }
+
+  @Override
+  @Nullable
+  public InputRow transform(@Nullable final InputRow row)
+  {
+    throw new UnsupportedOperationException(
+        "ScanTransformer does not support single-row transform; use transformToList()"
+    );
+  }
+
+  @Override
+  public List<InputRow> transformToList(@Nullable final InputRow row)
+  {
+    if (row == null) {
+      return List.of();
+    }
+
+    return process(row);
+  }
+
+  @Override
+  @Nullable
+  public InputRowListPlusRawValues transform(@Nullable final InputRowListPlusRawValues row)
+  {
+    if (row == null || row.getInputRows() == null) {
+      return row;
+    }
+
+    final List<InputRow> inputRows = row.getInputRows();
+    final List<Map<String, Object>> inputRawValues = row.getRawValuesList();
+    final List<InputRow> outputRows = new ArrayList<>();
+    final List<Map<String, Object>> outputRawValues = inputRawValues == null ? null : new ArrayList<>();
+
+    for (int i = 0; i < inputRows.size(); i++) {
+      final List<InputRow> expandedRows = transformToList(inputRows.get(i));
+      outputRows.addAll(expandedRows);
+      if (outputRawValues != null) {
+        for (int j = 0; j < expandedRows.size(); j++) {
+          outputRawValues.add(inputRawValues.get(i));
+        }
+      }
+    }
+
+    return InputRowListPlusRawValues.ofList(outputRawValues, outputRows, row.getParseException());
+  }
+
+  @Override
+  public void close() throws IOException
+  {
+    cursorHolder.close();
+  }
+
+  private List<InputRow> process(final InputRow inputRow)
+  {
+    baseCursorFactory.set(inputRow);
+
+    if (cursor == null) {
+      cursor = cursorHolder.asCursor();
+    } else {
+      cursor.reset();
+    }
+
+    if (cursor == null || cursor.isDone()) {
+      return List.of();
+    }
+
+    final List<String> columns = resolveColumnsForRow(inputRow);
+    final List<String> dimensionColumns = resolveDimensionColumns(inputRow, columns);
+    final ColumnSelectorFactory selectorFactory = cursor.getColumnSelectorFactory();
+
+    final List<InputRow> result = new ArrayList<>();
+    while (!cursor.isDone()) {
+      final Map<String, Object> event = new LinkedHashMap<>();
+      for (final String col : columns) {
+        event.put(col, selectorFactory.makeColumnValueSelector(col).getObject());
+      }
+      result.add(new MapBasedInputRow(inputRow.getTimestampFromEpoch(), dimensionColumns, event));
+      cursor.advance();
+    }
+
+    return result;
+  }
+
+  private List<String> resolveColumnsForRow(final InputRow inputRow)
+  {
+    final Set<String> columns = new LinkedHashSet<>();
+    columns.add(ColumnHolder.TIME_COLUMN_NAME);
+    columns.addAll(inputRow.getDimensions());
+    // Include raw event fields that aren't in getDimensions() — e.g. metric inputs that DataSchema added
+    // to dimensionExclusions. Without this, fixed-dimension ingestions with metrics would read null for
+    // their metric source fields in expanded rows.
+    if (inputRow instanceof MapBasedInputRow) {
+      columns.addAll(((MapBasedInputRow) inputRow).getEvent().keySet());

Review Comment:
   Addressed in the latest patch.



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "FrankChen021 (via GitHub)" <gi...@apache.org>.
FrankChen021 commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r3154598898


##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,285 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row passes through with unnest output columns set to null and virtual columns still evaluated.
+ * This differs from {@link TransformSpec}'s filter behavior which drops the row entirely.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()
+                                                           .setInterval(query.getSingleInterval())
+                                                           .setFilter(Filters.toFilter(query.getFilter()))
+                                                           .setVirtualColumns(query.getVirtualColumns())
+                                                           .build();
+
+    this.baseCursorFactory = new SettableRowCursorFactory(broadSignature);
+    final SegmentMapFunction segmentMapFunction = query.getDataSource().createSegmentMapFunction(query);
+    final Segment mappedSegment = segmentMapFunction.apply(Optional.of(new CursorFactorySegment(baseCursorFactory)))
+                                                    .orElseThrow(() -> new ISE("SegmentMapFunction returned empty"));
+    final CursorFactory mappedCursorFactory = mappedSegment.as(CursorFactory.class);
+    this.cursorHolder = mappedCursorFactory.makeCursorHolder(cursorBuildSpec);
+  }
+
+  @Override
+  public boolean hasMultiRowTransform()
+  {
+    return true;
+  }
+
+  @Override
+  @Nullable
+  public InputRow transform(@Nullable final InputRow row)
+  {
+    throw new UnsupportedOperationException(
+        "ScanTransformer does not support single-row transform; use transformToList()"
+    );
+  }
+
+  @Override
+  public List<InputRow> transformToList(@Nullable final InputRow row)
+  {
+    if (row == null) {
+      return List.of();
+    }
+
+    return process(row);
+  }
+
+  @Override
+  @Nullable
+  public InputRowListPlusRawValues transform(@Nullable final InputRowListPlusRawValues row)
+  {
+    if (row == null || row.getInputRows() == null) {
+      return row;
+    }
+
+    final List<InputRow> inputRows = row.getInputRows();
+    final List<Map<String, Object>> inputRawValues = row.getRawValuesList();
+    final List<InputRow> outputRows = new ArrayList<>();
+    final List<Map<String, Object>> outputRawValues = inputRawValues == null ? null : new ArrayList<>();
+
+    for (int i = 0; i < inputRows.size(); i++) {
+      final List<InputRow> expandedRows = transformToList(inputRows.get(i));
+      outputRows.addAll(expandedRows);
+      if (outputRawValues != null) {
+        for (int j = 0; j < expandedRows.size(); j++) {
+          outputRawValues.add(inputRawValues.get(i));
+        }
+      }
+    }
+
+    return InputRowListPlusRawValues.ofList(outputRawValues, outputRows, row.getParseException());
+  }
+
+  @Override
+  public void close() throws IOException
+  {
+    cursorHolder.close();
+  }
+
+  private List<InputRow> process(final InputRow inputRow)
+  {
+    baseCursorFactory.set(inputRow);
+
+    if (cursor == null) {
+      cursor = cursorHolder.asCursor();
+    } else {
+      cursor.reset();
+    }
+
+    if (cursor == null || cursor.isDone()) {
+      return List.of(buildPassthroughRow(inputRow));
+    }
+
+    final List<String> columns = resolveColumnsForRow(inputRow);
+    final List<String> dimensionColumns = resolveDimensionColumns(inputRow, columns);
+    final ColumnSelectorFactory selectorFactory = cursor.getColumnSelectorFactory();
+
+    final List<InputRow> result = new ArrayList<>();
+    while (!cursor.isDone()) {
+      final Map<String, Object> event = new LinkedHashMap<>();
+      for (final String col : columns) {
+        event.put(col, selectorFactory.makeColumnValueSelector(col).getObject());
+      }
+      result.add(new MapBasedInputRow(inputRow.getTimestampFromEpoch(), dimensionColumns, event));
+      cursor.advance();
+    }
+
+    return result.isEmpty() ? List.of(buildPassthroughRow(inputRow)) : result;
+  }
+
+  private InputRow buildPassthroughRow(final InputRow inputRow)
+  {
+    final Set<String> unnestOutputColumns = new LinkedHashSet<>();
+    collectOutputColumnNames(query.getDataSource(), unnestOutputColumns);
+
+    final List<String> columns = resolveColumnsForRow(inputRow);
+    final List<String> dimensionColumns = resolveDimensionColumns(inputRow, columns);
+    final ColumnSelectorFactory factory = baseCursorFactory.getColumnSelectorFactory(query.getVirtualColumns());
+    final Map<String, Object> event = new LinkedHashMap<>();
+    for (final String col : columns) {
+      if (unnestOutputColumns.contains(col)) {
+        event.put(col, null);
+      } else {
+        event.put(col, factory.makeColumnValueSelector(col).getObject());
+      }
+    }
+    return new MapBasedInputRow(inputRow.getTimestampFromEpoch(), dimensionColumns, event);
+  }
+
+  private List<String> resolveColumnsForRow(final InputRow inputRow)
+  {
+    final Set<String> columns = new LinkedHashSet<>();

Review Comment:
   [P1] Preserve non-dimension raw columns in scan output
   
   resolveColumnsForRow only emits __time, inputRow.getDimensions(), scan virtual columns, and unnest output columns. In ingestion, fields used by metricsSpec are commonly excluded from dimensions, so after a scan transform expands a row those raw metric fields disappear from the MapBasedInputRow event and downstream aggregators read null/zero instead of the original value. The previous implementation explicitly included MapBasedInputRow event keys, and the incremental diff removes the test that covered this case. Include all raw event keys, where available, when constructing scan output rows.



##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,285 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row passes through with unnest output columns set to null and virtual columns still evaluated.
+ * This differs from {@link TransformSpec}'s filter behavior which drops the row entirely.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()
+                                                           .setInterval(query.getSingleInterval())
+                                                           .setFilter(Filters.toFilter(query.getFilter()))
+                                                           .setVirtualColumns(query.getVirtualColumns())
+                                                           .build();
+
+    this.baseCursorFactory = new SettableRowCursorFactory(broadSignature);
+    final SegmentMapFunction segmentMapFunction = query.getDataSource().createSegmentMapFunction(query);
+    final Segment mappedSegment = segmentMapFunction.apply(Optional.of(new CursorFactorySegment(baseCursorFactory)))
+                                                    .orElseThrow(() -> new ISE("SegmentMapFunction returned empty"));
+    final CursorFactory mappedCursorFactory = mappedSegment.as(CursorFactory.class);
+    this.cursorHolder = mappedCursorFactory.makeCursorHolder(cursorBuildSpec);
+  }
+
+  @Override
+  public boolean hasMultiRowTransform()
+  {
+    return true;
+  }
+
+  @Override
+  @Nullable
+  public InputRow transform(@Nullable final InputRow row)
+  {
+    throw new UnsupportedOperationException(
+        "ScanTransformer does not support single-row transform; use transformToList()"
+    );
+  }
+
+  @Override
+  public List<InputRow> transformToList(@Nullable final InputRow row)
+  {
+    if (row == null) {
+      return List.of();
+    }
+
+    return process(row);
+  }
+
+  @Override
+  @Nullable
+  public InputRowListPlusRawValues transform(@Nullable final InputRowListPlusRawValues row)
+  {
+    if (row == null || row.getInputRows() == null) {
+      return row;
+    }
+
+    final List<InputRow> inputRows = row.getInputRows();
+    final List<Map<String, Object>> inputRawValues = row.getRawValuesList();
+    final List<InputRow> outputRows = new ArrayList<>();
+    final List<Map<String, Object>> outputRawValues = inputRawValues == null ? null : new ArrayList<>();
+
+    for (int i = 0; i < inputRows.size(); i++) {
+      final List<InputRow> expandedRows = transformToList(inputRows.get(i));
+      outputRows.addAll(expandedRows);
+      if (outputRawValues != null) {
+        for (int j = 0; j < expandedRows.size(); j++) {
+          outputRawValues.add(inputRawValues.get(i));
+        }
+      }
+    }
+
+    return InputRowListPlusRawValues.ofList(outputRawValues, outputRows, row.getParseException());
+  }
+
+  @Override
+  public void close() throws IOException
+  {
+    cursorHolder.close();
+  }
+
+  private List<InputRow> process(final InputRow inputRow)
+  {
+    baseCursorFactory.set(inputRow);
+
+    if (cursor == null) {
+      cursor = cursorHolder.asCursor();
+    } else {
+      cursor.reset();
+    }
+
+    if (cursor == null || cursor.isDone()) {

Review Comment:
   [P2] Do not pass through rows rejected by scan filters
   
   When the scan cursor is done, the transformer always returns buildPassthroughRow(inputRow). That makes a scan query filter unable to drop rows: a row rejected by query.getFilter() is still ingested once with unnest outputs set to null, as the updated test now asserts. This diverges from normal TransformSpec filtering and from scan/unnest filtering semantics, and it inflates row counts for specs that use scan filters to exclude input or unnested rows. Distinguish empty/null unnest passthrough from filter rejection and return an empty list when the filter rejects the row.



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "FrankChen021 (via GitHub)" <gi...@apache.org>.
FrankChen021 commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r3969766358


##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,293 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.ColumnValueSelector;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row is dropped. This matches native Druid UNNEST / CROSS JOIN semantics where
+ * null or empty arrays produce zero rows.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()
+                                                           .setInterval(query.getSingleInterval())
+                                                           .setFilter(Filters.toFilter(query.getFilter()))
+                                                           .setVirtualColumns(query.getVirtualColumns())
+                                                           .build();
+
+    this.baseCursorFactory = new SettableRowCursorFactory(broadSignature);
+    final SegmentMapFunction segmentMapFunction = query.getDataSource().createSegmentMapFunction(query);
+    final Segment mappedSegment = segmentMapFunction.apply(Optional.of(new CursorFactorySegment(baseCursorFactory)))
+                                                    .orElseThrow(() -> new ISE("SegmentMapFunction returned empty"));
+    final CursorFactory mappedCursorFactory = mappedSegment.as(CursorFactory.class);
+    this.cursorHolder = mappedCursorFactory.makeCursorHolder(cursorBuildSpec);
+  }
+
+  @Override
+  public boolean hasMultiRowTransform()
+  {
+    return true;
+  }
+
+  @Override
+  @Nullable
+  public InputRow transform(@Nullable final InputRow row)
+  {
+    throw new UnsupportedOperationException(
+        "ScanTransformer does not support single-row transform; use transformToList()"
+    );
+  }
+
+  @Override
+  public List<InputRow> transformToList(@Nullable final InputRow row)
+  {
+    if (row == null) {
+      return List.of();
+    }
+
+    return process(row);
+  }
+
+  @Override
+  @Nullable
+  public InputRowListPlusRawValues transform(@Nullable final InputRowListPlusRawValues row)
+  {
+    if (row == null || row.getInputRows() == null) {
+      return row;
+    }
+
+    final List<InputRow> inputRows = row.getInputRows();
+    final List<Map<String, Object>> inputRawValues = row.getRawValuesList();
+    final List<InputRow> outputRows = new ArrayList<>();
+    final List<Map<String, Object>> outputRawValues = inputRawValues == null ? null : new ArrayList<>();
+
+    for (int i = 0; i < inputRows.size(); i++) {
+      final List<InputRow> expandedRows = transformToList(inputRows.get(i));
+      outputRows.addAll(expandedRows);
+      if (outputRawValues != null) {
+        for (int j = 0; j < expandedRows.size(); j++) {
+          outputRawValues.add(inputRawValues.get(i));
+        }
+      }
+    }
+
+    return InputRowListPlusRawValues.ofList(outputRawValues, outputRows, row.getParseException());
+  }
+
+  @Override
+  public void close() throws IOException
+  {
+    cursorHolder.close();
+  }
+
+  private List<InputRow> process(final InputRow inputRow)
+  {
+    baseCursorFactory.set(inputRow);
+
+    if (cursor == null) {
+      cursor = cursorHolder.asCursor();
+    } else {
+      cursor.reset();
+    }
+
+    if (cursor == null || cursor.isDone()) {
+      return List.of();
+    }
+
+    final Set<String> nonDimensionEventFields = resolveNonDimensionEventFields(inputRow);
+    final List<String> columns = resolveColumnsForRow(inputRow, nonDimensionEventFields);
+    final List<String> dimensionColumns = resolveDimensionColumns(inputRow, columns, nonDimensionEventFields);
+    final ColumnSelectorFactory selectorFactory = cursor.getColumnSelectorFactory();
+
+    // Selectors are lazy views over the cursor's current position — create them once per column
+    // here, then re-read via getObject() as the cursor advances, rather than reallocating a selector
+    // for every (output-row x column) pair.
+    final ColumnValueSelector<?>[] selectors = new ColumnValueSelector<?>[columns.size()];
+    for (int i = 0; i < columns.size(); i++) {
+      selectors[i] = selectorFactory.makeColumnValueSelector(columns.get(i));
+    }
+
+    final List<InputRow> result = new ArrayList<>();
+    while (!cursor.isDone()) {
+      final Map<String, Object> event = new LinkedHashMap<>();
+      for (int i = 0; i < columns.size(); i++) {
+        event.put(columns.get(i), selectors[i].getObject());
+      }
+      result.add(new MapBasedInputRow(inputRow.getTimestampFromEpoch(), dimensionColumns, event));
+      cursor.advance();
+    }
+
+    return result;
+  }
+
+  /**
+   * Returns the raw event fields present on {@code inputRow} that are not in {@link InputRow#getDimensions()}
+   * — e.g. metric inputs that {@code DataSchema} added to dimensionExclusions. These must still be read
+   * into the expanded rows' event maps (for aggregators), but must not be promoted to dimensions.
+   */
+  private static Set<String> resolveNonDimensionEventFields(final InputRow inputRow)
+  {
+    if (!(inputRow instanceof MapBasedInputRow)) {

Review Comment:
   P2 Preserve metric fields for list-backed rows
   
   This guard returns an empty set for every `ListBasedInputRow`, even though its `RowSignature` and data contain fields that `InputRow.getDimensions()` intentionally excludes, such as metric inputs from CSV or delimited ingestion. Since `ScanTransformSpec` is wired through the generic `DataSchema`/`InputSourceReader` path, a list-backed row with a metric field and scan expansion omits that field from the expanded event map; the aggregator then reads null/zero. Enumerate non-dimension fields from the list-backed row signature (or pass the input schema) as well as from `MapBasedInputRow`.



##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,293 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.ColumnValueSelector;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row is dropped. This matches native Druid UNNEST / CROSS JOIN semantics where
+ * null or empty arrays produce zero rows.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()
+                                                           .setInterval(query.getSingleInterval())
+                                                           .setFilter(Filters.toFilter(query.getFilter()))
+                                                           .setVirtualColumns(query.getVirtualColumns())
+                                                           .build();
+
+    this.baseCursorFactory = new SettableRowCursorFactory(broadSignature);
+    final SegmentMapFunction segmentMapFunction = query.getDataSource().createSegmentMapFunction(query);
+    final Segment mappedSegment = segmentMapFunction.apply(Optional.of(new CursorFactorySegment(baseCursorFactory)))
+                                                    .orElseThrow(() -> new ISE("SegmentMapFunction returned empty"));
+    final CursorFactory mappedCursorFactory = mappedSegment.as(CursorFactory.class);
+    this.cursorHolder = mappedCursorFactory.makeCursorHolder(cursorBuildSpec);
+  }
+
+  @Override
+  public boolean hasMultiRowTransform()
+  {
+    return true;
+  }
+
+  @Override
+  @Nullable
+  public InputRow transform(@Nullable final InputRow row)
+  {
+    throw new UnsupportedOperationException(
+        "ScanTransformer does not support single-row transform; use transformToList()"
+    );
+  }
+
+  @Override
+  public List<InputRow> transformToList(@Nullable final InputRow row)
+  {
+    if (row == null) {
+      return List.of();
+    }
+
+    return process(row);
+  }
+
+  @Override
+  @Nullable
+  public InputRowListPlusRawValues transform(@Nullable final InputRowListPlusRawValues row)
+  {
+    if (row == null || row.getInputRows() == null) {
+      return row;
+    }
+
+    final List<InputRow> inputRows = row.getInputRows();
+    final List<Map<String, Object>> inputRawValues = row.getRawValuesList();
+    final List<InputRow> outputRows = new ArrayList<>();
+    final List<Map<String, Object>> outputRawValues = inputRawValues == null ? null : new ArrayList<>();
+
+    for (int i = 0; i < inputRows.size(); i++) {
+      final List<InputRow> expandedRows = transformToList(inputRows.get(i));
+      outputRows.addAll(expandedRows);
+      if (outputRawValues != null) {
+        for (int j = 0; j < expandedRows.size(); j++) {
+          outputRawValues.add(inputRawValues.get(i));
+        }
+      }
+    }
+
+    return InputRowListPlusRawValues.ofList(outputRawValues, outputRows, row.getParseException());
+  }
+
+  @Override
+  public void close() throws IOException
+  {
+    cursorHolder.close();
+  }
+
+  private List<InputRow> process(final InputRow inputRow)
+  {
+    baseCursorFactory.set(inputRow);
+
+    if (cursor == null) {
+      cursor = cursorHolder.asCursor();
+    } else {
+      cursor.reset();
+    }
+
+    if (cursor == null || cursor.isDone()) {
+      return List.of();
+    }
+
+    final Set<String> nonDimensionEventFields = resolveNonDimensionEventFields(inputRow);
+    final List<String> columns = resolveColumnsForRow(inputRow, nonDimensionEventFields);
+    final List<String> dimensionColumns = resolveDimensionColumns(inputRow, columns, nonDimensionEventFields);
+    final ColumnSelectorFactory selectorFactory = cursor.getColumnSelectorFactory();
+
+    // Selectors are lazy views over the cursor's current position — create them once per column
+    // here, then re-read via getObject() as the cursor advances, rather than reallocating a selector
+    // for every (output-row x column) pair.
+    final ColumnValueSelector<?>[] selectors = new ColumnValueSelector<?>[columns.size()];
+    for (int i = 0; i < columns.size(); i++) {
+      selectors[i] = selectorFactory.makeColumnValueSelector(columns.get(i));
+    }
+
+    final List<InputRow> result = new ArrayList<>();
+    while (!cursor.isDone()) {
+      final Map<String, Object> event = new LinkedHashMap<>();
+      for (int i = 0; i < columns.size(); i++) {
+        event.put(columns.get(i), selectors[i].getObject());
+      }
+      result.add(new MapBasedInputRow(inputRow.getTimestampFromEpoch(), dimensionColumns, event));
+      cursor.advance();
+    }
+
+    return result;
+  }
+
+  /**
+   * Returns the raw event fields present on {@code inputRow} that are not in {@link InputRow#getDimensions()}
+   * — e.g. metric inputs that {@code DataSchema} added to dimensionExclusions. These must still be read
+   * into the expanded rows' event maps (for aggregators), but must not be promoted to dimensions.
+   */
+  private static Set<String> resolveNonDimensionEventFields(final InputRow inputRow)
+  {
+    if (!(inputRow instanceof MapBasedInputRow)) {
+      return Set.of();
+    }
+    final Set<String> nonDimensionFields = new LinkedHashSet<>(((MapBasedInputRow) inputRow).getEvent().keySet());
+    nonDimensionFields.removeAll(inputRow.getDimensions());
+    return nonDimensionFields;
+  }
+
+  private List<String> resolveColumnsForRow(final InputRow inputRow, final Set<String> nonDimensionEventFields)
+  {
+    final Set<String> columns = new LinkedHashSet<>();
+    columns.add(ColumnHolder.TIME_COLUMN_NAME);
+    columns.addAll(inputRow.getDimensions());
+    columns.addAll(nonDimensionEventFields);
+    for (final VirtualColumn vc : query.getVirtualColumns().getVirtualColumns()) {
+      columns.add(vc.getOutputName());
+    }
+    collectOutputColumnNames(query.getDataSource(), columns);
+    return new ArrayList<>(columns);
+  }
+
+  private static void collectOutputColumnNames(final DataSource dataSource, final Set<String> columns)
+  {
+    if (dataSource instanceof UnnestDataSource) {
+      final UnnestDataSource unnest = (UnnestDataSource) dataSource;
+      columns.add(unnest.getVirtualColumn().getOutputName());
+    }
+    for (final DataSource child : dataSource.getChildren()) {
+      collectOutputColumnNames(child, columns);
+    }
+  }
+
+  private static List<String> resolveDimensionColumns(
+      final InputRow inputRow,
+      @Nullable final List<String> resultColumns,
+      final Set<String> nonDimensionEventFields
+  )
+  {
+    final LinkedHashSet<String> dims = new LinkedHashSet<>(inputRow.getDimensions());
+    if (resultColumns != null) {
+      for (final String col : resultColumns) {
+        if (!ColumnHolder.TIME_COLUMN_NAME.equals(col) && !nonDimensionEventFields.contains(col)) {

Review Comment:
   P2 Keep generated metric fields out of dimensions
   
   `nonDimensionEventFields` contains only keys from the pre-scan `MapBasedInputRow`. A scan virtual-column output or unnested output used as a metric is generated after that step, so it is absent from this set and this loop adds it to `dimensionColumns`. For example, with a virtual column `rate` used by `longSum(total, rate)` but not declared as a dimension, every expanded row still reports `rate` from `getDimensions()`, causing the metric input to be stored as a discovered dimension. Track metric-only generated outputs when deriving dimensions while retaining them in the event map.



##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row is dropped. This matches native Druid UNNEST / CROSS JOIN semantics where
+ * null or empty arrays produce zero rows.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()
+                                                           .setInterval(query.getSingleInterval())
+                                                           .setFilter(Filters.toFilter(query.getFilter()))
+                                                           .setVirtualColumns(query.getVirtualColumns())
+                                                           .build();
+
+    this.baseCursorFactory = new SettableRowCursorFactory(broadSignature);
+    final SegmentMapFunction segmentMapFunction = query.getDataSource().createSegmentMapFunction(query);
+    final Segment mappedSegment = segmentMapFunction.apply(Optional.of(new CursorFactorySegment(baseCursorFactory)))
+                                                    .orElseThrow(() -> new ISE("SegmentMapFunction returned empty"));
+    final CursorFactory mappedCursorFactory = mappedSegment.as(CursorFactory.class);
+    this.cursorHolder = mappedCursorFactory.makeCursorHolder(cursorBuildSpec);
+  }
+
+  @Override
+  public boolean hasMultiRowTransform()
+  {
+    return true;
+  }
+
+  @Override
+  @Nullable
+  public InputRow transform(@Nullable final InputRow row)
+  {
+    throw new UnsupportedOperationException(
+        "ScanTransformer does not support single-row transform; use transformToList()"
+    );
+  }
+
+  @Override
+  public List<InputRow> transformToList(@Nullable final InputRow row)
+  {
+    if (row == null) {
+      return List.of();
+    }
+
+    return process(row);
+  }
+
+  @Override
+  @Nullable
+  public InputRowListPlusRawValues transform(@Nullable final InputRowListPlusRawValues row)
+  {
+    if (row == null || row.getInputRows() == null) {
+      return row;
+    }
+
+    final List<InputRow> inputRows = row.getInputRows();
+    final List<Map<String, Object>> inputRawValues = row.getRawValuesList();
+    final List<InputRow> outputRows = new ArrayList<>();
+    final List<Map<String, Object>> outputRawValues = inputRawValues == null ? null : new ArrayList<>();
+
+    for (int i = 0; i < inputRows.size(); i++) {
+      final List<InputRow> expandedRows = transformToList(inputRows.get(i));
+      outputRows.addAll(expandedRows);
+      if (outputRawValues != null) {
+        for (int j = 0; j < expandedRows.size(); j++) {
+          outputRawValues.add(inputRawValues.get(i));
+        }
+      }
+    }
+
+    return InputRowListPlusRawValues.ofList(outputRawValues, outputRows, row.getParseException());
+  }
+
+  @Override
+  public void close() throws IOException
+  {
+    cursorHolder.close();
+  }
+
+  private List<InputRow> process(final InputRow inputRow)
+  {
+    baseCursorFactory.set(inputRow);
+
+    if (cursor == null) {
+      cursor = cursorHolder.asCursor();
+    } else {
+      cursor.reset();
+    }
+
+    if (cursor == null || cursor.isDone()) {
+      return List.of();
+    }
+
+    final List<String> columns = resolveColumnsForRow(inputRow);
+    final List<String> dimensionColumns = resolveDimensionColumns(inputRow, columns);
+    final ColumnSelectorFactory selectorFactory = cursor.getColumnSelectorFactory();
+
+    final List<InputRow> result = new ArrayList<>();
+    while (!cursor.isDone()) {
+      final Map<String, Object> event = new LinkedHashMap<>();
+      for (final String col : columns) {
+        event.put(col, selectorFactory.makeColumnValueSelector(col).getObject());
+      }
+      result.add(new MapBasedInputRow(inputRow.getTimestampFromEpoch(), dimensionColumns, event));
+      cursor.advance();
+    }
+
+    return result;
+  }
+
+  private List<String> resolveColumnsForRow(final InputRow inputRow)
+  {
+    final Set<String> columns = new LinkedHashSet<>();
+    columns.add(ColumnHolder.TIME_COLUMN_NAME);
+    columns.addAll(inputRow.getDimensions());
+    // Include raw event fields that aren't in getDimensions() — e.g. metric inputs that DataSchema added
+    // to dimensionExclusions. Without this, fixed-dimension ingestions with metrics would read null for
+    // their metric source fields in expanded rows.
+    if (inputRow instanceof MapBasedInputRow) {
+      columns.addAll(((MapBasedInputRow) inputRow).getEvent().keySet());

Review Comment:
   Confirmed at head `072990954936d6755dd94460a90d4e088b40732a`: the raw `MapBasedInputRow` case is addressed. The transformer now retains those event keys for selectors/aggregators while excluding fields absent from `inputRow.getDimensions()` from the output dimension list, and the added unit and embedded coverage checks both sides of that behavior. I reviewed all 23 changed files; I recorded two related cases separately where generated metric outputs and list-backed metric fields still need the same treatment.
   
   <!-- mergelens:review -->



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #19379:
URL: https://github.com/apache/druid/pull/19379#issuecomment-4828112182

   This pull request has been marked as stale due to 60 days of inactivity.
   It will be closed in 4 weeks if no further activity occurs. If you think
   that's incorrect or this pull request should instead be reviewed, please simply
   write any comment. Even if closed, you can still revive the PR at any time or
   discuss it on the dev@druid.apache.org list.
   Thank you for your contributions.


-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #19379:
URL: https://github.com/apache/druid/pull/19379#issuecomment-5098495576

   This pull request/issue has been closed due to lack of activity. If you think that
   is incorrect, or the pull request requires review, you can revive the PR at any time.


-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "abhishekrb19 (via GitHub)" <gi...@apache.org>.
abhishekrb19 commented on PR #19379:
URL: https://github.com/apache/druid/pull/19379#issuecomment-5594130705

   
   Benchmark 1 — transform mode comparison (unnestArraySize=5, 5×10s warmup + 10×10s measurement, 1 fork, 10k rows/op)
   
   ```
   Benchmark                                       (mode)  (unnestArraySize)  Mode  Cnt     Score    Error  Units
   TransformSpecBenchmark.transformRows              NONE                  5  avgt   10     0.542 ±  0.006  ns/op
   TransformSpecBenchmark.transformRows        EXPRESSION                  5  avgt   10     5.985 ±  0.113  ns/op
   TransformSpecBenchmark.transformRows  SCAN_PASSTHROUGH                  5  avgt   10   369.312 ±  9.751  ns/op
   TransformSpecBenchmark.transformRows           SCAN_VC                  5  avgt   10  1851.823 ± 61.218  ns/op
   TransformSpecBenchmark.transformRows       SCAN_UNNEST                  5  avgt   10  1061.146 ±  7.973  ns/op
   ```
   
   Benchmark 2 — SCAN_UNNEST batch-size scaling (mode=SCAN_UNNEST, 5×10s warmup + 10×10s measurement, 1 fork, 10k rows/op)
   
   ```
   Benchmark                                  (mode)  (unnestArraySize)  Mode  Cnt      Score      Error  Units
   TransformSpecBenchmark.transformRows  SCAN_UNNEST                  5  avgt   10    963.466 ±   11.975  ns/op
   TransformSpecBenchmark.transformRows  SCAN_UNNEST                 20  avgt   10   2237.936 ±   17.684  ns/op
   TransformSpecBenchmark.transformRows  SCAN_UNNEST                100  avgt   10   9156.740 ±  148.981  ns/op
   TransformSpecBenchmark.transformRows  SCAN_UNNEST               1000  avgt   10  84573.609 ± 4139.941  ns/op
   ```
   
   
   Relative ordering (fastest → slowest): NONE < EXPRESSION < SCAN_PASSTHROUGH < SCAN_UNNEST < SCAN_VC.
   The classic EXPRESSION transform is cheaper than any scan-based path: even a bare scan pipeline with no virtual columns or unnest (SCAN_PASSTHROUGH) costs more than EXPRESSION doing real work, and running that same expression through a scan virtual column (SCAN_VC) is the most expensive mode measured - more than SCAN_UNNEST. There's a real integration penalty from routing through the scan-query engine that likely has room to be optimized.
   
   For SCAN_UNNEST specifically, per-input-row overhead drops as the unnest array grows, since the fixed per-row cost (cursor reset, selector setup) amortizes over more output rows - wider arrays are cheaper per output row than narrow ones.
   
   Note: this benchmark isolates the transform stage only - it excludes Kafka fetch/poll, JSON parsing, and downstream indexing/persist, which are likely larger fixed costs per record in a real ingestion task. So these numbers are an upper bound on the transform stage's overhead, not a prediction of overall end-to-end throughput impact. The real-world impact may in fact be smaller, since Kafka I/O and other per-record costs are incurred regardless of transform mode and would dilute the relative overhead once folded into total per-record cost.


-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "FrankChen021 (via GitHub)" <gi...@apache.org>.
FrankChen021 commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r4082728445


##########
benchmarks/src/test/java/org/apache/druid/benchmark/TransformSpecBenchmark.java:
##########
@@ -0,0 +1,229 @@
+/*
+ * 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.benchmark;
+
+import com.google.common.collect.ImmutableList;
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.Druids;
+import org.apache.druid.query.TableDataSource;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.expression.TestExprMacroTable;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.transform.BaseTransformer;
+import org.apache.druid.segment.transform.ExpressionTransform;
+import org.apache.druid.segment.transform.ScanTransformSpec;
+import org.apache.druid.segment.transform.TransformSpec;
+import org.apache.druid.segment.virtual.ExpressionVirtualColumn;
+import org.apache.druid.testing.InitializedNullHandlingTest;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OperationsPerInvocation;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Warmup;
+import org.openjdk.jmh.infra.Blackhole;
+import org.openjdk.jmh.runner.Runner;
+import org.openjdk.jmh.runner.RunnerException;
+import org.openjdk.jmh.runner.options.Options;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Measures per-row throughput of the ingestion-time transform pipeline for the three shapes
+ * streaming ingestion actually hits:
+ *   NONE              — TransformSpec.NONE, baseline overhead of the transform wrapper.
+ *   EXPRESSION        — TransformSpec with a single expression transform (upper(user)).
+ *   SCAN_PASSTHROUGH  — ScanTransformSpec with no unnest (scan-query baseline over a 1-row cursor).
+ *   SCAN_VC           — ScanTransformSpec with one scan-query virtual column (upper(user)), equivalent
+ *                       work to EXPRESSION but via the scan pipeline.
+ *   SCAN_UNNEST       — ScanTransformSpec that unnests an array of {@code unnestArraySize} elements.
+ *
+ * Output is nanoseconds per input row. For SCAN_UNNEST, use {@link #totalOutputRowsPerInput()} to
+ * translate to ns/output-row.
+ *
+ * The input row is a {@link MapBasedInputRow} matching what Kafka JSON ingestion produces.
+ */
+@State(Scope.Benchmark)
+@BenchmarkMode(Mode.AverageTime)

Review Comment:
   [P1] Resolve the shadowed JMH Mode type
   
   **Finding:** The class imports JMH's org.openjdk.jmh.annotations.Mode but also declares a nested enum named Mode. In @BenchmarkMode(Mode.AverageTime), the nested enum wins name resolution and has no AverageTime constant, so this new benchmark source does not compile and blocks the benchmarks module/build.
   
   **Suggestion:** Rename the benchmark parameter enum (for example, to BenchmarkMode) or fully qualify org.openjdk.jmh.annotations.Mode in the annotation so the JMH mode type is selected.



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "jtuglu1 (via GitHub)" <gi...@apache.org>.
jtuglu1 commented on PR #19379:
URL: https://github.com/apache/druid/pull/19379#issuecomment-4337526186

   Have we done performance profiles on this? Generally I've found transforms to really slow down tput on streaming ingests.


-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #19379: feat: Add `scan` transform to unnest arrays for realtime ingestion
URL: https://github.com/apache/druid/pull/19379


-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "FrankChen021 (via GitHub) via commits" <co...@druid.apache.org>.
FrankChen021 commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r4800118503


##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,339 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.ListBasedInputRow;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.error.DruidException;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.ColumnValueSelector;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row is dropped. This matches native Druid UNNEST / CROSS JOIN semantics where
+ * null or empty arrays produce zero rows.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  // Field names that must never be promoted to a dimension, regardless of whether they show up in this
+  // scan query's result columns. See resolveDimensionColumns() for why this can't be derived locally.
+  private final Set<String> dimensionExclusions;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery, final Set<String> dimensionExclusions)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+    this.dimensionExclusions = dimensionExclusions;
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()
+                                                           .setInterval(query.getSingleInterval())
+                                                           .setFilter(Filters.toFilter(query.getFilter()))
+                                                           .setVirtualColumns(query.getVirtualColumns())
+                                                           .build();
+
+    this.baseCursorFactory = new SettableRowCursorFactory(broadSignature);
+    final SegmentMapFunction segmentMapFunction = query.getDataSource().createSegmentMapFunction(query);
+    final Segment mappedSegment = segmentMapFunction.apply(Optional.of(new CursorFactorySegment(baseCursorFactory)))
+                                                    .orElseThrow(() -> new ISE("SegmentMapFunction returned empty"));
+    final CursorFactory mappedCursorFactory = mappedSegment.as(CursorFactory.class);
+    this.cursorHolder = mappedCursorFactory.makeCursorHolder(cursorBuildSpec);
+  }
+
+  @Override
+  public boolean hasMultiRowTransform()
+  {
+    return true;
+  }
+
+  @Override
+  @Nullable
+  public InputRow transform(@Nullable final InputRow row)
+  {
+    throw new UnsupportedOperationException(
+        "ScanTransformer does not support single-row transform; use transformToList()"
+    );
+  }
+
+  @Override
+  public List<InputRow> transformToList(@Nullable final InputRow row)
+  {
+    if (row == null) {
+      return List.of();
+    }
+
+    return process(row);
+  }
+
+  @Override
+  @Nullable
+  public InputRowListPlusRawValues transform(@Nullable final InputRowListPlusRawValues row)
+  {
+    if (row == null || row.getInputRows() == null) {
+      return row;
+    }
+
+    final List<InputRow> inputRows = row.getInputRows();
+    final List<Map<String, Object>> inputRawValues = row.getRawValuesList();
+    final List<InputRow> outputRows = new ArrayList<>();
+    final List<Map<String, Object>> outputRawValues = inputRawValues == null ? null : new ArrayList<>();
+
+    for (int i = 0; i < inputRows.size(); i++) {
+      final List<InputRow> expandedRows = transformToList(inputRows.get(i));
+      outputRows.addAll(expandedRows);
+      if (outputRawValues != null) {
+        for (int j = 0; j < expandedRows.size(); j++) {
+          outputRawValues.add(inputRawValues.get(i));
+        }
+      }
+    }
+
+    return InputRowListPlusRawValues.ofList(outputRawValues, outputRows, row.getParseException());
+  }
+
+  @Override
+  public void close() throws IOException
+  {
+    cursorHolder.close();
+  }
+
+  private List<InputRow> process(final InputRow inputRow)
+  {
+    baseCursorFactory.set(inputRow);
+
+    if (cursor == null) {
+      cursor = cursorHolder.asCursor();
+    } else {
+      cursor.reset();
+    }
+
+    if (cursor == null || cursor.isDone()) {
+      return List.of();
+    }
+
+    final Set<String> nonDimensionEventFields = resolveNonDimensionEventFields(inputRow);
+    final List<String> columns = resolveColumnsForRow(inputRow, nonDimensionEventFields);
+    final List<String> dimensionColumns = resolveDimensionColumns(inputRow, columns, nonDimensionEventFields);
+    final ColumnSelectorFactory selectorFactory = cursor.getColumnSelectorFactory();
+
+    // Selectors are lazy views over the cursor's current position — create them once per column
+    // here, then re-read via getObject() as the cursor advances, rather than reallocating a selector
+    // for every (output-row x column) pair.
+    final ColumnValueSelector<?>[] selectors = new ColumnValueSelector<?>[columns.size()];
+    for (int i = 0; i < columns.size(); i++) {
+      selectors[i] = selectorFactory.makeColumnValueSelector(columns.get(i));
+    }
+
+    // The query re-executes fresh for each input row (cursor reset above), so this row's own unnested
+    // expansion is the query's entire result set for this execution — offset/limit bound that set,
+    // the same way they'd bound any other scan query's result set. This is necessarily per input row
+    // rather than global across the ingestion job: there is no single ordered stream spanning rows
+    // (let alone across the parallel/rolling readers of a real ingestion job) for them to paginate.
+    final long offset = query.getScanRowsOffset();

Review Comment:
   [P2] Honor or reject non-time ordering before pagination
   
   **Finding:** ScanQuery accepts non-time orderBy values, but ScanTransformer neither validates them nor adds the requested ordering to its CursorBuildSpec. It applies offset and limit to the cursor's physical order, so a query such as orderBy tag ASC with limit 1 can emit the wrong row subset.
   
   **Suggestion:** Reject non-time orderBy consistently with native scan execution, or apply the requested ordering before offset and limit.



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "FrankChen021 (via GitHub)" <gi...@apache.org>.
FrankChen021 commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r3161337178


##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row is dropped. This matches native Druid UNNEST / CROSS JOIN semantics where
+ * null or empty arrays produce zero rows.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()
+                                                           .setInterval(query.getSingleInterval())
+                                                           .setFilter(Filters.toFilter(query.getFilter()))
+                                                           .setVirtualColumns(query.getVirtualColumns())
+                                                           .build();
+
+    this.baseCursorFactory = new SettableRowCursorFactory(broadSignature);
+    final SegmentMapFunction segmentMapFunction = query.getDataSource().createSegmentMapFunction(query);
+    final Segment mappedSegment = segmentMapFunction.apply(Optional.of(new CursorFactorySegment(baseCursorFactory)))
+                                                    .orElseThrow(() -> new ISE("SegmentMapFunction returned empty"));
+    final CursorFactory mappedCursorFactory = mappedSegment.as(CursorFactory.class);
+    this.cursorHolder = mappedCursorFactory.makeCursorHolder(cursorBuildSpec);
+  }
+
+  @Override
+  public boolean hasMultiRowTransform()
+  {
+    return true;
+  }
+
+  @Override
+  @Nullable
+  public InputRow transform(@Nullable final InputRow row)
+  {
+    throw new UnsupportedOperationException(
+        "ScanTransformer does not support single-row transform; use transformToList()"
+    );
+  }
+
+  @Override
+  public List<InputRow> transformToList(@Nullable final InputRow row)
+  {
+    if (row == null) {
+      return List.of();
+    }
+
+    return process(row);
+  }
+
+  @Override
+  @Nullable
+  public InputRowListPlusRawValues transform(@Nullable final InputRowListPlusRawValues row)
+  {
+    if (row == null || row.getInputRows() == null) {
+      return row;
+    }
+
+    final List<InputRow> inputRows = row.getInputRows();
+    final List<Map<String, Object>> inputRawValues = row.getRawValuesList();
+    final List<InputRow> outputRows = new ArrayList<>();
+    final List<Map<String, Object>> outputRawValues = inputRawValues == null ? null : new ArrayList<>();
+
+    for (int i = 0; i < inputRows.size(); i++) {
+      final List<InputRow> expandedRows = transformToList(inputRows.get(i));
+      outputRows.addAll(expandedRows);
+      if (outputRawValues != null) {
+        for (int j = 0; j < expandedRows.size(); j++) {
+          outputRawValues.add(inputRawValues.get(i));
+        }
+      }
+    }
+
+    return InputRowListPlusRawValues.ofList(outputRawValues, outputRows, row.getParseException());
+  }
+
+  @Override
+  public void close() throws IOException
+  {
+    cursorHolder.close();
+  }
+
+  private List<InputRow> process(final InputRow inputRow)
+  {
+    baseCursorFactory.set(inputRow);
+
+    if (cursor == null) {
+      cursor = cursorHolder.asCursor();
+    } else {
+      cursor.reset();
+    }
+
+    if (cursor == null || cursor.isDone()) {
+      return List.of();
+    }
+
+    final List<String> columns = resolveColumnsForRow(inputRow);
+    final List<String> dimensionColumns = resolveDimensionColumns(inputRow, columns);
+    final ColumnSelectorFactory selectorFactory = cursor.getColumnSelectorFactory();
+
+    final List<InputRow> result = new ArrayList<>();
+    while (!cursor.isDone()) {
+      final Map<String, Object> event = new LinkedHashMap<>();
+      for (final String col : columns) {
+        event.put(col, selectorFactory.makeColumnValueSelector(col).getObject());
+      }
+      result.add(new MapBasedInputRow(inputRow.getTimestampFromEpoch(), dimensionColumns, event));
+      cursor.advance();
+    }
+
+    return result;
+  }
+
+  private List<String> resolveColumnsForRow(final InputRow inputRow)
+  {
+    final Set<String> columns = new LinkedHashSet<>();
+    columns.add(ColumnHolder.TIME_COLUMN_NAME);
+    columns.addAll(inputRow.getDimensions());
+    // Include raw event fields that aren't in getDimensions() — e.g. metric inputs that DataSchema added
+    // to dimensionExclusions. Without this, fixed-dimension ingestions with metrics would read null for
+    // their metric source fields in expanded rows.
+    if (inputRow instanceof MapBasedInputRow) {
+      columns.addAll(((MapBasedInputRow) inputRow).getEvent().keySet());

Review Comment:
   [P2] Keep metric source fields out of dimensions
   
   Adding every MapBasedInputRow event key to the resolved scan columns also feeds those keys into resolveDimensionColumns, which promotes metric input fields such as bytes_sent into row.getDimensions() after expansion. IncrementalIndex treats row.getDimensions() as authoritative and will discover/store those metric source fields as dimensions even though DataSchema excluded them for metricsSpec. Preserve the raw field in the event map for aggregators, but do not add non-dimension event fields to the output dimension list; add a test that verifies the metric source is not ingested as a dimension.



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "FrankChen021 (via GitHub)" <gi...@apache.org>.
FrankChen021 commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r3147672255


##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransform.java:
##########
@@ -0,0 +1,268 @@
+/*
+ * 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.segment.transform;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.java.util.common.guava.Sequences;
+import org.apache.druid.query.filter.DimFilter;
+import org.apache.druid.segment.BaseObjectColumnValueSelector;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.RowAdapters;
+import org.apache.druid.segment.RowBasedSegment;
+import org.apache.druid.segment.UnnestCursorFactory;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+
+import javax.annotation.Nullable;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * A multi-row transform that unnests array columns during ingestion using the cursor-based unnest machinery.
+ * Each input row is wrapped in a single-row segment, the unnest cursor iterates over array elements,
+ * and each element becomes a separate output row.
+ *
+ * If the unnest column is missing or the array is empty, the input row passes through with the
+ * unnest output column set to null.
+ */
+public class ScanTransform implements Transform
+{
+  private final String name;
+  private final VirtualColumn unnestColumn;
+  @Nullable
+  private final DimFilter unnestFilter;
+
+  @JsonCreator
+  public ScanTransform(
+      @JsonProperty("name") final String name,
+      @JsonProperty("unnestColumn") final VirtualColumn unnestColumn,
+      @JsonProperty("unnestFilter") @Nullable final DimFilter unnestFilter
+  )
+  {
+    this.name = name;

Review Comment:
   [P2] Validate scan transform output name
   
   ScanTransform stores `name` separately from `unnestColumn.getOutputName()`, but the transform framework treats `Transform.getName()` as the generated field name for collision checks and input-column pruning. If a spec sets `name: "tag"` but the virtual column outputs `"elt"`, Druid accepts it, writes `elt`, and silently leaves references to `tag` unresolved while also missing collisions on `elt`. Reject mismatches or derive the transform name from the virtual column output.



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "abhishekrb19 (via GitHub)" <gi...@apache.org>.
abhishekrb19 commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r3975084289


##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,293 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.ColumnValueSelector;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row is dropped. This matches native Druid UNNEST / CROSS JOIN semantics where
+ * null or empty arrays produce zero rows.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()
+                                                           .setInterval(query.getSingleInterval())
+                                                           .setFilter(Filters.toFilter(query.getFilter()))
+                                                           .setVirtualColumns(query.getVirtualColumns())
+                                                           .build();
+
+    this.baseCursorFactory = new SettableRowCursorFactory(broadSignature);
+    final SegmentMapFunction segmentMapFunction = query.getDataSource().createSegmentMapFunction(query);
+    final Segment mappedSegment = segmentMapFunction.apply(Optional.of(new CursorFactorySegment(baseCursorFactory)))
+                                                    .orElseThrow(() -> new ISE("SegmentMapFunction returned empty"));
+    final CursorFactory mappedCursorFactory = mappedSegment.as(CursorFactory.class);
+    this.cursorHolder = mappedCursorFactory.makeCursorHolder(cursorBuildSpec);
+  }
+
+  @Override
+  public boolean hasMultiRowTransform()
+  {
+    return true;
+  }
+
+  @Override
+  @Nullable
+  public InputRow transform(@Nullable final InputRow row)
+  {
+    throw new UnsupportedOperationException(
+        "ScanTransformer does not support single-row transform; use transformToList()"
+    );
+  }
+
+  @Override
+  public List<InputRow> transformToList(@Nullable final InputRow row)
+  {
+    if (row == null) {
+      return List.of();
+    }
+
+    return process(row);
+  }
+
+  @Override
+  @Nullable
+  public InputRowListPlusRawValues transform(@Nullable final InputRowListPlusRawValues row)
+  {
+    if (row == null || row.getInputRows() == null) {
+      return row;
+    }
+
+    final List<InputRow> inputRows = row.getInputRows();
+    final List<Map<String, Object>> inputRawValues = row.getRawValuesList();
+    final List<InputRow> outputRows = new ArrayList<>();
+    final List<Map<String, Object>> outputRawValues = inputRawValues == null ? null : new ArrayList<>();
+
+    for (int i = 0; i < inputRows.size(); i++) {
+      final List<InputRow> expandedRows = transformToList(inputRows.get(i));
+      outputRows.addAll(expandedRows);
+      if (outputRawValues != null) {
+        for (int j = 0; j < expandedRows.size(); j++) {
+          outputRawValues.add(inputRawValues.get(i));
+        }
+      }
+    }
+
+    return InputRowListPlusRawValues.ofList(outputRawValues, outputRows, row.getParseException());
+  }
+
+  @Override
+  public void close() throws IOException
+  {
+    cursorHolder.close();
+  }
+
+  private List<InputRow> process(final InputRow inputRow)
+  {
+    baseCursorFactory.set(inputRow);
+
+    if (cursor == null) {
+      cursor = cursorHolder.asCursor();
+    } else {
+      cursor.reset();
+    }
+
+    if (cursor == null || cursor.isDone()) {
+      return List.of();
+    }
+
+    final Set<String> nonDimensionEventFields = resolveNonDimensionEventFields(inputRow);
+    final List<String> columns = resolveColumnsForRow(inputRow, nonDimensionEventFields);
+    final List<String> dimensionColumns = resolveDimensionColumns(inputRow, columns, nonDimensionEventFields);
+    final ColumnSelectorFactory selectorFactory = cursor.getColumnSelectorFactory();
+
+    // Selectors are lazy views over the cursor's current position — create them once per column
+    // here, then re-read via getObject() as the cursor advances, rather than reallocating a selector
+    // for every (output-row x column) pair.
+    final ColumnValueSelector<?>[] selectors = new ColumnValueSelector<?>[columns.size()];
+    for (int i = 0; i < columns.size(); i++) {
+      selectors[i] = selectorFactory.makeColumnValueSelector(columns.get(i));
+    }
+
+    final List<InputRow> result = new ArrayList<>();
+    while (!cursor.isDone()) {
+      final Map<String, Object> event = new LinkedHashMap<>();
+      for (int i = 0; i < columns.size(); i++) {
+        event.put(columns.get(i), selectors[i].getObject());
+      }
+      result.add(new MapBasedInputRow(inputRow.getTimestampFromEpoch(), dimensionColumns, event));
+      cursor.advance();
+    }
+
+    return result;
+  }
+
+  /**
+   * Returns the raw event fields present on {@code inputRow} that are not in {@link InputRow#getDimensions()}
+   * — e.g. metric inputs that {@code DataSchema} added to dimensionExclusions. These must still be read
+   * into the expanded rows' event maps (for aggregators), but must not be promoted to dimensions.
+   */
+  private static Set<String> resolveNonDimensionEventFields(final InputRow inputRow)
+  {
+    if (!(inputRow instanceof MapBasedInputRow)) {
+      return Set.of();
+    }
+    final Set<String> nonDimensionFields = new LinkedHashSet<>(((MapBasedInputRow) inputRow).getEvent().keySet());
+    nonDimensionFields.removeAll(inputRow.getDimensions());
+    return nonDimensionFields;
+  }
+
+  private List<String> resolveColumnsForRow(final InputRow inputRow, final Set<String> nonDimensionEventFields)
+  {
+    final Set<String> columns = new LinkedHashSet<>();
+    columns.add(ColumnHolder.TIME_COLUMN_NAME);
+    columns.addAll(inputRow.getDimensions());
+    columns.addAll(nonDimensionEventFields);
+    for (final VirtualColumn vc : query.getVirtualColumns().getVirtualColumns()) {
+      columns.add(vc.getOutputName());
+    }
+    collectOutputColumnNames(query.getDataSource(), columns);
+    return new ArrayList<>(columns);
+  }
+
+  private static void collectOutputColumnNames(final DataSource dataSource, final Set<String> columns)
+  {
+    if (dataSource instanceof UnnestDataSource) {
+      final UnnestDataSource unnest = (UnnestDataSource) dataSource;
+      columns.add(unnest.getVirtualColumn().getOutputName());
+    }
+    for (final DataSource child : dataSource.getChildren()) {
+      collectOutputColumnNames(child, columns);
+    }
+  }
+
+  private static List<String> resolveDimensionColumns(
+      final InputRow inputRow,
+      @Nullable final List<String> resultColumns,
+      final Set<String> nonDimensionEventFields
+  )
+  {
+    final LinkedHashSet<String> dims = new LinkedHashSet<>(inputRow.getDimensions());
+    if (resultColumns != null) {
+      for (final String col : resultColumns) {
+        if (!ColumnHolder.TIME_COLUMN_NAME.equals(col) && !nonDimensionEventFields.contains(col)) {

Review Comment:
   Fixed in the latest commit.



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add `scan` transform to unnest arrays for realtime ingestion (druid)

Posted by "FrankChen021 (via GitHub)" <gi...@apache.org>.
FrankChen021 commented on code in PR #19379:
URL: https://github.com/apache/druid/pull/19379#discussion_r4206911085


##########
processing/src/main/java/org/apache/druid/segment/transform/ScanTransformer.java:
##########
@@ -0,0 +1,339 @@
+/*
+ * 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.segment.transform;
+
+import org.apache.druid.data.input.InputRow;
+import org.apache.druid.data.input.InputRowListPlusRawValues;
+import org.apache.druid.data.input.ListBasedInputRow;
+import org.apache.druid.data.input.MapBasedInputRow;
+import org.apache.druid.error.DruidException;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.QueryContexts;
+import org.apache.druid.query.UnnestDataSource;
+import org.apache.druid.query.scan.ScanQuery;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.ColumnValueSelector;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.CursorBuildSpec;
+import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.filter.Filters;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * A {@link BaseTransformer} that processes input rows through a reusable scan query cursor pipeline.
+ *
+ * <p>The pipeline is built once at construction: a {@link SettableRowCursorFactory} is wrapped by the
+ * scan query's {@link SegmentMapFunction} (e.g., unnest, filter). For each input row, the row is set
+ * on the factory and the cursor is {@link Cursor#reset reset} — no per-row segment or cursor allocation.
+ *
+ * <p>When the scan query produces zero output rows (e.g., null/missing arrays, or filter rejection),
+ * the input row is dropped. This matches native Druid UNNEST / CROSS JOIN semantics where
+ * null or empty arrays produce zero rows.
+ *
+ * <p>This class is not thread-safe. Each reader thread should have its own instance.
+ */
+public class ScanTransformer implements BaseTransformer
+{
+  private final ScanQuery query;
+  // Field names that must never be promoted to a dimension, regardless of whether they show up in this
+  // scan query's result columns. See resolveDimensionColumns() for why this can't be derived locally.
+  private final Set<String> dimensionExclusions;
+  private final SettableRowCursorFactory baseCursorFactory;
+  private final CursorHolder cursorHolder;
+  private Cursor cursor;
+
+  ScanTransformer(final ScanQuery scanQuery, final Set<String> dimensionExclusions)
+  {
+    this.query = scanQuery.withOverriddenContext(
+        Map.of(QueryContexts.TIMEOUT_KEY, 0)
+    );
+    this.dimensionExclusions = dimensionExclusions;
+
+    final RowSignature broadSignature = RowSignature.builder()
+                                                     .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG)
+                                                     .build();
+
+    final CursorBuildSpec cursorBuildSpec = CursorBuildSpec.builder()

Review Comment:
   [P2] Reject unsupported non-time ordering before pagination
   
   **Finding:** A ScanQuery can carry a non-time `orderBy`, but this transformer bypasses the normal scan-query execution path and neither validates that ordering nor passes it to the cursor build spec. It then applies `offset` and `limit` while iterating the cursor, so a transform with `orderBy` plus pagination silently ingests rows in natural cursor order; native scan execution rejects non-time ordering through `ScanQuery.verifyOrderByForNativeExecution`.
   
   **Suggestion:** Validate the embedded query with `ScanQuery.verifyOrderByForNativeExecution` (or explicitly reject non-time ordering) before applying offset and limit.



-- 
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: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org