FrankChen021 commented on code in PR #19510: URL: https://github.com/apache/druid/pull/19510#discussion_r3996201054
########## extensions-contrib/druid-iceberg-extensions/src/main/java/org/apache/druid/iceberg/input/IcebergArrowInputSourceReader.java: ########## @@ -0,0 +1,483 @@ +/* + * 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.iceberg.input; + +import com.google.common.collect.Maps; +import org.apache.arrow.vector.FieldVector; +import org.apache.druid.data.input.ColumnsFilter; +import org.apache.druid.data.input.InputRow; +import org.apache.druid.data.input.InputRowListPlusRawValues; +import org.apache.druid.data.input.InputRowSchema; +import org.apache.druid.data.input.InputSourceReader; +import org.apache.druid.data.input.InputStats; +import org.apache.druid.data.input.MapBasedInputRow; +import org.apache.druid.error.DruidException; +import org.apache.druid.iceberg.filter.IcebergFilter; +import org.apache.druid.java.util.common.parsers.CloseableIterator; +import org.apache.iceberg.CombinedScanTask; +import org.apache.iceberg.FileScanTask; +import org.apache.iceberg.Schema; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableScan; +import org.apache.iceberg.arrow.vectorized.ArrowReader; +import org.apache.iceberg.arrow.vectorized.ColumnVector; +import org.apache.iceberg.arrow.vectorized.ColumnarBatch; +import org.apache.iceberg.io.CloseableIterable; +import org.apache.iceberg.types.Type; +import org.apache.iceberg.types.Types; +import org.apache.iceberg.util.TableScanUtil; +import org.joda.time.DateTime; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +/** + * Reads an Iceberg table via iceberg-arrow's {@link ArrowReader}, yielding {@link InputRow} objects. + * + * Type coercion and compatible schema evolution are handled by the Iceberg library. Druid only consumes + * the resulting {@link ColumnarBatch} batches and maps them to {@link MapBasedInputRow}. + * + * Column projection and predicate push-down are applied at scan planning time so only requested + * columns and matching files are read from storage. + * + * Note: iceberg-arrow currently supports Parquet data files only. ORC and Avro files will throw + * {@link UnsupportedOperationException} at read time. Delete-file snapshots are rejected because + * iceberg-arrow does not apply equality or positional deletes. + */ +public class IcebergArrowInputSourceReader implements InputSourceReader +{ + static final int DEFAULT_BATCH_SIZE = 1024; + + private final Table table; + @Nullable + private final IcebergFilter icebergFilter; + @Nullable + private final DateTime snapshotTime; + private final boolean caseSensitive; + private final InputRowSchema schema; + private final int batchSize; + private final ResidualFilterMode residualFilterMode; + + public IcebergArrowInputSourceReader( + final Table table, + @Nullable final IcebergFilter icebergFilter, + @Nullable final DateTime snapshotTime, + final boolean caseSensitive, + final InputRowSchema schema, + final int batchSize + ) + { + this(table, icebergFilter, snapshotTime, caseSensitive, schema, batchSize, ResidualFilterMode.IGNORE); + } + + public IcebergArrowInputSourceReader( + final Table table, + @Nullable final IcebergFilter icebergFilter, + @Nullable final DateTime snapshotTime, + final boolean caseSensitive, + final InputRowSchema schema, + final int batchSize, + final ResidualFilterMode residualFilterMode + ) + { + this.table = table; + this.icebergFilter = icebergFilter; + this.snapshotTime = snapshotTime; + this.caseSensitive = caseSensitive; + this.schema = schema; + this.batchSize = batchSize; + this.residualFilterMode = residualFilterMode; + } + + @Override + public CloseableIterator<InputRow> read(@Nullable final InputStats inputStats) throws IOException + { + final TableScan scan = buildScan(); + validateNoDeleteFiles(scan); + validateDecimalPrecision(scan); + final CloseableIterable<CombinedScanTask> tasks = TableScanUtil.planTasks( + scan.planFiles(), + scan.targetSplitSize(), + scan.splitLookback(), + scan.splitOpenFileCost() + ); + final ClassLoader extensionClassLoader = IcebergArrowInputSourceReader.class.getClassLoader(); + final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + ArrowReader arrowReader = null; + boolean ownershipTransferred = false; + try { + Thread.currentThread().setContextClassLoader(extensionClassLoader); + arrowReader = new ArrowReader(scan, batchSize, true); + final org.apache.iceberg.io.CloseableIterator<ColumnarBatch> batchIter = arrowReader.open(tasks); + final CloseableIterator<InputRow> iterator = new ArrowInputRowIterator( + batchIter, + arrowReader, + tasks, + inputStats != null ? inputStats : new NoopInputStats(), + scan.schema(), + extensionClassLoader + ); + ownershipTransferred = true; + return iterator; + } + finally { + Thread.currentThread().setContextClassLoader(originalClassLoader); + if (!ownershipTransferred) { + try { + if (arrowReader != null) { + arrowReader.close(); + } + } + finally { + tasks.close(); + } + } + } + } + + private void validateNoDeleteFiles(final TableScan scan) throws IOException + { + try (CloseableIterable<FileScanTask> fileTasks = scan.planFiles()) { + for (FileScanTask fileTask : fileTasks) { + if (!fileTask.deletes().isEmpty()) { + throw DruidException.forPersona(DruidException.Persona.USER) + .ofCategory(DruidException.Category.UNSUPPORTED) + .build( + "Arrow reader does not support Iceberg snapshots with delete files. " + + "Use a delete-aware input path." + ); + } + } + } + } + + private void validateDecimalPrecision(final TableScan scan) + { + for (final Types.NestedField field : scan.schema().columns()) { + if (field.type().typeId() == Type.TypeID.DECIMAL + && ((Types.DecimalType) field.type()).precision() > 18) { + throw DruidException.forPersona(DruidException.Persona.USER) + .ofCategory(DruidException.Category.UNSUPPORTED) + .build( + "Arrow reader does not support decimal fields with precision greater than 18. " + + "Use the standard Iceberg reader." + ); + } + } + } + + @Override + public CloseableIterator<InputRowListPlusRawValues> sample() throws IOException + { + final CloseableIterator<InputRow> rows = read(new NoopInputStats()); + return new CloseableIterator<InputRowListPlusRawValues>() + { + @Override + public boolean hasNext() + { + return rows.hasNext(); + } + + @Override + public InputRowListPlusRawValues next() + { + final InputRow row = rows.next(); + return InputRowListPlusRawValues.of(row, ((MapBasedInputRow) row).getEvent()); + } + + @Override + public void close() throws IOException + { + rows.close(); + } + }; + } + + private TableScan buildScan() + { + TableScan scan = table.newScan().caseSensitive(caseSensitive); + + if (snapshotTime != null) { + scan = scan.asOfTime(snapshotTime.getMillis()); + } + + final List<String> projection = projectedColumns(scan.schema()); + if (projection != null) { + scan = scan.select(projection); + } + if (icebergFilter != null) { + scan = icebergFilter.filter(scan); + if (residualFilterMode == ResidualFilterMode.IGNORE) { + scan = scan.ignoreResiduals(); + } + } + return scan; + } + + /** Projection authority is ColumnsFilter, not DimensionsSpec. Mirrors DeltaInputSource#pruneSchema. */ + @Nullable + private List<String> projectedColumns(final Schema scanSchema) + { + final ColumnsFilter filter = schema.getColumnsFilter(); + final List<String> allColumns = scanSchema.columns().stream() + .map(Types.NestedField::name) + .collect(Collectors.toList()); + final List<String> filtered = allColumns.stream() + .filter(filter::apply) + .collect(Collectors.toList()); + if (filtered.equals(allColumns)) { + return null; + } + final String tsCol = schema.getTimestampSpec().getTimestampColumn(); + if (tsCol != null && allColumns.contains(tsCol) && !filtered.contains(tsCol)) { + filtered.add(tsCol); + } + return filtered; + } + + private InputRow batchRowToInputRow( + final ColumnarBatch batch, + final int rowIdx, + final Schema readSchema + ) + { + final int numCols = batch.numCols(); + final Map<String, Object> event = Maps.newHashMapWithExpectedSize(numCols); + for (int col = 0; col < numCols; col++) { + final ColumnVector column = batch.column(col); + final Types.NestedField field = readSchema.columns().get(col); + if (!column.isNullAt(rowIdx)) { + event.put(field.name(), extractValue(column, field.type(), rowIdx)); + } + } + final long timestamp = schema.getTimestampSpec().extractTimestamp(event).getMillis(); + final List<String> dimensions = resolveDimensions(readSchema); + return new MapBasedInputRow(timestamp, dimensions, event); + } + + private List<String> resolveDimensions(final Schema readSchema) + { + final List<String> configured = schema.getDimensionsSpec().getDimensionNames(); Review Comment: ## Follow-up assessment The prior P1 is resolved at current head `b82709bcbc97cc8fa9e5f7d2fa92f57bff98b96a`: `resolveDimensions` now delegates to Druid's canonical `MapInputRowParser.findDimensions`, so explicit dimensions, include-all/schema-discovery fields, exclusions, and the timestamp column follow the standard reader semantics. The added tests cover explicit dynamic dimensions and exclusions. I rechecked the full current-head change and found no additional PR-caused correctness, edge-case, concurrency/lifecycle, security, data-loss, API-compatibility, or missing-test issue. Reviewed 11 of 11 changed files. Validation: `git diff --check 61ed0a389d6af0a3e410b651f379d4f554bbcacb..b82709bcbc97cc8fa9e5f7d2fa92f57bff98b96a` passed. No builds or tests were run. <!-- mergelens:review --> --- This is an automated review by Codex GPT-5.6-Luna(max) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
