From f2003389d077364c47006217882c68f8e4baffb4 Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Mon, 23 Nov 2026 17:56:40 -0800 Subject: [PATCH 1/5] Allow cleanup publication in the named-delete transaction Pass the locked versions to a database-local handoff before changing the name. Roll back on publication failure and leave the existing delete path unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../github/ambry/named/MySqlNamedBlobDb.java | 38 +++++++++++++- .../ambry/named/MySqlNamedBlobDbTest.java | 51 +++++++++++++++++++ 2 files changed, 87 insertions(+), 2 deletions(-) diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java index b21e869f13..09d45eedf0 100644 --- a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java @@ -54,6 +54,7 @@ import java.util.IdentityHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -494,10 +495,36 @@ public CompletableFuture updateBlobTtlAndStateToReady(NamedBlobRecord @Override public CompletableFuture delete(String accountName, String containerName, String blobName) { + return delete(accountName, containerName, blobName, null); + } + + /** + * Hand ownership of the root and child cleanup to a durable worker. Unlike {@link #delete}, this path does not + * return IDs to dispatch a second, in-memory router delete. + */ + CompletableFuture deleteWithCleanupHandoff(String accountName, String containerName, String blobName, + CleanupHandoff handoff) { + return delete(accountName, containerName, blobName, Objects.requireNonNull(handoff)).thenApply(ignored -> null); + } + + @FunctionalInterface + interface CleanupHandoff { + /** + * Publish previously staged, immutable cleanup manifests for the exact locked versions, or throw if any is + * missing or mismatched. Use only this transaction: workers must not see the jobs until the name deletion + * commits. Do not fetch manifests over the network while holding the name locks. On a repeat, verify an + * existing handoff rather than issuing new deletes for a previously deleted version. + */ + void publish(Connection connection, short accountId, short containerId, String name, + List versions) throws SQLException; + } + + private CompletableFuture delete(String accountName, String containerName, String blobName, + CleanupHandoff handoff) { return executeTransactionAsync(accountName, containerName, false, (accountId, containerId, connection) -> { long startTime = this.time.milliseconds(); DeleteResult deleteResult = - run_delete_v2(accountName, containerName, blobName, accountId, containerId, connection); + run_delete_v2(accountName, containerName, blobName, accountId, containerId, connection, handoff); metricsRecoder.namedBlobDeleteTimeInMs.update(this.time.milliseconds() - startTime); return deleteResult; }, null, this.metricsRecoder.namedBlobDBDeleteErrorCount); @@ -1163,7 +1190,7 @@ private PutResult apply_ttl_update(NamedBlobRecord record, short accountId, shor } private DeleteResult run_delete_v2(String accountName, String containerName, String blobName, short accountId, - short containerId, Connection connection) throws Exception { + short containerId, Connection connection, CleanupHandoff handoff) throws Exception { String blobId; long version; Timestamp currentDeleteTime = null; @@ -1199,6 +1226,13 @@ private DeleteResult run_delete_v2(String accountName, String containerName, Str logger.error("Failed to execute query {}, {}", query, e.getMessage()); throw e; } + if (handoff != null) { + try { + handoff.publish(connection, accountId, containerId, blobName, Collections.unmodifiableList(blobVersions)); + } catch (SQLException e) { + throw new RestServiceException("Could not record named blob cleanup", e, RestServiceErrorCode.ServiceUnavailable); + } + } // only need to issue an update statement if the row was not already marked as deleted. if (!versionsToDelete.isEmpty()) { applyDelete(accountId, containerId, blobName, currentDeleteTime, versionsToDelete, connection); diff --git a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java index 397bf14def..598cb4be3c 100644 --- a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java +++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java @@ -62,6 +62,7 @@ import org.json.JSONObject; import org.junit.Assert; import org.junit.Test; +import org.mockito.InOrder; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @@ -124,6 +125,56 @@ public void testRetryDeleteNamedBlob() throws Exception { checkErrorCode(() -> namedBlobDb.delete(account.getName(), container.getName(), "blobName"), RestServiceErrorCode.NotFound); } + @Test + public void testCleanupHandoffFailureLeavesNamedVersionsIntact() throws Exception { + Connection connection = mock(Connection.class); + mockNamedVersionsForDelete(connection); + checkErrorCode(() -> namedBlobDb.deleteWithCleanupHandoff(account.getName(), container.getName(), "name", + (transaction, accountId, containerId, name, versions) -> { + assertSame(connection, transaction); + assertEquals(account.getId(), accountId); + assertEquals(container.getId(), containerId); + assertEquals("name", name); + assertEquals(Arrays.asList(new DeleteResult.BlobVersion(id, 2, false), + new DeleteResult.BlobVersion(id, 1, false)), versions); + throw new SQLException("Incomplete manifest for the second version"); + }), RestServiceErrorCode.ServiceUnavailable); + verify(connection).setAutoCommit(false); + verify(connection).rollback(); + verify(connection, never()).commit(); + verify(connection, never()).prepareStatement(startsWith("UPDATE")); + verify(connection, never()).prepareStatement(startsWith("DELETE")); + } + + @Test + public void testCleanupHandoffPrecedesNameMutationAndCommit() throws Exception { + Connection connection = mock(Connection.class); + PreparedStatement delete = mockNamedVersionsForDelete(connection); + MySqlNamedBlobDb.CleanupHandoff handoff = mock(MySqlNamedBlobDb.CleanupHandoff.class); + namedBlobDb.deleteWithCleanupHandoff(account.getName(), container.getName(), "name", handoff) + .get(5, TimeUnit.SECONDS); + InOrder order = inOrder(connection, handoff, delete); + order.verify(connection).setAutoCommit(false); + order.verify(handoff).publish(eq(connection), eq(account.getId()), eq(container.getId()), eq("name"), anyList()); + order.verify(delete).executeUpdate(); + order.verify(connection).commit(); + } + + private PreparedStatement mockNamedVersionsForDelete(Connection connection) throws SQLException { + PreparedStatement select = mock(PreparedStatement.class); + PreparedStatement delete = mock(PreparedStatement.class); + ResultSet versions = mock(ResultSet.class); + when(dataSourceFactory.dataSources.get(localDatacenter).getConnection()).thenReturn(connection); + when(connection.prepareStatement(startsWith("SELECT"))).thenReturn(select); + when(connection.prepareStatement(startsWith("UPDATE"))).thenReturn(delete); + when(connection.prepareStatement(startsWith("DELETE"))).thenReturn(delete); + when(select.executeQuery()).thenReturn(versions); + when(versions.next()).thenReturn(true, true, false); + when(versions.getBytes(1)).thenReturn(Utils.base64DecodeUrlSafe(id)); + when(versions.getLong(2)).thenReturn(2L, 1L); + return delete; + } + /** * Test connection failure. */ From 6d173f133fa4f3fe839cd8f7c0369f906d95472f Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Mon, 23 Nov 2026 22:14:54 -0800 Subject: [PATCH 2/5] Roll back failed named-delete handoffs and fence TTL finalization Publish only newly retired versions. Never reset autocommit on an unresolved transaction; discard the connection when rollback fails. Check publication and mutation atomicity from a second MySQL connection. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../MySqlNamedBlobDbIntegrationTest.java | 79 ++++++++++- .../github/ambry/named/MySqlNamedBlobDb.java | 133 +++++++++--------- .../ambry/named/MySqlNamedBlobDbTest.java | 49 +++++-- 3 files changed, 183 insertions(+), 78 deletions(-) diff --git a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/MySqlNamedBlobDbIntegrationTest.java b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/MySqlNamedBlobDbIntegrationTest.java index 28a01c154f..f7c4881404 100644 --- a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/MySqlNamedBlobDbIntegrationTest.java +++ b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/MySqlNamedBlobDbIntegrationTest.java @@ -36,6 +36,7 @@ import java.util.List; import java.util.Set; import java.util.TimeZone; +import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -67,6 +68,80 @@ public MySqlNamedBlobDbIntegrationTest(boolean enableHardDelete) throws Exceptio super(enableHardDelete, MySqlNamedBlobDbConfig.DEFAULT_LIST_NAMED_BLOBS_SQL_OPTION); } + @Test + public void testNameMutationFailureRollsBackPublishedJob() throws Exception { + Account account = accountService.getAllAccounts().iterator().next(); + Container container = account.getAllContainers().iterator().next(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + String name = "rollback-" + suffix; + String jobs = "test_jobs_" + suffix; + String trigger = "test_reject_" + suffix; + NamedBlobRecord record = namedBlobDb.put(new NamedBlobRecord(account.getName(), container.getName(), name, + getBlobId(account, container), Utils.Infinite_Time)).get(10, TimeUnit.SECONDS).getInsertedRecord(); + DataSource db = namedBlobDb.getDataSources().get("dc1"); + try (Connection observer = db.getConnection(); Statement sql = observer.createStatement()) { + sql.execute("CREATE TABLE " + jobs + " (version BIGINT PRIMARY KEY) ENGINE=InnoDB"); + try { + sql.execute("CREATE TRIGGER " + trigger + " BEFORE " + (enableHardDelete ? "DELETE" : "UPDATE") + + " ON named_blobs_v2 FOR EACH ROW BEGIN IF OLD.blob_name = '" + name + + "' THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'test rejected name mutation'; END IF; END"); + try { + TestUtils.assertException(ExecutionException.class, () -> namedBlobDb.deleteWithCleanupHandoff( + account.getName(), container.getName(), name, (connection, a, b, n, versions) -> { + try (PreparedStatement insert = connection.prepareStatement("INSERT INTO " + jobs + " VALUES (?)")) { + insert.setLong(1, versions.get(0).getVersion()); + insert.executeUpdate(); + } + }).get(10, TimeUnit.SECONDS), e -> assertEquals("45000", ((SQLException) e.getCause()).getSQLState())); + try (ResultSet rows = sql.executeQuery("SELECT COUNT(*) FROM " + jobs)) { + assertTrue(rows.next()); + assertEquals(0, rows.getInt(1)); + } + try (PreparedStatement get = observer.prepareStatement("SELECT blob_id, deleted_ts FROM named_blobs_v2" + + " WHERE account_id=? AND container_id=? AND blob_name=? AND version=?")) { + get.setInt(1, account.getId()); + get.setInt(2, container.getId()); + get.setString(3, name); + get.setLong(4, record.getVersion()); + try (ResultSet rows = get.executeQuery()) { + assertTrue(rows.next()); + assertArrayEquals(Utils.base64DecodeUrlSafe(record.getBlobId()), rows.getBytes(1)); + assertNull(rows.getTimestamp(2)); + } + } + } finally { + sql.execute("DROP TRIGGER " + trigger); + } + } finally { + sql.execute("DROP TABLE " + jobs); + } + } + } + + @Test + public void testHandoffOnlyOwnsNewlyRetiredVersions() throws Exception { + Account account = accountService.getAllAccounts().iterator().next(); + Container container = account.getAllContainers().iterator().next(); + String name = "mixed-versions"; + namedBlobDb.put(new NamedBlobRecord(account.getName(), container.getName(), name, getBlobId(account, container), + 1, 1), NamedBlobState.READY, true).get(10, TimeUnit.SECONDS); + NamedBlobRecord live = namedBlobDb.put(new NamedBlobRecord(account.getName(), container.getName(), name, + getBlobId(account, container), Utils.Infinite_Time, 2), NamedBlobState.READY, true) + .get(10, TimeUnit.SECONDS).getInsertedRecord(); + List published = new ArrayList<>(); + MySqlNamedBlobDb.CleanupHandoff handoff = (connection, a, b, n, versions) -> published.addAll(versions); + namedBlobDb.deleteWithCleanupHandoff(account.getName(), container.getName(), name, handoff) + .get(10, TimeUnit.SECONDS); + assertEquals(Arrays.asList(new DeleteResult.BlobVersion(live.getBlobId(), live.getVersion(), false)), published); + checkErrorCode(() -> namedBlobDb.updateBlobTtlAndStateToReady(live), RestServiceErrorCode.NotFound); + published.clear(); + namedBlobDb.deleteWithCleanupHandoff(account.getName(), container.getName(), name, handoff) + .get(10, TimeUnit.SECONDS); + assertTrue(published.isEmpty()); + checkErrorCode(() -> namedBlobDb.deleteWithCleanupHandoff(account.getName(), container.getName(), "absent", handoff), + RestServiceErrorCode.NotFound); + } + @Test public void testPurgeAllVersionsAcrossPages() throws Exception { time.setCurrentMilliseconds(System.currentTimeMillis()); @@ -729,7 +804,7 @@ public void testCleanupBlobGoodCase6() throws Exception { String blobId = getBlobId(account, container); String blobName = "good/" + "case6" + "/more path segments--"; NamedBlobRecord record = new NamedBlobRecord(account.getName(), container.getName(), blobName, blobId, - staleCutoffTime + TimeUnit.HOURS.toMillis(1)); + System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)); time.setCurrentMilliseconds(staleCutoffTime); PutResult putResult = namedBlobDb.put(record, NamedBlobState.IN_PROGRESS, true).get(); @@ -999,7 +1074,7 @@ private NamedBlobRecord createAndPutNamedBlob(String blobId, NamedBlobState stat * @param errorCode the expected {@link RestServiceErrorCode}. */ private void checkErrorCode(Callable> callable, RestServiceErrorCode errorCode) throws Exception { - TestUtils.assertException(ExecutionException.class, () -> callable.call().get(), e -> { + TestUtils.assertException(ExecutionException.class, () -> callable.call().get(10, TimeUnit.SECONDS), e -> { RestServiceException rse = (RestServiceException) e.getCause(); assertEquals("Unexpected error code for get after delete", errorCode, rse.getErrorCode()); }); diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java index 09d45eedf0..c4ead02ed4 100644 --- a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java @@ -36,6 +36,7 @@ import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.Time; import com.github.ambry.utils.Utils; +import com.zaxxer.hikari.HikariDataSource; import java.io.Closeable; import java.io.IOException; import java.sql.Connection; @@ -160,7 +161,8 @@ public class MySqlNamedBlobDb implements NamedBlobDb { * Set named blob state to be READY and delete timestamp to null for TtlUpdate case */ private static final String TTL_UPDATE_QUERY = - String.format("UPDATE %s SET %s, %s = NULL WHERE %s", NAMED_BLOBS_V2, STATE_MATCH, DELETED_TS, PK_MATCH_VERSION); + String.format("UPDATE %s SET %s, %s = NULL WHERE %s AND (%s IS NULL OR %s > %s)", NAMED_BLOBS_V2, STATE_MATCH, + DELETED_TS, PK_MATCH_VERSION, DELETED_TS, DELETED_TS, CURRENT_TIME); private static final String GET_BLOBS_FOR_CONTAINER_TEMPLATE = String.format( "SELECT %s, %s, %s, %s, %s, %s, %s, %s " + "FROM %s " @@ -512,8 +514,8 @@ interface CleanupHandoff { /** * Publish previously staged, immutable cleanup manifests for the exact locked versions, or throw if any is * missing or mismatched. Use only this transaction: workers must not see the jobs until the name deletion - * commits. Do not fetch manifests over the network while holding the name locks. On a repeat, verify an - * existing handoff rather than issuing new deletes for a previously deleted version. + * commits. Only versions retired by this transaction are supplied. A repeat with no live rows does not publish; + * an absent name returns NotFound, not proof of a previous handoff. Do not do network I/O or commit here. */ void publish(Connection connection, short accountId, short containerId, String name, List versions) throws SQLException; @@ -796,73 +798,71 @@ private static boolean isConnectionFailure(Throwable t) { void executeTransaction(Container container, boolean autoCommit, Transaction transaction, Callback callback) { + executeTransactionGeneric(autoCommit, + connection -> transaction.run(container.getParentAccountId(), container.getId(), connection), callback); + } + + void executeTransactionGeneric(boolean autoCommit, TransactionGeneric transaction, Callback callback) { final long enqueueTimeMs = System.currentTimeMillis(); try { executor.submit(() -> { enqueueWaitTimeInMs.update(System.currentTimeMillis() - enqueueTimeMs); - try (Connection connection = dataSource.getConnection()) { - T result; - if (autoCommit) { - result = transaction.run(container.getParentAccountId(), container.getId(), connection); - } else { - // if autocommit is set to false, treat this as a multi-step txn that requires an explicit commit/rollback - connection.setAutoCommit(false); - try { - result = transaction.run(container.getParentAccountId(), container.getId(), connection); - connection.commit(); - } catch (Exception e) { - connection.rollback(); - throw e; - } finally { - connection.setAutoCommit(true); - } - } - callback.onCompletion(result, null); - } catch (Exception e) { + T result; + try { + result = runTransaction(autoCommit, transaction); + } catch (Exception | Error e) { if (isConnectionFailure(e)) { connectionFailureCount.inc(); } - callback.onCompletion(null, e); + callback.onCompletion(null, e instanceof Exception ? (Exception) e : new IllegalStateException(e)); + return; } + callback.onCompletion(result, null); }); } catch (RejectedExecutionException e) { rejectTransaction(callback, e); } } - void executeTransactionGeneric(boolean autoCommit, TransactionGeneric transaction, Callback callback) { - final long enqueueTimeMs = System.currentTimeMillis(); + private T runTransaction(boolean autoCommit, TransactionGeneric transaction) throws Exception { + Connection connection = dataSource.getConnection(); + T result; try { - executor.submit(() -> { - enqueueWaitTimeInMs.update(System.currentTimeMillis() - enqueueTimeMs); - try (Connection connection = dataSource.getConnection()) { - T result; - if (autoCommit) { - result = transaction.run(connection); - } else { - // if autocommit is set to false, treat this as a multi-step txn that requires an explicit commit/rollback - connection.setAutoCommit(false); - try { - result = transaction.run(connection); - connection.commit(); - } catch (Exception e) { - connection.rollback(); - throw e; - } finally { - connection.setAutoCommit(true); + if (!autoCommit) { + connection.setAutoCommit(false); + } + result = transaction.run(connection); + if (!autoCommit) { + connection.commit(); + } + } catch (Exception | Error failure) { + if (!autoCommit) { + try { + connection.rollback(); + } catch (Exception | Error rollbackFailure) { + failure.addSuppressed(rollbackFailure); + // Returning an unresolved transaction to the pool could commit it when autocommit is restored. + try { + if (dataSource instanceof HikariDataSource) { + ((HikariDataSource) dataSource).evictConnection(connection); + } else { + connection.abort(Runnable::run); } + } catch (Exception | Error discardFailure) { + failure.addSuppressed(discardFailure); } - callback.onCompletion(result, null); - } catch (Exception e) { - if (isConnectionFailure(e)) { - connectionFailureCount.inc(); - } - callback.onCompletion(null, e); + throw failure; } - }); - } catch (RejectedExecutionException e) { - rejectTransaction(callback, e); + } + try { + connection.close(); + } catch (Exception | Error closeFailure) { + failure.addSuppressed(closeFailure); + } + throw failure; } + connection.close(); + return result; } private void rejectTransaction(Callback callback, RejectedExecutionException cause) { @@ -1194,7 +1194,7 @@ private DeleteResult run_delete_v2(String accountName, String containerName, Str String blobId; long version; Timestamp currentDeleteTime = null; - boolean alreadyDeleted; + boolean found = false; List blobVersions = new ArrayList<>(); List versionsToDelete = new ArrayList<>(); String query = ""; @@ -1211,13 +1211,16 @@ private DeleteResult run_delete_v2(String accountName, String containerName, Str version = resultSet.getLong(2); Timestamp originalDeletionTime = resultSet.getTimestamp(3); currentDeleteTime = resultSet.getTimestamp(4); - alreadyDeleted = (originalDeletionTime != null && currentDeleteTime.after(originalDeletionTime)); - blobVersions.add(new DeleteResult.BlobVersion(blobId, version, alreadyDeleted)); + found = true; + boolean alreadyDeleted = originalDeletionTime != null && !originalDeletionTime.after(currentDeleteTime); + if (handoff == null || !alreadyDeleted) { + blobVersions.add(new DeleteResult.BlobVersion(blobId, version, alreadyDeleted)); + } if (!alreadyDeleted) { versionsToDelete.add(version); } } - if (blobVersions.isEmpty()) { + if (!found) { throw buildException("DELETE: Blob not found", RestServiceErrorCode.NotFound, accountName, containerName, blobName); } @@ -1226,18 +1229,20 @@ private DeleteResult run_delete_v2(String accountName, String containerName, Str logger.error("Failed to execute query {}, {}", query, e.getMessage()); throw e; } - if (handoff != null) { - try { - handoff.publish(connection, accountId, containerId, blobName, Collections.unmodifiableList(blobVersions)); - } catch (SQLException e) { - throw new RestServiceException("Could not record named blob cleanup", e, RestServiceErrorCode.ServiceUnavailable); - } - } - // only need to issue an update statement if the row was not already marked as deleted. + DeleteResult result = new DeleteResult(blobVersions); if (!versionsToDelete.isEmpty()) { + if (handoff != null) { + try { + handoff.publish(connection, accountId, containerId, blobName, result.getBlobVersions()); + } catch (SQLException e) { + metricsRecoder.namedBlobDBDeleteErrorCount.inc(); + throw new RestServiceException("Could not record named blob cleanup", e, + RestServiceErrorCode.ServiceUnavailable); + } + } applyDelete(accountId, containerId, blobName, currentDeleteTime, versionsToDelete, connection); } - return new DeleteResult(blobVersions); + return result; } /** diff --git a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java index 598cb4be3c..058f64181c 100644 --- a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java +++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java @@ -78,6 +78,7 @@ public class MySqlNamedBlobDbTest { private final String foundDatacenter = "dc3"; private final MockDataSourceFactory dataSourceFactory = new MockDataSourceFactory(); private final InMemAccountService accountService = new InMemAccountService(false, false); + private final Metrics metrics = new Metrics(new MetricRegistry(), ""); private final MySqlNamedBlobDb namedBlobDb; private final Account account; private final Container container; @@ -97,7 +98,7 @@ public MySqlNamedBlobDbTest() throws IOException { } properties.setProperty(MySqlNamedBlobDbConfig.DB_INFO, dbInfo.toString()); namedBlobDb = new MySqlNamedBlobDb(accountService, new MySqlNamedBlobDbConfig(new VerifiableProperties(properties)), - dataSourceFactory, localDatacenter, new Metrics(new MetricRegistry(), "")); + dataSourceFactory, localDatacenter, metrics); account = accountService.createAndAddRandomAccount(); container = account.getAllContainers().iterator().next(); MockClusterMap clusterMap = new MockClusterMap(); @@ -129,16 +130,14 @@ public void testRetryDeleteNamedBlob() throws Exception { public void testCleanupHandoffFailureLeavesNamedVersionsIntact() throws Exception { Connection connection = mock(Connection.class); mockNamedVersionsForDelete(connection); - checkErrorCode(() -> namedBlobDb.deleteWithCleanupHandoff(account.getName(), container.getName(), "name", - (transaction, accountId, containerId, name, versions) -> { - assertSame(connection, transaction); - assertEquals(account.getId(), accountId); - assertEquals(container.getId(), containerId); - assertEquals("name", name); - assertEquals(Arrays.asList(new DeleteResult.BlobVersion(id, 2, false), - new DeleteResult.BlobVersion(id, 1, false)), versions); - throw new SQLException("Incomplete manifest for the second version"); - }), RestServiceErrorCode.ServiceUnavailable); + MySqlNamedBlobDb.CleanupHandoff handoff = mock(MySqlNamedBlobDb.CleanupHandoff.class); + doThrow(new SQLException("Cannot insert job")).when(handoff) + .publish(any(), anyShort(), anyShort(), anyString(), anyList()); + checkErrorCode(() -> namedBlobDb.deleteWithCleanupHandoff(account.getName(), container.getName(), "name", handoff), + RestServiceErrorCode.ServiceUnavailable); + verify(handoff).publish(connection, account.getId(), container.getId(), "name", + Arrays.asList(new DeleteResult.BlobVersion(id, 2, false), new DeleteResult.BlobVersion(id, 1, false))); + assertEquals(1, metrics.namedBlobDBDeleteErrorCount.getCount()); verify(connection).setAutoCommit(false); verify(connection).rollback(); verify(connection, never()).commit(); @@ -146,6 +145,32 @@ public void testCleanupHandoffFailureLeavesNamedVersionsIntact() throws Exceptio verify(connection, never()).prepareStatement(startsWith("DELETE")); } + @Test + public void testFatalHandoffFailureRollsBackOrDiscardsConnection() throws Exception { + for (boolean rollbackFails : Arrays.asList(false, true)) { + Connection connection = mock(Connection.class); + mockNamedVersionsForDelete(connection); + SQLException rollbackFailure = new SQLException("Rollback failed"); + if (rollbackFails) { + doThrow(rollbackFailure).when(connection).rollback(); + } + AssertionError failure = new AssertionError("Publisher failed"); + TestUtils.assertException(ExecutionException.class, () -> namedBlobDb.deleteWithCleanupHandoff( + account.getName(), container.getName(), "name", (c, a, b, n, v) -> { throw failure; }).get(5, TimeUnit.SECONDS), + e -> assertSame(failure, e.getCause().getCause())); + verify(connection).rollback(); + verify(connection, never()).setAutoCommit(true); + verify(connection, never()).commit(); + if (rollbackFails) { + verify(connection).abort(any()); + verify(connection, never()).close(); + assertArrayEquals(new Throwable[]{rollbackFailure}, failure.getSuppressed()); + } else { + verify(connection).close(); + } + } + } + @Test public void testCleanupHandoffPrecedesNameMutationAndCommit() throws Exception { Connection connection = mock(Connection.class); @@ -700,7 +725,7 @@ public void testUpdateBlobTtlAndStateToReady() throws Exception { * @param errorCode the expected {@link RestServiceErrorCode}. */ private void checkErrorCode(Callable> callable, RestServiceErrorCode errorCode) throws Exception { - TestUtils.assertException(ExecutionException.class, () -> callable.call().get(), e -> { + TestUtils.assertException(ExecutionException.class, () -> callable.call().get(5, TimeUnit.SECONDS), e -> { RestServiceException rse = (RestServiceException) e.getCause(); assertEquals("Unexpected error code for get after delete", errorCode, rse.getErrorCode()); }); From 617fd9a7e716ba58c88e85dbf0d9a5d938299b67 Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Mon, 23 Nov 2026 22:36:51 -0800 Subject: [PATCH 3/5] Preserve named DB transaction outcomes when returning connections Separate connection-close errors from the operation result. Exercise confirmed and indeterminate commits and the Hikari eviction path. Leave delete publication and TTL SQL out of this change. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../MySqlNamedBlobDbIntegrationTest.java | 79 +--------- .../java/com/github/ambry/named/Metrics.java | 3 + .../github/ambry/named/MySqlNamedBlobDb.java | 90 ++++-------- .../ambry/named/MySqlNamedBlobDbTest.java | 139 ++++++++++-------- 4 files changed, 115 insertions(+), 196 deletions(-) diff --git a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/MySqlNamedBlobDbIntegrationTest.java b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/MySqlNamedBlobDbIntegrationTest.java index f7c4881404..28a01c154f 100644 --- a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/MySqlNamedBlobDbIntegrationTest.java +++ b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/MySqlNamedBlobDbIntegrationTest.java @@ -36,7 +36,6 @@ import java.util.List; import java.util.Set; import java.util.TimeZone; -import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -68,80 +67,6 @@ public MySqlNamedBlobDbIntegrationTest(boolean enableHardDelete) throws Exceptio super(enableHardDelete, MySqlNamedBlobDbConfig.DEFAULT_LIST_NAMED_BLOBS_SQL_OPTION); } - @Test - public void testNameMutationFailureRollsBackPublishedJob() throws Exception { - Account account = accountService.getAllAccounts().iterator().next(); - Container container = account.getAllContainers().iterator().next(); - String suffix = UUID.randomUUID().toString().replace("-", ""); - String name = "rollback-" + suffix; - String jobs = "test_jobs_" + suffix; - String trigger = "test_reject_" + suffix; - NamedBlobRecord record = namedBlobDb.put(new NamedBlobRecord(account.getName(), container.getName(), name, - getBlobId(account, container), Utils.Infinite_Time)).get(10, TimeUnit.SECONDS).getInsertedRecord(); - DataSource db = namedBlobDb.getDataSources().get("dc1"); - try (Connection observer = db.getConnection(); Statement sql = observer.createStatement()) { - sql.execute("CREATE TABLE " + jobs + " (version BIGINT PRIMARY KEY) ENGINE=InnoDB"); - try { - sql.execute("CREATE TRIGGER " + trigger + " BEFORE " + (enableHardDelete ? "DELETE" : "UPDATE") - + " ON named_blobs_v2 FOR EACH ROW BEGIN IF OLD.blob_name = '" + name - + "' THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'test rejected name mutation'; END IF; END"); - try { - TestUtils.assertException(ExecutionException.class, () -> namedBlobDb.deleteWithCleanupHandoff( - account.getName(), container.getName(), name, (connection, a, b, n, versions) -> { - try (PreparedStatement insert = connection.prepareStatement("INSERT INTO " + jobs + " VALUES (?)")) { - insert.setLong(1, versions.get(0).getVersion()); - insert.executeUpdate(); - } - }).get(10, TimeUnit.SECONDS), e -> assertEquals("45000", ((SQLException) e.getCause()).getSQLState())); - try (ResultSet rows = sql.executeQuery("SELECT COUNT(*) FROM " + jobs)) { - assertTrue(rows.next()); - assertEquals(0, rows.getInt(1)); - } - try (PreparedStatement get = observer.prepareStatement("SELECT blob_id, deleted_ts FROM named_blobs_v2" - + " WHERE account_id=? AND container_id=? AND blob_name=? AND version=?")) { - get.setInt(1, account.getId()); - get.setInt(2, container.getId()); - get.setString(3, name); - get.setLong(4, record.getVersion()); - try (ResultSet rows = get.executeQuery()) { - assertTrue(rows.next()); - assertArrayEquals(Utils.base64DecodeUrlSafe(record.getBlobId()), rows.getBytes(1)); - assertNull(rows.getTimestamp(2)); - } - } - } finally { - sql.execute("DROP TRIGGER " + trigger); - } - } finally { - sql.execute("DROP TABLE " + jobs); - } - } - } - - @Test - public void testHandoffOnlyOwnsNewlyRetiredVersions() throws Exception { - Account account = accountService.getAllAccounts().iterator().next(); - Container container = account.getAllContainers().iterator().next(); - String name = "mixed-versions"; - namedBlobDb.put(new NamedBlobRecord(account.getName(), container.getName(), name, getBlobId(account, container), - 1, 1), NamedBlobState.READY, true).get(10, TimeUnit.SECONDS); - NamedBlobRecord live = namedBlobDb.put(new NamedBlobRecord(account.getName(), container.getName(), name, - getBlobId(account, container), Utils.Infinite_Time, 2), NamedBlobState.READY, true) - .get(10, TimeUnit.SECONDS).getInsertedRecord(); - List published = new ArrayList<>(); - MySqlNamedBlobDb.CleanupHandoff handoff = (connection, a, b, n, versions) -> published.addAll(versions); - namedBlobDb.deleteWithCleanupHandoff(account.getName(), container.getName(), name, handoff) - .get(10, TimeUnit.SECONDS); - assertEquals(Arrays.asList(new DeleteResult.BlobVersion(live.getBlobId(), live.getVersion(), false)), published); - checkErrorCode(() -> namedBlobDb.updateBlobTtlAndStateToReady(live), RestServiceErrorCode.NotFound); - published.clear(); - namedBlobDb.deleteWithCleanupHandoff(account.getName(), container.getName(), name, handoff) - .get(10, TimeUnit.SECONDS); - assertTrue(published.isEmpty()); - checkErrorCode(() -> namedBlobDb.deleteWithCleanupHandoff(account.getName(), container.getName(), "absent", handoff), - RestServiceErrorCode.NotFound); - } - @Test public void testPurgeAllVersionsAcrossPages() throws Exception { time.setCurrentMilliseconds(System.currentTimeMillis()); @@ -804,7 +729,7 @@ public void testCleanupBlobGoodCase6() throws Exception { String blobId = getBlobId(account, container); String blobName = "good/" + "case6" + "/more path segments--"; NamedBlobRecord record = new NamedBlobRecord(account.getName(), container.getName(), blobName, blobId, - System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)); + staleCutoffTime + TimeUnit.HOURS.toMillis(1)); time.setCurrentMilliseconds(staleCutoffTime); PutResult putResult = namedBlobDb.put(record, NamedBlobState.IN_PROGRESS, true).get(); @@ -1074,7 +999,7 @@ private NamedBlobRecord createAndPutNamedBlob(String blobId, NamedBlobState stat * @param errorCode the expected {@link RestServiceErrorCode}. */ private void checkErrorCode(Callable> callable, RestServiceErrorCode errorCode) throws Exception { - TestUtils.assertException(ExecutionException.class, () -> callable.call().get(10, TimeUnit.SECONDS), e -> { + TestUtils.assertException(ExecutionException.class, () -> callable.call().get(), e -> { RestServiceException rse = (RestServiceException) e.getCause(); assertEquals("Unexpected error code for get after delete", errorCode, rse.getErrorCode()); }); diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java index 726075da1d..cd4d966b18 100644 --- a/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java @@ -62,6 +62,7 @@ public class Metrics { public final Counter namedBlobDBDeleteErrorCount; public final Counter namedBlobDBInsertErrorCount; public final Counter namedBlobDBUpdateErrorCount; + final Counter connectionCloseErrorCount; /** * Constructor to create the Metrics. @@ -129,6 +130,8 @@ public Metrics(MetricRegistry metricRegistry, String prefix) { metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "NamedBlobDBInsertErrorCount")); namedBlobDBUpdateErrorCount = metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "NamedBlobDBUpdateErrorCount")); + connectionCloseErrorCount = + metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "ConnectionCloseErrorCount")); } /** diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java index c4ead02ed4..bc1fafc23f 100644 --- a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java @@ -55,7 +55,6 @@ import java.util.IdentityHashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -161,8 +160,7 @@ public class MySqlNamedBlobDb implements NamedBlobDb { * Set named blob state to be READY and delete timestamp to null for TtlUpdate case */ private static final String TTL_UPDATE_QUERY = - String.format("UPDATE %s SET %s, %s = NULL WHERE %s AND (%s IS NULL OR %s > %s)", NAMED_BLOBS_V2, STATE_MATCH, - DELETED_TS, PK_MATCH_VERSION, DELETED_TS, DELETED_TS, CURRENT_TIME); + String.format("UPDATE %s SET %s, %s = NULL WHERE %s", NAMED_BLOBS_V2, STATE_MATCH, DELETED_TS, PK_MATCH_VERSION); private static final String GET_BLOBS_FOR_CONTAINER_TEMPLATE = String.format( "SELECT %s, %s, %s, %s, %s, %s, %s, %s " + "FROM %s " @@ -497,36 +495,10 @@ public CompletableFuture updateBlobTtlAndStateToReady(NamedBlobRecord @Override public CompletableFuture delete(String accountName, String containerName, String blobName) { - return delete(accountName, containerName, blobName, null); - } - - /** - * Hand ownership of the root and child cleanup to a durable worker. Unlike {@link #delete}, this path does not - * return IDs to dispatch a second, in-memory router delete. - */ - CompletableFuture deleteWithCleanupHandoff(String accountName, String containerName, String blobName, - CleanupHandoff handoff) { - return delete(accountName, containerName, blobName, Objects.requireNonNull(handoff)).thenApply(ignored -> null); - } - - @FunctionalInterface - interface CleanupHandoff { - /** - * Publish previously staged, immutable cleanup manifests for the exact locked versions, or throw if any is - * missing or mismatched. Use only this transaction: workers must not see the jobs until the name deletion - * commits. Only versions retired by this transaction are supplied. A repeat with no live rows does not publish; - * an absent name returns NotFound, not proof of a previous handoff. Do not do network I/O or commit here. - */ - void publish(Connection connection, short accountId, short containerId, String name, - List versions) throws SQLException; - } - - private CompletableFuture delete(String accountName, String containerName, String blobName, - CleanupHandoff handoff) { return executeTransactionAsync(accountName, containerName, false, (accountId, containerId, connection) -> { long startTime = this.time.milliseconds(); DeleteResult deleteResult = - run_delete_v2(accountName, containerName, blobName, accountId, containerId, connection, handoff); + run_delete_v2(accountName, containerName, blobName, accountId, containerId, connection); metricsRecoder.namedBlobDeleteTimeInMs.update(this.time.milliseconds() - startTime); return deleteResult; }, null, this.metricsRecoder.namedBlobDBDeleteErrorCount); @@ -826,22 +798,26 @@ void executeTransactionGeneric(boolean autoCommit, TransactionGeneric tra private T runTransaction(boolean autoCommit, TransactionGeneric transaction) throws Exception { Connection connection = dataSource.getConnection(); - T result; + boolean returnToPool = true; try { if (!autoCommit) { connection.setAutoCommit(false); } - result = transaction.run(connection); + T result = transaction.run(connection); if (!autoCommit) { connection.commit(); } + return result; } catch (Exception | Error failure) { if (!autoCommit) { try { connection.rollback(); } catch (Exception | Error rollbackFailure) { - failure.addSuppressed(rollbackFailure); // Returning an unresolved transaction to the pool could commit it when autocommit is restored. + returnToPool = false; + if (failure != rollbackFailure) { + failure.addSuppressed(rollbackFailure); + } try { if (dataSource instanceof HikariDataSource) { ((HikariDataSource) dataSource).evictConnection(connection); @@ -849,20 +825,24 @@ private T runTransaction(boolean autoCommit, TransactionGeneric transacti connection.abort(Runnable::run); } } catch (Exception | Error discardFailure) { - failure.addSuppressed(discardFailure); + if (failure != discardFailure) { + failure.addSuppressed(discardFailure); + } } - throw failure; } } - try { - connection.close(); - } catch (Exception | Error closeFailure) { - failure.addSuppressed(closeFailure); - } throw failure; + } finally { + if (returnToPool) { + try { + connection.close(); + } catch (Exception | Error closeFailure) { + // Returning the connection cannot change the transaction outcome reported to the caller. + metrics.connectionCloseErrorCount.inc(); + logger.error("Failed to return a named blob DB connection in {}", datacenter, closeFailure); + } + } } - connection.close(); - return result; } private void rejectTransaction(Callback callback, RejectedExecutionException cause) { @@ -1190,11 +1170,11 @@ private PutResult apply_ttl_update(NamedBlobRecord record, short accountId, shor } private DeleteResult run_delete_v2(String accountName, String containerName, String blobName, short accountId, - short containerId, Connection connection, CleanupHandoff handoff) throws Exception { + short containerId, Connection connection) throws Exception { String blobId; long version; Timestamp currentDeleteTime = null; - boolean found = false; + boolean alreadyDeleted; List blobVersions = new ArrayList<>(); List versionsToDelete = new ArrayList<>(); String query = ""; @@ -1211,16 +1191,13 @@ private DeleteResult run_delete_v2(String accountName, String containerName, Str version = resultSet.getLong(2); Timestamp originalDeletionTime = resultSet.getTimestamp(3); currentDeleteTime = resultSet.getTimestamp(4); - found = true; - boolean alreadyDeleted = originalDeletionTime != null && !originalDeletionTime.after(currentDeleteTime); - if (handoff == null || !alreadyDeleted) { - blobVersions.add(new DeleteResult.BlobVersion(blobId, version, alreadyDeleted)); - } + alreadyDeleted = (originalDeletionTime != null && currentDeleteTime.after(originalDeletionTime)); + blobVersions.add(new DeleteResult.BlobVersion(blobId, version, alreadyDeleted)); if (!alreadyDeleted) { versionsToDelete.add(version); } } - if (!found) { + if (blobVersions.isEmpty()) { throw buildException("DELETE: Blob not found", RestServiceErrorCode.NotFound, accountName, containerName, blobName); } @@ -1229,20 +1206,11 @@ private DeleteResult run_delete_v2(String accountName, String containerName, Str logger.error("Failed to execute query {}, {}", query, e.getMessage()); throw e; } - DeleteResult result = new DeleteResult(blobVersions); + // only need to issue an update statement if the row was not already marked as deleted. if (!versionsToDelete.isEmpty()) { - if (handoff != null) { - try { - handoff.publish(connection, accountId, containerId, blobName, result.getBlobVersions()); - } catch (SQLException e) { - metricsRecoder.namedBlobDBDeleteErrorCount.inc(); - throw new RestServiceException("Could not record named blob cleanup", e, - RestServiceErrorCode.ServiceUnavailable); - } - } applyDelete(accountId, containerId, blobName, currentDeleteTime, versionsToDelete, connection); } - return result; + return new DeleteResult(blobVersions); } /** diff --git a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java index 058f64181c..3f3cde606e 100644 --- a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java +++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java @@ -34,6 +34,7 @@ import com.github.ambry.rest.RestServiceException; import com.github.ambry.utils.TestUtils; import com.github.ambry.utils.Utils; +import com.zaxxer.hikari.HikariDataSource; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; @@ -62,7 +63,6 @@ import org.json.JSONObject; import org.junit.Assert; import org.junit.Test; -import org.mockito.InOrder; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @@ -78,7 +78,6 @@ public class MySqlNamedBlobDbTest { private final String foundDatacenter = "dc3"; private final MockDataSourceFactory dataSourceFactory = new MockDataSourceFactory(); private final InMemAccountService accountService = new InMemAccountService(false, false); - private final Metrics metrics = new Metrics(new MetricRegistry(), ""); private final MySqlNamedBlobDb namedBlobDb; private final Account account; private final Container container; @@ -98,7 +97,7 @@ public MySqlNamedBlobDbTest() throws IOException { } properties.setProperty(MySqlNamedBlobDbConfig.DB_INFO, dbInfo.toString()); namedBlobDb = new MySqlNamedBlobDb(accountService, new MySqlNamedBlobDbConfig(new VerifiableProperties(properties)), - dataSourceFactory, localDatacenter, metrics); + dataSourceFactory, localDatacenter, new Metrics(new MetricRegistry(), "")); account = accountService.createAndAddRandomAccount(); container = account.getAllContainers().iterator().next(); MockClusterMap clusterMap = new MockClusterMap(); @@ -127,77 +126,101 @@ public void testRetryDeleteNamedBlob() throws Exception { } @Test - public void testCleanupHandoffFailureLeavesNamedVersionsIntact() throws Exception { + public void testHardDeleteReturnsVersionsWhenPoolReturnFails() throws Exception { Connection connection = mock(Connection.class); - mockNamedVersionsForDelete(connection); - MySqlNamedBlobDb.CleanupHandoff handoff = mock(MySqlNamedBlobDb.CleanupHandoff.class); - doThrow(new SQLException("Cannot insert job")).when(handoff) - .publish(any(), anyShort(), anyShort(), anyString(), anyList()); - checkErrorCode(() -> namedBlobDb.deleteWithCleanupHandoff(account.getName(), container.getName(), "name", handoff), - RestServiceErrorCode.ServiceUnavailable); - verify(handoff).publish(connection, account.getId(), container.getId(), "name", - Arrays.asList(new DeleteResult.BlobVersion(id, 2, false), new DeleteResult.BlobVersion(id, 1, false))); - assertEquals(1, metrics.namedBlobDBDeleteErrorCount.getCount()); - verify(connection).setAutoCommit(false); - verify(connection).rollback(); - verify(connection, never()).commit(); - verify(connection, never()).prepareStatement(startsWith("UPDATE")); - verify(connection, never()).prepareStatement(startsWith("DELETE")); + DataSource source = mock(DataSource.class); + when(source.getConnection()).thenReturn(connection); + PreparedStatement mutation = mockHardDelete(connection); + doThrow(new SQLException("Failed to return connection")).when(connection).close(); + Metrics metrics = new Metrics(new MetricRegistry(), ""); + try (MySqlNamedBlobDb db = hardDeleteDb(source, metrics)) { + DeleteResult result = db.delete(account.getName(), container.getName(), "name").get(5, TimeUnit.SECONDS); + assertEquals(Arrays.asList(new DeleteResult.BlobVersion(id, 2, false), new DeleteResult.BlobVersion(id, 1, false)), + result.getBlobVersions()); + org.mockito.InOrder order = inOrder(mutation, connection); + order.verify(mutation).executeUpdate(); + order.verify(connection).commit(); + order.verify(connection).close(); + verify(connection, never()).rollback(); + assertEquals(1, metrics.connectionCloseErrorCount.getCount()); + assertEquals(0, metrics.namedBlobDBDeleteErrorCount.getCount()); + } } @Test - public void testFatalHandoffFailureRollsBackOrDiscardsConnection() throws Exception { - for (boolean rollbackFails : Arrays.asList(false, true)) { - Connection connection = mock(Connection.class); - mockNamedVersionsForDelete(connection); - SQLException rollbackFailure = new SQLException("Rollback failed"); - if (rollbackFails) { - doThrow(rollbackFailure).when(connection).rollback(); - } - AssertionError failure = new AssertionError("Publisher failed"); - TestUtils.assertException(ExecutionException.class, () -> namedBlobDb.deleteWithCleanupHandoff( - account.getName(), container.getName(), "name", (c, a, b, n, v) -> { throw failure; }).get(5, TimeUnit.SECONDS), - e -> assertSame(failure, e.getCause().getCause())); + public void testCommitFailureRemainsPrimaryWhenPoolReturnFails() throws Exception { + Connection connection = mock(Connection.class); + DataSource source = mock(DataSource.class); + when(source.getConnection()).thenReturn(connection); + mockHardDelete(connection); + SQLException commitFailure = new SQLException("Commit not acknowledged"); + doThrow(commitFailure).when(connection).commit(); + doThrow(new SQLException("Failed to return connection")).when(connection).close(); + Metrics metrics = new Metrics(new MetricRegistry(), ""); + try (MySqlNamedBlobDb db = hardDeleteDb(source, metrics)) { + TestUtils.assertException(ExecutionException.class, + () -> db.delete(account.getName(), container.getName(), "name").get(5, TimeUnit.SECONDS), + e -> assertSame(commitFailure, e.getCause())); verify(connection).rollback(); - verify(connection, never()).setAutoCommit(true); - verify(connection, never()).commit(); - if (rollbackFails) { - verify(connection).abort(any()); - verify(connection, never()).close(); + assertEquals(1, metrics.connectionCloseErrorCount.getCount()); + assertEquals(1, metrics.namedBlobDBDeleteErrorCount.getCount()); + } + } + + @Test + public void testRollbackFailureEvictsHikariConnection() throws Exception { + DataSource physicalSource = mock(DataSource.class); + Connection broken = mock(Connection.class); + Connection replacement = mock(Connection.class); + for (Connection physical : Arrays.asList(broken, replacement)) { + when(physical.getAutoCommit()).thenReturn(true); + when(physical.isValid(anyInt())).thenReturn(true); + } + when(physicalSource.getConnection()).thenReturn(broken, replacement); + AssertionError failure = new AssertionError("Transaction interrupted"); + when(broken.prepareStatement(startsWith("SELECT"))).thenThrow(failure); + SQLException rollbackFailure = new SQLException("Rollback failed"); + doThrow(rollbackFailure).when(broken).rollback(); + try (HikariDataSource pool = new HikariDataSource()) { + pool.setDataSource(physicalSource); + pool.setMaximumPoolSize(1); + pool.setMinimumIdle(0); + pool.setInitializationFailTimeout(-1); + pool.setConnectionTimeout(3000); + try (MySqlNamedBlobDb db = hardDeleteDb(pool, new Metrics(new MetricRegistry(), ""))) { + TestUtils.assertException(ExecutionException.class, + () -> db.delete(account.getName(), container.getName(), "name").get(5, TimeUnit.SECONDS), + e -> assertSame(failure, e.getCause().getCause())); assertArrayEquals(new Throwable[]{rollbackFailure}, failure.getSuppressed()); - } else { - verify(connection).close(); + try (Connection next = pool.getConnection()) { + assertSame(replacement, next.unwrap(Connection.class)); + } + verify(broken, never()).setAutoCommit(true); + verify(broken, never()).commit(); } } } - @Test - public void testCleanupHandoffPrecedesNameMutationAndCommit() throws Exception { - Connection connection = mock(Connection.class); - PreparedStatement delete = mockNamedVersionsForDelete(connection); - MySqlNamedBlobDb.CleanupHandoff handoff = mock(MySqlNamedBlobDb.CleanupHandoff.class); - namedBlobDb.deleteWithCleanupHandoff(account.getName(), container.getName(), "name", handoff) - .get(5, TimeUnit.SECONDS); - InOrder order = inOrder(connection, handoff, delete); - order.verify(connection).setAutoCommit(false); - order.verify(handoff).publish(eq(connection), eq(account.getId()), eq(container.getId()), eq("name"), anyList()); - order.verify(delete).executeUpdate(); - order.verify(connection).commit(); - } - - private PreparedStatement mockNamedVersionsForDelete(Connection connection) throws SQLException { + private MySqlNamedBlobDb hardDeleteDb(DataSource localSource, Metrics metrics) { + Properties props = new Properties(); + props.setProperty(MySqlNamedBlobDbConfig.DB_INFO, buildSmallPoolConfig(1, 1, 1).dbInfo); + props.setProperty(MySqlNamedBlobDbConfig.ENABLE_HARD_DELETE, "true"); + return new MySqlNamedBlobDb(accountService, new MySqlNamedBlobDbConfig(new VerifiableProperties(props)), + endpoint -> localDatacenter.equals(endpoint.getDatacenter()) ? localSource : mock(DataSource.class), + localDatacenter, metrics); + } + + private PreparedStatement mockHardDelete(Connection connection) throws SQLException { PreparedStatement select = mock(PreparedStatement.class); - PreparedStatement delete = mock(PreparedStatement.class); ResultSet versions = mock(ResultSet.class); - when(dataSourceFactory.dataSources.get(localDatacenter).getConnection()).thenReturn(connection); when(connection.prepareStatement(startsWith("SELECT"))).thenReturn(select); - when(connection.prepareStatement(startsWith("UPDATE"))).thenReturn(delete); - when(connection.prepareStatement(startsWith("DELETE"))).thenReturn(delete); when(select.executeQuery()).thenReturn(versions); when(versions.next()).thenReturn(true, true, false); when(versions.getBytes(1)).thenReturn(Utils.base64DecodeUrlSafe(id)); when(versions.getLong(2)).thenReturn(2L, 1L); - return delete; + PreparedStatement mutation = mock(PreparedStatement.class); + when(connection.prepareStatement(startsWith("DELETE"))).thenReturn(mutation); + return mutation; } /** @@ -725,7 +748,7 @@ public void testUpdateBlobTtlAndStateToReady() throws Exception { * @param errorCode the expected {@link RestServiceErrorCode}. */ private void checkErrorCode(Callable> callable, RestServiceErrorCode errorCode) throws Exception { - TestUtils.assertException(ExecutionException.class, () -> callable.call().get(5, TimeUnit.SECONDS), e -> { + TestUtils.assertException(ExecutionException.class, () -> callable.call().get(), e -> { RestServiceException rse = (RestServiceException) e.getCause(); assertEquals("Unexpected error code for get after delete", errorCode, rse.getErrorCode()); }); From ef8bc034ec07a94ae020a6d68658022ad9c0f476 Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Mon, 23 Nov 2026 23:01:24 -0800 Subject: [PATCH 4/5] Evict named DB connections when autocommit reset fails Restore autocommit before releasing a resolved transaction. Keep cleanup failures separate from the write outcome and visible in the per-datacenter connection failure count. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../github/ambry/named/MySqlNamedBlobDb.java | 63 ++++++++++---- .../ambry/named/MySqlNamedBlobDbTest.java | 87 ++++++++++++++++--- 2 files changed, 121 insertions(+), 29 deletions(-) diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java index bc1fafc23f..427ad8584e 100644 --- a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java @@ -730,9 +730,8 @@ private static class TransactionExecutor implements Closeable { * exception" class (08001/08003/08004/08006/08007/08S01). * * - *

The walk traverses both {@link Throwable#getCause()} and {@link SQLException#getNextException()} - * so wrapped/chained variants (e.g. RuntimeException-wrapped, Hikari-wrapped, batch error chains) - * are detected. SQLSTATE "40*" (transaction rollback), "57*" (operator intervention), and other + *

The walk includes causes, chained SQL exceptions and suppressed cleanup failures. + * SQLSTATE "40*" (transaction rollback), "57*" (operator intervention), and other * adjacent classes are intentionally NOT counted — those are not connection failures. */ private static boolean isConnectionFailure(Throwable t) { @@ -764,6 +763,7 @@ private static boolean isConnectionFailure(Throwable t) { if (cause != null) { stack.push(cause); } + Collections.addAll(stack, cur.getSuppressed()); } return false; } @@ -799,6 +799,7 @@ void executeTransactionGeneric(boolean autoCommit, TransactionGeneric tra private T runTransaction(boolean autoCommit, TransactionGeneric transaction) throws Exception { Connection connection = dataSource.getConnection(); boolean returnToPool = true; + Throwable operationFailure = null; try { if (!autoCommit) { connection.setAutoCommit(false); @@ -809,39 +810,63 @@ private T runTransaction(boolean autoCommit, TransactionGeneric transacti } return result; } catch (Exception | Error failure) { + operationFailure = failure; if (!autoCommit) { try { connection.rollback(); } catch (Exception | Error rollbackFailure) { // Returning an unresolved transaction to the pool could commit it when autocommit is restored. returnToPool = false; + discardConnection(connection, rollbackFailure); if (failure != rollbackFailure) { failure.addSuppressed(rollbackFailure); } - try { - if (dataSource instanceof HikariDataSource) { - ((HikariDataSource) dataSource).evictConnection(connection); - } else { - connection.abort(Runnable::run); - } - } catch (Exception | Error discardFailure) { - if (failure != discardFailure) { - failure.addSuppressed(discardFailure); - } - } } } throw failure; } finally { if (returnToPool) { + returnConnection(connection, autoCommit, operationFailure); + } + } + } + + private void returnConnection(Connection connection, boolean autoCommit, Throwable operationFailure) { + try { + if (!autoCommit) { try { - connection.close(); - } catch (Exception | Error closeFailure) { - // Returning the connection cannot change the transaction outcome reported to the caller. - metrics.connectionCloseErrorCount.inc(); - logger.error("Failed to return a named blob DB connection in {}", datacenter, closeFailure); + connection.setAutoCommit(true); + } catch (Exception | Error resetFailure) { + // Hikari can recycle a connection even when a reset inside close() fails. + discardConnection(connection, resetFailure); + throw resetFailure; } } + connection.close(); + } catch (Exception | Error cleanupFailure) { + metrics.connectionCloseErrorCount.inc(); + if (operationFailure == null) { + if (isConnectionFailure(cleanupFailure)) { + connectionFailureCount.inc(); + } + } else if (operationFailure != cleanupFailure) { + operationFailure.addSuppressed(cleanupFailure); + } + logger.error("Failed to return a named blob DB connection in {}", datacenter, cleanupFailure); + } + } + + private void discardConnection(Connection connection, Throwable failure) { + try { + if (dataSource instanceof HikariDataSource) { + ((HikariDataSource) dataSource).evictConnection(connection); + } else { + connection.abort(Runnable::run); + } + } catch (Exception | Error discardFailure) { + if (failure != discardFailure) { + failure.addSuppressed(discardFailure); + } } } diff --git a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java index 3f3cde606e..513a6e0be2 100644 --- a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java +++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java @@ -63,6 +63,7 @@ import org.json.JSONObject; import org.junit.Assert; import org.junit.Test; +import org.mockito.InOrder; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @@ -131,19 +132,20 @@ public void testHardDeleteReturnsVersionsWhenPoolReturnFails() throws Exception DataSource source = mock(DataSource.class); when(source.getConnection()).thenReturn(connection); PreparedStatement mutation = mockHardDelete(connection); - doThrow(new SQLException("Failed to return connection")).when(connection).close(); + doThrow(new SQLException("Failed to return connection", "08006")).when(connection).close(); Metrics metrics = new Metrics(new MetricRegistry(), ""); try (MySqlNamedBlobDb db = hardDeleteDb(source, metrics)) { DeleteResult result = db.delete(account.getName(), container.getName(), "name").get(5, TimeUnit.SECONDS); assertEquals(Arrays.asList(new DeleteResult.BlobVersion(id, 2, false), new DeleteResult.BlobVersion(id, 1, false)), result.getBlobVersions()); - org.mockito.InOrder order = inOrder(mutation, connection); + InOrder order = inOrder(mutation, connection); order.verify(mutation).executeUpdate(); order.verify(connection).commit(); order.verify(connection).close(); verify(connection, never()).rollback(); assertEquals(1, metrics.connectionCloseErrorCount.getCount()); assertEquals(0, metrics.namedBlobDBDeleteErrorCount.getCount()); + assertEquals(1, localConnectionFailures(metrics)); } } @@ -168,25 +170,90 @@ public void testCommitFailureRemainsPrimaryWhenPoolReturnFails() throws Exceptio } @Test - public void testRollbackFailureEvictsHikariConnection() throws Exception { - DataSource physicalSource = mock(DataSource.class); + public void testResetFailureAfterCommitEvictsHikariConnection() throws Exception { Connection broken = mock(Connection.class); Connection replacement = mock(Connection.class); + mockHardDelete(broken); + // A non-connection SQLState is not fatal to Hikari. The executor must evict before returning this connection. + doThrow(new SQLException("Autocommit reset failed", "HY000")).doNothing().when(broken).setAutoCommit(true); + Metrics metrics = new Metrics(new MetricRegistry(), ""); + try (HikariDataSource pool = singleConnectionPool(broken, replacement); + MySqlNamedBlobDb db = hardDeleteDb(pool, metrics)) { + DeleteResult result = db.delete(account.getName(), container.getName(), "name").get(5, TimeUnit.SECONDS); + assertEquals(Arrays.asList(new DeleteResult.BlobVersion(id, 2, false), new DeleteResult.BlobVersion(id, 1, false)), + result.getBlobVersions()); + InOrder order = inOrder(broken); + order.verify(broken).commit(); + order.verify(broken).setAutoCommit(true); + verify(broken, never()).rollback(); + try (Connection next = pool.getConnection()) { + assertSame(replacement, next.unwrap(Connection.class)); + assertTrue(next.getAutoCommit()); + } + assertEquals(0, metrics.namedBlobDBDeleteErrorCount.getCount()); + assertEquals(1, metrics.connectionCloseErrorCount.getCount()); + assertEquals(0, localConnectionFailures(metrics)); + } + } + + @Test + public void testResetFailureAfterRollbackPreservesCommitFailure() throws Exception { + Connection connection = mock(Connection.class); + DataSource source = mock(DataSource.class); + when(source.getConnection()).thenReturn(connection); + mockHardDelete(connection); + SQLException commitFailure = new SQLException("Commit not acknowledged"); + SQLException resetFailure = new SQLException("Connection lost resetting autocommit", "08006"); + doThrow(commitFailure).when(connection).commit(); + doThrow(resetFailure).when(connection).setAutoCommit(true); + Metrics metrics = new Metrics(new MetricRegistry(), ""); + try (MySqlNamedBlobDb db = hardDeleteDb(source, metrics)) { + TestUtils.assertException(ExecutionException.class, + () -> db.delete(account.getName(), container.getName(), "name").get(5, TimeUnit.SECONDS), + e -> assertSame(commitFailure, e.getCause())); + assertArrayEquals(new Throwable[]{resetFailure}, commitFailure.getSuppressed()); + InOrder order = inOrder(connection); + order.verify(connection).rollback(); + order.verify(connection).setAutoCommit(true); + order.verify(connection).abort(any()); + verify(connection, never()).close(); + assertEquals(1, metrics.namedBlobDBDeleteErrorCount.getCount()); + assertEquals(1, metrics.connectionCloseErrorCount.getCount()); + assertEquals(1, localConnectionFailures(metrics)); + } + } + + private long localConnectionFailures(Metrics metrics) { + return metrics.getMetricRegistry().getCounters() + .get(MetricRegistry.name(MySqlNamedBlobDb.class, "NamedBlobDBConnectionFailureCount." + localDatacenter)) + .getCount(); + } + + private HikariDataSource singleConnectionPool(Connection broken, Connection replacement) throws SQLException { + DataSource physicalSource = mock(DataSource.class); for (Connection physical : Arrays.asList(broken, replacement)) { when(physical.getAutoCommit()).thenReturn(true); when(physical.isValid(anyInt())).thenReturn(true); } when(physicalSource.getConnection()).thenReturn(broken, replacement); + HikariDataSource pool = new HikariDataSource(); + pool.setDataSource(physicalSource); + pool.setMaximumPoolSize(1); + pool.setMinimumIdle(0); + pool.setInitializationFailTimeout(-1); + pool.setConnectionTimeout(3000); + return pool; + } + + @Test + public void testRollbackFailureEvictsHikariConnection() throws Exception { + Connection broken = mock(Connection.class); + Connection replacement = mock(Connection.class); AssertionError failure = new AssertionError("Transaction interrupted"); when(broken.prepareStatement(startsWith("SELECT"))).thenThrow(failure); SQLException rollbackFailure = new SQLException("Rollback failed"); doThrow(rollbackFailure).when(broken).rollback(); - try (HikariDataSource pool = new HikariDataSource()) { - pool.setDataSource(physicalSource); - pool.setMaximumPoolSize(1); - pool.setMinimumIdle(0); - pool.setInitializationFailTimeout(-1); - pool.setConnectionTimeout(3000); + try (HikariDataSource pool = singleConnectionPool(broken, replacement)) { try (MySqlNamedBlobDb db = hardDeleteDb(pool, new Metrics(new MetricRegistry(), ""))) { TestUtils.assertException(ExecutionException.class, () -> db.delete(account.getName(), container.getName(), "name").get(5, TimeUnit.SECONDS), From 2015d1825d697c2f64e984f409942b124a38dcd1 Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Mon, 23 Nov 2026 23:21:45 -0800 Subject: [PATCH 5/5] Make named DB connection return paths explicit Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../com/github/ambry/named/MySqlNamedBlobDb.java | 16 ++++++---------- .../github/ambry/named/MySqlNamedBlobDbTest.java | 1 - 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java index 427ad8584e..1ff933229e 100644 --- a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java @@ -798,37 +798,33 @@ void executeTransactionGeneric(boolean autoCommit, TransactionGeneric tra private T runTransaction(boolean autoCommit, TransactionGeneric transaction) throws Exception { Connection connection = dataSource.getConnection(); - boolean returnToPool = true; - Throwable operationFailure = null; + final T result; try { if (!autoCommit) { connection.setAutoCommit(false); } - T result = transaction.run(connection); + result = transaction.run(connection); if (!autoCommit) { connection.commit(); } - return result; } catch (Exception | Error failure) { - operationFailure = failure; if (!autoCommit) { try { connection.rollback(); } catch (Exception | Error rollbackFailure) { // Returning an unresolved transaction to the pool could commit it when autocommit is restored. - returnToPool = false; discardConnection(connection, rollbackFailure); if (failure != rollbackFailure) { failure.addSuppressed(rollbackFailure); } + throw failure; } } + returnConnection(connection, autoCommit, failure); throw failure; - } finally { - if (returnToPool) { - returnConnection(connection, autoCommit, operationFailure); - } } + returnConnection(connection, autoCommit, null); + return result; } private void returnConnection(Connection connection, boolean autoCommit, Throwable operationFailure) { diff --git a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java index 513a6e0be2..bb89f0b2c1 100644 --- a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java +++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java @@ -188,7 +188,6 @@ public void testResetFailureAfterCommitEvictsHikariConnection() throws Exception verify(broken, never()).rollback(); try (Connection next = pool.getConnection()) { assertSame(replacement, next.unwrap(Connection.class)); - assertTrue(next.getAutoCommit()); } assertEquals(0, metrics.namedBlobDBDeleteErrorCount.getCount()); assertEquals(1, metrics.connectionCloseErrorCount.getCount());