tkhurana commented on code in PR #2673:
URL: https://github.com/apache/phoenix/pull/2673#discussion_r4589379102


##########
phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/HighAvailabilityUtil.java:
##########
@@ -98,6 +112,36 @@ public static boolean 
isReplicationFailoverInProgressExceptionExistsInThrowable(
     return 
isReplicationFailoverInProgressExceptionExistsInThrowable(e.getCause());
   }
 
+  /**
+   * If {@code e} on an HA connection carries a {@link 
StaleClusterRoleRecordException}, force a CRR
+   * refresh (which closes the connection when its cluster is no longer 
active) and return
+   * FAILOVER_IN_PROGRESS with {@code e} as the cause; otherwise return {@code 
e} unchanged.
+   */
+  public static SQLException toFailoverInProgressIfStale(PhoenixConnection 
conn, SQLException e) {
+    HighAvailabilityGroup haGroup = conn == null ? null : conn.getHAGroup();
+    if (
+      haGroup == null || e.getErrorCode() == 
SQLExceptionCode.FAILOVER_IN_PROGRESS.getErrorCode()
+        || !isStaleClusterRoleRecordExceptionExistsInThrowable(e)
+    ) {
+      return e;
+    }
+    GLOBAL_HA_STALE_CRR_DETECTED_COUNT.increment();
+    HAGroupMetricsManager.increment(haGroup.getName(), 
MetricType.HA_STALE_CRR_DETECTED_COUNT);
+    try {
+      if (!haGroup.refreshClusterRoleRecord(true)) {
+        LOG.error("Failed to refresh cluster role record for HAGroup {}", 
haGroup.getName());
+      }
+    } catch (SQLException refreshError) {
+      LOG.error("Failed to refresh cluster role record for HAGroup {}", 
haGroup.getName(),
+        refreshError);
+      e.setNextException(refreshError);

Review Comment:
   `setNextException` mutates the caller's exception. It also leaves the 
refresh error at `getCause().getNextException()`, where neither 
`printStackTrace` nor iterating the top-level exception reaches it. Suggest 
building the FAILOVER_IN_PROGRESS exception first and calling 
`addSuppressed(refreshError)` on it.
   
   Also, this turns a `HA_ROLE_TRANSITION_NOT_ALLOWED` from the refresh into 
FAILOVER_IN_PROGRESS. `FailoverPhoenixConnection.wrapActionDuringFailover` 
(`:364`) lets that error propagate as-is. Should it be rethrown here too, for 
consistency?



##########
phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/HighAvailabilityUtil.java:
##########
@@ -98,6 +112,36 @@ public static boolean 
isReplicationFailoverInProgressExceptionExistsInThrowable(
     return 
isReplicationFailoverInProgressExceptionExistsInThrowable(e.getCause());
   }
 
+  /**
+   * If {@code e} on an HA connection carries a {@link 
StaleClusterRoleRecordException}, force a CRR
+   * refresh (which closes the connection when its cluster is no longer 
active) and return
+   * FAILOVER_IN_PROGRESS with {@code e} as the cause; otherwise return {@code 
e} unchanged.
+   */
+  public static SQLException toFailoverInProgressIfStale(PhoenixConnection 
conn, SQLException e) {

Review Comment:
   Could we add a unit test for this helper in `HighAvailabilityUtilTest`? The 
mocks in `FailoverPhoenixConnectionTest` already stub 
`PhoenixConnection`/`HighAvailabilityGroup`. Cases:
   - non-HA connection (null `haGroup`)
   - already FAILOVER_IN_PROGRESS
   - non-stale error
   - stale error nested in the cause chain
   - refresh returns false
   - refresh throws (no IT covers this path)
   
   A similar test for the new early rethrow in `wrapActionDuringFailover` 
should verify that `refreshClusterRoleRecord` is never called.



##########
phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/HighAvailabilityUtil.java:
##########
@@ -98,6 +112,36 @@ public static boolean 
isReplicationFailoverInProgressExceptionExistsInThrowable(
     return 
isReplicationFailoverInProgressExceptionExistsInThrowable(e.getCause());
   }
 
+  /**
+   * If {@code e} on an HA connection carries a {@link 
StaleClusterRoleRecordException}, force a CRR
+   * refresh (which closes the connection when its cluster is no longer 
active) and return
+   * FAILOVER_IN_PROGRESS with {@code e} as the cause; otherwise return {@code 
e} unchanged.
+   */
+  public static SQLException toFailoverInProgressIfStale(PhoenixConnection 
conn, SQLException e) {
+    HighAvailabilityGroup haGroup = conn == null ? null : conn.getHAGroup();
+    if (
+      haGroup == null || e.getErrorCode() == 
SQLExceptionCode.FAILOVER_IN_PROGRESS.getErrorCode()
+        || !isStaleClusterRoleRecordExceptionExistsInThrowable(e)
+    ) {
+      return e;
+    }
+    GLOBAL_HA_STALE_CRR_DETECTED_COUNT.increment();
+    HAGroupMetricsManager.increment(haGroup.getName(), 
MetricType.HA_STALE_CRR_DETECTED_COUNT);
+    try {
+      if (!haGroup.refreshClusterRoleRecord(true)) {
+        LOG.error("Failed to refresh cluster role record for HAGroup {}", 
haGroup.getName());
+      }
+    } catch (SQLException refreshError) {
+      LOG.error("Failed to refresh cluster role record for HAGroup {}", 
haGroup.getName(),
+        refreshError);
+      e.setNextException(refreshError);
+    }
+    return new SQLExceptionInfo.Builder(SQLExceptionCode.FAILOVER_IN_PROGRESS)
+      .setMessage(String.format("Operation failed because failover is in 
progress for HAGroup %s",
+        haGroup.getName()))
+      
.setRootCause(e).setHaGroupInfo(haGroup.getGroupInfo().toString()).build().buildException();

Review Comment:
   nit: the message leaves out the original error's message. The equivalent 
conversions in `FailoverPhoenixConnection.java:369` and 
`TableResultIterator.java:261` include it, which helps when only the top-level 
message gets logged.



##########
phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixStatement.java:
##########
@@ -2570,15 +2583,20 @@ public int[] executeBatch() throws SQLException {
       // Throw MutationLimitBatchException with checkpoint information
       throw new MutationLimitBatchException(returnCodes, limitEx, i);
     } catch (SQLException t) {
+      SQLException e = toFailoverInProgressIfStale(connection, t);
       if (i == returnCodes.length) {
         // Exception after for loop, perhaps in commit(), discard returnCodes.
-        throw new BatchUpdateException(t);
+        throw new BatchUpdateException(e);
       } else {
         returnCodes[i] = Statement.EXECUTE_FAILED;
-        throw new BatchUpdateException(returnCodes, t);
+        throw new BatchUpdateException(returnCodes, e);
       }
     } finally {
-      connection.setAutoCommit(autoCommit);
+      // A stale-CRR refresh above can close the connection; setAutoCommit 
would then throw and
+      // mask the BatchUpdateException.
+      if (!connection.isClosed()) {

Review Comment:
   `setAutoCommit` calls `checkOpen()`, which rejects `isClosed || isClosing` 
(`PhoenixConnection.java:805`). `refreshClusterRoleRecord` waits only 
`maxTransitionTimeMs` for the transition and does not cancel it on timeout 
(`HighAvailabilityGroup.java:1240-1247`), so the close can still be running 
here. In that case `setAutoCommit` throws and masks the `BatchUpdateException`. 
This is unlikely at the 5-minute default, but cheap to close:
   ```suggestion
         if (!connection.isClosed() && !connection.isClosing()) {
   ```



##########
phoenix-core/src/it/java/org/apache/phoenix/jdbc/FailoverPhoenixConnection2IT.java:
##########
@@ -524,6 +527,108 @@ public void testStaleCrrVersionDetection() throws 
Exception {
 
   }
 
+  /**
+   * Autocommit DML through PreparedStatement.executeUpdate commits on the 
wrapped connection, so
+   * the stale-CRR rejection must be mapped below FailoverPhoenixConnection.
+   */
+  @Test(timeout = 300000)
+  public void testStaleCrrWithAutoCommitPreparedStatementUpdate() throws 
Exception {
+    doTestStaleCrrWithAutoCommitDml(conn -> {
+      try (PreparedStatement ps =
+        conn.prepareStatement(String.format("UPSERT INTO %s VALUES(?, ?)", 
tableName))) {
+        int value = RandomUtils.nextInt();
+        ps.setInt(1, value);
+        ps.setInt(2, value);
+        assertEquals(1, ps.executeUpdate());
+      }
+    });
+  }
+
+  /** Same as above for Statement.executeUpdate(String). */
+  @Test(timeout = 300000)
+  public void testStaleCrrWithAutoCommitStatementUpdate() throws Exception {
+    doTestStaleCrrWithAutoCommitDml(conn -> {
+      try (Statement stmt = conn.createStatement()) {
+        int value = RandomUtils.nextInt();
+        assertEquals(1, stmt
+          .executeUpdate(String.format("UPSERT INTO %s VALUES(%d, %d)", 
tableName, value, value)));
+      }
+    });
+  }
+
+  /** Same as above for executeBatch, which commits once at the end of the 
batch. */
+  @Test(timeout = 300000)
+  public void testStaleCrrWithAutoCommitExecuteBatch() throws Exception {
+    doTestStaleCrrWithAutoCommitDml(conn -> {
+      try (PreparedStatement ps =
+        conn.prepareStatement(String.format("UPSERT INTO %s VALUES(?, ?)", 
tableName))) {
+        for (int i = 0; i < 2; i++) {
+          int value = RandomUtils.nextInt();
+          ps.setInt(1, value);
+          ps.setInt(2, value);
+          ps.addBatch();
+        }
+        try {
+          ps.executeBatch();
+        } catch (BatchUpdateException e) {
+          if (e.getCause() instanceof SQLException) {
+            throw (SQLException) e.getCause();
+          }
+          throw e;
+        }
+      }
+    });
+  }
+
+  private interface DmlOperation {
+    void run(Connection conn) throws SQLException;
+  }
+
+  private void doTestStaleCrrWithAutoCommitDml(DmlOperation op) throws 
Exception {
+    // Set autocommit through the connect properties: failover() reconnects 
with these properties,
+    // so a setAutoCommit(true) on the old wrapped connection is not carried 
over.
+    Properties props = new Properties();
+    props.putAll(clientProperties);
+    props.setProperty(PhoenixRuntime.AUTO_COMMIT_ATTRIB, "true");
+    Connection connection = 
DriverManager.getConnection(CLUSTERS.getJdbcHAUrl(), props);
+    assertTrue(connection.getAutoCommit());
+    op.run(connection);
+
+    // Demote cluster 1 on the server side only; the client keeps the old 
(ACTIVE) CRR.
+    CLUSTERS.transitClusterRole(haGroup, ACTIVE_TO_STANDBY, STANDBY, false);
+    CLUSTERS.transitClusterRole(haGroup, STANDBY, STANDBY, false);
+
+    try {
+      op.run(connection);

Review Comment:
   Suggest recording `GLOBAL_HA_STALE_CRR_DETECTED_COUNT` before this call and 
asserting it went up by exactly 1. That backs the "no double count" claim. 
`HAGroupMetricsIT.testStaleCrrDetectedCount` only asserts `after > before`, so 
a double count would still pass.
   
   A few small things in this helper too:
   - Wrap `connection` in try-with-resources, so a failed assertion doesn't 
leak it into later tests on this shared cluster.
   - Restore the `e.getCause() instanceof FailoverSQLException` check that 
`testStaleCrrVersionDetection` makes at `:513`.
   - In the `executeBatch` test, assert on `BatchUpdateException.getCause()` 
directly rather than rethrowing it. Rethrowing also unwraps unrelated failures.



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