From 574a0998e60b75abd8515dfc11bbcbb68e60e52d Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Wed, 2 Dec 2026 17:32:53 -0800 Subject: [PATCH 1/3] Bound exact named retirement preparation and replay Bound preparation and publication to one exact retirement intent per named DB instance. Limit the writer checkout read timeout and evict connections that cannot be safely returned. Use synchronous MySQL timeout updates in the fault-injection fixture. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ambry-named-mysql/README.md | 23 +- ...NamedBlobManifestStoreIntegrationTest.java | 439 ++++++++++++++++-- .../github/ambry/named/MySqlNamedBlobDb.java | 222 +++++++-- .../ambry/named/NamedBlobManifestStore.java | 210 ++++----- .../named/NamedBlobManifestStoreTest.java | 34 +- 5 files changed, 686 insertions(+), 242 deletions(-) diff --git a/ambry-named-mysql/README.md b/ambry-named-mysql/README.md index 919c88c07c..1dec59e553 100644 --- a/ambry-named-mysql/README.md +++ b/ambry-named-mysql/README.md @@ -6,10 +6,25 @@ the source of the list; repeated child IDs retain their positions. Prepare the l manifest and retire the named versions in one transaction. A crash before commit leaves neither a manifest nor a retirement. -Before dispatch, retain the original named-version keys, each root ID, and its ordered child IDs. If the commit reply is -lost, check that exact request on the authoritative writer. A match confirms the commit; it does not authorize cleanup. -No match means the commit was not observed, not that it rolled back. Retry only the original request. If the inputs are -unavailable, stop. Never resolve the current name to reconstruct the request or fall back to the router's ordinary delete. +`prepareRetirement` resolves the account and container once and reserves one request per named DB instance before +invoking the descriptor supplier. Supply the exact named versions and roots, and defer descriptor work to the supplier. +Preparation, publication, and receipt checks block; run them off the event loop. There is no payload queue. Close the +handle on all paths: while it is open, a second request is rejected as unavailable. The 32 MiB limit is on encoded child +bytes, not peak heap: allow for encoding buffers, supplier memory, and JDBC packet buffers. Publication or confirmation +can also occupy one connection from the same pool as ordinary requests, outside the transaction executor. + +Use the same handle to publish, to check its receipt after an uncertain result, and to retry. Each call checks out an +idle, autocommit `REPEATABLE READ` session from the configured local writer pool and starts a fresh transaction. +Publication and confirmation require a fixed Connector/J connection with reconnect disabled. The retirement checkout +caps socket reads at five seconds and restores the previous timeout before returning a healthy connection. Do not set a +pool-wide `socketTimeout` for retirement. Socket or communications failures discard the checkout without a rollback +attempt; an interrupted commit is still an unknown outcome. Configure bounded pool checkout and descriptor fetches. +The read timeout is not an end-to-end deadline, and closing the handle does not interrupt an active call. + +A matching receipt confirms the commit; it does not authorize cleanup. No match means the commit was not observed, not +that it rolled back. A replay whose read snapshot predates a concurrent commit can still reject if replacements now +exceed the range cap; confirm again in a fresh transaction. If the original inputs are unavailable, stop. Never resolve +the current name to reconstruct the request or use the router's ordinary delete. A reader with a saved tuple can recover the published list after a restart without fetching the original root. Configure the reader data source for `READ COMMITTED` or stronger on every checkout. diff --git a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java index 69c053e6c1..c4ada36df7 100644 --- a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java +++ b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java @@ -9,6 +9,7 @@ import static org.mockito.Mockito.*; import java.io.InputStream; +import java.net.SocketTimeoutException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -26,11 +27,13 @@ import java.util.Scanner; import java.util.UUID; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import javax.sql.DataSource; @@ -57,6 +60,7 @@ import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.Time; import com.mysql.cj.jdbc.MysqlDataSource; +import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; public class NamedBlobManifestStoreIntegrationTest { @@ -118,6 +122,12 @@ private static MySqlNamedBlobDb namedDb(DataSource db) throws Exception { return namedDb(db, new Properties(), SystemTime.getInstance()); } + private static MySqlNamedBlobDb namedDb(DataSource db, boolean hardDelete) throws Exception { + Properties properties = new Properties(); + properties.setProperty(MySqlNamedBlobDbConfig.ENABLE_HARD_DELETE, Boolean.toString(hardDelete)); + return namedDb(db, properties, SystemTime.getInstance()); + } + private static MySqlNamedBlobDb namedDb(DataSource db, Properties properties, Time time) throws Exception { properties.setProperty(MySqlNamedBlobDbConfig.DB_INFO, "[{\"url\":\"jdbc:mysql://[::1]\",\"datacenter\":\"local\",\"isWriteable\":true," @@ -266,8 +276,7 @@ private static void assertPage(MySqlNamedBlobDb reader, String prefix, String to } /** - * Validate, publish and fence one named version in one call; there is no separate staging step, so the - * descriptors are supplied and consumed in the same transaction that retires the version. + * Capture descriptors in memory, then publish the manifest and fence the named version in one transaction. */ private static void retireOne(MySqlNamedBlobDb db, long version, BlobId root, int count, Iterator children) throws Exception { @@ -287,16 +296,23 @@ private static void retireMany(MySqlNamedBlobDb db, Map pending) throws Exception { - try { - db.retireWithManifests("account", "container", name, pending).get(10, TimeUnit.SECONDS); - } catch (ExecutionException e) { - if (e.getCause() instanceof SQLException) { - throw (SQLException) e.getCause(); - } - throw e; + try (MySqlNamedBlobDb.Retirement retirement = db.prepareRetirement("account", "container", name, () -> pending)) { + retirement.publish(); + } + } + + private static boolean isPublished(MySqlNamedBlobDb db, Map pending) + throws Exception { + try (MySqlNamedBlobDb.Retirement retirement = db.prepareRetirement("account", "container", NAME, () -> pending)) { + return retirement.isPublished(); } } + private static void retireInTransaction(Connection c, String name, + Map pending) throws SQLException { + NamedBlobManifestStore.retire(c, NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, name, pending)); + } + private static Map pendingFor(List versions, Map roots, Map> childrenByVersion) { Map pending = new LinkedHashMap<>(); @@ -333,10 +349,8 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep List ids = children.stream().map(BlobId::getID).collect(Collectors.toList()); insertNamed(db, 7, old, NamedBlobState.READY); insertNamed(db, 8, replacement, NamedBlobState.IN_PROGRESS); - NamedBlobManifestStore writer = new NamedBlobManifestStore(db); - // Retirement only ever covers a contiguous prefix of the unfenced range: an unrequested, still-live version - // blocks retiring an older one, exactly as it did before capture and retire were merged. + // An unrequested, still-live version blocks retiring an older version of the same name. expectDataError("Unrepresented or ineligible", () -> retireOne(named, 7, old, children.size(), children.iterator())); assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); @@ -371,14 +385,13 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep insertNamed(db, 8, replacement, NamedBlobState.READY); retireOne(named, 7, old, children.size(), children.iterator()); // isPublished resolves a lost commit reply from the exact content-bound intent, not merely the version set. - assertTrue(writer.isPublished(NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, NAME, - Collections.singletonMap(7L, new NamedBlobManifestStore.PendingVersion(old, children.size(), - children.iterator()))))); + assertTrue(isPublished(named, Collections.singletonMap(7L, + new NamedBlobManifestStore.PendingVersion(old, children.size(), children.iterator())))); Map unpublishedPair = new LinkedHashMap<>(); unpublishedPair.put(7L, new NamedBlobManifestStore.PendingVersion(old, children.size(), children.iterator())); unpublishedPair.put(8L, new NamedBlobManifestStore.PendingVersion(replacement, 1, Collections.singletonList(children.get(0)).iterator())); - assertFalse(writer.isPublished(NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, NAME, unpublishedPair))); + assertFalse(isPublished(named, unpublishedPair)); assertEquals(replacement.getID(), named.get("account", "container", NAME).get(10, TimeUnit.SECONDS).getBlobId()); // Remove the retired fixture row entirely: a worker that resolves the source name cannot pass. try (Connection c = db.getConnection(); PreparedStatement remove = c.prepareStatement( @@ -458,10 +471,10 @@ public void testStaleSnapshotRetireReplayObservesCommittedPublication() throws E retireOne(named, 1, root, 1, children.iterator()); // A racer whose snapshot predates the winner's commit must still observe the published row when its own // locking read runs: that read is not snapshot-isolated, so the replay is idempotent rather than blind. - NamedBlobManifestStore.retire(loser, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(1L, + retireInTransaction(loser, NAME, Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); expectDataError("Conflicting manifest for named version", - () -> NamedBlobManifestStore.retire(loser, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(1L, + () -> retireInTransaction(loser, NAME, Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())))); loser.rollback(); @@ -560,7 +573,7 @@ public void testFenceAwarePutDuringPublication() throws Exception { rc.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); when(checkouts.getConnection()).thenReturn(rr, rc); publisher.setAutoCommit(false); - NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, NAME, pending); + retireInTransaction(publisher, NAME, pending); CompletableFuture waiting = writer.put(lower, NamedBlobState.READY, true); awaitCount(publisher, "SELECT COUNT(*) FROM performance_schema.data_lock_waits" + " WHERE BLOCKING_THREAD_ID=PS_CURRENT_THREAD_ID()", 1); @@ -866,7 +879,7 @@ public void testRetirementLocksGapForReplacement() throws Exception { try (Connection publisher = db.getConnection(); Connection replacement = db.getConnection(); Statement insert = replacement.createStatement()) { publisher.setAutoCommit(false); - NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(7L, + retireInTransaction(publisher, NAME, Collections.singletonMap(7L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); insert.execute("SET SESSION innodb_lock_wait_timeout=1"); String put = "INSERT INTO named_blobs_v2 (account_id,container_id,blob_name,version,blob_id,blob_state)" @@ -923,10 +936,9 @@ public void testPublicationRollsBackWhenNameMutationFails() throws Exception { reversed.sort(Collections.reverseOrder()); try (Connection replay = db.getConnection()) { replay.setAutoCommit(false); - NamedBlobManifestStore.retire(replay, ACCOUNT, CONTAINER, NAME, - pendingFor(reversed, roots, childrenByVersion)); + retireInTransaction(replay, NAME, pendingFor(reversed, roots, childrenByVersion)); try { - NamedBlobManifestStore.retire(replay, ACCOUNT, CONTAINER, NAME, Collections.emptyMap()); + retireInTransaction(replay, NAME, Collections.emptyMap()); fail("An empty set is not a publication receipt"); } catch (IllegalArgumentException expected) { assertEquals("Invalid number of manifests", expected.getMessage()); @@ -972,7 +984,7 @@ public void testWaitingTtlCannotReviveRetiredVersion() throws Exception { + " AND info LIKE 'UPDATE named_blobs_v2 SET blob_state=%'") == 0) { assertTrue("TTL statement never began", System.nanoTime() < deadline && !blocked.isDone()); } - NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(7L, + retireInTransaction(publisher, NAME, Collections.singletonMap(7L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); publisher.commit(); assertEquals("45000", blocked.get(10, TimeUnit.SECONDS)); @@ -1152,9 +1164,9 @@ public void testTwoUnrelatedFreshPublicationsDoNotContendOnTheManifestTable() th } // Both are genuinely fresh inserts into the same, otherwise empty manifest table; a preceding locking // read on either absent key would gap-lock the other, and the two inserts would then deadlock (1213). - NamedBlobManifestStore.retire(first, ACCOUNT, CONTAINER, nameA, Collections.singletonMap(1L, + retireInTransaction(first, nameA, Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(rootA, 1, childrenA.iterator()))); - NamedBlobManifestStore.retire(second, ACCOUNT, CONTAINER, nameB, Collections.singletonMap(1L, + retireInTransaction(second, nameB, Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(rootB, 1, childrenB.iterator()))); first.commit(); second.commit(); @@ -1199,23 +1211,16 @@ public void testDifferentRootForTheSameVersionCannotImpersonateAPublishedIntent( insertNamed(db, 1, publishedRoot, NamedBlobState.READY); List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); retireOne(named, 1, publishedRoot, 1, children.iterator()); - NamedBlobManifestStore writer = new NamedBlobManifestStore(db); - assertFalse(writer.isPublished(NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, NAME, - Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(impostorRoot, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()))))); + assertFalse(isPublished(named, Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(impostorRoot, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())))); expectDataError("Conflicting manifest for named version", () -> retireOne(named, 1, impostorRoot, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); }); } - /** - * The concretely reported gap: retireWithManifests used to capture the caller's own mutable map by reference - * into a lambda queued for a background thread. Everything is now validated and every iterator fully consumed - * into an immutable, caller-retainable description before that dispatch, so mutating or clearing the caller's - * map immediately after the call returns must not change what gets published. - */ @Test - public void testMutatingCallerMapAfterDispatchDoesNotAffectThePublishedContent() throws Exception { + public void testMutatingCallerMapAfterPreparationDoesNotAffectThePublishedContent() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); BlobId decoy = blob(BlobId.BlobDataType.METADATA); @@ -1223,19 +1228,353 @@ public void testMutatingCallerMapAfterDispatchDoesNotAffectThePublishedContent() List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); Map pending = new LinkedHashMap<>(); pending.put(1L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator())); - Future future = named.retireWithManifests("account", "container", NAME, pending); - // Mutate the caller's own map immediately after dispatch: a captured reference to this map would let this - // mutation race the background transaction and silently change what it publishes. - pending.clear(); - pending.put(1L, new NamedBlobManifestStore.PendingVersion(decoy, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); - future.get(10, TimeUnit.SECONDS); + try (MySqlNamedBlobDb.Retirement retirement = + named.prepareRetirement("account", "container", NAME, () -> pending)) { + pending.clear(); + pending.put(1L, new NamedBlobManifestStore.PendingVersion(decoy, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); + retirement.publish(); + } NamedBlobManifestStore worker = new NamedBlobManifestStore(db); NamedBlobManifestStore.Manifest manifest = worker.getPublished(ACCOUNT, CONTAINER, NAME, 1); assertEquals(root.getID(), manifest.root); }); } + @Test + public void testReplacementDuringEncodingCannotChangeValidatedVersion() throws Exception { + withDatabase((db, named) -> { + BlobId first = blob(BlobId.BlobDataType.METADATA); + BlobId second = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, first, NamedBlobState.READY); + insertNamed(db, 2, second, NamedBlobState.READY); + Map pending = new LinkedHashMap<>(); + pending.put(1L, new NamedBlobManifestStore.PendingVersion(first, 1, new Iterator() { + private boolean consumed; + + @Override + public boolean hasNext() { + return !consumed; + } + + @Override + public BlobId next() { + consumed = true; + pending.put(2L, new NamedBlobManifestStore.PendingVersion(first, MAX_CHILDREN, poisonIterator())); + return child; + } + })); + pending.put(2L, new NamedBlobManifestStore.PendingVersion(second, 1, Collections.singleton(child).iterator())); + retireMany(named, pending); + NamedBlobManifestStore store = new NamedBlobManifestStore(db); + NamedBlobManifestStore.Manifest manifest = store.getPublished(ACCOUNT, CONTAINER, NAME, 2); + assertEquals(second.getID(), manifest.root); + assertEquals(Collections.singletonList(child.getID()), store.read(manifest)); + }); + } + + @Test + public void testAdmissionCoversPreparationAndRecoveryAndReleasesOnFailure() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + ExecutorService preparer = Executors.newSingleThreadExecutor(); + CountDownLatch preparing = new CountDownLatch(1); + CountDownLatch resume = new CountDownLatch(1); + Future preparingFuture = preparer.submit( + () -> named.prepareRetirement("account", "container", NAME, () -> { + preparing.countDown(); + try { + assertTrue(resume.await(10, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError(e); + } + return Collections.emptyMap(); + })); + try { + assertTrue(preparing.await(10, TimeUnit.SECONDS)); + assertRetirementBusy(named); + } finally { + resume.countDown(); + preparer.shutdown(); + } + try { + preparingFuture.get(10, TimeUnit.SECONDS); + fail("No versions were supplied"); + } catch (ExecutionException e) { + assertTrue(e.getCause().toString(), e.getCause() instanceof IllegalArgumentException); + } + insertNamed(db, 1, root, NamedBlobState.READY); + try (MySqlNamedBlobDb.Retirement retirement = named.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + assertFalse(retirement.isPublished()); + retirement.publish(); + assertRetirementBusy(named); + } + retireOne(named, 1, root, 1, Collections.singleton(child).iterator()); + }); + } + + private static void assertRetirementBusy(MySqlNamedBlobDb named) throws Exception { + try { + named.prepareRetirement("account", "container", NAME, () -> { + throw new AssertionError("Rejected request must not fetch descriptors"); + }); + fail("Concurrent preparation was admitted"); + } catch (RestServiceException e) { + assertEquals(RestServiceErrorCode.ServiceUnavailable, e.getErrorCode()); + } + } + + @Test + public void testExactHandleConfirmsLostReplyAfterOverCapReplacement() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + try (Connection physical = db.getConnection()) { + Connection lostReply = mock(Connection.class, delegatesTo(physical)); + doAnswer(call -> { + physical.commit(); + throw new SQLException("Simulated lost commit reply", "S1000", new SocketTimeoutException()); + }).when(lostReply).commit(); + DataSource writer = mock(DataSource.class); + when(writer.getConnection()).thenReturn(lostReply).thenAnswer(call -> db.getConnection()); + try (MySqlNamedBlobDb withLostReply = namedDb(writer); + MySqlNamedBlobDb.Retirement retirement = withLostReply.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + assertLostReplyAndRecover(db, retirement, root, child); + } + verify(lostReply, never()).rollback(); + } + }); + } + + private static void assertLostReplyAndRecover(DataSource db, MySqlNamedBlobDb.Retirement retirement, BlobId root, + BlobId child) throws Exception { + try (Connection stale = db.getConnection(); Statement snapshot = stale.createStatement()) { + stale.setAutoCommit(false); + try (ResultSet rs = snapshot.executeQuery("SELECT COUNT(*) FROM named_blob_manifests_v1")) { + assertTrue(rs.next()); + assertEquals(0, rs.getInt(1)); + } + try { + retirement.publish(); + fail("Expected the commit reply to be lost"); + } catch (SQLException e) { + assertEquals("Simulated lost commit reply", e.getMessage()); + } + for (int version = 2; version <= 34; version++) { + insertNamed(db, version, blob(BlobId.BlobDataType.METADATA), NamedBlobState.READY); + } + expectDataError("Unsupported named version range", + () -> retireInTransaction(stale, NAME, Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))); + stale.rollback(); + } + assertTrue(retirement.isPublished()); + retirement.publish(); + assertEquals(33, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE retirement_fenced=FALSE")); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + } + + @Test + public void testRetirementRejectsActiveWriterTransactionWithoutCommittingIt() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + try (Connection writer = db.getConnection(); Statement sql = writer.createStatement()) { + sql.execute("START TRANSACTION"); + assertEquals(1, sql.executeUpdate("UPDATE named_blobs_v2 SET blob_size=123")); + assertTrue(writer.getAutoCommit()); + DataSource source = mock(DataSource.class); + when(source.getConnection()).thenReturn(writer); + try (MySqlNamedBlobDb unsafe = namedDb(source); + MySqlNamedBlobDb.Retirement retirement = unsafe.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + try { + retirement.publish(); + fail("Borrowed an active writer transaction"); + } catch (SQLException e) { + assertTrue(e.getMessage(), e.getMessage().contains("idle autocommit")); + } + } + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE blob_size=123 OR retirement_fenced")); + }); + } + + @Test + public void testPublishOverridesPendingReadCommittedAndLocksNamingGap() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + try (Connection physical = db.getConnection(); Statement setting = physical.createStatement(); + Connection competing = db.getConnection(); Statement limit = competing.createStatement()) { + setting.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + limit.execute("SET SESSION innodb_lock_wait_timeout=1"); + Connection writer = mock(Connection.class, delegatesTo(physical)); + doAnswer(call -> { + // Probe after the range was read but before any manifest or named-row write. + try { + insertNamed(competing, NAME, 2, blob(BlobId.BlobDataType.METADATA), NamedBlobState.READY); + fail("A replacement entered the name range before publication"); + } catch (SQLException expected) { + assertEquals(expected.getMessage(), 1205, expected.getErrorCode()); + } + return physical.prepareStatement(call.getArgument(0)); + }).when(writer).prepareStatement(startsWith("INSERT INTO named_blob_manifests_v1")); + DataSource checkout = mock(DataSource.class); + when(checkout.getConnection()).thenReturn(writer).thenAnswer(call -> db.getConnection()); + try (MySqlNamedBlobDb isolated = namedDb(checkout); + MySqlNamedBlobDb.Retirement retirement = isolated.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + retirement.publish(); + assertTrue(retirement.isPublished()); + } + verify(writer).prepareStatement(startsWith("INSERT INTO named_blob_manifests_v1")); + insertNamed(competing, NAME, 2, blob(BlobId.BlobDataType.METADATA), NamedBlobState.READY); + } + }); + } + + @Test + public void testRetirementRestoresPooledTimeoutAndEvictsAfterReadStall() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + MysqlDataSource source; + try (Connection connection = db.getConnection()) { + source = source(connection.getCatalog()); + } + source.setSocketTimeout(0); + HikariConfig config = new HikariConfig(); + config.setDataSource(source); + config.setMaximumPoolSize(1); + config.setConnectionInitSql("SET SESSION innodb_lock_wait_timeout=15"); + try (HikariDataSource pool = new HikariDataSource(config); + MySqlNamedBlobDb pooled = namedDb(pool); + MySqlNamedBlobDb.Retirement retirement = pooled.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + int originalId = ordinaryCheckout(pool, 0); + assertFalse(retirement.isPublished()); + assertEquals(originalId, ordinaryCheckout(pool, 0)); + + try (Connection blocker = db.getConnection(); Statement lock = blocker.createStatement()) { + blocker.setAutoCommit(false); + try (ResultSet locked = lock.executeQuery("SELECT version FROM named_blobs_v2 FOR UPDATE")) { + assertTrue(locked.next()); + } + try { + retirement.publish(); + fail("Published while another transaction held the row lock"); + } catch (SQLException expected) { + Throwable cause = expected; + while (cause != null && !(cause instanceof SocketTimeoutException)) { + cause = cause.getCause(); + } + assertNotNull(expected.toString(), cause); + } finally { + blocker.rollback(); + } + } + int replacementId = ordinaryCheckout(pool, 0); + assertNotEquals(originalId, replacementId); + assertFalse(retirement.isPublished()); + retirement.publish(); + assertTrue(retirement.isPublished()); + assertEquals(replacementId, ordinaryCheckout(pool, 0)); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + } + }); + } + + @Test + public void testRetirementPreservesCommitAndEvictsWhenTimeoutRestoreFails() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + long version = 1; + insertNamed(db, version, root, NamedBlobState.READY); + try (Connection physical = db.getConnection()) { + int originalTimeout = physical.getNetworkTimeout(); + AtomicBoolean committed = new AtomicBoolean(); + AtomicBoolean restoreFailed = new AtomicBoolean(); + Connection failingRestore = mock(Connection.class, delegatesTo(physical)); + doAnswer(call -> { + physical.commit(); + committed.set(true); + return null; + }).when(failingRestore).commit(); + doAnswer(call -> { + // Fail only the first restore so a later Hikari health check cannot mask a missing eviction. + if (committed.get() && restoreFailed.compareAndSet(false, true)) { + throw new SQLException("Socket timeout restore failed", "HY000"); + } + physical.setNetworkTimeout(call.getArgument(0), originalTimeout); + return null; + }).when(failingRestore).setNetworkTimeout(any(), eq(originalTimeout)); + DataSource checkout = mock(DataSource.class); + when(checkout.getConnection()).thenReturn(failingRestore).thenAnswer(call -> db.getConnection()); + HikariConfig config = new HikariConfig(); + config.setDataSource(checkout); + // Keep the injected checkout but select Hikari's synchronous MySQL timeout executor. + config.setJdbcUrl(physical.getMetaData().getURL()); + config.setMaximumPoolSize(1); + config.setConnectionTimeout(3000); + try (HikariDataSource pool = new HikariDataSource(config); + MySqlNamedBlobDb pooled = namedDb(pool); + MySqlNamedBlobDb.Retirement retirement = pooled.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(version, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + int originalId = ordinaryCheckout(pool, originalTimeout); + retirement.publish(); + assertTrue("Timeout restoration must fail after the real commit", restoreFailed.get()); + assertNotEquals("The next borrower must get a different physical connection", originalId, + ordinaryCheckout(pool, originalTimeout)); + assertTrue("The exact receipt must survive the cleanup failure", retirement.isPublished()); + } + } + }); + } + + private static int ordinaryCheckout(DataSource pool, int expectedTimeout) throws SQLException { + try (Connection c = pool.getConnection(); Statement s = c.createStatement(); + ResultSet rows = s.executeQuery("SELECT CONNECTION_ID()")) { + assertEquals(expectedTimeout, c.getNetworkTimeout()); + assertTrue(c.getAutoCommit()); + assertTrue(rows.next()); + return rows.getInt(1); + } + } + + @Test + public void testHardDeleteRejectsBeforeLoadingDescriptors() throws Exception { + withDatabase((db, named) -> { + try (MySqlNamedBlobDb hardDelete = namedDb(db, true)) { + try { + hardDelete.prepareRetirement("account", "container", NAME, () -> { + throw new AssertionError("Hard-delete mode must not fetch descriptors"); + }); + fail("Accepted manifest retirement in hard-delete mode"); + } catch (UnsupportedOperationException expected) { + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + } + } + }); + } + /** * The actual race the guard and the lock order exist for: a retire that has locked the named range (but not yet * committed its manifest insert) must block a concurrent direct replace for the same tuple. Once it commits, @@ -1251,7 +1590,7 @@ public void testConcurrentRetireBlocksRacingDirectReplaceThenRejectsReuse() thro try (Connection retiring = db.getConnection(); Connection replacing = db.getConnection(); Statement replace = replacing.createStatement()) { retiring.setAutoCommit(false); - NamedBlobManifestStore.retire(retiring, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(7L, + retireInTransaction(retiring, NAME, Collections.singletonMap(7L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); replace.execute("SET SESSION innodb_lock_wait_timeout=1"); try { @@ -1399,6 +1738,7 @@ private static MysqlDataSource source(String schema) throws SQLException { } db.setDatabaseName(schema); db.setServerTimezone("UTC"); + db.setSocketTimeout(15_000); // Mirror production's Hikari useServerPrepStmts=true so large-payload tests exercise the same statement mode. db.setUseServerPrepStmts(true); return db; @@ -1438,7 +1778,14 @@ private static void insertNamed(DataSource db, long version, BlobId root, NamedB private static void insertNamed(DataSource db, String name, long version, BlobId root, NamedBlobState state) throws SQLException { - try (Connection c = db.getConnection(); PreparedStatement s = c.prepareStatement( + try (Connection c = db.getConnection()) { + insertNamed(c, name, version, root, state); + } + } + + private static void insertNamed(Connection c, String name, long version, BlobId root, NamedBlobState state) + throws SQLException { + try (PreparedStatement s = c.prepareStatement( "INSERT INTO named_blobs_v2 (account_id,container_id,blob_name,version,blob_id,blob_state)" + " VALUES (?,?,?,?,?,?)")) { s.setShort(1, ACCOUNT); 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 463d0c5a21..d7334fbac4 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 @@ -41,7 +41,10 @@ import com.mysql.cj.jdbc.JdbcConnection; import com.zaxxer.hikari.HikariDataSource; import java.io.Closeable; +import java.io.EOFException; import java.io.IOException; +import java.net.SocketException; +import java.net.SocketTimeoutException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -64,8 +67,10 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.sql.DataSource; @@ -84,6 +89,7 @@ public class MySqlNamedBlobDb implements NamedBlobDb { private static final Logger logger = LoggerFactory.getLogger(MySqlNamedBlobDb.class); private static final int MAX_NUMBER_OF_VERSIONS_IN_DELETE = 1000; private static final int VERSION_BASE = 100000; + private static final int RETIREMENT_READ_TIMEOUT_MS = 5_000; private final Time time; private static final String MULTI_VERSION_PLACE_HOLDER = "MULTI_VERSION_PLACE_HOLDER"; @@ -189,6 +195,8 @@ public class MySqlNamedBlobDb implements NamedBlobDb { private final Map transactionExecutors; private final MySqlNamedBlobDbConfig config; private final Metrics metricsRecoder; + // Reserve one worst-case encoded request (32 MiB), including while its caller decides whether to retry. + private final Semaphore retirementSlot = new Semaphore(1); MySqlNamedBlobDb(AccountService accountService, MySqlNamedBlobDbConfig config, DataSourceFactory dataSourceFactory, String localDatacenter, Metrics metricRecorder, Time time) { @@ -467,45 +475,90 @@ public CompletableFuture updateBlobTtlAndStateToReady(NamedBlobRecord } /** - * Validate, publish and fence this exact set of named versions in one transaction. Never returns IDs for a - * router cascade. There is no separate staging step: a version's descriptors are supplied and consumed in the - * same call that retires it. Everything is validated and every iterator is fully consumed into an immutable - * {@link NamedBlobManifestStore.PreparedRetirement} synchronously, before this is handed to the background - * transaction thread: the thread never sees {@code pendingVersions} itself, so the caller mutating or clearing - * that map after this call returns cannot change what gets published. + * Admit and prepare one exact intent. The supplier must defer fetching descriptors until invoked. This blocks, + * as do the returned handle's methods; callers must run it off the event loop and close the handle on all paths. */ - CompletableFuture retireWithManifests(String accountName, String containerName, String blobName, - Map pendingVersions) { + Retirement prepareRetirement(String accountName, String containerName, String blobName, + Supplier> pendingVersions) throws RestServiceException, + SQLException { + if (config.enableHardDelete) { + throw new UnsupportedOperationException("Manifest retirement requires named soft delete"); + } + TransactionExecutor writer = transactionExecutors.get(localDatacenter); + if (writer == null || writer.executor.isShutdown()) { + throw new RestServiceException("Named retirement writer is unavailable", RestServiceErrorCode.ServiceUnavailable); + } Account account = accountService.getAccountByName(accountName); if (account == null) { - CompletableFuture failed = new CompletableFuture<>(); - failed.completeExceptionally( - new RestServiceException("Account not found: " + accountName, RestServiceErrorCode.NotFound)); - return failed; + throw new RestServiceException("Account not found: " + accountName, RestServiceErrorCode.NotFound); } Container container = account.getContainerByName(containerName); if (container == null) { - CompletableFuture failed = new CompletableFuture<>(); - failed.completeExceptionally( - new RestServiceException("Container not found: " + containerName, RestServiceErrorCode.NotFound)); - return failed; + throw new RestServiceException("Container not found: " + containerName, RestServiceErrorCode.NotFound); } - NamedBlobManifestStore.PreparedRetirement prepared; + if (!retirementSlot.tryAcquire()) { + throw new RestServiceException("Named retirement already in progress", RestServiceErrorCode.ServiceUnavailable); + } + boolean prepared = false; try { - prepared = NamedBlobManifestStore.prepare((short) account.getId(), (short) container.getId(), blobName, - pendingVersions); - } catch (SQLException e) { - CompletableFuture failed = new CompletableFuture<>(); - failed.completeExceptionally(e); - return failed; + Retirement retirement = new Retirement(writer, + NamedBlobManifestStore.prepare(account.getId(), container.getId(), blobName, pendingVersions.get())); + prepared = true; + return retirement; + } finally { + if (!prepared) { + retirementSlot.release(); + } + } + } + + /** Owns the admission slot and the encoded bytes until close. Never queues a payload. */ + final class Retirement implements AutoCloseable { + private final TransactionExecutor writer; + private NamedBlobManifestStore.PreparedRetirement prepared; + + private Retirement(TransactionExecutor writer, NamedBlobManifestStore.PreparedRetirement prepared) { + this.writer = writer; + this.prepared = prepared; + } + + synchronized void publish() throws Exception { + run(connection -> { + NamedBlobManifestStore.retire(connection, prepared); + return null; + }); + } + + /** A negative result means "not observed"; only a positive exact receipt confirms publication. */ + synchronized boolean isPublished() throws Exception { + return run(connection -> NamedBlobManifestStore.matchesReceipt(connection, prepared)); + } + + private T run(TransactionGeneric transaction) throws Exception { + if (prepared == null) { + throw new IllegalStateException("Named retirement is closed"); + } + if (writer.executor.isShutdown()) { + throw new RestServiceException("Named retirement writer is unavailable", RestServiceErrorCode.ServiceUnavailable); + } + try { + return writer.runRetirementTransaction(transaction); + } catch (Exception | Error e) { + writer.recordConnectionFailure(e); + if (e instanceof SQLException) { + metricsRecoder.namedBlobDBDeleteErrorCount.inc(); + } + throw e; + } } - return executeTransactionAsync(accountName, containerName, false, (ignoredAccount, ignoredContainer, connection) -> { - if (config.enableHardDelete) { - throw new UnsupportedOperationException("Manifest retirement requires named soft delete"); + + @Override + public synchronized void close() { + if (prepared != null) { + prepared = null; + retirementSlot.release(); } - NamedBlobManifestStore.retire(connection, prepared); - return null; - }, null, metricsRecoder.namedBlobDBDeleteErrorCount); + } } @Override @@ -735,7 +788,7 @@ private static class TransactionExecutor implements Closeable { /** * Whether the given throwable represents a JDBC connection failure (vs. any other SQL error). * - *

Three independent positive signals, all spec-defined as connection-class: + *

Positive signals include: *

    *
  1. {@link SQLNonTransientConnectionException} — JDBC's non-transient connection-failure * subclass; MySQL {@code CommunicationsException} extends this.
  2. @@ -746,6 +799,7 @@ private static class TransactionExecutor implements Closeable { *
* *

The walk includes causes, chained SQL exceptions and suppressed cleanup failures. + * Connector/J can wrap a socket failure in a generic SQLException. * SQLSTATE "40*" (transaction rollback), "57*" (operator intervention), and other * adjacent classes are intentionally NOT counted — those are not connection failures. */ @@ -761,7 +815,8 @@ private static boolean isConnectionFailure(Throwable t) { if (!seen.add(cur)) { continue; } - if (cur instanceof SQLNonTransientConnectionException || cur instanceof SQLTransientConnectionException) { + if (cur instanceof SQLNonTransientConnectionException || cur instanceof SQLTransientConnectionException + || cur instanceof SocketTimeoutException || cur instanceof SocketException || cur instanceof EOFException) { return true; } if (cur instanceof SQLException) { @@ -789,6 +844,12 @@ void executeTransaction(Container container, boolean autoCommit, Transaction connection -> transaction.run(container.getParentAccountId(), container.getId(), connection), callback); } + private void recordConnectionFailure(Throwable failure) { + if (isConnectionFailure(failure)) { + connectionFailureCount.inc(); + } + } + void executeTransactionGeneric(boolean autoCommit, TransactionGeneric transaction, Callback callback) { final long enqueueTimeMs = System.currentTimeMillis(); try { @@ -796,11 +857,9 @@ void executeTransactionGeneric(boolean autoCommit, TransactionGeneric tra enqueueWaitTimeInMs.update(System.currentTimeMillis() - enqueueTimeMs); T result; try { - result = runTransaction(autoCommit, transaction); + result = runTransaction(autoCommit ? TransactionMode.AUTOCOMMIT : TransactionMode.EXPLICIT, transaction); } catch (Exception | Error e) { - if (isConnectionFailure(e)) { - connectionFailureCount.inc(); - } + recordConnectionFailure(e); callback.onCompletion(null, e instanceof Exception ? (Exception) e : new IllegalStateException(e)); return; } @@ -811,13 +870,51 @@ void executeTransactionGeneric(boolean autoCommit, TransactionGeneric tra } } - private T runTransaction(boolean autoCommit, TransactionGeneric transaction) throws Exception { + private enum TransactionMode { + AUTOCOMMIT, EXPLICIT, RETIREMENT + } + + private T runRetirementTransaction(TransactionGeneric transaction) throws Exception { + return runTransaction(TransactionMode.RETIREMENT, transaction); + } + + private T runTransaction(TransactionMode mode, TransactionGeneric transaction) throws Exception { + boolean autoCommit = mode == TransactionMode.AUTOCOMMIT; + boolean retirement = mode == TransactionMode.RETIREMENT; Connection connection = dataSource.getConnection(); + int timeoutToRestore = -1; + if (retirement) { + try { + JdbcConnection driver = requireFixedRetirementSession(connection); + int originalTimeout = connection.getNetworkTimeout(); + if (originalTimeout == 0 || originalTimeout > RETIREMENT_READ_TIMEOUT_MS) { + connection.setNetworkTimeout(Runnable::run, RETIREMENT_READ_TIMEOUT_MS); + timeoutToRestore = originalTimeout; + } + requireIdleRetirementSession(connection, driver); + } catch (Exception | Error failure) { + // This connection may contain someone else's transaction. Do not reset autocommit. + discardConnection(connection, failure); + throw failure; + } + } final T result; try { if (!autoCommit) { connection.setAutoCommit(false); } + if (retirement) { + try (Statement check = connection.createStatement(); + ResultSet settings = check.executeQuery("SELECT @@session.autocommit")) { + if (!settings.next() || settings.getBoolean(1)) { + throw new SQLException("Named retirement could not disable autocommit"); + } + } + // A per-transaction override is not visible in @@session.transaction_isolation. + try (Statement statement = connection.createStatement()) { + statement.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + } + } result = transaction.run(connection); if (!autoCommit) { connection.commit(); @@ -827,6 +924,10 @@ private T runTransaction(boolean autoCommit, TransactionGeneric transacti discardConnection(connection, failure); throw failure; } catch (Exception | Error failure) { + if (retirement && isConnectionFailure(failure)) { + discardConnection(connection, failure); + throw failure; + } if (!autoCommit) { try { connection.rollback(); @@ -839,31 +940,56 @@ private T runTransaction(boolean autoCommit, TransactionGeneric transacti throw failure; } } - returnConnection(connection, autoCommit, failure); + returnConnection(connection, autoCommit, timeoutToRestore, failure); throw failure; } - returnConnection(connection, autoCommit, null); + returnConnection(connection, autoCommit, timeoutToRestore, null); return result; } - private void returnConnection(Connection connection, boolean autoCommit, Throwable operationFailure) { + private static JdbcConnection requireFixedRetirementSession(Connection connection) throws SQLException { + JdbcConnection driver = connection.unwrap(JdbcConnection.class); + if (!(driver instanceof ConnectionImpl) || driver.isProxySet() + || driver.getPropertySet().getBooleanProperty(PropertyKey.autoReconnect).getValue() + || driver.getPropertySet().getBooleanProperty(PropertyKey.autoReconnectForPools).getValue() + || driver.getPropertySet().getBooleanProperty(PropertyKey.reconnectAtTxEnd).getValue()) { + throw new SQLException("Named retirement requires a fixed physical MySQL session"); + } + return driver; + } + + private static void requireIdleRetirementSession(Connection connection, JdbcConnection driver) throws SQLException { + try (Statement check = connection.createStatement()) { + check.setFetchSize(0); + try (ResultSet settings = check.executeQuery("SELECT @@session.autocommit, @@session.transaction_isolation")) { + if (!settings.next() || !settings.getBoolean(1) || !"REPEATABLE-READ".equals(settings.getString(2)) + || driver.getSession().getServerSession().inTransactionOnServer()) { + throw new SQLException("Named retirement requires an idle autocommit REPEATABLE READ session"); + } + } + } + } + + private void returnConnection(Connection connection, boolean autoCommit, int timeoutToRestore, + Throwable operationFailure) { try { - if (!autoCommit) { - try { + try { + if (!autoCommit) { connection.setAutoCommit(true); - } catch (Exception | Error resetFailure) { - // Hikari can recycle a connection even when a reset inside close() fails. - discardConnection(connection, resetFailure); - throw resetFailure; } + if (timeoutToRestore >= 0) { + connection.setNetworkTimeout(Runnable::run, timeoutToRestore); + } + } 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(); - } + recordConnectionFailure(cleanupFailure); } else if (operationFailure != cleanupFailure) { operationFailure.addSuppressed(cleanupFailure); } diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java index 9ebab8f921..4270fb1d52 100644 --- a/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java @@ -24,7 +24,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.TreeSet; +import java.util.TreeMap; import javax.sql.DataSource; import com.github.ambry.commons.BlobId; import com.github.ambry.protocol.NamedBlobState; @@ -83,36 +83,37 @@ static final class PendingVersion { } /** - * An entire publication request, fully validated and fully encoded: every iterator has already been consumed - * into an immutable {@code byte[]} body, and every bound (per-version and aggregate child count, root shape) has - * already been checked. It owns its own bytes rather than the caller's map or iterators, so it is safe to retain - * across an asynchronous dispatch boundary and hand to a background thread. + * An immutable publication request that owns its encoded bytes for publication, confirmation, and replay. */ static final class PreparedRetirement { final short account; final short container; final String name; - final List requested; - private final Map rootBytes; - private final Map rootIds; - private final Map counts; - private final Map bodies; - private final Map rowHashes; + private final Map versions; private final byte[] intentToken; - private PreparedRetirement(short account, short container, String name, List requested, - Map rootBytes, Map rootIds, Map counts, Map bodies, - Map rowHashes, byte[] intentToken) { + private PreparedRetirement(short account, short container, String name, Map versions) { this.account = account; this.container = container; this.name = name; - this.requested = Collections.unmodifiableList(requested); - this.rootBytes = Collections.unmodifiableMap(rootBytes); - this.rootIds = Collections.unmodifiableMap(rootIds); - this.counts = Collections.unmodifiableMap(counts); - this.bodies = Collections.unmodifiableMap(bodies); - this.rowHashes = Collections.unmodifiableMap(rowHashes); - this.intentToken = intentToken; + this.versions = Collections.unmodifiableMap(versions); + this.intentToken = intentToken(name, versions); + } + } + + private static final class PreparedVersion { + private final byte[] root; + private final int count; + private final byte[] body; + private final byte[] hash; + + private PreparedVersion(short account, short container, String name, long version, PendingVersion pending) + throws SQLException { + root = pending.root.toBytes(); + count = pending.expected; + body = encode(pending.descriptors, count, root); + hash = hash(account, container, name, version, count, + Base64.getUrlEncoder().withoutPadding().encodeToString(root), body); } } @@ -139,32 +140,10 @@ private static byte[] encode(Iterator descriptors, int expec private static void bindKey(PreparedStatement s, short account, short container, String name, long version) throws SQLException { - bindKey(s, account, container, name, version, 1); - } - - private static void bindKey(PreparedStatement s, short account, short container, String name, long version, int at) - throws SQLException { - s.setInt(at, account); - s.setInt(at + 1, container); - s.setString(at + 2, name); - s.setLong(at + 3, version); - } - - static void checkManifestCount(List versions) { - if (versions == null || versions.isEmpty() || versions.size() > MAX_VERSIONS) { - throw new IllegalArgumentException("Invalid number of manifests"); - } - } - - static List canonicalVersions(List versions) { - checkManifestCount(versions); - TreeSet sorted = new TreeSet<>(); - for (Long version : versions) { - if (version == null || !sorted.add(version)) { - throw new IllegalArgumentException("Expected distinct canonical manifest versions"); - } - } - return new ArrayList<>(sorted); + s.setInt(1, account); + s.setInt(2, container); + s.setString(3, name); + s.setLong(4, version); } /** @@ -172,8 +151,7 @@ static List canonicalVersions(List versions) { * exactly what will be published. Every declared bound -- per-version child count, aggregate child count across * the whole request, root shape -- is checked purely against caller-supplied values before a single iterator is * touched, a payload is encoded, or a connection is opened: a doomed oversized request never reads or hashes a - * byte. The result owns its own encoded bytes and holds no reference to {@code pending}, so it is safe to retain - * and hand to another thread for asynchronous publication. + * byte. The result holds no reference to {@code pending} or its iterators. */ static PreparedRetirement prepare(short account, short container, String name, Map pending) throws SQLException { @@ -181,22 +159,29 @@ static PreparedRetirement prepare(short account, short container, String name, M throw new SQLDataException("Unsupported named composite capture"); } Objects.requireNonNull(pending, "pending"); - List requested = canonicalVersions(new ArrayList<>(pending.keySet())); - - long totalDeclared = 0; - Map counts = new LinkedHashMap<>(); - for (long version : requested) { - PendingVersion p = pending.get(version); - if (p == null) { - throw new IllegalArgumentException("Missing pending descriptors for version " + version); + // Copy both key and value, not Map.Entry references that may continue to reflect changes to the caller's map. + Map captured = new TreeMap<>(); + for (Map.Entry entry : pending.entrySet()) { + Long version = entry.getKey(); + PendingVersion input = entry.getValue(); + if (captured.size() >= MAX_VERSIONS) { + throw new IllegalArgumentException("Invalid number of manifests"); } + if (version == null || input == null || captured.putIfAbsent(version, input) != null) { + throw new IllegalArgumentException("Invalid pending manifest versions"); + } + } + if (captured.isEmpty()) { + throw new IllegalArgumentException("Invalid number of manifests"); + } + long totalDeclared = 0; + for (PendingVersion p : captured.values()) { BlobId root = p.root; if (p.expected < 1 || p.expected > MAX_CHILDREN || root.sizeInBytes() < 1 || root.sizeInBytes() > 50 || root.getAccountId() != account || root.getContainerId() != container || root.getBlobDataType() != BlobId.BlobDataType.METADATA) { throw new SQLDataException("Unsupported named composite capture"); } - counts.put(version, p.expected); totalDeclared += p.expected; } if (totalDeclared > MAX_CHILDREN) { @@ -204,51 +189,27 @@ static PreparedRetirement prepare(short account, short container, String name, M } // Only now, with the whole request's declared size already bounded, consume each iterator and encode its body. - Map rootBytes = new LinkedHashMap<>(); - Map rootIds = new LinkedHashMap<>(); - Map bodies = new LinkedHashMap<>(); - Map rowHashes = new LinkedHashMap<>(); - for (long version : requested) { - PendingVersion p = pending.get(version); - byte[] rb = p.root.toBytes(); - rootBytes.put(version, rb); - String rootId = Base64.getUrlEncoder().withoutPadding().encodeToString(rb); - rootIds.put(version, rootId); - byte[] body = encode(p.descriptors, p.expected, rb); - bodies.put(version, body); - rowHashes.put(version, hash(account, container, name, version, p.expected, rootId, body)); + Map versions = new LinkedHashMap<>(); + for (Map.Entry entry : captured.entrySet()) { + long version = entry.getKey(); + versions.put(version, new PreparedVersion(account, container, name, version, entry.getValue())); } - - return new PreparedRetirement(account, container, name, requested, rootBytes, rootIds, counts, bodies, rowHashes, - intentToken(name, requested, rowHashes)); - } - - /** - * Validate, publish and fence this exact set of named versions in one transaction. A replay that already carries - * this exact content for every requested version returns successfully without resolving the name or locking the - * named range; anything less than all of them matching is rejected rather than partially honored. - */ - static void retire(Connection c, short account, short container, String name, Map pending) - throws SQLException { - retire(c, prepare(account, container, name, pending)); + return new PreparedRetirement(account, container, name, versions); } /** * Publish and fence the given prepared request in one transaction. A pure, non-locking check for an already- - * complete publication runs first and never touches {@code named_blobs_v2} at all, so a legitimate replay is - * never blocked by the named range's own size cap, however many unrelated versions have since replaced it. Only - * when that check is incomplete does this lock the named range -- the same order (named_blobs_v2, then - * named_blob_manifests_v1) an ordinary named PUT's own AFTER INSERT/UPDATE guard uses, so neither ever waits on - * the other in the opposite order. Every requested version is then published by a plain {@code INSERT}, never by - * a locking read against a key that might not exist: only once a duplicate-key signal proves a row already - * exists is a locking read issued against that now-known-existing key. This keeps two unrelated publishers' - * concurrent inserts into the same manifest-table gap from contending on a shared gap lock at all. + * complete publication runs first and never touches {@code named_blobs_v2}, so a replay that sees its existing + * receipt is not blocked by the named range's size cap. If the receipt does not match, lock the named range before + * inserting manifests, in the same order as the named PUT's AFTER INSERT/UPDATE guard. Use a plain {@code INSERT} + * for each manifest and issue a locking read only on a duplicate key. This avoids gap locks from checking for a + * missing manifest and lets unrelated publishers insert into the same manifest-table gap. */ static void retire(Connection c, PreparedRetirement p) throws SQLException { if (c.getAutoCommit() || c.getTransactionIsolation() != Connection.TRANSACTION_REPEATABLE_READ) { throw new IllegalStateException("Publication requires an InnoDB REPEATABLE READ transaction"); } - if (fullyMatches(c, p)) { + if (matchesReceipt(c, p)) { return; } @@ -276,7 +237,8 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { throw new SQLDataException("Unsupported named version range"); } long version = r.getLong(2); - if (!p.counts.containsKey(version)) { + PreparedVersion expected = p.versions.get(version); + if (expected == null) { if (r.getBoolean(5)) { history.add(version); } else { @@ -285,7 +247,7 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { continue; } boolean eligible = r.getInt(4) == NamedBlobState.READY.ordinal() && !r.getBoolean(5) - && Arrays.equals(r.getBytes(3), p.rootBytes.get(version)); + && Arrays.equals(r.getBytes(3), expected.root); liveMatch.put(version, eligible); } } @@ -297,16 +259,18 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { List freshlyPublished = new ArrayList<>(); try (PreparedStatement insert = c.prepareStatement( "INSERT INTO " + TABLE + " (" + HEADER_COLUMNS + ",payload,payload_hash) VALUES (?,?,?,?,?,?,?,?,?)")) { - for (long version : p.requested) { + for (Map.Entry entry : p.versions.entrySet()) { + long version = entry.getKey(); + PreparedVersion requested = entry.getValue(); insert.setInt(1, p.account); insert.setInt(2, p.container); insert.setString(3, p.name); insert.setLong(4, version); - insert.setBytes(5, p.rootBytes.get(version)); - insert.setInt(6, p.counts.get(version)); + insert.setBytes(5, requested.root); + insert.setInt(6, requested.count); insert.setBytes(7, p.intentToken); - insert.setBytes(8, p.bodies.get(version)); - insert.setBytes(9, p.rowHashes.get(version)); + insert.setBytes(8, requested.body); + insert.setBytes(9, requested.hash); try { if (insert.executeUpdate() != 1) { throw new SQLDataException("Cannot publish sealed manifest"); @@ -321,7 +285,7 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { if (duplicate.getErrorCode() != 1062) { throw duplicate; } - confirmExistingMatches(c, p, version); + confirmExistingMatches(c, p, version, requested); } } } @@ -329,7 +293,7 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { if (freshlyPublished.isEmpty()) { return; } - if (freshlyPublished.size() != p.requested.size()) { + if (freshlyPublished.size() != p.versions.size()) { throw new SQLDataException("Partial manifest set"); } try (PreparedStatement retireRow = c.prepareStatement( @@ -360,7 +324,8 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { * A row proven to already exist by a duplicate-key signal must carry exactly this request's content and this * request's intent, or the request is rejected rather than silently accepted or silently dropped. */ - private static void confirmExistingMatches(Connection c, PreparedRetirement p, long version) throws SQLException { + private static void confirmExistingMatches(Connection c, PreparedRetirement p, long version, + PreparedVersion requested) throws SQLException { try (PreparedStatement s = c.prepareStatement( "SELECT payload_hash,publication_key FROM " + TABLE + " WHERE " + KEY + " FOR UPDATE")) { bindKey(s, p.account, p.container, p.name, version); @@ -368,7 +333,7 @@ private static void confirmExistingMatches(Connection c, PreparedRetirement p, l if (!r.next()) { throw new SQLDataException("Manifest belongs to a different publication"); } - if (!MessageDigest.isEqual(r.getBytes(1), p.rowHashes.get(version))) { + if (!MessageDigest.isEqual(r.getBytes(1), requested.hash)) { throw new SQLDataException("Conflicting manifest for named version"); } if (!MessageDigest.isEqual(r.getBytes(2), p.intentToken)) { @@ -379,22 +344,21 @@ private static void confirmExistingMatches(Connection c, PreparedRetirement p, l } /** - * A pure, non-locking check for an already-complete publication: never touches {@code named_blobs_v2}, so it is - * never blocked by the named range's own size cap. This can under-report on a connection whose REPEATABLE READ - * snapshot predates a just-committed publication, but it can never over-report -- a plain read only ever shows - * what was truly committed -- so a false negative here only costs falling through to the slower, authoritative - * path below, never a wrongful success. + * Match the exact receipt visible to the supplied transaction without locking or reading {@code named_blobs_v2}. + * A transaction can see its own uncommitted writes, and an older snapshot can miss a committed receipt. + * To confirm publication, check in a fresh writer transaction before making any writes. */ - private static boolean fullyMatches(Connection c, PreparedRetirement p) throws SQLException { - String placeholders = String.join(",", Collections.nCopies(p.requested.size(), "?")); + static boolean matchesReceipt(Connection c, PreparedRetirement p) throws SQLException { + String placeholders = String.join(",", Collections.nCopies(p.versions.size(), "?")); String sql = "SELECT blob_name,version,payload_hash,publication_key FROM " + TABLE + " WHERE account_id=? AND container_id=? AND blob_name=? AND version IN (" + placeholders + ")"; try (PreparedStatement s = c.prepareStatement(sql)) { s.setInt(1, p.account); s.setInt(2, p.container); s.setString(3, p.name); - for (int i = 0; i < p.requested.size(); i++) { - s.setLong(i + 4, p.requested.get(i)); + int parameter = 4; + for (long version : p.versions.keySet()) { + s.setLong(parameter++, version); } try (ResultSet r = s.executeQuery()) { int matched = 0; @@ -403,13 +367,13 @@ private static boolean fullyMatches(Connection c, PreparedRetirement p) throws S return false; } long version = r.getLong(2); - if (!MessageDigest.isEqual(r.getBytes(3), p.rowHashes.get(version)) || !MessageDigest.isEqual( + if (!MessageDigest.isEqual(r.getBytes(3), p.versions.get(version).hash) || !MessageDigest.isEqual( r.getBytes(4), p.intentToken)) { return false; } matched++; } - return matched == p.requested.size(); + return matched == p.versions.size(); } } } @@ -444,26 +408,18 @@ private Manifest(ResultSet r) throws SQLException { * grouped into this request, changes the token: two intents cannot impersonate each other merely by sharing a * version set or merely by sharing content. */ - private static byte[] intentToken(String name, List orderedVersions, Map rowHashes) { + private static byte[] intentToken(String name, Map versions) { MessageDigest d = sha256(); byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8); d.update(ByteBuffer.allocate(Integer.BYTES).putInt(nameBytes.length).array()); d.update(nameBytes); - for (long version : orderedVersions) { - d.update(ByteBuffer.allocate(Long.BYTES).putLong(version).array()); - d.update(rowHashes.get(version)); + for (Map.Entry entry : versions.entrySet()) { + d.update(ByteBuffer.allocate(Long.BYTES).putLong(entry.getKey()).array()); + d.update(entry.getValue().hash); } return d.digest(); } - /** Resolve a lost commit reply from an exact, content-bound intent, without reading the name. */ - boolean isPublished(PreparedRetirement p) throws SQLException { - try (Connection c = db.getConnection()) { - requireCommittedReads(c); - return fullyMatches(c, p); - } - } - /** * Recover a known publication by its exact tuple, without resolving the name or reading the original root. Every * row in this table is published by construction, so existence alone is sufficient. diff --git a/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java b/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java index debd4ee353..97c40ff30a 100644 --- a/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java +++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java @@ -6,12 +6,12 @@ import java.sql.Connection; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; -import java.util.List; +import java.util.LinkedHashMap; +import java.util.Map; import javax.sql.DataSource; import org.junit.Test; +import com.github.ambry.commons.BlobId; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @@ -38,30 +38,30 @@ public void testReaderRejectsDirtyReadsWithoutChangingPoolIsolation() throws SQL } @Test - public void testPublicationUsesADistinctOrderIndependentSet() { - assertEquals(Arrays.asList(1L, 2L), NamedBlobManifestStore.canonicalVersions(Arrays.asList(2L, 1L))); - for (List invalid : Arrays.asList(Arrays.asList(1L, 1L), Collections.singletonList(null), - Collections.emptyList())) { - try { - NamedBlobManifestStore.canonicalVersions(invalid); - fail("Invalid publication set accepted: " + invalid); - } catch (IllegalArgumentException expected) { - // Reject before acquiring database locks. - } + public void testPublicationRejectsNullVersion() throws SQLException { + try { + NamedBlobManifestStore.prepare((short) 17, (short) 4, "name", + Collections.singletonMap(null, new NamedBlobManifestStore.PendingVersion(mock(BlobId.class), 1, + Collections.emptyList().iterator()))); + fail("Accepted a null version"); + } catch (IllegalArgumentException expected) { + assertEquals("Invalid pending manifest versions", expected.getMessage()); } } @Test - public void testPublicationRejectsMoreThanTheDeclaredVersionCap() { - List tooMany = new ArrayList<>(); + public void testPublicationRejectsMoreThanTheDeclaredVersionCap() throws SQLException { + Map tooMany = new LinkedHashMap<>(); + BlobId root = mock(BlobId.class); for (long version = 1; version <= 33; version++) { - tooMany.add(version); + tooMany.put(version, new NamedBlobManifestStore.PendingVersion(root, 1, Collections.emptyList().iterator())); } try { - NamedBlobManifestStore.checkManifestCount(tooMany); + NamedBlobManifestStore.prepare((short) 17, (short) 4, "name", tooMany); fail("More than the declared cap of distinct named versions was accepted in one publication"); } catch (IllegalArgumentException expected) { assertEquals("Invalid number of manifests", expected.getMessage()); } + verifyNoInteractions(root); } } From f5b10bf57c0c2cb1d36e8773bfb5a5738d26a4e0 Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Thu, 3 Dec 2026 14:43:44 -0800 Subject: [PATCH 2/3] Isolate named retirement metrics and verify driver safeguards Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ambry-named-mysql/README.md | 6 +++ ...NamedBlobManifestStoreIntegrationTest.java | 39 ++++++++++++++++++- .../java/com/github/ambry/named/Metrics.java | 6 +++ .../github/ambry/named/MySqlNamedBlobDb.java | 30 +++++++------- .../ambry/named/MySqlNamedBlobDbTest.java | 9 +++++ 5 files changed, 74 insertions(+), 16 deletions(-) diff --git a/ambry-named-mysql/README.md b/ambry-named-mysql/README.md index 1dec59e553..7c1a503e1a 100644 --- a/ambry-named-mysql/README.md +++ b/ambry-named-mysql/README.md @@ -12,6 +12,7 @@ Preparation, publication, and receipt checks block; run them off the event loop. handle on all paths: while it is open, a second request is rejected as unavailable. The 32 MiB limit is on encoded child bytes, not peak heap: allow for encoding buffers, supplier memory, and JDBC packet buffers. Publication or confirmation can also occupy one connection from the same pool as ordinary requests, outside the transaction executor. +`RetirementWriterBusyCount` records admission rejections; use it with heap and writer load before changing concurrency. Use the same handle to publish, to check its receipt after an uncertain result, and to retry. Each call checks out an idle, autocommit `REPEATABLE READ` session from the configured local writer pool and starts a fresh transaction. @@ -20,6 +21,7 @@ caps socket reads at five seconds and restores the previous timeout before retur pool-wide `socketTimeout` for retirement. Socket or communications failures discard the checkout without a rollback attempt; an interrupted commit is still an unknown outcome. Configure bounded pool checkout and descriptor fetches. The read timeout is not an end-to-end deadline, and closing the handle does not interrupt an active call. +`RetirementConnectionFailureCount` tracks retirement transport failures separately from ordinary named DB connections. A matching receipt confirms the commit; it does not authorize cleanup. No match means the commit was not observed, not that it rolled back. A replay whose read snapshot predates a concurrent commit can still reject if replacements now @@ -50,6 +52,10 @@ Connector/J 8.0.21 with client-side prepared statements rejected a synthetic 32 the measured query exceeded 64 MiB before transmission. The same bytes round-tripped with server-side prepared statements at 64 MiB and with either mode at 128 MiB on local MySQL 8.0.46. These are tested configurations, not production settings. Check the client limit as well as MySQL and replication limits on each deployment. +Measure binlog growth, replica lag, transaction size and backup growth under a representative workload. A root ID and +hash cannot recover descriptors if the raw root expires or becomes unreadable. Storing descriptors separately would +require keeping that object available and reconciling its lifecycle with MySQL publication. There is no manifest purge +in this path; retention and safe removal must account for receipt recovery, replica progress and reclamation. ## Installing or resuming the migration diff --git a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java index c4ada36df7..95548768c7 100644 --- a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java +++ b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java @@ -129,11 +129,16 @@ private static MySqlNamedBlobDb namedDb(DataSource db, boolean hardDelete) throw } private static MySqlNamedBlobDb namedDb(DataSource db, Properties properties, Time time) throws Exception { + return namedDb(db, properties, time, new Metrics(new MetricRegistry(), "")); + } + + private static MySqlNamedBlobDb namedDb(DataSource db, Properties properties, Time time, Metrics metrics) + throws Exception { properties.setProperty(MySqlNamedBlobDbConfig.DB_INFO, "[{\"url\":\"jdbc:mysql://[::1]\",\"datacenter\":\"local\",\"isWriteable\":true," + "\"username\":\"unused\",\"password\":\"unused\",\"sslMode\":\"NONE\"}]"); return new MySqlNamedBlobDb(fixtureAccounts(), new MySqlNamedBlobDbConfig(new VerifiableProperties(properties)), - endpoint -> db, "local", new Metrics(new MetricRegistry(), ""), time); + endpoint -> db, "local", metrics, time); } private static InMemAccountService fixtureAccounts() throws Exception { @@ -1343,17 +1348,47 @@ public void testExactHandleConfirmsLostReplyAfterOverCapReplacement() throws Exc }).when(lostReply).commit(); DataSource writer = mock(DataSource.class); when(writer.getConnection()).thenReturn(lostReply).thenAnswer(call -> db.getConnection()); - try (MySqlNamedBlobDb withLostReply = namedDb(writer); + Metrics metrics = new Metrics(new MetricRegistry(), ""); + try (MySqlNamedBlobDb withLostReply = namedDb(writer, new Properties(), SystemTime.getInstance(), metrics); MySqlNamedBlobDb.Retirement retirement = withLostReply.prepareRetirement("account", "container", NAME, () -> Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { assertLostReplyAndRecover(db, retirement, root, child); + assertEquals(1, metrics.retirementConnectionFailureCount.getCount()); + assertEquals(0, metrics.getMetricRegistry().counter( + MetricRegistry.name(MySqlNamedBlobDb.class, "NamedBlobDBConnectionFailureCount.local")).getCount()); } verify(lostReply, never()).rollback(); } }); } + @Test + public void testRetirementRejectsConnectorJReconnectOptions() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + for (String option : Arrays.asList("autoReconnect", "autoReconnectForPools", "reconnectAtTxEnd")) { + MysqlDataSource unsafeSource = source(db.unwrap(MysqlDataSource.class).getDatabaseName()); + unsafeSource.setUrl(unsafeSource.getUrl() + "?" + option + "=true"); + try (MySqlNamedBlobDb unsafe = namedDb(unsafeSource); + MySqlNamedBlobDb.Retirement retirement = unsafe.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + try { + retirement.publish(); + fail("Accepted a writer with " + option); + } catch (SQLException e) { + assertTrue(e.getMessage(), e.getMessage().contains("fixed physical MySQL session")); + } + } + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE retirement_fenced")); + }); + } + private static void assertLostReplyAndRecover(DataSource db, MySqlNamedBlobDb.Retirement retirement, BlobId root, BlobId child) throws Exception { try (Connection stale = db.getConnection(); Statement snapshot = stale.createStatement()) { 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 4ef05b3e99..8471c18168 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 @@ -66,6 +66,8 @@ public class Metrics { final Counter fenceAwarePutVersionRejectedCount; public final Counter namedBlobDBUpdateErrorCount; final Counter connectionCloseErrorCount; + final Counter retirementConnectionFailureCount; + final Counter retirementWriterBusyCount; /** * Constructor to create the Metrics. @@ -141,6 +143,10 @@ public Metrics(MetricRegistry metricRegistry, String prefix) { metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "NamedBlobDBUpdateErrorCount")); connectionCloseErrorCount = metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "ConnectionCloseErrorCount")); + retirementConnectionFailureCount = + metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "RetirementConnectionFailureCount")); + retirementWriterBusyCount = + metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "RetirementWriterBusyCount")); } /** 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 d7334fbac4..9c2cbcdf09 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 @@ -497,6 +497,7 @@ Retirement prepareRetirement(String accountName, String containerName, String bl throw new RestServiceException("Container not found: " + containerName, RestServiceErrorCode.NotFound); } if (!retirementSlot.tryAcquire()) { + metricsRecoder.retirementWriterBusyCount.inc(); throw new RestServiceException("Named retirement already in progress", RestServiceErrorCode.ServiceUnavailable); } boolean prepared = false; @@ -544,7 +545,7 @@ private T run(TransactionGeneric transaction) throws Exception { try { return writer.runRetirementTransaction(transaction); } catch (Exception | Error e) { - writer.recordConnectionFailure(e); + writer.recordConnectionFailure(e, true); if (e instanceof SQLException) { metricsRecoder.namedBlobDBDeleteErrorCount.inc(); } @@ -799,11 +800,11 @@ private static class TransactionExecutor implements Closeable { * * *

The walk includes causes, chained SQL exceptions and suppressed cleanup failures. - * Connector/J can wrap a socket failure in a generic SQLException. + * For retirement only, also recognize socket failures wrapped in a generic SQLException. * 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) { + private static boolean isConnectionFailure(Throwable t, boolean retirement) { if (t == null) { return false; } @@ -816,7 +817,8 @@ private static boolean isConnectionFailure(Throwable t) { continue; } if (cur instanceof SQLNonTransientConnectionException || cur instanceof SQLTransientConnectionException - || cur instanceof SocketTimeoutException || cur instanceof SocketException || cur instanceof EOFException) { + || (retirement && (cur instanceof SocketTimeoutException || cur instanceof SocketException + || cur instanceof EOFException))) { return true; } if (cur instanceof SQLException) { @@ -844,9 +846,9 @@ void executeTransaction(Container container, boolean autoCommit, Transaction connection -> transaction.run(container.getParentAccountId(), container.getId(), connection), callback); } - private void recordConnectionFailure(Throwable failure) { - if (isConnectionFailure(failure)) { - connectionFailureCount.inc(); + private void recordConnectionFailure(Throwable failure, boolean retirement) { + if (isConnectionFailure(failure, retirement)) { + (retirement ? metrics.retirementConnectionFailureCount : connectionFailureCount).inc(); } } @@ -859,7 +861,7 @@ void executeTransactionGeneric(boolean autoCommit, TransactionGeneric tra try { result = runTransaction(autoCommit ? TransactionMode.AUTOCOMMIT : TransactionMode.EXPLICIT, transaction); } catch (Exception | Error e) { - recordConnectionFailure(e); + recordConnectionFailure(e, false); callback.onCompletion(null, e instanceof Exception ? (Exception) e : new IllegalStateException(e)); return; } @@ -924,7 +926,7 @@ private T runTransaction(TransactionMode mode, TransactionGeneric transac discardConnection(connection, failure); throw failure; } catch (Exception | Error failure) { - if (retirement && isConnectionFailure(failure)) { + if (retirement && isConnectionFailure(failure, true)) { discardConnection(connection, failure); throw failure; } @@ -940,10 +942,10 @@ private T runTransaction(TransactionMode mode, TransactionGeneric transac throw failure; } } - returnConnection(connection, autoCommit, timeoutToRestore, failure); + returnConnection(connection, mode, timeoutToRestore, failure); throw failure; } - returnConnection(connection, autoCommit, timeoutToRestore, null); + returnConnection(connection, mode, timeoutToRestore, null); return result; } @@ -970,11 +972,11 @@ private static void requireIdleRetirementSession(Connection connection, JdbcConn } } - private void returnConnection(Connection connection, boolean autoCommit, int timeoutToRestore, + private void returnConnection(Connection connection, TransactionMode mode, int timeoutToRestore, Throwable operationFailure) { try { try { - if (!autoCommit) { + if (mode != TransactionMode.AUTOCOMMIT) { connection.setAutoCommit(true); } if (timeoutToRestore >= 0) { @@ -989,7 +991,7 @@ private void returnConnection(Connection connection, boolean autoCommit, int tim } catch (Exception | Error cleanupFailure) { metrics.connectionCloseErrorCount.inc(); if (operationFailure == null) { - recordConnectionFailure(cleanupFailure); + recordConnectionFailure(cleanupFailure, mode == TransactionMode.RETIREMENT); } else if (operationFailure != cleanupFailure) { operationFailure.addSuppressed(cleanupFailure); } 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 8f01378b43..b0610f8225 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 @@ -41,6 +41,7 @@ import com.mysql.cj.protocol.ServerSession; import com.zaxxer.hikari.HikariDataSource; import java.io.IOException; +import java.net.SocketTimeoutException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -521,6 +522,14 @@ public void testConnectionFailureCounterIncrementsOnSqlState08() throws Exceptio e -> Assert.assertEquals(nullState, e.getCause())); assertEquals("counter must not increment when SQLSTATE is null", 2L, counter.getCount()); + SQLException wrappedTimeout = new SQLException("generic driver error", "S1000", new SocketTimeoutException()); + dataSourceFactory.triggerQueryExecutionError(localDatacenter, wrappedTimeout); + TestUtils.assertException(ExecutionException.class, + () -> db.get(account.getName(), container.getName(), "blobName").get(5, TimeUnit.SECONDS), + e -> assertEquals(wrappedTimeout, e.getCause())); + assertEquals("legacy transactions must not count generic socket errors", 2L, counter.getCount()); + assertEquals(0, metrics.retirementConnectionFailureCount.getCount()); + // Direct SQLNonTransientConnectionException (mimics MySQL CommunicationsException) — counts via type. SQLException directNonTransient = new SQLNonTransientConnectionException("communications failure"); dataSourceFactory.triggerQueryExecutionError(localDatacenter, directNonTransient); From edc503891f875a94ac856595d48a7d9f708e5ce3 Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Thu, 3 Dec 2026 14:47:08 -0800 Subject: [PATCH 3/3] Use the actual Connector/J data source in the compatibility test Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../ambry/named/NamedBlobManifestStoreIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java index 95548768c7..9e9d2ee2cc 100644 --- a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java +++ b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java @@ -1370,7 +1370,7 @@ public void testRetirementRejectsConnectorJReconnectOptions() throws Exception { BlobId child = blob(BlobId.BlobDataType.DATACHUNK); insertNamed(db, 1, root, NamedBlobState.READY); for (String option : Arrays.asList("autoReconnect", "autoReconnectForPools", "reconnectAtTxEnd")) { - MysqlDataSource unsafeSource = source(db.unwrap(MysqlDataSource.class).getDatabaseName()); + MysqlDataSource unsafeSource = source(((MysqlDataSource) db).getDatabaseName()); unsafeSource.setUrl(unsafeSource.getUrl() + "?" + option + "=true"); try (MySqlNamedBlobDb unsafe = namedDb(unsafeSource); MySqlNamedBlobDb.Retirement retirement = unsafe.prepareRetirement("account", "container", NAME,