Copilot commented on code in PR #15308:
URL: https://github.com/apache/iceberg/pull/15308#discussion_r2836339474


##########
bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryTableOperations.java:
##########
@@ -82,48 +84,49 @@ public void doRefresh() {
   // atomically
   @Override
   public void doCommit(TableMetadata base, TableMetadata metadata) {
-    String newMetadataLocation =
-        base == null && metadata.metadataFileLocation() != null
-            ? metadata.metadataFileLocation()
-            : writeNewMetadata(metadata, currentVersion() + 1);
-    BaseMetastoreOperations.CommitStatus commitStatus =
-        BaseMetastoreOperations.CommitStatus.FAILURE;
+    CommitStatus commitStatus = CommitStatus.FAILURE;
+    RetryDetector retryDetector = new RetryDetector();
+
+    String newMetadataLocation = null;
     try {
-      if (base == null) {
-        createTable(newMetadataLocation, metadata);
+      boolean newTable = base == null;
+      newMetadataLocation = writeNewMetadataIfRequired(newTable, metadata);
+
+      if (newTable) {
+        createTable(newMetadataLocation, metadata, retryDetector);
       } else {
-        updateTable(newMetadataLocation, metadata);
+        updateTable(newMetadataLocation, metadata, retryDetector);
       }
-      commitStatus = BaseMetastoreOperations.CommitStatus.SUCCESS;
-    } catch (CommitFailedException | CommitStateUnknownException e) {
+      commitStatus = CommitStatus.SUCCESS;
+    } catch (CommitFailedException e) {
       throw e;
     } catch (Throwable e) {
       LOG.error("Exception thrown on commit: ", e);
-      if (e instanceof AlreadyExistsException) {
-        throw e;
+      boolean isAlreadyExistsException = e instanceof AlreadyExistsException;
+      boolean isRuntimeIOException = e instanceof RuntimeIOException;
+
+      // If retries occurred, an earlier attempt may have succeeded. If we got 
a
+      // RuntimeIOException, we have no way of knowing if the request reached 
the server.
+      // In either case, check whether the commit actually succeeded.
+      if (isRuntimeIOException || retryDetector.retried()) {
+        LOG.warn(
+            "Received unexpected failure when committing to {}, validating if 
commit ended up succeeding.",
+            tableName(),
+            e);
+        commitStatus = checkCommitStatus(newMetadataLocation, metadata);
       }

Review Comment:
   There's a potential NullPointerException if an exception occurs during 
writeNewMetadataIfRequired. If a RuntimeIOException is thrown before 
newMetadataLocation is set, the code will call checkCommitStatus with a null 
newMetadataLocation, which will cause a NullPointerException in the parent 
class's checkCurrentMetadataLocation method when it calls .equals() on the null 
value. Consider adding a null check: `if ((isRuntimeIOException || 
retryDetector.retried()) && newMetadataLocation != null)`



##########
bigquery/src/test/java/org/apache/iceberg/gcp/bigquery/TestBigQueryTableOperations.java:
##########
@@ -288,4 +294,44 @@ private static Optional<String> metadataFilePath(String 
tableDir) throws IOExcep
 
     return Optional.empty();
   }
+
+  private TableMetadata createTestMetadata() {
+    return TableMetadata.newTableMetadata(
+        SCHEMA,
+        PartitionSpec.unpartitioned(),
+        SortOrder.unsorted(),
+        tempFolder.getPath() + "/test-table",
+        ImmutableMap.of());
+  }
+
+  @Test
+  public void testCommitFailedExceptionThrowsDirectly() {
+    // CommitFailedException should fail immediately without retry or status 
checks
+    when(client.load(TABLE_REFERENCE)).thenThrow(new 
NoSuchTableException("Table not found"));
+    when(client.create(any(), any())).thenThrow(new 
CommitFailedException("Commit rejected"));
+
+    tableOps.refresh();
+
+    assertThatThrownBy(() -> tableOps.commit(null, createTestMetadata()))
+        .isInstanceOf(CommitFailedException.class)
+        .hasMessage("Commit rejected");
+
+    verify(client, times(1)).create(any(Table.class), 
any(RetryDetector.class));
+    verify(client, times(1)).load(TABLE_REFERENCE);
+  }
+
+  @Test
+  public void testRuntimeIOExceptionTriggersCommitStatusCheck() {
+    // RuntimeIOException should trigger commit status check as the commit may 
have succeeded
+    when(client.load(TABLE_REFERENCE)).thenThrow(new 
NoSuchTableException("Table not found"));
+    when(client.create(any(), any())).thenThrow(new 
RuntimeIOException("Network error"));
+
+    tableOps.refresh();
+
+    assertThatThrownBy(() -> tableOps.commit(null, createTestMetadata()))
+        .isInstanceOf(CommitStateUnknownException.class)
+        .hasMessageContaining("Network error");
+
+    verify(client, atLeast(2)).load(TABLE_REFERENCE);
+  }

Review Comment:
   Consider adding test coverage for additional scenarios: (1) a retry occurs 
and the commit actually succeeds (mock should return success on 
checkCommitStatus), (2) AlreadyExistsException is thrown during create/update, 
and (3) RuntimeIOException during update operation (not just create). These 
scenarios would help ensure the retry detection logic works correctly across 
different failure modes.



##########
bigquery/src/test/java/org/apache/iceberg/gcp/bigquery/util/TestRetryDetector.java:
##########
@@ -0,0 +1,75 @@
+/*
+ * 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.iceberg.gcp.bigquery.util;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+public class TestRetryDetector {
+  @Test
+  public void testNoAttempts() {
+    RetryDetector detector = new RetryDetector();
+    assertThat(detector.retried()).isFalse();
+    assertThat(detector.attempts()).isEqualTo(0);
+  }
+
+  @Test
+  public void testSingleAttempt() throws Exception {
+    RetryDetector detector = new RetryDetector();
+    detector.wrap(() -> "result").call();
+    assertThat(detector.retried()).isFalse();
+    assertThat(detector.attempts()).isEqualTo(1);
+  }
+
+  @Test
+  public void testAttemptCountedOnException() {
+    RetryDetector detector = new RetryDetector();
+    try {
+      detector
+          .wrap(
+              () -> {
+                throw new RuntimeException("test error");
+              })
+          .call();
+    } catch (Exception e) {
+      // an exception is expected, we're verifying the counter increments 
before the callable
+      // executes

Review Comment:
   The comment is slightly misleading. Consider rephrasing to: "an exception is 
expected, we're verifying the counter increments even when the callable throws 
an exception" to make it clearer that the test verifies exception handling 
rather than execution order.
   ```suggestion
         // an exception is expected; we're verifying the counter increments 
even when the callable
         // throws an exception
   ```



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