Copilot commented on code in PR #12900:
URL: https://github.com/apache/gluten/pull/12900#discussion_r4664434704


##########
gluten-iceberg/src/main/scala/org/apache/iceberg/spark/source/GlutenIcebergSourceUtil.scala:
##########
@@ -158,22 +164,93 @@ object GlutenIcebergSourceUtil {
     )
   }
 
-  def getFieldIds(sparkScan: Scan): JHashMap[String, Integer] = {
-    val fieldIds = new JHashMap[String, Integer]()
-    getTable(sparkScan).schema().columns().asScala.foreach {
-      field => fieldIds.put(field.name(), field.fieldId())
+  def getFieldIds(sparkScan: Scan): JArrayList[IcebergFieldId] = {
+    val fieldIds = new JArrayList[IcebergFieldId]()
+    getExpectedSchema(sparkScan).columns().asScala.foreach {
+      field =>
+        fieldIds.add(new IcebergFieldId(
+          AvroSchemaUtil.makeCompatibleName(field.name()),
+          field.fieldId(),
+          childFieldIds(field.`type`())))
     }
     fieldIds
   }
 
+  def validateDataFileFieldIds(sparkScan: Scan, maxFiles: Int): Option[String] 
= {
+    val files = getScanTasks(sparkScan).flatMap {
+      case task if task.isFileScanTask => 
Iterator(task.asFileScanTask().file())
+      case task: CombinedScanTask => 
task.tasks().asScala.iterator.map(_.file())
+      case _ =>
+        throw new UnsupportedOperationException(
+          "Only support iceberg CombinedScanTask and FileScanTask.")
+    }
+    validateDataFileFieldIds(files, getTable(sparkScan).io(), maxFiles)
+  }
+
+  private def validateDataFileFieldIds(
+      files: Iterator[DataFile],
+      io: FileIO,
+      maxFiles: Int): Option[String] = {
+    require(maxFiles >= 0, "Field ID validation file limit must be 
nonnegative")
+    // Decide whether the whole scan fits the budget before opening any 
footer. Checking a
+    // sample is unsafe: an unchecked legacy file can silently return nulls or 
wrong columns.
+    val paths = mutable.LinkedHashSet.empty[(String, FileFormat)]
+    while (files.hasNext && paths.size <= maxFiles) {
+      val file = files.next()
+      paths += ((file.path().toString, file.format()))
+    }
+    if (paths.size > maxFiles) {
+      return Some(s"Iceberg field ID validation exceeds the limit of $maxFiles 
data files")
+    }
+
+    paths.iterator.map {
+      case (path, format) =>
+        try {
+          val hasIds = format match {
+            case FileFormat.PARQUET => 
GlutenParquetUtil.hasFieldIds(io.newInputFile(path))
+            case FileFormat.ORC => 
GlutenOrcUtil.hasFieldIds(io.newInputFile(path))

Review Comment:
   `ParquetSchemaUtil.hasIds` and `ORCSchemaUtil.hasIds` are existential 
checks: they return true when any field in the schema has an ID, not when every 
nested field has one. A file with only top-level (or partially nested) IDs 
therefore passes this validation, but the new reader is then given a recursive 
identity tree that cannot resolve the missing nested IDs, so evolved nested 
fields can still be read by name or incorrectly. Please validate that all 
fields needed by the projected schema have physical IDs, or explicitly support 
partial-ID files before accepting them here.



##########
cpp/velox/compute/iceberg/IcebergPlanConverter.cc:
##########
@@ -37,8 +39,72 @@ std::unordered_map<int32_t, std::string> parseBounds(const 
SubstraitDeleteBounds
   return parsed;
 }
 
+IcebergFieldIdInfo parseFieldId(const 
::gluten::IcebergReadExtension::ColumnFieldId& field) {
+  IcebergFieldIdInfo parsed{field.name(), field.field_id(), {}};
+  parsed.children.reserve(field.children_size());
+  for (const auto& child : field.children()) {
+    parsed.children.emplace_back(parseFieldId(child));
+  }
+  return parsed;
+}
+
+const IcebergFieldIdInfo* findChild(const IcebergFieldIdInfo& field, const 
std::string& name, bool asLowerCase) {
+  for (const auto& child : field.children) {
+    if (child.name == name) {
+      return &child;
+    }
+    if (asLowerCase) {
+      auto normalizedName = child.name;
+      folly::toLowerAscii(normalizedName);
+      if (normalizedName == name) {
+        return &child;
+      }
+    }
+  }
+  return nullptr;
+}
+
 } // namespace
 
+facebook::velox::parquet::ParquetFieldId 
IcebergPlanConverter::toParquetFieldId(
+    const IcebergFieldIdInfo& field,
+    const facebook::velox::TypePtr& type,
+    bool asLowerCase) {
+  facebook::velox::parquet::ParquetFieldId result{field.fieldId, {}};
+  // Plans produced before nested field IDs were added only contain the root 
ID.
+  if (field.children.empty()) {
+    return result;
+  }
+  auto appendChild = [&](const std::string& childName, const 
facebook::velox::TypePtr& childType) {
+    const auto* child = findChild(field, childName, asLowerCase);
+    VELOX_USER_CHECK(child != nullptr, "Missing Iceberg field ID for nested 
field '{}.{}'", field.name, childName);
+    result.children.emplace_back(toParquetFieldId(*child, childType, 
asLowerCase));
+  };
+
+  switch (type->kind()) {
+    case facebook::velox::TypeKind::ROW: {
+      const auto& rowType = type->asRow();
+      result.children.reserve(rowType.size());
+      for (facebook::velox::column_index_t i = 0; i < rowType.size(); ++i) {
+        appendChild(rowType.nameOf(i), rowType.childAt(i));
+      }
+      break;
+    }
+    case facebook::velox::TypeKind::ARRAY:
+      result.children.reserve(1);
+      appendChild("element", type->childAt(0));
+      break;
+    case facebook::velox::TypeKind::MAP:
+      result.children.reserve(2);
+      appendChild("key", type->childAt(0));
+      appendChild("value", type->childAt(1));

Review Comment:
   The new recursive conversion has no regression test for the cases this PR 
adds: struct children, array `element`, and map `key`/`value` IDs (including 
case-insensitive matching and missing-child failures). The existing Iceberg C++ 
test target is registered in `cpp/velox/tests/CMakeLists.txt`, but this diff 
only adjusts an unrelated Java constructor test, so a malformed or incomplete 
recursive tree could compile and regress without detection. Add plan-conversion 
tests covering these nested shapes and their generated `ParquetFieldId` trees.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to