hudi-agent commented on code in PR #18741:
URL: https://github.com/apache/hudi/pull/18741#discussion_r3301249182


##########
hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowDataLanceWriter.java:
##########
@@ -0,0 +1,167 @@
+/*
+ * 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.hudi.io.storage.row;
+
+import org.apache.hudi.client.model.HoodieRowDataCreation;
+import org.apache.hudi.common.bloom.BloomFilter;
+import org.apache.hudi.common.engine.TaskContextSupplier;
+import org.apache.hudi.common.model.HoodieKey;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.common.util.ValidationUtils;
+import org.apache.hudi.io.lance.HoodieBaseLanceWriter;
+import org.apache.hudi.storage.StoragePath;
+
+import org.apache.arrow.vector.VectorSchemaRoot;
+import org.apache.arrow.vector.types.pojo.Schema;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.types.logical.RowType;
+
+import java.io.IOException;
+import java.util.function.Function;
+
+/**
+ * Lance writer for Flink {@link RowData} append-only base files.
+ */
+public class HoodieRowDataLanceWriter extends HoodieBaseLanceWriter<RowData, 
String>
+    implements HoodieRowDataFileWriter {
+
+  private static final long MIN_RECORDS_FOR_SIZE_CHECK = 100L;
+  private static final long MAX_RECORDS_FOR_SIZE_CHECK = 10000L;
+
+  private final RowType rowType;
+  private final Schema arrowSchema;
+  private final String fileName;
+  private final String instantTime;
+  private final long maxFileSize;
+  private final boolean utcTimestamp;
+  private final boolean populateMetaFields;
+  private final boolean withOperation;
+  private final Function<Long, String> seqIdGenerator;
+  private long recordCountForNextSizeCheck = MIN_RECORDS_FOR_SIZE_CHECK;
+
+  public HoodieRowDataLanceWriter(
+      StoragePath file,
+      RowType rowType,
+      String instantTime,
+      TaskContextSupplier taskContextSupplier,
+      Option<BloomFilter> bloomFilterOpt,
+      long maxFileSize,
+      long allocatorSize,
+      long flushByteWatermark,
+      boolean utcTimestamp,
+      boolean populateMetaFields,
+      boolean withOperation) {
+    super(file, DEFAULT_BATCH_SIZE, allocatorSize, flushByteWatermark,
+        bloomFilterOpt.map(HoodieBloomFilterRowDataWriteSupport::new));
+    ValidationUtils.checkArgument(maxFileSize > 0, "maxFileSize must be a 
positive number");
+    ValidationUtils.checkArgument(allocatorSize > 0, "allocatorSize must be a 
positive number");
+    ValidationUtils.checkArgument(flushByteWatermark > 0, "flushByteWatermark 
must be a positive number");
+    ValidationUtils.checkArgument(flushByteWatermark < allocatorSize,
+        "flushByteWatermark (" + flushByteWatermark + ") must be less than 
allocatorSize ("
+            + allocatorSize + ")");
+    this.rowType = rowType;
+    this.arrowSchema = HoodieFlinkLanceArrowUtils.toArrowSchema(rowType);
+    this.fileName = file.getName();
+    this.instantTime = instantTime;
+    this.maxFileSize = maxFileSize;
+    this.utcTimestamp = utcTimestamp;
+    this.populateMetaFields = populateMetaFields;
+    this.withOperation = withOperation;
+    this.seqIdGenerator = recordIndex -> {
+      Integer partitionId = taskContextSupplier.getPartitionIdSupplier().get();
+      return HoodieRecord.generateSequenceId(instantTime, partitionId, 
recordIndex);
+    };
+  }
+
+  @Override
+  public boolean canWrite() {
+    long writtenCount = getWrittenRecordCount();
+    if (writtenCount >= recordCountForNextSizeCheck) {
+      long dataSize = getDataSize();
+      long avgRecordSize = Math.max(dataSize / writtenCount, 1);
+      if (dataSize > (maxFileSize - avgRecordSize * 2)) {
+        return false;
+      }
+      recordCountForNextSizeCheck = writtenCount + Math.min(
+          Math.max(MIN_RECORDS_FOR_SIZE_CHECK, (maxFileSize / avgRecordSize - 
writtenCount) / 2),

Review Comment:
   🤖 nit: it might be worth adding a brief comment here explaining the 
heuristic — something like `// schedule the next check halfway between now and 
the estimated full-file record count, clamped to [MIN, MAX]`. The formula is 
non-trivial enough that a future reader will need to reverse-engineer the 
intent.
   
   <sub><i>- AI-generated; verify before applying. React 👍/👎 to flag 
quality.</i></sub>



##########
hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowDataFileWriterFactory.java:
##########
@@ -55,6 +62,30 @@ public HoodieRowDataFileWriterFactory(HoodieStorage storage) 
{
     super(storage);
   }
 
+  public HoodieFileWriter getFileWriter(String instantTime, StoragePath 
storagePath, HoodieWriteConfig config, RowType rowType,
+                                     TaskContextSupplier taskContextSupplier) 
throws IOException {
+    final String extension = FSUtils.getFileExtension(storagePath.getName());
+    return getFileWriterByFormat(extension, instantTime, storagePath, config, 
rowType, taskContextSupplier);
+  }
+
+  private  <T, I, K, O> HoodieFileWriter getFileWriterByFormat(
+      String extension, String instantTime, StoragePath path, HoodieConfig 
config, RowType rowType,

Review Comment:
   🤖 nit: could you drop the `<T, I, K, O>` type parameters? They're not 
referenced anywhere in the method body or return type, so they read as 
inherited boilerplate that doesn't apply here — a future reader will waste time 
trying to figure out what they're parameterizing.
   
   <sub><i>- AI-generated; verify before applying. React 👍/👎 to flag 
quality.</i></sub>



##########
hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/storage/row/HoodieFlinkLanceArrowUtils.java:
##########
@@ -0,0 +1,305 @@
+/*
+ * 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.hudi.io.storage.row;
+
+import org.apache.hudi.exception.HoodieNotSupportedException;
+
+import org.apache.arrow.vector.BigIntVector;
+import org.apache.arrow.vector.BitVector;
+import org.apache.arrow.vector.DateDayVector;
+import org.apache.arrow.vector.DecimalVector;
+import org.apache.arrow.vector.FieldVector;
+import org.apache.arrow.vector.Float4Vector;
+import org.apache.arrow.vector.Float8Vector;
+import org.apache.arrow.vector.IntVector;
+import org.apache.arrow.vector.SmallIntVector;
+import org.apache.arrow.vector.TimeMilliVector;
+import org.apache.arrow.vector.TimeStampMicroVector;
+import org.apache.arrow.vector.TinyIntVector;
+import org.apache.arrow.vector.ValueVector;
+import org.apache.arrow.vector.VarBinaryVector;
+import org.apache.arrow.vector.VarCharVector;
+import org.apache.arrow.vector.types.DateUnit;
+import org.apache.arrow.vector.types.FloatingPointPrecision;
+import org.apache.arrow.vector.types.TimeUnit;
+import org.apache.arrow.vector.types.pojo.ArrowType;
+import org.apache.arrow.vector.types.pojo.Field;
+import org.apache.arrow.vector.types.pojo.FieldType;
+import org.apache.arrow.vector.types.pojo.Schema;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.BigIntType;
+import org.apache.flink.table.types.logical.BooleanType;
+import org.apache.flink.table.types.logical.DateType;
+import org.apache.flink.table.types.logical.DecimalType;
+import org.apache.flink.table.types.logical.DoubleType;
+import org.apache.flink.table.types.logical.FloatType;
+import org.apache.flink.table.types.logical.IntType;
+import org.apache.flink.table.types.logical.LocalZonedTimestampType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.logical.SmallIntType;
+import org.apache.flink.table.types.logical.TimeType;
+import org.apache.flink.table.types.logical.TimestampType;
+import org.apache.flink.table.types.logical.TinyIntType;
+import org.apache.flink.table.types.logical.VarBinaryType;
+import org.apache.flink.table.types.logical.VarCharType;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import static 
org.apache.flink.table.types.logical.utils.LogicalTypeChecks.getPrecision;
+
+/**
+ * Primitive RowData/Arrow conversion helpers for Flink Lance base files.
+ */
+public final class HoodieFlinkLanceArrowUtils {
+
+  private HoodieFlinkLanceArrowUtils() {
+  }
+
+  public static Schema toArrowSchema(RowType rowType) {
+    List<Field> fields = new ArrayList<>(rowType.getFieldCount());
+    for (RowType.RowField field : rowType.getFields()) {
+      fields.add(toArrowField(field.getName(), field.getType()));
+    }
+    return new Schema(fields);
+  }
+
+  public static RowType toRowType(Schema schema) {
+    List<RowType.RowField> fields = new ArrayList<>(schema.getFields().size());
+    for (Field field : schema.getFields()) {
+      fields.add(new RowType.RowField(field.getName(), 
toLogicalType(field.getType())));
+    }
+    return new RowType(fields);
+  }
+
+  public static RowData toRowData(RowType rowType, List<FieldVector> vectors, 
int rowId) {
+    GenericRowData rowData = new GenericRowData(vectors.size());
+    for (int i = 0; i < vectors.size(); i++) {
+      FieldVector vector = vectors.get(i);
+      if (vector.isNull(rowId)) {
+        rowData.setField(i, null);
+      } else {
+        rowData.setField(i, readValue(rowType.getTypeAt(i), vector, rowId));
+      }
+    }
+    return rowData;
+  }
+
+  public static void writeValue(LogicalType type, FieldVector vector, int 
rowId, RowData rowData, int ordinal) {
+    writeValue(type, vector, rowId, rowData, ordinal, true);
+  }
+
+  public static void writeValue(LogicalType type, FieldVector vector, int 
rowId, RowData rowData, int ordinal, boolean utcTimestamp) {
+    if (rowData.isNullAt(ordinal)) {
+      vector.setNull(rowId);
+      return;
+    }
+    switch (type.getTypeRoot()) {
+      case BOOLEAN:
+        ((BitVector) vector).setSafe(rowId, rowData.getBoolean(ordinal) ? 1 : 
0);
+        return;
+      case TINYINT:
+        ((TinyIntVector) vector).setSafe(rowId, rowData.getByte(ordinal));
+        return;
+      case SMALLINT:
+        ((SmallIntVector) vector).setSafe(rowId, rowData.getShort(ordinal));
+        return;
+      case INTEGER:
+        ((IntVector) vector).setSafe(rowId, rowData.getInt(ordinal));
+        return;
+      case DATE:

Review Comment:
   🤖 Could this produce a malformed `TimestampData` for pre-1970 timestamps? 
For `micros = -1_234_567`, Java's truncating `/` and `%` give `(-1234, 
-567000)`, so `fromEpochMillis(-1234, -567000)` is stored with a negative 
`nanoOfMillisecond` (contract says 0..999_999). That isn't 
`equals()`-comparable to the original `TimestampData(-1235, 433000)` even 
though both represent the same instant. Other Hudi-Flink paths (`RowDataUtils`, 
`AvroToRowDataConverters`) go through `Instant.ofEpochSecond(seconds, nanos)` / 
`TimestampData.fromInstant(...)` which normalize negatives — `Math.floorDiv` / 
`Math.floorMod` would also work here. Worth aligning, or is this intentional?
   
   <sub><i>- AI-generated; verify before applying. React 👍/👎 to flag 
quality.</i></sub>



##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/table/format/HoodieRowDataLanceReader.java:
##########
@@ -0,0 +1,301 @@
+/*
+ * 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.hudi.table.format;
+
+import org.apache.hudi.client.model.HoodieFlinkRecord;
+import org.apache.hudi.common.bloom.BloomFilter;
+import org.apache.hudi.common.bloom.HoodieDynamicBoundedBloomFilter;
+import org.apache.hudi.common.bloom.SimpleBloomFilter;
+import org.apache.hudi.common.config.HoodieConfig;
+import org.apache.hudi.common.config.HoodieStorageConfig;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.schema.HoodieSchema;
+import org.apache.hudi.common.schema.HoodieSchemaUtils;
+import org.apache.hudi.common.util.collection.ClosableIterator;
+import org.apache.hudi.common.util.collection.CloseableMappingIterator;
+import org.apache.hudi.common.util.collection.Pair;
+import org.apache.hudi.exception.HoodieException;
+import org.apache.hudi.exception.HoodieIOException;
+import org.apache.hudi.io.memory.HoodieArrowAllocator;
+import org.apache.hudi.io.storage.HoodieFileReader;
+import org.apache.hudi.io.storage.row.HoodieFlinkLanceArrowUtils;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.util.HoodieSchemaConverter;
+import org.apache.hudi.util.RowDataQueryContexts;
+
+import org.apache.arrow.memory.BufferAllocator;
+import org.apache.arrow.vector.FieldVector;
+import org.apache.arrow.vector.VectorSchemaRoot;
+import org.apache.arrow.vector.ipc.ArrowReader;
+import org.apache.arrow.vector.types.pojo.Schema;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.logical.RowType;
+import org.lance.file.LanceFileReader;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static 
org.apache.hudi.avro.HoodieBloomFilterWriteSupport.HOODIE_AVRO_BLOOM_FILTER_METADATA_KEY;
+import static 
org.apache.hudi.avro.HoodieBloomFilterWriteSupport.HOODIE_BLOOM_FILTER_TYPE_CODE;
+import static 
org.apache.hudi.avro.HoodieBloomFilterWriteSupport.HOODIE_MAX_RECORD_KEY_FOOTER;
+import static 
org.apache.hudi.avro.HoodieBloomFilterWriteSupport.HOODIE_MIN_RECORD_KEY_FOOTER;
+
+/**
+ * Lance reader for Flink RowData base files.
+ */
+public class HoodieRowDataLanceReader implements HoodieFileReader<RowData> {
+
+  private static final int DEFAULT_BATCH_SIZE = 512;
+
+  private final StoragePath path;
+  private final long dataAllocatorSize;
+  private final BufferAllocator metadataAllocator;
+  private final LanceFileReader metadataReader;
+  private final Schema arrowSchema;
+  private boolean closed;
+
+  public HoodieRowDataLanceReader(StoragePath path, HoodieConfig hoodieConfig) 
{
+    this.path = path;
+    this.dataAllocatorSize = 
hoodieConfig.getLongOrDefault(HoodieStorageConfig.LANCE_READ_ALLOCATOR_SIZE_BYTES);
+    this.metadataAllocator = HoodieArrowAllocator.newChildAllocator(
+        getClass().getSimpleName() + "-metadata-" + path.getName(),
+        
hoodieConfig.getLongOrDefault(HoodieStorageConfig.LANCE_READ_METADATA_ALLOCATOR_SIZE_BYTES));
+    try {
+      this.metadataReader = LanceFileReader.open(path.toString(), 
metadataAllocator);
+      this.arrowSchema = metadataReader.schema();
+    } catch (Exception e) {
+      close();
+      throw new HoodieException("Failed to create Lance reader for: " + path, 
e);
+    }
+  }
+
+  @Override
+  public String[] readMinMaxRecordKeys() {
+    Map<String, String> metadata = arrowSchema.getCustomMetadata();
+    if (metadata != null) {
+      String minKey = metadata.get(HOODIE_MIN_RECORD_KEY_FOOTER);
+      String maxKey = metadata.get(HOODIE_MAX_RECORD_KEY_FOOTER);
+      if (minKey != null && maxKey != null) {
+        return new String[] {minKey, maxKey};
+      }
+    }
+    throw new HoodieException("Could not read min/max record key out of Lance 
file: " + path);
+  }
+
+  @Override
+  public BloomFilter readBloomFilter() {
+    Map<String, String> metadata = arrowSchema.getCustomMetadata();
+    if (metadata == null || 
!metadata.containsKey(HOODIE_AVRO_BLOOM_FILTER_METADATA_KEY)) {
+      return null;
+    }
+    String bloomSer = metadata.get(HOODIE_AVRO_BLOOM_FILTER_METADATA_KEY);
+    String filterType = metadata.get(HOODIE_BLOOM_FILTER_TYPE_CODE);
+    if (filterType != null && 
filterType.contains(HoodieDynamicBoundedBloomFilter.TYPE_CODE_PREFIX)) {
+      return new HoodieDynamicBoundedBloomFilter(bloomSer);
+    }
+    return new SimpleBloomFilter(bloomSer);
+  }
+
+  @Override
+  public Set<Pair<String, Long>> filterRowKeys(Set<String> candidateRowKeys) {
+    throw new HoodieException("Filtering row keys from Lance files is not 
supported for Flink append-only tables without primary keys: " + path);
+  }
+
+  @Override
+  public ClosableIterator<HoodieRecord<RowData>> 
getRecordIterator(HoodieSchema readerSchema, HoodieSchema requestedSchema) 
throws IOException {
+    ClosableIterator<RowData> rowDataItr = 
getRowDataIterator(RowDataQueryContexts.fromSchema(requestedSchema).getRowType(),
 requestedSchema);
+    return new CloseableMappingIterator<>(rowDataItr, HoodieFlinkRecord::new);
+  }
+
+  @Override
+  public ClosableIterator<String> getRecordKeyIterator() throws IOException {
+    HoodieSchema schema = HoodieSchemaUtils.getRecordKeySchema();
+    ClosableIterator<RowData> rowDataItr = 
getRowDataIterator(RowDataQueryContexts.fromSchema(schema).getRowType(), 
schema);
+    return new CloseableMappingIterator<>(rowDataItr, rowData -> 
rowData.getString(0).toString());
+  }
+
+  public ClosableIterator<RowData> getRowDataIterator(DataType dataType, 
HoodieSchema requestedSchema) {
+    RowType rowType = (RowType) dataType.getLogicalType();

Review Comment:
   🤖 nit: `requestedSchema` is declared but never used in the method body — 
only `dataType` drives the column projection. Could you either remove the 
unused parameter or add a brief comment explaining why it's kept (e.g. reserved 
for future filter pushdown)?
   
   <sub><i>- AI-generated; verify before applying. React 👍/👎 to flag 
quality.</i></sub>



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

Reply via email to