wgtmac commented on code in PR #576:
URL: https://github.com/apache/iceberg-cpp/pull/576#discussion_r2930169864


##########
src/iceberg/update/update_snapshot_reference.h:
##########
@@ -134,6 +134,8 @@ class ICEBERG_EXPORT UpdateSnapshotReference : public 
PendingUpdate {
 
   Kind kind() const final { return Kind::kUpdateSnapshotReference; }
 
+  bool IsRetryable() const override { return false; }

Review Comment:
   Overriding `IsRetryable()` to explicitly return `false` causes 
`Transaction::CanRetry()` to fail any transaction containing branch or tag 
updates on conflicts. In Java, `SnapshotManager.commit()` utilizes 
`transaction.commitTransaction()`, which safely retries 
`UpdateSnapshotReferencesOperation`. Branch and tag creations should be 
retryable. Consider removing this override or returning `true`.



##########
src/iceberg/transaction.cc:
##########
@@ -343,6 +347,49 @@ Result<std::shared_ptr<Table>> Transaction::Commit() {
   return table_;
 }
 
+Result<std::shared_ptr<Table>> Transaction::CommitOnce() {
+  auto refresh_result = table_->Refresh();
+  if (!refresh_result.has_value()) {
+    return std::unexpected(refresh_result.error());
+  }
+
+  if (metadata_builder_->base() != table_->metadata().get()) {

Review Comment:
   `CommitOnce()` relies on `weak_update.lock()` to re-apply updates over 
refreshed metadata during a retry. Because `pending_updates_` holds 
`std::weak_ptr`, if a caller does not explicitly retain the 
`shared_ptr<PendingUpdate>` instance returned by `tx->New*()` methods (e.g., 
standard chained usage like 
`tx->NewUpdateSchema().value()->AddColumn(...)->Commit();`), the pointer 
expires. On retry, the expired update is silently skipped, resulting in a 
partially committed transaction that drops the user's modifications. A 
transaction must strongly own its updates to guarantee safe retries. Consider 
changing `pending_updates_` to use `std::shared_ptr<PendingUpdate>` and resolve 
the circular dependency by having `PendingUpdate` hold a 
`std::weak_ptr<Transaction>`.



##########
src/iceberg/util/retry_util.h:
##########
@@ -0,0 +1,180 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <chrono>
+#include <functional>
+#include <optional>
+#include <random>
+#include <thread>
+#include <vector>
+
+#include "iceberg/result.h"
+
+namespace iceberg {
+
+/// \brief Configuration for retry behavior
+struct RetryConfig {
+  /// Maximum number of retry attempts (not including the first attempt)
+  int32_t num_retries = 4;
+  /// Minimum wait time between retries in milliseconds
+  int32_t min_wait_ms = 100;
+  /// Maximum wait time between retries in milliseconds
+  int32_t max_wait_ms = 60 * 1000;  // 1 minute
+  /// Total maximum time for all retries in milliseconds
+  int32_t total_timeout_ms = 30 * 60 * 1000;  // 30 minutes
+  /// Exponential backoff scale factor
+  double scale_factor = 2.0;
+};
+
+/// \brief Utility class for running tasks with retry logic
+class RetryRunner {
+ public:
+  RetryRunner() = default;
+
+  RetryRunner& WithRetries(int32_t num_retries) {
+    config_.num_retries = num_retries;
+    return *this;
+  }
+
+  RetryRunner& WithExponentialBackoff(int32_t min_wait_ms, int32_t max_wait_ms,
+                                      int32_t total_timeout_ms, double 
scale_factor) {
+    config_.min_wait_ms = min_wait_ms;
+    config_.max_wait_ms = max_wait_ms;
+    config_.total_timeout_ms = total_timeout_ms;
+    config_.scale_factor = scale_factor;
+    return *this;
+  }
+
+  /// \brief Specify error types that should trigger a retry
+  RetryRunner& OnlyRetryOn(std::initializer_list<ErrorKind> error_kinds) {
+    only_retry_on_ = std::vector<ErrorKind>(error_kinds);
+    return *this;
+  }
+
+  /// \brief Specify error types that should trigger a retry
+  RetryRunner& OnlyRetryOn(ErrorKind error_kind) {
+    only_retry_on_ = std::vector<ErrorKind>{error_kind};
+    return *this;
+  }
+
+  /// \brief Specify error types that should stop retries immediately
+  RetryRunner& StopRetryOn(std::initializer_list<ErrorKind> error_kinds) {
+    stop_retry_on_ = std::vector<ErrorKind>(error_kinds);
+    return *this;
+  }
+
+  /// \brief Run a task that returns a Result<T>
+  template <typename F, typename T = typename 
std::invoke_result_t<F>::value_type>
+  Result<T> Run(F&& task, int32_t* attempt_counter = nullptr) {
+    auto start_time = std::chrono::steady_clock::now();
+    int32_t attempt = 0;
+    int32_t max_attempts = config_.num_retries + 1;
+
+    while (true) {
+      ++attempt;
+      if (attempt_counter != nullptr) {
+        *attempt_counter = attempt;
+      }
+
+      auto result = task();
+      if (result.has_value()) {
+        return result;
+      }
+
+      const auto& error = result.error();
+
+      auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
+                         std::chrono::steady_clock::now() - start_time)
+                         .count();
+
+      // total_timeout_ms <= 0 means no total timeout limit
+      bool timed_out = config_.total_timeout_ms > 0 &&
+                       elapsed > config_.total_timeout_ms && attempt > 1;
+      if (attempt >= max_attempts || timed_out) {
+        return result;

Review Comment:
   The `timed_out` check requires `attempt > 1`. If the *first* execution takes 
longer than `total_timeout_ms` to fail, `timed_out` will be falsely evaluated 
as `false`, and the runner will erroneously proceed to sleep and execute a 
second attempt. Java's `Tasks.java` strictly validates `durationMs > 
maxDurationMs` unconditionally and aborts immediately without attempting a 
retry. Remove the `&& attempt > 1` condition.



##########
src/iceberg/util/retry_util.h:
##########
@@ -0,0 +1,180 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <chrono>
+#include <functional>
+#include <optional>
+#include <random>
+#include <thread>
+#include <vector>
+
+#include "iceberg/result.h"
+
+namespace iceberg {
+
+/// \brief Configuration for retry behavior
+struct RetryConfig {
+  /// Maximum number of retry attempts (not including the first attempt)
+  int32_t num_retries = 4;
+  /// Minimum wait time between retries in milliseconds
+  int32_t min_wait_ms = 100;
+  /// Maximum wait time between retries in milliseconds
+  int32_t max_wait_ms = 60 * 1000;  // 1 minute
+  /// Total maximum time for all retries in milliseconds
+  int32_t total_timeout_ms = 30 * 60 * 1000;  // 30 minutes
+  /// Exponential backoff scale factor
+  double scale_factor = 2.0;
+};
+
+/// \brief Utility class for running tasks with retry logic
+class RetryRunner {
+ public:
+  RetryRunner() = default;
+
+  RetryRunner& WithRetries(int32_t num_retries) {
+    config_.num_retries = num_retries;
+    return *this;
+  }
+
+  RetryRunner& WithExponentialBackoff(int32_t min_wait_ms, int32_t max_wait_ms,
+                                      int32_t total_timeout_ms, double 
scale_factor) {
+    config_.min_wait_ms = min_wait_ms;
+    config_.max_wait_ms = max_wait_ms;
+    config_.total_timeout_ms = total_timeout_ms;
+    config_.scale_factor = scale_factor;
+    return *this;
+  }
+
+  /// \brief Specify error types that should trigger a retry
+  RetryRunner& OnlyRetryOn(std::initializer_list<ErrorKind> error_kinds) {
+    only_retry_on_ = std::vector<ErrorKind>(error_kinds);
+    return *this;
+  }
+
+  /// \brief Specify error types that should trigger a retry
+  RetryRunner& OnlyRetryOn(ErrorKind error_kind) {
+    only_retry_on_ = std::vector<ErrorKind>{error_kind};
+    return *this;
+  }
+
+  /// \brief Specify error types that should stop retries immediately
+  RetryRunner& StopRetryOn(std::initializer_list<ErrorKind> error_kinds) {
+    stop_retry_on_ = std::vector<ErrorKind>(error_kinds);
+    return *this;
+  }
+
+  /// \brief Run a task that returns a Result<T>
+  template <typename F, typename T = typename 
std::invoke_result_t<F>::value_type>
+  Result<T> Run(F&& task, int32_t* attempt_counter = nullptr) {
+    auto start_time = std::chrono::steady_clock::now();
+    int32_t attempt = 0;
+    int32_t max_attempts = config_.num_retries + 1;
+
+    while (true) {
+      ++attempt;
+      if (attempt_counter != nullptr) {
+        *attempt_counter = attempt;
+      }
+
+      auto result = task();
+      if (result.has_value()) {
+        return result;
+      }
+
+      const auto& error = result.error();
+
+      auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
+                         std::chrono::steady_clock::now() - start_time)
+                         .count();
+
+      // total_timeout_ms <= 0 means no total timeout limit
+      bool timed_out = config_.total_timeout_ms > 0 &&
+                       elapsed > config_.total_timeout_ms && attempt > 1;
+      if (attempt >= max_attempts || timed_out) {
+        return result;
+      }
+
+      if (!ShouldRetry(error.kind)) {
+        return result;
+      }
+
+      int32_t delay_ms = CalculateDelay(attempt);
+      Sleep(delay_ms);
+    }
+  }
+
+ private:
+  /// \brief Check if the given error kind should trigger a retry
+  bool ShouldRetry(ErrorKind kind) const {
+    if (only_retry_on_.has_value()) {
+      for (const auto& retry_kind : only_retry_on_.value()) {
+        if (kind == retry_kind) {
+          return true;
+        }
+      }
+      return false;
+    }
+
+    if (stop_retry_on_.has_value()) {
+      for (const auto& stop_kind : stop_retry_on_.value()) {
+        if (kind == stop_kind) {
+          return false;
+        }
+      }
+    }
+
+    return true;
+  }
+
+  /// \brief Calculate delay with exponential backoff and jitter
+  int32_t CalculateDelay(int32_t attempt) const {
+    // Calculate base delay with exponential backoff
+    double base_delay = config_.min_wait_ms * std::pow(config_.scale_factor, 
attempt - 1);
+    int32_t delay_ms = static_cast<int32_t>(
+        std::min(base_delay, static_cast<double>(config_.max_wait_ms)));
+
+    static thread_local std::mt19937 gen(std::random_device{}());
+    int32_t jitter_range = std::max(1, delay_ms / 10);
+    std::uniform_int_distribution<> dis(-jitter_range, jitter_range);
+    delay_ms += dis(gen);
+    return std::max(1, delay_ms);
+  }
+
+  /// \brief Sleep for the specified duration

Review Comment:
   The C++ jitter calculation uses a bidirectional spread `[-jitter_range, 
jitter_range]`. Java's `Tasks.java` specifically adds a strictly positive 
jitter: `[0, delayMs * 0.1)`. Consider generating a strictly positive random 
value `[0, jitter_range]` to align precisely with Java.



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