ahmedabu98 commented on code in PR #39836:
URL: https://github.com/apache/beam/pull/39836#discussion_r3832185414


##########
sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/AddFilesTest.java:
##########
@@ -518,6 +522,241 @@ public void testCatchFileNotFoundException() throws 
IOException {
     pipeline.run().waitUntilFinish();
   }
 
+  /** Infrastructure failures must fail the bundle, not become 
silently-dropped error rows. */
+  @Test
+  public void testCatalogOutageFailsBundleInsteadOfDlq() throws Exception {
+    String file1 = root + "data1.parquet";
+    DataWriter<Record> writer = createWriter(file1);
+    writer.write(record(1, "Mark", 20));
+    writer.close();
+
+    IcebergCatalogConfig unreachable =
+        IcebergCatalogConfig.builder()
+            .setCatalogProperties(ImmutableMap.of("type", "rest", "uri", 
"http://localhost:1";))
+            .build();
+    pipeline
+        .apply("Create Input", Create.of(file1))
+        .apply(new AddFiles(unreachable, tableId.toString(), null, null, null, 
null, null, null));
+    assertThrows(Exception.class, () -> pipeline.run().waitUntilFinish());
+  }
+
+  /** A file deleted between listing and registration is one error row, never 
a stuck bundle. */
+  @Test
+  public void testMissingFileWithExistingTableRoutesToDlq() {
+    catalog.createTable(tableId, icebergSchema);
+    String missing = root + "missing.parquet";
+
+    PCollectionRowTuple output =
+        pipeline
+            .apply("Create Input", Create.of(missing))
+            .apply(
+                new AddFiles(
+                    catalogConfig, tableId.toString(), null, null, null, null, 
null, null));
+    PAssert.that(output.get("errors"))
+        .satisfies(
+            rows -> {
+              Row row = Iterables.getOnlyElement(rows);
+              assertEquals(missing, row.getString("file"));
+              assertThat(row.getString("error"), containsString("No files 
found"));
+              return null;
+            });
+    pipeline.run().waitUntilFinish();
+
+    assertEquals(0, Iterables.size(catalog.loadTable(tableId).snapshots()));
+  }
+
+  @Test
+  public void testGarbageParquetWithExistingTableRoutesToDlq() throws 
Exception {
+    catalog.createTable(tableId, icebergSchema);
+    File garbage = temp.newFile("garbage.parquet");
+    java.nio.file.Files.write(
+        garbage.toPath(), "not 
parquet".getBytes(java.nio.charset.StandardCharsets.UTF_8));
+    String file = garbage.getAbsolutePath();
+
+    PCollectionRowTuple output =
+        pipeline
+            .apply("Create Input", Create.of(file))
+            .apply(
+                new AddFiles(
+                    catalogConfig, tableId.toString(), null, null, null, null, 
null, null));
+    PAssert.that(output.get("errors"))
+        .satisfies(
+            rows -> {
+              Row row = Iterables.getOnlyElement(rows);
+              assertEquals(file, row.getString("file"));
+              assertNotNull(row.getString("error"));
+              return null;
+            });
+    pipeline.run().waitUntilFinish();
+
+    assertEquals(0, Iterables.size(catalog.loadTable(tableId).snapshots()));
+  }
+
+  @Test
+  public void testStaleNameMappingRegeneratedAtCommit() throws Exception {
+    Table table = catalog.createTable(tableId, icebergSchema);
+    // A mapping generated against an older version of the schema (covers only 
"id"), carrying a
+    // user-added alias.
+    table
+        .updateProperties()
+        .set(
+            TableProperties.DEFAULT_NAME_MAPPING,
+            json("[ {'field-id': 1, 'names': ['id', 'ident']} ]"))
+        .commit();
+
+    String file1 = root + "data1.parquet";
+    DataWriter<Record> writer = createWriter(file1);
+    writer.write(record(1, "Mark", 20));
+    writer.close();
+
+    PCollectionRowTuple output =
+        pipeline
+            .apply("Create Input", Create.of(file1))
+            .apply(
+                new AddFiles(
+                    catalogConfig, tableId.toString(), null, null, null, null, 
null, null));
+    PAssert.that(output.get("errors")).empty();
+    pipeline.run().waitUntilFinish();
+
+    NameMapping mapping = currentMapping();
+    assertNotNull(mapping.find("name"));
+    assertNotNull(mapping.find("age"));
+    // The user's alias survived the regeneration.
+    assertNotNull(mapping.find("ident"));

Review Comment:
   include     `assertNotNull(mapping.find("id"));` ?



##########
sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/AddFilesTest.java:
##########
@@ -518,6 +522,241 @@ public void testCatchFileNotFoundException() throws 
IOException {
     pipeline.run().waitUntilFinish();
   }
 
+  /** Infrastructure failures must fail the bundle, not become 
silently-dropped error rows. */
+  @Test
+  public void testCatalogOutageFailsBundleInsteadOfDlq() throws Exception {
+    String file1 = root + "data1.parquet";
+    DataWriter<Record> writer = createWriter(file1);
+    writer.write(record(1, "Mark", 20));
+    writer.close();
+
+    IcebergCatalogConfig unreachable =
+        IcebergCatalogConfig.builder()
+            .setCatalogProperties(ImmutableMap.of("type", "rest", "uri", 
"http://localhost:1";))
+            .build();
+    pipeline
+        .apply("Create Input", Create.of(file1))
+        .apply(new AddFiles(unreachable, tableId.toString(), null, null, null, 
null, null, null));
+    assertThrows(Exception.class, () -> pipeline.run().waitUntilFinish());
+  }
+
+  /** A file deleted between listing and registration is one error row, never 
a stuck bundle. */
+  @Test
+  public void testMissingFileWithExistingTableRoutesToDlq() {
+    catalog.createTable(tableId, icebergSchema);
+    String missing = root + "missing.parquet";
+
+    PCollectionRowTuple output =
+        pipeline
+            .apply("Create Input", Create.of(missing))
+            .apply(
+                new AddFiles(
+                    catalogConfig, tableId.toString(), null, null, null, null, 
null, null));
+    PAssert.that(output.get("errors"))
+        .satisfies(
+            rows -> {
+              Row row = Iterables.getOnlyElement(rows);
+              assertEquals(missing, row.getString("file"));
+              assertThat(row.getString("error"), containsString("No files 
found"));
+              return null;
+            });
+    pipeline.run().waitUntilFinish();
+
+    assertEquals(0, Iterables.size(catalog.loadTable(tableId).snapshots()));
+  }
+
+  @Test
+  public void testGarbageParquetWithExistingTableRoutesToDlq() throws 
Exception {
+    catalog.createTable(tableId, icebergSchema);
+    File garbage = temp.newFile("garbage.parquet");
+    java.nio.file.Files.write(
+        garbage.toPath(), "not 
parquet".getBytes(java.nio.charset.StandardCharsets.UTF_8));
+    String file = garbage.getAbsolutePath();
+
+    PCollectionRowTuple output =
+        pipeline
+            .apply("Create Input", Create.of(file))
+            .apply(
+                new AddFiles(
+                    catalogConfig, tableId.toString(), null, null, null, null, 
null, null));
+    PAssert.that(output.get("errors"))
+        .satisfies(
+            rows -> {
+              Row row = Iterables.getOnlyElement(rows);
+              assertEquals(file, row.getString("file"));
+              assertNotNull(row.getString("error"));
+              return null;
+            });
+    pipeline.run().waitUntilFinish();
+
+    assertEquals(0, Iterables.size(catalog.loadTable(tableId).snapshots()));
+  }
+
+  @Test
+  public void testStaleNameMappingRegeneratedAtCommit() throws Exception {
+    Table table = catalog.createTable(tableId, icebergSchema);
+    // A mapping generated against an older version of the schema (covers only 
"id"), carrying a
+    // user-added alias.
+    table
+        .updateProperties()
+        .set(
+            TableProperties.DEFAULT_NAME_MAPPING,
+            json("[ {'field-id': 1, 'names': ['id', 'ident']} ]"))
+        .commit();
+
+    String file1 = root + "data1.parquet";
+    DataWriter<Record> writer = createWriter(file1);
+    writer.write(record(1, "Mark", 20));
+    writer.close();
+
+    PCollectionRowTuple output =
+        pipeline
+            .apply("Create Input", Create.of(file1))
+            .apply(
+                new AddFiles(
+                    catalogConfig, tableId.toString(), null, null, null, null, 
null, null));
+    PAssert.that(output.get("errors")).empty();
+    pipeline.run().waitUntilFinish();
+
+    NameMapping mapping = currentMapping();
+    assertNotNull(mapping.find("name"));
+    assertNotNull(mapping.find("age"));
+    // The user's alias survived the regeneration.
+    assertNotNull(mapping.find("ident"));

Review Comment:
   also for all these assertions, would it be possible to generate an 
"expected" cherNameMapping object (i think the general case would just be 
creating it from the schema) and do a simple equality check?



##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/AddFiles.java:
##########
@@ -749,12 +747,23 @@ public CommitManifestFilesDoFn(IcebergCatalogConfig 
catalogConfig, String identi
     }
 
     private static void ensureNameMappingPresent(Table table) {
-      if (table.properties().get(TableProperties.DEFAULT_NAME_MAPPING) == 
null) {
-        // Forces Name based resolution instead of position based resolution
-        NameMapping mapping = MappingUtil.create(table.schema());
-        String mappingJson = NameMappingParser.toJson(mapping);
-        table.updateProperties().set(TableProperties.DEFAULT_NAME_MAPPING, 
mappingJson).commit();
+      // Forces name-based resolution: zero-copy files carry no field ids, so 
any schema column

Review Comment:
   ```suggestion
         // Forces name-based resolution: zero-copy files typically don't carry 
field ids, so any schema column
   ```
   
   nit: Parquet files written with Iceberg will have field ids, so this doesn't 
apply for use cases registering files written by another Iceberg catalog



##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/NameMappingUtils.java:
##########
@@ -0,0 +1,211 @@
+/*
+ * 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.beam.sdk.io.iceberg;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import 
org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.mapping.MappedField;
+import org.apache.iceberg.mapping.MappedFields;
+import org.apache.iceberg.mapping.MappingUtil;
+import org.apache.iceberg.mapping.NameMapping;
+import org.apache.iceberg.mapping.NameMappingParser;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Helpers for the {@code schema.name-mapping.default} table property, which 
zero-copy registered
+ * files (no embedded field ids) depend on for column resolution.
+ */
+class NameMappingUtils {
+  private static final Logger LOG = 
LoggerFactory.getLogger(NameMappingUtils.class);
+
+  private NameMappingUtils() {}
+
+  /** A damaged property must self-heal via regeneration, never poison the 
stage reading it. */
+  static @Nullable NameMapping parseOrNull(@Nullable String mappingJson) {
+    if (mappingJson == null) {
+      return null;
+    }
+    try {
+      return NameMappingParser.fromJson(mappingJson);
+    } catch (RuntimeException e) {
+      LOG.warn(
+          "Malformed {} property; it will be regenerated from the schema: {}",

Review Comment:
   should we also log the malformed `mappingJson` ?



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