github-actions[bot] commented on code in PR #41856:
URL: https://github.com/apache/beam/pull/41856#discussion_r4759465857


##########
sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryAvroUtilsTest.java:
##########
@@ -1239,4 +1244,98 @@ public void testSchemaCollisionsInAvroConversion() {
     String output = BigQueryAvroUtils.toGenericAvroSchema(schema, 
false).toString();
     assertThat(output.length(), greaterThan(0));
   }
+
+  @Test
+  public void testNullableNestedRecordWithDifferentNamespaceFailsToWrite() {
+    TableFieldSchema street = new 
TableFieldSchema().setName("street").setType("STRING");
+    TableFieldSchema city = new 
TableFieldSchema().setName("city").setType("STRING");
+    TableFieldSchema address =
+        new TableFieldSchema()
+            .setName("address")
+            .setType("RECORD")
+            .setMode("NULLABLE")
+            .setFields(Lists.newArrayList(street, city));
+    TableSchema table = new 
TableSchema().setFields(Lists.newArrayList(address));
+
+    Schema beamSchema = BigQueryAvroUtils.toGenericAvroSchema(table);
+
+    Schema userAddressSchema =
+        SchemaBuilder.record("address")
+            .namespace("com.example.events")
+            .fields()
+            .optionalString("street")
+            .optionalString("city")
+            .endRecord();
+
+    GenericRecord userAddress =
+        new GenericRecordBuilder(userAddressSchema)
+            .set("street", "1 Main St")
+            .set("city", "New York")
+            .build();
+
+    GenericRecord event = new GenericRecordBuilder(beamSchema).set("address", 
userAddress).build();
+
+    GenericDatumWriter<GenericRecord> writer = new 
GenericDatumWriter<>(beamSchema);
+
+    assertThrows(
+        UnresolvedUnionException.class,
+        () ->
+            writer.write(
+                event, EncoderFactory.get().binaryEncoder(new 
ByteArrayOutputStream(), null)));
+  }
+
+  @Test
+  public void testAvroRowWriterReportsNamespaceMismatch() throws Exception {
+    org.apache.beam.sdk.io.FileSystems.setDefaultPipelineOptions(
+        org.apache.beam.sdk.options.PipelineOptionsFactory.create());
+
+    TableFieldSchema street = new 
TableFieldSchema().setName("street").setType("STRING");
+    TableFieldSchema city = new 
TableFieldSchema().setName("city").setType("STRING");
+    TableFieldSchema address =
+        new TableFieldSchema()
+            .setName("address")
+            .setType("RECORD")
+            .setMode("NULLABLE")
+            .setFields(Lists.newArrayList(street, city));
+    TableSchema table = new 
TableSchema().setFields(Lists.newArrayList(address));
+    Schema beamSchema = BigQueryAvroUtils.toGenericAvroSchema(table);
+
+    Schema userAddressSchema =
+        SchemaBuilder.record("address")
+            .namespace("com.example.events")
+            .fields()
+            .optionalString("street")
+            .optionalString("city")
+            .endRecord();
+    GenericRecord userAddress =
+        new GenericRecordBuilder(userAddressSchema)
+            .set("street", "1 Main St")
+            .set("city", "New York")
+            .build();
+
+    String basename =
+        
java.nio.file.Files.createTempDirectory("bq-avro").toAbsolutePath().toString() 
+ "/out-";

Review Comment:
   **🟢 Low**: `Files.createTempDirectory("bq-avro")` leaves temporary 
directories behind on disk after the test finishes, and `rowWriter.close()` is 
not guaranteed to run if `assertThrows` fails. Consider using a JUnit `@Rule 
public TemporaryFolder tmpFolder = new TemporaryFolder();` and wrapping 
`AvroRowWriter` in a `try`-with-resources block (also consider adding a test 
verifying that a non-record `UnresolvedUnionException` on a nullable primitive 
field is rethrown as `DataFileWriter.AppendWriteException`).



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/AvroRowWriter.java:
##########
@@ -56,7 +57,48 @@ public void write(T element) throws IOException, 
BigQueryRowSerializationExcepti
     } catch (Exception e) {
       throw new BigQueryRowSerializationException(e);
     }
-    writer.append(serializedRequest);
+    try {
+      writer.append(serializedRequest);
+    } catch (DataFileWriter.AppendWriteException e) {
+      org.apache.avro.UnresolvedUnionException unionError = 
findUnresolvedUnion(e);
+      if (unionError != null) {
+        throw new 
BigQueryRowSerializationException(namespaceMismatchMessage(unionError), e);
+      }
+      throw e;
+    }
+  }
+
+  private static org.apache.avro.@Nullable UnresolvedUnionException 
findUnresolvedUnion(
+      Throwable error) {
+    for (Throwable current = error; current != null; current = 
current.getCause()) {
+      if (current instanceof org.apache.avro.UnresolvedUnionException) {
+        return (org.apache.avro.UnresolvedUnionException) current;
+      }
+    }
+    return null;

Review Comment:
   **🔴 Critical**: `UnresolvedUnionException` is thrown for *any* value that 
cannot be resolved against a union schema—not only nested record namespace 
mismatches. Because every `NULLABLE` column in a Beam-generated BigQuery Avro 
schema is a `["null", <type>]` union, passing the wrong Java type for a 
primitive nullable field (for example, an `Integer` instead of `Long` for an 
`INT64` column, or a `GenericData.Array`/`GenericData.Fixed` which also 
implement `GenericContainer`) will trigger `UnresolvedUnionException` and 
produce a misleading message:
   
   `Failed to write nested Avro record 'unknown' because it does not match the 
schema Beam generated from the BigQuery table ('unknown')...`
   
   In addition, this converts unrelated `AppendWriteException`s into 
`BigQueryRowSerializationException`s instead of rethrowing `e` as intended.
   
   Check that the unresolved datum is a `GenericContainer` with 
`Schema.Type.RECORD` and that the union contains a `Schema.Type.RECORD` branch 
with a different full name before constructing the mismatch message (returning 
`@Nullable String` from `namespaceMismatchMessage` and rethrowing `e` when 
`null`).



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