huaxingao commented on code in PR #3584:
URL: https://github.com/apache/polaris/pull/3584#discussion_r2761397826


##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStore.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * 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.polaris.persistence.relational.jdbc.idempotency;
+
+import jakarta.annotation.Nonnull;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import javax.sql.DataSource;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.persistence.relational.jdbc.DatasourceOperations;
+import org.apache.polaris.persistence.relational.jdbc.QueryGenerator;
+import 
org.apache.polaris.persistence.relational.jdbc.RelationalJdbcConfiguration;
+import 
org.apache.polaris.persistence.relational.jdbc.models.ImmutableModelIdempotencyRecord;
+import 
org.apache.polaris.persistence.relational.jdbc.models.ModelIdempotencyRecord;
+
+public class RelationalJdbcIdempotencyStore implements IdempotencyStore {
+
+  private final DatasourceOperations datasourceOperations;
+
+  public RelationalJdbcIdempotencyStore(
+      @Nonnull DataSource dataSource, @Nonnull RelationalJdbcConfiguration cfg)
+      throws SQLException {
+    this.datasourceOperations = new DatasourceOperations(dataSource, cfg);
+  }
+
+  @Override
+  public ReserveResult reserve(
+      String realmId,
+      String idempotencyKey,
+      String operationType,
+      String normalizedResourceId,
+      Instant expiresAt,
+      String executorId,
+      Instant now) {
+    try {
+      ModelIdempotencyRecord model =
+          ImmutableModelIdempotencyRecord.builder()
+              .realmId(realmId)
+              .idempotencyKey(idempotencyKey)
+              .operationType(operationType)
+              .resourceId(normalizedResourceId)
+              .createdAt(now)
+              .updatedAt(now)
+              .heartbeatAt(now)
+              .executorId(executorId)
+              .expiresAt(expiresAt)
+              .build();
+
+      List<Object> values =
+          
model.toMap(datasourceOperations.databaseType()).values().stream().toList();
+      QueryGenerator.PreparedQuery insert =
+          QueryGenerator.generateInsertQuery(
+              ModelIdempotencyRecord.ALL_COLUMNS,
+              ModelIdempotencyRecord.TABLE_NAME,
+              values,
+              realmId);
+      datasourceOperations.executeUpdate(insert);
+      return new ReserveResult(ReserveResultType.OWNED, Optional.empty());
+    } catch (SQLException e) {
+      if (datasourceOperations.isConstraintViolation(e)) {
+        return new ReserveResult(ReserveResultType.DUPLICATE, load(realmId, 
idempotencyKey));
+      }
+      throw new RuntimeException("Failed to reserve idempotency key", e);

Review Comment:
   Added `IdempotencyPersistenceException`



##########
persistence/relational-jdbc/src/test/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStorePostgresIT.java:
##########
@@ -37,14 +39,20 @@
 import org.testcontainers.junit.jupiter.Testcontainers;
 
 @Testcontainers
-public class PostgresIdempotencyStoreIT {
+public class RelationalJdbcIdempotencyStorePostgresIT {
 
   @Container
   private static final PostgreSQLContainer<?> POSTGRES =
-      new PostgreSQLContainer<>("postgres:17.5-alpine");
+      new PostgreSQLContainer<>(
+              containerSpecHelper("postgres", 
PostgresRelationalJdbcLifeCycleManagement.class)
+                  .dockerImageName(null)

Review Comment:
   null is intentional here: containerSpecHelper(...).dockerImageName(null) 
means “use the pinned default from Dockerfile-postgres-version and allow 
overrides via system props/env.



##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/QueryGenerator.java:
##########
@@ -209,6 +277,32 @@ public static PreparedQuery generateDeleteQuery(
         "DELETE FROM " + getFullyQualifiedTableName(tableName) + where.sql(), 
where.parameters());
   }
 
+  /**
+   * Builds a DELETE query that supports richer WHERE predicates (equality, 
greater-than, less-than,
+   * IS NULL, IS NOT NULL).
+   */
+  public static PreparedQuery generateDeleteQuery(

Review Comment:
   Added. Thanks



##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStore.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * 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.polaris.persistence.relational.jdbc.idempotency;
+
+import jakarta.annotation.Nonnull;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import javax.sql.DataSource;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.persistence.relational.jdbc.DatasourceOperations;
+import org.apache.polaris.persistence.relational.jdbc.QueryGenerator;
+import 
org.apache.polaris.persistence.relational.jdbc.RelationalJdbcConfiguration;
+import 
org.apache.polaris.persistence.relational.jdbc.models.ImmutableModelIdempotencyRecord;
+import 
org.apache.polaris.persistence.relational.jdbc.models.ModelIdempotencyRecord;
+
+public class RelationalJdbcIdempotencyStore implements IdempotencyStore {
+
+  private final DatasourceOperations datasourceOperations;
+
+  public RelationalJdbcIdempotencyStore(
+      @Nonnull DataSource dataSource, @Nonnull RelationalJdbcConfiguration cfg)
+      throws SQLException {
+    this.datasourceOperations = new DatasourceOperations(dataSource, cfg);
+  }
+
+  @Override
+  public ReserveResult reserve(
+      String realmId,
+      String idempotencyKey,
+      String operationType,
+      String normalizedResourceId,
+      Instant expiresAt,
+      String executorId,
+      Instant now) {
+    try {
+      ModelIdempotencyRecord model =
+          ImmutableModelIdempotencyRecord.builder()
+              .realmId(realmId)
+              .idempotencyKey(idempotencyKey)
+              .operationType(operationType)
+              .resourceId(normalizedResourceId)
+              .createdAt(now)
+              .updatedAt(now)
+              .heartbeatAt(now)
+              .executorId(executorId)
+              .expiresAt(expiresAt)
+              .build();
+
+      List<Object> values =
+          
model.toMap(datasourceOperations.databaseType()).values().stream().toList();
+      QueryGenerator.PreparedQuery insert =
+          QueryGenerator.generateInsertQuery(
+              ModelIdempotencyRecord.ALL_COLUMNS,
+              ModelIdempotencyRecord.TABLE_NAME,
+              values,
+              realmId);
+      datasourceOperations.executeUpdate(insert);
+      return new ReserveResult(ReserveResultType.OWNED, Optional.empty());
+    } catch (SQLException e) {
+      if (datasourceOperations.isConstraintViolation(e)) {
+        return new ReserveResult(ReserveResultType.DUPLICATE, load(realmId, 
idempotencyKey));
+      }
+      throw new RuntimeException("Failed to reserve idempotency key", e);
+    }
+  }
+
+  @Override
+  public Optional<IdempotencyRecord> load(String realmId, String 
idempotencyKey) {
+    try {
+      QueryGenerator.PreparedQuery query =
+          QueryGenerator.generateSelectQuery(
+              ModelIdempotencyRecord.SELECT_COLUMNS,
+              ModelIdempotencyRecord.TABLE_NAME,
+              Map.of(
+                  ModelIdempotencyRecord.REALM_ID,
+                  realmId,
+                  ModelIdempotencyRecord.IDEMPOTENCY_KEY,
+                  idempotencyKey));
+      List<IdempotencyRecord> results =
+          datasourceOperations.executeSelect(query, 
ModelIdempotencyRecord.CONVERTER);
+      if (results.isEmpty()) {
+        return Optional.empty();
+      }
+      if (results.size() > 1) {
+        throw new IllegalStateException(
+            "More than one idempotency record found for realm/key: "
+                + realmId
+                + "/"
+                + idempotencyKey);

Review Comment:
   This path is a safety check: (realmId, idempotencyKey) should be unique. 
Expected behavior is HTTP 500.



##########
persistence/relational-jdbc/src/test/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStorePostgresIT.java:
##########
@@ -37,14 +39,20 @@
 import org.testcontainers.junit.jupiter.Testcontainers;
 
 @Testcontainers
-public class PostgresIdempotencyStoreIT {
+public class RelationalJdbcIdempotencyStorePostgresIT {
 
   @Container
   private static final PostgreSQLContainer<?> POSTGRES =
-      new PostgreSQLContainer<>("postgres:17.5-alpine");
+      new PostgreSQLContainer<>(
+              containerSpecHelper("postgres", 
PostgresRelationalJdbcLifeCycleManagement.class)
+                  .dockerImageName(null)
+                  .asCompatibleSubstituteFor("postgres"))
+          .withDatabaseName("polaris_db")

Review Comment:
   Removed



##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/models/ModelIdempotencyRecord.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.polaris.persistence.relational.jdbc.models;
+
+import jakarta.annotation.Nullable;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.immutables.PolarisImmutable;
+import org.apache.polaris.persistence.relational.jdbc.DatabaseType;
+
+/**
+ * JDBC model for {@link IdempotencyRecord} mirroring the {@code 
idempotency_records} table.
+ *
+ * <p>This follows the same pattern as {@link ModelEvent}, separating the 
storage representation
+ * from the core domain model while still providing {@link Converter} helpers.
+ */
+@PolarisImmutable
+public interface ModelIdempotencyRecord extends Converter<IdempotencyRecord> {
+
+  String TABLE_NAME = "idempotency_records";
+
+  String REALM_ID = "realm_id";
+  String IDEMPOTENCY_KEY = "idempotency_key";
+  String OPERATION_TYPE = "operation_type";
+  String RESOURCE_ID = "resource_id";
+
+  String HTTP_STATUS = "http_status";
+  String ERROR_SUBTYPE = "error_subtype";
+  String RESPONSE_SUMMARY = "response_summary";
+  String RESPONSE_HEADERS = "response_headers";
+  String FINALIZED_AT = "finalized_at";
+
+  String CREATED_AT = "created_at";
+  String UPDATED_AT = "updated_at";
+  String HEARTBEAT_AT = "heartbeat_at";
+  String EXECUTOR_ID = "executor_id";
+  String EXPIRES_AT = "expires_at";
+
+  List<String> ALL_COLUMNS =
+      List.of(
+          IDEMPOTENCY_KEY,
+          OPERATION_TYPE,
+          RESOURCE_ID,
+          HTTP_STATUS,
+          ERROR_SUBTYPE,
+          RESPONSE_SUMMARY,
+          RESPONSE_HEADERS,
+          FINALIZED_AT,
+          CREATED_AT,
+          UPDATED_AT,
+          HEARTBEAT_AT,
+          EXECUTOR_ID,
+          EXPIRES_AT);
+
+  /**
+   * Columns to select when reading idempotency records.
+   *
+   * <p>{@code realm_id} is intentionally not part of {@link #ALL_COLUMNS} 
because {@link
+   * 
org.apache.polaris.persistence.relational.jdbc.QueryGenerator#generateInsertQuery(List,
 String,
+   * List, String)} appends it automatically for all relational-jdbc tables.
+   */
+  List<String> SELECT_COLUMNS =
+      List.of(
+          REALM_ID,
+          IDEMPOTENCY_KEY,
+          OPERATION_TYPE,
+          RESOURCE_ID,
+          HTTP_STATUS,
+          ERROR_SUBTYPE,
+          RESPONSE_SUMMARY,
+          RESPONSE_HEADERS,
+          FINALIZED_AT,
+          CREATED_AT,
+          UPDATED_AT,
+          HEARTBEAT_AT,
+          EXECUTOR_ID,
+          EXPIRES_AT);
+
+  /**
+   * Dummy instance to be used as a Converter when calling {@link 
#fromResultSet(ResultSet)}.
+   *
+   * <p>FIXME: fromResultSet() is a factory method and should be static or 
moved to a factory class.
+   */
+  ModelIdempotencyRecord CONVERTER =
+      ImmutableModelIdempotencyRecord.builder()
+          .realmId("")
+          .idempotencyKey("")
+          .operationType("")
+          .resourceId("")
+          .createdAt(Instant.EPOCH)
+          .updatedAt(Instant.EPOCH)
+          .expiresAt(Instant.EPOCH)
+          .build();

Review Comment:
   I’ve refactored this to avoid the dummy instance by introducing a static 
fromRow(ResultSet) and a stateless CONVERTER singleton that delegates to it.



##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/QueryGenerator.java:
##########
@@ -50,6 +50,15 @@ public record PreparedBatchQuery(String sql, 
List<List<Object>> parametersList)
   /** A container for the query fragment SQL string and the ordered parameter 
values. */
   record QueryFragment(String sql, List<Object> parameters) {}
 
+  /**
+   * Returns the fully-qualified table name used by relational-jdbc queries.
+   *
+   * @param tableName Target table name.
+   */
+  public static String fullyQualifiedTableName(@Nonnull String tableName) {
+    return getFullyQualifiedTableName(tableName);
+  }

Review Comment:
   Right, we don't need this. removed.



##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/models/ModelIdempotencyRecord.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.polaris.persistence.relational.jdbc.models;
+
+import jakarta.annotation.Nullable;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.immutables.PolarisImmutable;
+import org.apache.polaris.persistence.relational.jdbc.DatabaseType;
+
+/**
+ * JDBC model for {@link IdempotencyRecord} mirroring the {@code 
idempotency_records} table.
+ *
+ * <p>This follows the same pattern as {@link ModelEvent}, separating the 
storage representation
+ * from the core domain model while still providing {@link Converter} helpers.
+ */
+@PolarisImmutable
+public interface ModelIdempotencyRecord extends Converter<IdempotencyRecord> {
+
+  String TABLE_NAME = "idempotency_records";
+
+  String REALM_ID = "realm_id";
+  String IDEMPOTENCY_KEY = "idempotency_key";
+  String OPERATION_TYPE = "operation_type";
+  String RESOURCE_ID = "resource_id";
+
+  String HTTP_STATUS = "http_status";
+  String ERROR_SUBTYPE = "error_subtype";
+  String RESPONSE_SUMMARY = "response_summary";
+  String RESPONSE_HEADERS = "response_headers";
+  String FINALIZED_AT = "finalized_at";
+
+  String CREATED_AT = "created_at";
+  String UPDATED_AT = "updated_at";
+  String HEARTBEAT_AT = "heartbeat_at";
+  String EXECUTOR_ID = "executor_id";
+  String EXPIRES_AT = "expires_at";

Review Comment:
   Added.



##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStore.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * 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.polaris.persistence.relational.jdbc.idempotency;
+
+import jakarta.annotation.Nonnull;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import javax.sql.DataSource;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.persistence.relational.jdbc.DatasourceOperations;
+import org.apache.polaris.persistence.relational.jdbc.QueryGenerator;
+import 
org.apache.polaris.persistence.relational.jdbc.RelationalJdbcConfiguration;
+import 
org.apache.polaris.persistence.relational.jdbc.models.ImmutableModelIdempotencyRecord;
+import 
org.apache.polaris.persistence.relational.jdbc.models.ModelIdempotencyRecord;
+
+public class RelationalJdbcIdempotencyStore implements IdempotencyStore {
+
+  private final DatasourceOperations datasourceOperations;
+
+  public RelationalJdbcIdempotencyStore(
+      @Nonnull DataSource dataSource, @Nonnull RelationalJdbcConfiguration cfg)
+      throws SQLException {
+    this.datasourceOperations = new DatasourceOperations(dataSource, cfg);
+  }
+
+  @Override
+  public ReserveResult reserve(
+      String realmId,
+      String idempotencyKey,
+      String operationType,
+      String normalizedResourceId,
+      Instant expiresAt,
+      String executorId,
+      Instant now) {
+    try {
+      ModelIdempotencyRecord model =
+          ImmutableModelIdempotencyRecord.builder()
+              .realmId(realmId)
+              .idempotencyKey(idempotencyKey)
+              .operationType(operationType)
+              .resourceId(normalizedResourceId)
+              .createdAt(now)
+              .updatedAt(now)
+              .heartbeatAt(now)
+              .executorId(executorId)
+              .expiresAt(expiresAt)
+              .build();
+
+      List<Object> values =
+          
model.toMap(datasourceOperations.databaseType()).values().stream().toList();
+      QueryGenerator.PreparedQuery insert =
+          QueryGenerator.generateInsertQuery(
+              ModelIdempotencyRecord.ALL_COLUMNS,
+              ModelIdempotencyRecord.TABLE_NAME,
+              values,
+              realmId);
+      datasourceOperations.executeUpdate(insert);
+      return new ReserveResult(ReserveResultType.OWNED, Optional.empty());
+    } catch (SQLException e) {
+      if (datasourceOperations.isConstraintViolation(e)) {
+        return new ReserveResult(ReserveResultType.DUPLICATE, load(realmId, 
idempotencyKey));
+      }
+      throw new RuntimeException("Failed to reserve idempotency key", e);
+    }
+  }
+
+  @Override
+  public Optional<IdempotencyRecord> load(String realmId, String 
idempotencyKey) {
+    try {
+      QueryGenerator.PreparedQuery query =
+          QueryGenerator.generateSelectQuery(
+              ModelIdempotencyRecord.SELECT_COLUMNS,
+              ModelIdempotencyRecord.TABLE_NAME,
+              Map.of(
+                  ModelIdempotencyRecord.REALM_ID,
+                  realmId,
+                  ModelIdempotencyRecord.IDEMPOTENCY_KEY,
+                  idempotencyKey));
+      List<IdempotencyRecord> results =
+          datasourceOperations.executeSelect(query, 
ModelIdempotencyRecord.CONVERTER);
+      if (results.isEmpty()) {
+        return Optional.empty();
+      }
+      if (results.size() > 1) {
+        throw new IllegalStateException(
+            "More than one idempotency record found for realm/key: "
+                + realmId
+                + "/"
+                + idempotencyKey);
+      }
+      return Optional.of(results.getFirst());
+    } catch (SQLException e) {
+      throw new RuntimeException("Failed to load idempotency record", e);
+    }
+  }
+
+  @Override
+  public HeartbeatResult updateHeartbeat(
+      String realmId, String idempotencyKey, String executorId, Instant now) {
+    Optional<IdempotencyRecord> existing = load(realmId, idempotencyKey);
+    if (existing.isEmpty()) {
+      return HeartbeatResult.NOT_FOUND;
+    }
+
+    IdempotencyRecord record = existing.get();
+    if (record.getHttpStatus() != null) {
+      return HeartbeatResult.FINALIZED;
+    }
+    if (record.getExecutorId() == null || 
!record.getExecutorId().equals(executorId)) {
+      return HeartbeatResult.LOST_OWNERSHIP;
+    }
+
+    QueryGenerator.PreparedQuery update =
+        QueryGenerator.generateUpdateQuery(
+            ModelIdempotencyRecord.SELECT_COLUMNS,
+            ModelIdempotencyRecord.TABLE_NAME,
+            Map.of(
+                ModelIdempotencyRecord.HEARTBEAT_AT,
+                Timestamp.from(now),
+                ModelIdempotencyRecord.UPDATED_AT,
+                Timestamp.from(now)),
+            Map.of(
+                ModelIdempotencyRecord.REALM_ID,
+                realmId,
+                ModelIdempotencyRecord.IDEMPOTENCY_KEY,
+                idempotencyKey,
+                ModelIdempotencyRecord.EXECUTOR_ID,
+                executorId),
+            Map.of(),
+            Map.of(),
+            Set.of(ModelIdempotencyRecord.HTTP_STATUS),
+            Set.of());
+
+    try {
+      int updated = datasourceOperations.executeUpdate(update);
+      if (updated > 0) {
+        return HeartbeatResult.UPDATED;
+      }
+    } catch (SQLException e) {
+      throw new RuntimeException("Failed to update idempotency heartbeat", e);
+    }
+
+    // Raced with finalize/ownership loss; re-check to return a meaningful 
result.
+    Optional<IdempotencyRecord> after = load(realmId, idempotencyKey);
+    if (after.isEmpty()) {
+      return HeartbeatResult.NOT_FOUND;
+    }
+    if (after.get().getHttpStatus() != null) {
+      return HeartbeatResult.FINALIZED;
+    }
+    return HeartbeatResult.LOST_OWNERSHIP;
+  }

Review Comment:
   The actual heartbeat change is done via a single atomic UPDATE ... WHERE 
realm/key/executor AND http_status IS NULL, so it doesn’t require an explicit 
transaction for correctness.



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