From 8cd2f54dc0080e92fa6c4ddfec39a2028e4c8a9e Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Wed, 25 Nov 2026 00:08:26 -0800 Subject: [PATCH 1/2] Honor named blob retirement fences on reads and writes Keep retired versions hidden from ordinary GET and LIST. On a verified writer session, reject PUT versions at or below a fence. Retry only a confirmed deadlocked upsert, once. Leave enforcement disabled by default. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../ambry/config/MySqlNamedBlobDbConfig.java | 7 + ambry-named-mysql/README.md | 45 +- ...NamedBlobManifestStoreIntegrationTest.java | 485 +++++++++++++++++- .../java/com/github/ambry/named/Metrics.java | 9 + .../github/ambry/named/MySqlNamedBlobDb.java | 212 ++++---- .../ambry/named/MySqlNamedBlobDbFactory.java | 19 +- .../named/MySqlNamedBlobDbFactoryTest.java | 30 ++ .../ambry/named/MySqlNamedBlobDbTest.java | 73 +++ 8 files changed, 776 insertions(+), 104 deletions(-) create mode 100644 ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbFactoryTest.java diff --git a/ambry-api/src/main/java/com/github/ambry/config/MySqlNamedBlobDbConfig.java b/ambry-api/src/main/java/com/github/ambry/config/MySqlNamedBlobDbConfig.java index 8f3ca0a3a7..92d679d2fb 100644 --- a/ambry-api/src/main/java/com/github/ambry/config/MySqlNamedBlobDbConfig.java +++ b/ambry-api/src/main/java/com/github/ambry/config/MySqlNamedBlobDbConfig.java @@ -38,6 +38,7 @@ public class MySqlNamedBlobDbConfig { public static final String TRANSACTION_ISOLATION_LEVEL = PREFIX + "transaction.isolation.level"; public static final String LIST_NAMED_BLOBS_SQL_OPTION = "list.named.blobs.sql.option"; public static final String ENABLE_HARD_DELETE = PREFIX + "enable.hard.delete"; + public static final String HONOR_RETIREMENT_FENCE = PREFIX + "honor.retirement.fence"; public static final String ENABLE_CERTIFICATE_BASED_AUTHENTICATION = PREFIX + "enable.certificate.based.authentication"; public static final String SSL_MODE = PREFIX + "ssl.mode"; @@ -175,6 +176,11 @@ public class MySqlNamedBlobDbConfig { @Config(ENABLE_HARD_DELETE) public final boolean enableHardDelete; + /** Honor retirement on named GET, LIST and PUT. Requires the migration on all named-blob endpoints. */ + @Config(HONOR_RETIREMENT_FENCE) + @Default("false") + public final boolean honorRetirementFence; + /** * True to use certificate based authentication for MYSQL connections. SSL certificates must be configured in the * configuration files. The keys are the same as keys in {@link SSLConfig}. We are expecting the following keys @@ -219,6 +225,7 @@ public MySqlNamedBlobDbConfig(VerifiableProperties verifiableProperties) { verifiableProperties.getEnum(TRANSACTION_ISOLATION_LEVEL, TransactionIsolationLevel.class, TransactionIsolationLevel.TRANSACTION_NONE); this.enableHardDelete = verifiableProperties.getBoolean(ENABLE_HARD_DELETE, false); + this.honorRetirementFence = verifiableProperties.getBoolean(HONOR_RETIREMENT_FENCE, false); this.enableCertificateBasedAuthentication = verifiableProperties.getBoolean(ENABLE_CERTIFICATE_BASED_AUTHENTICATION, false); this.sslConfig = this.enableCertificateBasedAuthentication ? new SSLConfig(verifiableProperties) : null; diff --git a/ambry-named-mysql/README.md b/ambry-named-mysql/README.md index 51422af30c..1c9a99fca6 100644 --- a/ambry-named-mysql/README.md +++ b/ambry-named-mysql/README.md @@ -94,13 +94,47 @@ definitions, and run the application smoke test. The database operations alone are not safe to activate. In addition to the DELETE and cleaner gates below: -- Make ordinary GET and all LIST paths honor `retirement_fenced` on the **selected version**, irrespective of the - frontend clock. Do not discard the newest tombstone before selecting a version: that can expose older data. Preserve - include-deleted GET access to the exact retired root. +- After verifying the migration on every read endpoint, enable `mysql.named.blob.honor.retirement.fence` on every + frontend before publishing any retirements. It defaults to `false`, so readers can run against the original schema. + When enabled, ordinary and include-expired GET return `Deleted` for a fenced version even if the frontend clock is + behind. Include-deleted and include-all GET return the selected root. Prefix and no-prefix LIST hide a fenced + selection without falling back to an older live row. A PUT whose version does not sort above the name's fence + returns `ServiceUnavailable` without inserting and increments `FenceAwarePutVersionRejectedCount`. Retry a + generated-version PUT once the frontend clock catches up. +- Use a direct, single-host Connector/J writer with automatic reconnect disabled and no intermediary that multiplexes + backend sessions. Fence-aware PUT rejects multi-host drivers and reconnect modes rather than allowing the probe and + INSERT to run on different sessions. With the flag on, the factory configures all writable endpoint pools, including + remote pools used for GET fallback, to reset isolation to `REPEATABLE READ`. It also sets that isolation explicitly + on each new physical connection to clear any next-transaction override from server initialization. Leave the isolation + setting unspecified (`TRANSACTION_NONE`) or choose `TRANSACTION_REPEATABLE_READ`; other values prevent pool startup. + Do not set a next-transaction override after initialization: the session default does not reveal it. +- Fence-aware PUT requires autocommit on and no active transaction. Before the non-upsert existence check or any + INSERT, it reads the server's autocommit and isolation settings and checks the transaction status in the same + response: `START TRANSACTION` leaves autocommit on. A rejected checkout is discarded without committing, resetting + autocommit, or returning its transaction to readers. At `READ COMMITTED` + the fence lookup can finish before a concurrent publication commits, even though the insert itself waits. + Even without retirements, concurrent PUTs to the same name or adjacent new names can deadlock in the same index gap. + On a confirmed InnoDB deadlock (`1213/40001`), an upsert retries the same conditional INSERT once, then returns + `ServiceUnavailable` if it deadlocks again. A create-only victim returns `ServiceUnavailable` immediately: its + existence check is stale. Neither a lock timeout nor an unknown commit outcome is retried. Monitor + `FenceAwarePutDeadlockCount` for every victim, including recovered upserts. `NamedBlobDBInsertErrorCount` counts + the deadlock only if it is returned to the caller. Monitor `FenceAwarePutSessionRejectedCount` for rejected checkouts. + `ConnectionCloseErrorCount` counts failed cleanup steps, not distinct checkouts. If reset and discard both fail, + one checkout increments it twice, even with the flag off. Ambry logs discard failures it sees; physical close + failures handled inside Hikari are not included. +- These checks cover named PUT only. Validate manifest publication separately on a fixed physical session with + autocommit **off** and verified `REPEATABLE READ` isolation. +- Every serving endpoint, cross-datacenter GET fallback, and promotion candidate must have applied all acknowledged + retirement transactions, not just the migration. A local `NotFound` can send GET to another datacenter. If an + endpoint cannot prove its applied position, exclude it from reads, retries, and promotion. - Before reclaiming any data, verify that every replica eligible to serve or be promoted has applied the retirement transaction (both the manifest and the named-version fence), even if the client never received the commit reply. Exclude replicas from serving and promotion until their applied position proves they include that transaction. If failover cannot enforce this rule, keep reclamation disabled: a stale replica could serve a name whose data is gone. +- Before enabling the flag, compare flag-on and flag-off LIST plans and first- and later-page latency on representative + large containers, with and without a prefix. Check the deployed SQL option, rows examined, and query timeouts. Also + measure PUT latency, deadlocks and 503s under same-name and sequential-name contention. The integration fixture is not + a load test. - Admit only namespaces that will stay within the version limit **with cleanup excluded**. PUT keeps older versions: an initial permanent PUT and 32 overwrites can leave 33 unfenced rows. Even below the limit, a live non-composite version cannot supply a composite manifest. Restrict writes accordingly or reconcile history safely first. @@ -113,8 +147,9 @@ every runner, for both stale cleanup and purge. Drain in-flight requests, cleane router deletes. Either path can send a root to the router, which can eagerly delete shared children. If the exclusion cannot be guaranteed (for example, the runner cannot resolve the account), keep the cleaner stopped. -On rollback, disable publication but retain the DELETE gate, cleaner exclusion, database fence, index, and -published evidence. Do not send affected traffic or cleaner work to an old binary that cannot honor those gates. +On rollback, disable publication but retain fence-aware reads, the DELETE gate, cleaner exclusion, database fence, +index, and published evidence. Do not send affected traffic or cleaner work to an old binary that cannot honor those +gates. This store does not retire raw parent IDs, establish exclusive ownership of chunks, schedule cleanup, or reclaim space. Those steps and an ownership policy are required before wiring the public DELETE path. 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 6fb6a89282..e203e54c44 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 @@ -25,13 +25,16 @@ import java.util.Properties; import java.util.Scanner; import java.util.UUID; +import java.util.concurrent.CompletableFuture; 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.AtomicLong; import java.util.stream.Collectors; import javax.sql.DataSource; +import org.json.JSONArray; import org.junit.Test; import com.codahale.metrics.MetricRegistry; import com.github.ambry.account.Account; @@ -41,13 +44,20 @@ import com.github.ambry.account.InMemAccountService; import com.github.ambry.clustermap.MockPartitionId; import com.github.ambry.commons.BlobId; +import com.github.ambry.config.ClusterMapConfig; import com.github.ambry.config.MySqlNamedBlobDbConfig; import com.github.ambry.config.VerifiableProperties; +import com.github.ambry.frontend.Page; +import com.github.ambry.mysql.MySqlUtils.DbEndpoint; import com.github.ambry.protocol.GetOption; import com.github.ambry.protocol.NamedBlobState; import com.github.ambry.rest.RestServiceErrorCode; import com.github.ambry.rest.RestServiceException; +import com.github.ambry.utils.MockTime; +import com.github.ambry.utils.SystemTime; +import com.github.ambry.utils.Time; import com.mysql.cj.jdbc.MysqlDataSource; +import com.zaxxer.hikari.HikariDataSource; public class NamedBlobManifestStoreIntegrationTest { private static final short ACCOUNT = 17; @@ -105,16 +115,155 @@ private static void withDatabase(BeforeMigration before, Scenario scenario) thro } private static MySqlNamedBlobDb namedDb(DataSource db) throws Exception { + return namedDb(db, new 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," + + "\"username\":\"unused\",\"password\":\"unused\",\"sslMode\":\"NONE\"}]"); + return new MySqlNamedBlobDb(fixtureAccounts(), new MySqlNamedBlobDbConfig(new VerifiableProperties(properties)), + endpoint -> db, "local", new Metrics(new MetricRegistry(), ""), time); + } + + private static InMemAccountService fixtureAccounts() throws Exception { InMemAccountService accounts = new InMemAccountService(false, false); accounts.updateAccounts(Collections.singletonList(new AccountBuilder(ACCOUNT, "account", Account.AccountStatus.ACTIVE) .addOrUpdateContainer(new ContainerBuilder(CONTAINER, "container", Container.ContainerStatus.ACTIVE, "", ACCOUNT).build()).build())); - Properties properties = new Properties(); - properties.setProperty(MySqlNamedBlobDbConfig.DB_INFO, - "[{\"url\":\"jdbc:mysql://[::1]\",\"datacenter\":\"local\",\"isWriteable\":true," - + "\"username\":\"unused\",\"password\":\"unused\",\"sslMode\":\"NONE\"}]"); - return new MySqlNamedBlobDb(accounts, new MySqlNamedBlobDbConfig(new VerifiableProperties(properties)), - endpoint -> db, "local", new Metrics(new MetricRegistry(), "")); + return accounts; + } + + @Test + public void testFenceAwareGetWithSlowFrontend() throws Exception { + withDatabase((db, writer) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + long now = System.currentTimeMillis(); + long expires = now + TimeUnit.DAYS.toMillis(1); + long fence = writer.put(NamedBlobRecord.forPut("account", "container", NAME, root.getID(), expires, 1), + NamedBlobState.READY, false).get(10, TimeUnit.SECONDS).getInsertedRecord().getVersion(); + retire(writer, Collections.singletonList(stage(writer, NAME, fence, root, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()))); + // A lower-version insert after publication must not become the visible root. + insertNamed(db, 6, blob(BlobId.BlobDataType.METADATA), NamedBlobState.READY); + MockTime frontend = new MockTime(now - TimeUnit.SECONDS.toMillis(5)); + String replacement = blob(BlobId.BlobDataType.METADATA).getID(); + NamedBlobRecord put = NamedBlobRecord.forPut("account", "container", NAME, replacement, expires, 1); + Properties props = new Properties(); + try (MySqlNamedBlobDb legacy = namedDb(db, props, frontend)) { + assertEquals(root.getID(), legacy.get("account", "container", NAME).get(10, TimeUnit.SECONDS).getBlobId()); + try { + legacy.put(put, NamedBlobState.READY, false).get(10, TimeUnit.SECONDS); + fail("Legacy non-upsert must conflict while the deletion timestamp appears to be in the future"); + } catch (ExecutionException e) { + assertEquals(RestServiceErrorCode.Conflict, ((RestServiceException) e.getCause()).getErrorCode()); + } + } + props.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, "true"); + try (MySqlNamedBlobDb reader = namedDb(db, props, frontend)) { + for (GetOption option : Arrays.asList(GetOption.None, GetOption.Include_Expired_Blobs)) { + try { + reader.get("account", "container", NAME, option, false).get(10, TimeUnit.SECONDS); + fail("Expected Deleted for " + option); + } catch (ExecutionException e) { + assertEquals(RestServiceErrorCode.Deleted, ((RestServiceException) e.getCause()).getErrorCode()); + } + } + for (GetOption option : Arrays.asList(GetOption.Include_Deleted_Blobs, GetOption.Include_All)) { + NamedBlobRecord record = reader.get("account", "container", NAME, option, false).get(10, TimeUnit.SECONDS); + assertEquals(root.getID(), record.getBlobId()); + assertEquals(fence, record.getVersion()); + } + for (boolean upsert : Arrays.asList(false, true)) { + try { + PutResult result = reader.put(put, NamedBlobState.READY, upsert).get(10, TimeUnit.SECONDS); + fail("Acknowledged version " + result.getInsertedRecord().getVersion() + " behind fence " + fence); + } catch (ExecutionException e) { + assertEquals(RestServiceErrorCode.ServiceUnavailable, ((RestServiceException) e.getCause()).getErrorCode()); + } + } + // Supplied versions use the same floor, including equality and the first phase of a permanent PUT. + try { + reader.put(new NamedBlobRecord("account", "container", NAME, replacement, -1, fence), + NamedBlobState.IN_PROGRESS, true).get(10, TimeUnit.SECONDS); + fail("A version equal to the fence must be rejected before insert"); + } catch (ExecutionException e) { + assertEquals(RestServiceErrorCode.ServiceUnavailable, ((RestServiceException) e.getCause()).getErrorCode()); + } + assertEquals(2, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2")); + frontend.setCurrentMilliseconds(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(5)); + long accepted = reader.put(put, NamedBlobState.READY, false).get(10, TimeUnit.SECONDS) + .getInsertedRecord().getVersion(); + assertTrue(accepted > fence); + assertEquals(replacement, reader.get("account", "container", NAME).get(10, TimeUnit.SECONDS).getBlobId()); + assertPage(reader, null, null, NAME, accepted, null); + } + }); + } + + @Test + public void testListAcrossRetirementFenceMigration() throws Exception { + BlobId root = blob(BlobId.BlobDataType.METADATA); + withDatabase(db -> { + insertNamed(db, 1, root, NamedBlobState.READY); + for (int option = 2; option <= 4; option++) { + Properties props = new Properties(); + props.setProperty(MySqlNamedBlobDbConfig.LIST_NAMED_BLOBS_SQL_OPTION, Integer.toString(option)); + try (MySqlNamedBlobDb reader = namedDb(db, props, SystemTime.getInstance())) { + assertEquals(root.getID(), reader.get("account", "container", NAME).get(10, TimeUnit.SECONDS).getBlobId()); + for (String prefix : Arrays.asList(null, "folder/")) { + assertPage(reader, prefix, null, NAME, 1, null); + } + } + } + }, (db, writer) -> { + String first = "folder/A", elapsed = "folder/B", legacy = "folder/C", last = "folder/Z"; + insertNamed(db, first, 1, root, NamedBlobState.READY); + insertNamed(db, elapsed, 1, root, NamedBlobState.READY); + insertNamed(db, elapsed, 2, root, NamedBlobState.READY); + insertNamed(db, legacy, 1, root, NamedBlobState.READY); + insertNamed(db, legacy, 2, root, NamedBlobState.READY); + insertNamed(db, 2, root, NamedBlobState.READY); + insertNamed(db, last, 1, root, NamedBlobState.READY); + sql(db, "UPDATE named_blobs_v2 SET retirement_fenced=TRUE WHERE blob_name='folder/B' AND version=2"); + sql(db, "UPDATE named_blobs_v2 SET deleted_ts='2000-01-01' WHERE blob_name='folder/C' AND version=2"); + // The writer clock is ahead of LIST's database clock. deleted_ts alone would pass the outer filter. + try (Connection c = db.getConnection(); Statement s = c.createStatement()) { + s.execute("SET SESSION timestamp = UNIX_TIMESTAMP() + 3600"); + s.executeUpdate("UPDATE named_blobs_v2 SET retirement_fenced=TRUE WHERE blob_name='folder/MixedCase'" + + " AND version=2"); + } + for (int option = 2; option <= 4; option++) { + Properties props = new Properties(); + props.setProperty(MySqlNamedBlobDbConfig.LIST_NAMED_BLOBS_SQL_OPTION, Integer.toString(option)); + props.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, "true"); + try (MySqlNamedBlobDb reader = namedDb(db, props, SystemTime.getInstance())) { + for (String prefix : Arrays.asList(null, "folder/")) { + // Only legacy no-prefix options 2/3 fall back past an ordinary, unfenced expired row. + boolean legacyFallback = prefix == null && option != 4; + assertPage(reader, prefix, null, first, 1, legacyFallback ? legacy : last); + if (legacyFallback) { + assertPage(reader, prefix, legacy, legacy, 1, last); + } + assertPage(reader, prefix, last, last, 1, null); + } + insertNamed(db, 3, root, NamedBlobState.READY); + for (String prefix : Arrays.asList(null, "folder/")) { + assertPage(reader, prefix, NAME, NAME, 3, last); + } + sql(db, "DELETE FROM named_blobs_v2 WHERE version=3"); + } + } + }); + } + + private static void assertPage(MySqlNamedBlobDb reader, String prefix, String token, String name, long version, + String next) throws Exception { + Page page = reader.list("account", "container", prefix, token, 1).get(10, TimeUnit.SECONDS); + assertEquals(1, page.getEntries().size()); + assertEquals(name, page.getEntries().get(0).getBlobName()); + assertEquals(version, page.getEntries().get(0).getVersion()); + assertEquals(next, page.getNextPageToken()); } /** @@ -392,6 +541,322 @@ public void testNameReuseDoesNotConsumeRetirementLimit() throws Exception { }); } + @Test + public void testFenceAwarePutDuringPublication() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 100, root, NamedBlobState.READY); + List jobs = Collections.singletonList(stage(named, NAME, 100, root, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); + NamedBlobRecord lower = new NamedBlobRecord("account", "container", NAME, root.getID(), -1, 50); + Properties props = new Properties(); + props.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, "true"); + DataSource checkouts = mock(DataSource.class); + try (Connection publisher = db.getConnection(); Connection rr = db.getConnection(); + Connection rc = db.getConnection(); + MySqlNamedBlobDb writer = namedDb(checkouts, props, SystemTime.getInstance())) { + rr.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + rc.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); + when(checkouts.getConnection()).thenReturn(rr, rc); + publisher.setAutoCommit(false); + NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, NAME, jobs); + 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); + // A different checkout at RC must fail before the publisher releases the insert gap. + assertTrue(unavailable(writer.put(lower, NamedBlobState.READY, true)).getMessage().contains("REPEATABLE READ")); + publisher.commit(); + assertTrue(unavailable(waiting).getMessage().contains("newer than the retirement fence")); + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=50")); + }); + } + + @Test + public void testFirstPutIsolationAfterConnectionInit() throws Exception { + withDatabase((db, named) -> { + sql(db, "CREATE TABLE put_isolation (level_name VARCHAR(32) NOT NULL) ENGINE=InnoDB"); + sql(db, "CREATE TRIGGER record_put_isolation BEFORE INSERT ON named_blobs_v2 FOR EACH ROW" + + " INSERT INTO put_isolation SELECT ISOLATION_LEVEL FROM performance_schema.events_transactions_current" + + " WHERE THREAD_ID=PS_CURRENT_THREAD_ID()"); + // Simulate a server logon hook on each new physical connection without changing global CI server settings. + DataSource physical = mock(DataSource.class); + when(physical.getConnection()).thenAnswer(invocation -> { + Connection c = db.getConnection(); + try (Statement s = c.createStatement()) { + s.execute("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + s.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + } + return c; + }); + Properties props = new Properties(); + props.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, "true"); + for (boolean initializeFenceAwarePool : Arrays.asList(false, true)) { + try (HikariDataSource pool = new HikariDataSource()) { + pool.setDataSource(physical); + pool.setMaximumPoolSize(1); + MySqlNamedBlobDbFactory.configureIsolation(pool, TransactionIsolationLevel.TRANSACTION_REPEATABLE_READ, + initializeFenceAwarePool); + try (MySqlNamedBlobDb writer = namedDb(pool, props, SystemTime.getInstance())) { + NamedBlobRecord record = NamedBlobRecord.forPut("account", "container", NAME + initializeFenceAwarePool, + blob(BlobId.BlobDataType.METADATA).getID(), -1, 1); + writer.put(record, NamedBlobState.READY, true).get(10, TimeUnit.SECONDS); + } + String expected = initializeFenceAwarePool ? "REPEATABLE READ" : "READ COMMITTED"; + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM put_isolation WHERE level_name='" + expected + "'")); + sql(db, "DELETE FROM put_isolation"); + } + } + }); + } + + @Test + public void testFenceAwarePutChecksServerInsteadOfCachedSessionSettings() throws Exception { + withDatabase((db, named) -> { + MysqlDataSource physical; + try (Connection c = db.getConnection()) { + physical = source(c.getCatalog()); + } + physical.setUseConfigs("maxPerformance"); + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 7, root, NamedBlobState.READY); + String job = stage(named, NAME, 7, root, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); + sql(db, "CREATE TABLE eviction_sentinel (id INT PRIMARY KEY) ENGINE=InnoDB"); + Properties props = new Properties(); + props.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, "true"); + try (HikariDataSource pool = repeatableReadPool(physical, 1); + MySqlNamedBlobDb writer = namedDb(pool, props, SystemTime.getInstance())) { + NamedBlobRecord put = NamedBlobRecord.forPut("account", "container", NAME, + blob(BlobId.BlobDataType.METADATA).getID(), -1, 1); + // Change only this pooled session, not the test server's defaults or Connector/J's local state. + for (String settings : Arrays.asList("autocommit=1, transaction_isolation='READ-COMMITTED'", + "autocommit=0, transaction_isolation='REPEATABLE-READ'")) { + int rejectedId; + try (Connection c = pool.getConnection(); Statement s = c.createStatement()) { + s.execute("SET SESSION " + settings); + rejectedId = scalar(c, "SELECT CONNECTION_ID()"); + assertTrue(c.getAutoCommit()); + assertEquals(Connection.TRANSACTION_REPEATABLE_READ, c.getTransactionIsolation()); + assertEquals(0, scalar(c, "SELECT @@session.autocommit=1 AND @@session.transaction_isolation='REPEATABLE-READ'")); + if (scalar(c, "SELECT @@session.autocommit") == 0) { + assertEquals(0, scalar(c, "SELECT retirement_fenced FROM named_blobs_v2 WHERE version=7")); + s.executeUpdate("INSERT INTO eviction_sentinel VALUES (1)"); + } + } + assertTrue(unavailable(writer.put(put, NamedBlobState.READY, false)).getMessage().contains("REPEATABLE READ")); + try (Connection next = pool.getConnection()) { + assertNotEquals(rejectedId, scalar(next, "SELECT CONNECTION_ID()")); + } + } + retire(named, Collections.singletonList(job)); + try { + writer.get("account", "container", NAME).get(10, TimeUnit.SECONDS); + fail("A subsequent GET must not reuse a pre-retirement snapshot"); + } catch (ExecutionException e) { + assertEquals(RestServiceErrorCode.Deleted, ((RestServiceException) e.getCause()).getErrorCode()); + } + assertTrue(writer.list("account", "container", null, null, 1).get(10, TimeUnit.SECONDS).getEntries().isEmpty()); + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM eviction_sentinel")); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2")); + }); + } + + @Test + public void testFenceAwarePutRejectsActiveTransaction() throws Exception { + checkActiveTransactionRejected(false); + } + + @Test + public void testFenceAwarePutRejectsActiveTransactionWithUncachedServerPrepares() throws Exception { + checkActiveTransactionRejected(true); + } + + private void checkActiveTransactionRejected(boolean serverPrepares) throws Exception { + withDatabase((db, named) -> { + MysqlDataSource physical; + try (Connection c = db.getConnection()) { + physical = source(c.getCatalog()); + } + physical.setUseServerPrepStmts(serverPrepares); + physical.setCachePrepStmts(false); + sql(db, "CREATE TABLE transaction_sentinel (id INT PRIMARY KEY) ENGINE=InnoDB"); + Properties props = new Properties(); + props.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, "true"); + try (HikariDataSource pool = repeatableReadPool(physical, 1); + MySqlNamedBlobDb writer = namedDb(pool, props, SystemTime.getInstance())) { + MySqlNamedBlobDbFactory.configureIsolation(pool, TransactionIsolationLevel.TRANSACTION_REPEATABLE_READ, true); + int rejectedId; + try (Connection c = pool.getConnection(); Statement s = c.createStatement()) { + s.execute("START TRANSACTION"); + s.executeUpdate("INSERT INTO transaction_sentinel VALUES (1)"); + assertEquals(1, scalar(c, "SELECT @@session.autocommit=1 AND @@session.transaction_isolation='REPEATABLE-READ'")); + rejectedId = scalar(c, "SELECT CONNECTION_ID()"); + } + NamedBlobRecord put = NamedBlobRecord.forPut("account", "container", NAME, + blob(BlobId.BlobDataType.METADATA).getID(), -1, 1); + assertTrue(unavailable(writer.put(put, NamedBlobState.READY, true)).getMessage().contains("active transaction")); + try (Connection next = pool.getConnection()) { + assertNotEquals(rejectedId, scalar(next, "SELECT CONNECTION_ID()")); + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM transaction_sentinel")); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2")); + writer.put(put, NamedBlobState.READY, true).get(10, TimeUnit.SECONDS); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2")); + } + }); + } + + @Test + public void testFenceAwarePutRejectsSwitchableSessions() throws Exception { + withDatabase((db, named) -> { + Properties props = new Properties(); + props.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, "true"); + try (Connection c = db.getConnection()) { + for (boolean loadBalanced : Arrays.asList(true, false)) { + MysqlDataSource physical = source(c.getCatalog()); + if (loadBalanced) { + physical.setURL(physical.getURL().replace("jdbc:mysql://", "jdbc:mysql:loadbalance://")); + physical.setLoadBalanceAutoCommitStatementThreshold(1); + } else { + physical.setAutoReconnect(true); + } + try (HikariDataSource pool = repeatableReadPool(physical, 1); + MySqlNamedBlobDb writer = namedDb(pool, props, SystemTime.getInstance())) { + NamedBlobRecord put = NamedBlobRecord.forPut("account", "container", NAME, + blob(BlobId.BlobDataType.METADATA).getID(), -1, 1); + assertTrue(unavailable(writer.put(put, NamedBlobState.READY, true)).getMessage().contains("fixed")); + } + } + assertEquals(0, scalar(c, "SELECT COUNT(*) FROM named_blobs_v2")); + } + }); + } + + private static HikariDataSource repeatableReadPool(DataSource source, int size) { + HikariDataSource pool = new HikariDataSource(); + pool.setDataSource(source); + pool.setMaximumPoolSize(size); + pool.setTransactionIsolation("TRANSACTION_REPEATABLE_READ"); + return pool; + } + + @Test + public void testFactoryAppliesFencePolicyToWritableEndpoints() throws Exception { + MysqlDataSource db = source(""); + Properties props = new Properties(); + props.setProperty(ClusterMapConfig.CLUSTERMAP_DATACENTER_NAME, "local"); + props.setProperty(MySqlNamedBlobDbConfig.DB_INFO, "[]"); + for (boolean enabled : Arrays.asList(false, true)) { + props.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, Boolean.toString(enabled)); + MySqlNamedBlobDbFactory factory = new MySqlNamedBlobDbFactory(new VerifiableProperties(props), + new MetricRegistry(), new InMemAccountService(false, false)); + for (boolean writable : Arrays.asList(false, true)) { + DbEndpoint endpoint = new DbEndpoint(db.getURL(), "remote", writable, db.getUser(), db.getPassword()); + try (HikariDataSource pool = factory.buildDataSource(endpoint)) { + assertEquals(enabled && writable ? "TRANSACTION_REPEATABLE_READ" : null, pool.getTransactionIsolation()); + assertEquals(enabled && writable ? "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ" : null, + pool.getConnectionInitSql()); + } + } + } + } + + @Test + public void testFenceAwareUpsertsRetryDeadlockOnAdjacentNames() throws Exception { + checkContendingPuts(Arrays.asList("a", "b"), true); + } + + @Test + public void testFenceAwareCreateOnlyDoesNotReplayAfterDeadlock() throws Exception { + checkContendingPuts(Arrays.asList("a", "a"), false); + } + + private void checkContendingPuts(List names, boolean isUpsert) throws Exception { + withDatabase((db, named) -> { + Properties props = new Properties(); + props.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, "true"); + // Pause both inserts after the fence lookup but before either can insert into the shared gap. + sql(db, "CREATE TRIGGER wait_for_puts BEFORE INSERT ON named_blobs_v2 FOR EACH ROW BEGIN" + + " IF GET_LOCK(DATABASE(),30) <> 1 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='barrier timeout'; END IF;" + + " DO RELEASE_LOCK(DATABASE()); END"); + MysqlDataSource physical = (MysqlDataSource) db; + DbEndpoint endpoint = new DbEndpoint(physical.getURL(), "local", true, physical.getUser(), physical.getPassword()); + props.setProperty(MySqlNamedBlobDbConfig.LOCAL_POOL_SIZE, "2"); + props.setProperty(MySqlNamedBlobDbConfig.DB_INFO, new JSONArray().put(endpoint.toJson()).toString()); + props.setProperty(ClusterMapConfig.CLUSTERMAP_DATACENTER_NAME, "local"); + MetricRegistry registry = new MetricRegistry(); + AtomicLong now = new AtomicLong(System.currentTimeMillis()); + Time clock = mock(Time.class); + when(clock.milliseconds()).thenAnswer(invocation -> now.get()); + MySqlNamedBlobDbFactory factory = new MySqlNamedBlobDbFactory(new VerifiableProperties(props), registry, + fixtureAccounts(), clock, ""); + try (Connection gate = db.getConnection(); MySqlNamedBlobDb writer = factory.getNamedBlobDb()) { + assertEquals(1, scalar(gate, "SELECT GET_LOCK(DATABASE(),0)")); + List> puts = new ArrayList<>(); + for (String name : names) { + puts.add(writer.put(NamedBlobRecord.forPut("account", "container", name, + blob(BlobId.BlobDataType.METADATA).getID(), -1, 1), NamedBlobState.READY, isUpsert)); + } + awaitCount(gate, "SELECT COUNT(*) FROM performance_schema.metadata_locks WHERE OBJECT_TYPE='USER LEVEL LOCK'" + + " AND OBJECT_NAME=DATABASE() AND LOCK_STATUS='PENDING'", 2); + // Both versions are bound. Any version generated after releasing the lock must exceed this boundary. + long boundary = MySqlNamedBlobDb.buildVersion(new MockTime(now.incrementAndGet())); + now.incrementAndGet(); + assertEquals(1, scalar(gate, "SELECT RELEASE_LOCK(DATABASE())")); + List acknowledged = new ArrayList<>(); + int victims = 0; + for (int i = 0; i < puts.size(); i++) { + try { + NamedBlobRecord record = puts.get(i).get(10, TimeUnit.SECONDS).getInsertedRecord(); + assertEquals(names.get(i), record.getBlobName()); + acknowledged.add(record); + } catch (ExecutionException e) { + RestServiceException failure = (RestServiceException) e.getCause(); + assertEquals(RestServiceErrorCode.ServiceUnavailable, failure.getErrorCode()); + assertEquals(1213, ((SQLException) failure.getCause()).getErrorCode()); + victims++; + } + } + assertEquals(isUpsert ? 0 : 1, victims); + assertEquals(1, registry.getCounters().get(MetricRegistry.name(MySqlNamedBlobDb.class, + "FenceAwarePutDeadlockCount")).getCount()); + assertEquals(victims, registry.getCounters().get(MetricRegistry.name(MySqlNamedBlobDb.class, + "NamedBlobDBInsertErrorCount")).getCount()); + try (Statement read = gate.createStatement(); + ResultSet stored = read.executeQuery("SELECT blob_name, version FROM named_blobs_v2 ORDER BY blob_name")) { + for (NamedBlobRecord record : acknowledged) { + assertTrue("Missing acknowledged PUT", stored.next()); + assertEquals(record.getBlobName(), stored.getString("blob_name")); + long version = stored.getLong("version"); + assertEquals(record.getVersion(), version); + assertTrue("Retry generated a new version", version < boundary); + } + assertFalse("Unexpected stored PUT", stored.next()); + } + } + }); + } + + private static RestServiceException unavailable(CompletableFuture put) throws Exception { + try { + put.get(10, TimeUnit.SECONDS); + throw new AssertionError("PUT must not be acknowledged"); + } catch (ExecutionException e) { + RestServiceException failure = (RestServiceException) e.getCause(); + assertEquals(RestServiceErrorCode.ServiceUnavailable, failure.getErrorCode()); + return failure; + } + } + + private static void awaitCount(Connection c, String query, int count) throws SQLException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (scalar(c, query) < count) { + assertTrue("Did not observe " + count + " lock waiter(s)", System.nanoTime() < deadline); + } + } + @Test public void testRetirementLocksGapForReplacement() throws Exception { withDatabase((db, named) -> { @@ -853,7 +1318,13 @@ public void testRetireRejectsOversizedAggregateBeforeReadingAnyIterator() throws } private static int scalar(DataSource db, String sql) throws SQLException { - try (Connection c = db.getConnection(); Statement s = c.createStatement(); ResultSet r = s.executeQuery(sql)) { + try (Connection c = db.getConnection()) { + return scalar(c, sql); + } + } + + private static int scalar(Connection c, String sql) throws SQLException { + try (Statement s = c.createStatement(); ResultSet r = s.executeQuery(sql)) { assertTrue(r.next()); return r.getInt(1); } 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 cd4d966b18..4ef05b3e99 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 @@ -61,6 +61,9 @@ public class Metrics { public final Counter namedBlobDBListErrorCount; public final Counter namedBlobDBDeleteErrorCount; public final Counter namedBlobDBInsertErrorCount; + final Counter fenceAwarePutDeadlockCount; + final Counter fenceAwarePutSessionRejectedCount; + final Counter fenceAwarePutVersionRejectedCount; public final Counter namedBlobDBUpdateErrorCount; final Counter connectionCloseErrorCount; @@ -128,6 +131,12 @@ public Metrics(MetricRegistry metricRegistry, String prefix) { metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "NamedBlobDBDeleteErrorCount")); namedBlobDBInsertErrorCount = metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "NamedBlobDBInsertErrorCount")); + fenceAwarePutDeadlockCount = + metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "FenceAwarePutDeadlockCount")); + fenceAwarePutSessionRejectedCount = + metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "FenceAwarePutSessionRejectedCount")); + fenceAwarePutVersionRejectedCount = + metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "FenceAwarePutVersionRejectedCount")); namedBlobDBUpdateErrorCount = metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "NamedBlobDBUpdateErrorCount")); 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 0efe6d5e5f..463d0c5a21 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,9 @@ import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.Time; import com.github.ambry.utils.Utils; +import com.mysql.cj.conf.PropertyKey; +import com.mysql.cj.jdbc.ConnectionImpl; +import com.mysql.cj.jdbc.JdbcConnection; import com.zaxxer.hikari.HikariDataSource; import java.io.Closeable; import java.io.IOException; @@ -45,6 +48,7 @@ import java.sql.SQLException; import java.sql.SQLNonTransientConnectionException; import java.sql.SQLTransientConnectionException; +import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayDeque; import java.util.ArrayList; @@ -110,9 +114,7 @@ public class MySqlNamedBlobDb implements NamedBlobDb { /** * Select a record that matches a blob name (lookup by primary key). */ - private static final String GET_QUERY = - String.format("SELECT %s, %s, %s, %s FROM %s WHERE %s AND %s ORDER BY %s DESC LIMIT 1", BLOB_ID, VERSION, DELETED_TS, DIGEST, - NAMED_BLOBS_V2, PK_MATCH, STATE_MATCH, VERSION); + private final String getQuery; private final String LIST_WITH_PREFIX_SQL; private final String LIST_ALL_SQL; @@ -121,9 +123,14 @@ public class MySqlNamedBlobDb implements NamedBlobDb { * Attempt to insert a new mapping into the database. The 'modified_ts' column in the DB will be auto-populated on * the server side */ - private static final String INSERT_QUERY = - String.format("INSERT INTO %1$s (%2$s, %3$s, %4$s, %5$s, %6$s, %7$s, %8$s, %9$s, %10$s) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + private static final String INSERT_COLUMNS = + String.format("INSERT INTO %s (%s, %s, %s, %s, %s, %s, %s, %s, %s)", NAMED_BLOBS_V2, ACCOUNT_ID, CONTAINER_ID, BLOB_NAME, BLOB_ID, DELETED_TS, VERSION, BLOB_STATE, BLOB_SIZE, DIGEST); + private static final String INSERT_QUERY = INSERT_COLUMNS + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; + // Check the database fence in the INSERT itself, including for upserts that skip GET. + private static final String FENCE_AWARE_INSERT_QUERY = INSERT_COLUMNS + " SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?" + + " FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM " + NAMED_BLOBS_V2 + " WHERE " + PK_MATCH + + " AND retirement_fenced = TRUE AND version >= ?)"; /** * Find if there is currently a record present for a blob and acquire an exclusive lock in preparation for a delete. @@ -187,6 +194,9 @@ public class MySqlNamedBlobDb implements NamedBlobDb { String localDatacenter, Metrics metricRecorder, Time time) { this.accountService = accountService; this.config = config; + this.getQuery = String.format("SELECT %s, %s, %s, %s%s FROM %s WHERE %s AND %s ORDER BY %s DESC LIMIT 1", + BLOB_ID, VERSION, DELETED_TS, DIGEST, config.honorRetirementFence ? ", retirement_fenced" : "", + NAMED_BLOBS_V2, PK_MATCH, STATE_MATCH, VERSION); this.LIST_WITH_PREFIX_SQL = getListWithPrefixSQLStatement(config); this.LIST_ALL_SQL = getListAllSQLStatement(config); this.localDatacenter = localDatacenter; @@ -233,6 +243,7 @@ private String getListWithPrefixSQLStatement(MySqlNamedBlobDbConfig config) { + " AND blob_name LIKE ? " // 3 + " AND blob_name >= ? " // 4 + " AND (deleted_ts IS NULL OR deleted_ts > %2$s) " + + (config.honorRetirementFence ? " AND retirement_fenced = FALSE " : "") + " ), " + " BlobsMaxVersion AS ( " + " SELECT blob_name, MAX(version) as version " @@ -253,56 +264,9 @@ private String getListWithPrefixSQLStatement(MySqlNamedBlobDbConfig config) { + " LIMIT ?", STATE_MATCH, CURRENT_TIME); // 9 // @formatter:on case 3: - /** - * List named-blobs query, given a prefix. - * This query uses a subquery to get the max version of a given blob name. - * 1. The subquery returns the max version whose blob_state is ready, even if it's deleted. - * 2. The outer query select goes through all the (blob_name, version) combination and only returns the one when - * version is the max version from the subquery and not deleted. - * This list sql statement uses subquery instead of CTE and inner join so it should be more efficient. - */ - // @formatter:off - return String.format("" - + "SELECT candidate.blob_name, candidate.blob_id, candidate.version, candidate.deleted_ts, candidate.blob_size, candidate.modified_ts " - + "FROM named_blobs_v2 candidate " - + "WHERE candidate.account_id = ? " - + " AND candidate.container_id = ? " - + " AND candidate.%1$s" - + " AND candidate.blob_name LIKE ? " - + " AND candidate.blob_name >= ? " - + " AND (candidate.deleted_ts IS NULL OR candidate.deleted_ts > %2$s) " - + " AND candidate.version = ( " - + " SELECT MAX(latest.version) " - + " FROM named_blobs_v2 latest " - + " WHERE latest.account_id = ? " - + " AND latest.container_id = ? " - + " AND latest.blob_name = candidate.blob_name " - + " AND latest.%1$s" - + " ) " - + "LIMIT ?", STATE_MATCH, CURRENT_TIME); - // @formatter:on case 4: - /** - * List named-blobs query, given a prefix. - * Correlated-subquery form (same shape as option 3) with an explicit ORDER BY. The prior option-4 - * form used MAX(version) OVER (PARTITION BY blob_name); that window plan buffers/materializes the - * ENTIRE prefix range (Sort -> Window-with-buffering -> Materialize) before LIMIT can apply, so its - * cost is O(container) regardless of page size. On large containers this ran for many seconds and - * was connection-killed by the EI watchdog at ~6s. This correlated form early-terminates: the PK - * (account_id, container_id, blob_name, version) range scan walks blob_name in order, probes an - * indexed MAX(version) per candidate, and LIMIT stops after one page -> O(page). - * - * Correctness invariant — same as options 2 and 3: - * 1. The subquery MAX(version) is computed over all blob_state=READY rows for a given blob_name, - * INCLUDING rows with a non-null deleted_ts. - * 2. The deleted_ts predicate is applied on the OUTER select, so if the latest READY version of a - * blob has expired or been soft-deleted the blob is hidden entirely; we never surface a stale - * older version. - * - * ORDER BY candidate.blob_name makes pagination deterministic. Because the PK range scan already - * yields blob_name in order, the optimizer satisfies it without an extra Sort. Binds SEVEN - * parameters — keep constructListQueryWithPrefixV4 in lockstep. - */ + // MAX includes every READY version; only the winning row is tested for expiry or retirement. + // The correlated lookup allows LIMIT to stop the PK scan without materializing the entire prefix range. // @formatter:off return String.format("" + "SELECT candidate.blob_name, candidate.blob_id, candidate.version, candidate.deleted_ts, candidate.blob_size, candidate.modified_ts " @@ -313,6 +277,7 @@ private String getListWithPrefixSQLStatement(MySqlNamedBlobDbConfig config) { + " AND candidate.blob_name LIKE ? " + " AND candidate.blob_name >= ? " + " AND (candidate.deleted_ts IS NULL OR candidate.deleted_ts > %2$s) " + + (config.honorRetirementFence ? " AND candidate.retirement_fenced = FALSE " : "") + " AND candidate.version = ( " + " SELECT MAX(latest.version) " + " FROM named_blobs_v2 latest " @@ -321,7 +286,7 @@ private String getListWithPrefixSQLStatement(MySqlNamedBlobDbConfig config) { + " AND latest.blob_name = candidate.blob_name " + " AND latest.%1$s" + " ) " - + "ORDER BY candidate.blob_name " + + (config.listNamedBlobsSQLOption == 4 || config.honorRetirementFence ? "ORDER BY candidate.blob_name " : "") + "LIMIT ?", STATE_MATCH, CURRENT_TIME); // @formatter:on default: @@ -363,10 +328,14 @@ private String getListAllSQLStatement(MySqlNamedBlobDbConfig config) { + "(SELECT account_id, container_id, blob_name, max(version) as version " + "FROM named_blobs_v2 " + "WHERE (account_id, container_id) = (?, ?) AND %1$s " - + " AND (deleted_ts IS NULL OR deleted_ts>%2$S) " + // A fenced version must participate in MAX even after its timestamp elapses, or an older row can win. + + " AND (deleted_ts IS NULL OR deleted_ts>%2$S" + + (config.honorRetirementFence ? " OR retirement_fenced = TRUE" : "") + + ") " + " GROUP BY account_id, container_id, blob_name) t2 " + "ON (t1.account_id,t1.container_id,t1.blob_name,t1.version) = (t2.account_id,t2.container_id,t2.blob_name,t2.version) " + "WHERE " + + (config.honorRetirementFence ? "t1.retirement_fenced = FALSE AND " : "") + " CASE " + " WHEN ? IS NOT NULL THEN t1.blob_name >= ? " + " ELSE 1 " @@ -399,6 +368,7 @@ private String getListAllSQLStatement(MySqlNamedBlobDbConfig config) { + " AND candidate.%1$s " // blob_state = x + " AND ( ? IS NULL OR candidate.blob_name >= ? ) " // 3, 4 (pageToken twice) + " AND (candidate.deleted_ts IS NULL OR candidate.deleted_ts > %2$s) " + + (config.honorRetirementFence ? " AND candidate.retirement_fenced = FALSE " : "") + " AND candidate.version = ( " + " SELECT MAX(latest.version) " + " FROM named_blobs_v2 latest " @@ -456,6 +426,9 @@ public CompletableFuture put(NamedBlobRecord record, NamedBlobState s // Do upsert when it's using new table and 'x-ambry-named-upsert' header is not set to false (default is true) logger.trace("NamedBlobPutInfo: accountId='{}', containerId='{}', blobName='{}', isUpsert='{}'", accountId, containerId, record.getBlobName(), isUpsert); + if (config.honorRetirementFence) { + requireFenceAwarePutSession(connection); + } if (!isUpsert) { NamedBlobRecord recordCurrent = null; try { @@ -475,7 +448,7 @@ public CompletableFuture put(NamedBlobRecord record, NamedBlobState s record.getContainerName(), record.getBlobName()); } } - PutResult putResult = run_put_v2(record, state, accountId, containerId, connection); + PutResult putResult = run_put_v2(record, state, accountId, containerId, connection, isUpsert); metricsRecoder.namedBlobPutTimeInMs.update(this.time.milliseconds() - startTime); return putResult; }, null, this.metricsRecoder.namedBlobDBInsertErrorCount); @@ -849,6 +822,10 @@ private T runTransaction(boolean autoCommit, TransactionGeneric transacti if (!autoCommit) { connection.commit(); } + } catch (RejectedPutSession failure) { + // Never reset or recycle an unknown transaction. Closing normally may return its snapshot to a reader. + discardConnection(connection, failure); + throw failure; } catch (Exception | Error failure) { if (!autoCommit) { try { @@ -902,6 +879,8 @@ private void discardConnection(Connection connection, Throwable failure) { connection.abort(Runnable::run); } } catch (Exception | Error discardFailure) { + metrics.connectionCloseErrorCount.inc(); + logger.error("Failed to discard a named blob DB connection in {}", datacenter, discardFailure); if (failure != discardFailure) { failure.addSuppressed(discardFailure); } @@ -960,7 +939,7 @@ Map getDataSources() { private NamedBlobRecord run_get_v2(String accountName, String containerName, String blobName, GetOption option, short accountId, short containerId, Connection connection) throws Exception { String query = ""; - try (PreparedStatement statement = connection.prepareStatement(GET_QUERY)) { + try (PreparedStatement statement = connection.prepareStatement(getQuery)) { statement.setInt(1, accountId); statement.setInt(2, containerId); statement.setString(3, blobName); @@ -976,6 +955,11 @@ private NamedBlobRecord run_get_v2(String accountName, String containerName, Str long version = resultSet.getLong(2); Timestamp deletionTime = resultSet.getTimestamp(3); String digest = resultSet.getString(4); + if (config.honorRetirementFence && resultSet.getBoolean(5) + && option != GetOption.Include_Deleted_Blobs && option != GetOption.Include_All) { + throw buildException("GET: Named version is retired", RestServiceErrorCode.Deleted, accountName, + containerName, blobName); + } long currentTime = this.time.milliseconds(); if (compareTimestamp(deletionTime, currentTime) <= 0 && !includeDeletedOrExpiredOptions.contains(option)) { throw buildException("GET: Blob is not available due to it is deleted or expired", @@ -1017,10 +1001,8 @@ private Page run_list_v2(String accountName, String containerNa constructListQueryWithPrefixV2(statement, accountId, containerId, blobNamePrefix, pageToken, maxKeysValue); break; case 3: - constructListQueryWithPrefixV3(statement, accountId, containerId, blobNamePrefix, pageToken, maxKeysValue); - break; case 4: - constructListQueryWithPrefixV4(statement, accountId, containerId, blobNamePrefix, pageToken, maxKeysValue); + constructCorrelatedPrefixQuery(statement, accountId, containerId, blobNamePrefix, pageToken, maxKeysValue); break; default: throw new IllegalStateException( @@ -1130,7 +1112,7 @@ private void constructListQueryWithPrefixV2(PreparedStatement statement, short a } /** - * Construct a list query statement with prefix when {@link MySqlNamedBlobDbConfig#listNamedBlobsSQLOption} is 3 + * Construct the correlated prefix LIST for SQL options 3 and 4. * @param statement The {@link PreparedStatement} to set the parameters on. * @param accountId The account id * @param containerId The container id @@ -1139,7 +1121,7 @@ private void constructListQueryWithPrefixV2(PreparedStatement statement, short a * @param maxKeysValue The max key to return * @throws SQLException */ - private void constructListQueryWithPrefixV3(PreparedStatement statement, short accountId, short containerId, + private void constructCorrelatedPrefixQuery(PreparedStatement statement, short accountId, short containerId, String blobNamePrefix, String pageToken, int maxKeysValue) throws SQLException { statement.setInt(1, accountId); statement.setInt(2, containerId); @@ -1150,36 +1132,56 @@ private void constructListQueryWithPrefixV3(PreparedStatement statement, short a statement.setInt(7, maxKeysValue + 1); } - /** - * Construct a list query statement with prefix when {@link MySqlNamedBlobDbConfig#listNamedBlobsSQLOption} is 4. - * Option 4 now uses a correlated subquery (see {@link #getListWithPrefixSQLStatement}) and binds seven - * parameters: (account_id, container_id, blob_name LIKE prefix%, blob_name >= cursor, account_id, - * container_id, LIMIT). Params 5 and 6 feed the inner MAX(version) subquery. Identical to - * {@link #constructListQueryWithPrefixV3}. - * @param statement The {@link PreparedStatement} to set the parameters on. - * @param accountId The account id - * @param containerId The container id - * @param blobNamePrefix The blobname prefix - * @param pageToken The page token - * @param maxKeysValue The max key to return - * @throws SQLException - */ - private void constructListQueryWithPrefixV4(PreparedStatement statement, short accountId, short containerId, - String blobNamePrefix, String pageToken, int maxKeysValue) throws SQLException { - statement.setInt(1, accountId); - statement.setInt(2, containerId); - statement.setString(3, blobNamePrefix + "%"); - statement.setString(4, pageToken != null ? pageToken : blobNamePrefix); - statement.setInt(5, accountId); - statement.setInt(6, containerId); - statement.setInt(7, maxKeysValue + 1); + private static final class RejectedPutSession extends RestServiceException { + RejectedPutSession(String message, Throwable cause) { + super(message, cause, RestServiceErrorCode.ServiceUnavailable); + } + } + + private void requireFenceAwarePutSession(Connection connection) throws RejectedPutSession { + try { + // Inspect the actual Connector/J delegate, not the URL or a multi-host proxy's currently selected host. + 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 rejectPutSession("PUT: Fence-aware insert requires a fixed physical MySQL session", null); + } + // JDBC getters can be cached; read the state that governs the insert's locks. + try (Statement check = connection.createStatement()) { + check.setFetchSize(0); + try (ResultSet settings = check.executeQuery("SELECT @@session.autocommit, @@session.transaction_isolation")) { + if (!settings.next()) { + throw new SQLException("MySQL did not return the writer session settings"); + } + if (!settings.getBoolean(1) || !"REPEATABLE-READ".equals(settings.getString(2))) { + throw rejectPutSession("PUT: Fence-aware insert requires autocommit and REPEATABLE READ", null); + } + // START TRANSACTION leaves autocommit on. Read this response's status before cleanup can clear it. + if (driver.getSession().getServerSession().inTransactionOnServer()) { + throw rejectPutSession("PUT: Fence-aware insert cannot use an active transaction", null); + } + } + } + } catch (SQLException e) { + metricsRecoder.namedBlobDBInsertErrorCount.inc(); + throw rejectPutSession("PUT: Could not verify the writer session", e); + } + } + + private RejectedPutSession rejectPutSession(String reason, Throwable cause) { + metricsRecoder.fenceAwarePutSessionRejectedCount.inc(); + logger.warn(reason, cause); + return new RejectedPutSession(reason, cause); } private PutResult run_put_v2(NamedBlobRecord record, NamedBlobState state, short accountId, short containerId, - Connection connection) throws Exception { + Connection connection, boolean isUpsert) throws Exception { String query = ""; NamedBlobRecord updatedRecord; - try (PreparedStatement statement = connection.prepareStatement(INSERT_QUERY)) { + try (PreparedStatement statement = + connection.prepareStatement(config.honorRetirementFence ? FENCE_AWARE_INSERT_QUERY : INSERT_QUERY)) { statement.setInt(1, accountId); statement.setInt(2, containerId); statement.setString(3, record.getBlobName()); @@ -1195,12 +1197,44 @@ private PutResult run_put_v2(NamedBlobRecord record, NamedBlobState state, short statement.setInt(7, state.ordinal()); statement.setLong(8, record.getBlobSize()); statement.setString(9, record.getDigest()); + if (config.honorRetirementFence) { + statement.setInt(10, accountId); + statement.setInt(11, containerId); + statement.setString(12, record.getBlobName()); + statement.setLong(13, newVersion); + } updatedRecord = new NamedBlobRecord(record.getAccountName(), record.getContainerName(), record.getBlobName(), record.getBlobId(), record.getExpirationTimeMs(), newVersion); query = statement.toString(); logger.debug("Putting blob name in MySql. Query {}", query); metricsRecoder.namedBlobInsertRate.mark(); - statement.executeUpdate(); + int inserted; + for (int attempt = 0; ; attempt++) { + try { + inserted = statement.executeUpdate(); + break; + } catch (SQLException e) { + if (!config.honorRetirementFence || e.getErrorCode() != 1213 || !"40001".equals(e.getSQLState())) { + throw e; + } + metricsRecoder.fenceAwarePutDeadlockCount.inc(); + // Reuse the bound version and fence predicate only after a confirmed rollback. A create-only PUT + // must not replay its INSERT on the strength of a now-stale existence check. + if (isUpsert && attempt == 0) { + continue; + } + metricsRecoder.namedBlobDBInsertErrorCount.inc(); + logger.warn("MySQL rolled back a fence-aware PUT (1213/40001)", e); + throw new RestServiceException("PUT: InnoDB rolled back a deadlocked insert", e, + RestServiceErrorCode.ServiceUnavailable); + } + } + if (inserted == 0 && config.honorRetirementFence) { + metricsRecoder.fenceAwarePutVersionRejectedCount.inc(); + throw buildException("PUT: Version must be newer than the retirement fence", + RestServiceErrorCode.ServiceUnavailable, record.getAccountName(), record.getContainerName(), + record.getBlobName()); + } } catch (SQLException e) { logger.error("Failed to execute query {}, {}", query, e.getMessage()); throw e; diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDbFactory.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDbFactory.java index 9aa4fc77da..5e6212491a 100644 --- a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDbFactory.java +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDbFactory.java @@ -85,10 +85,23 @@ public HikariDataSource buildDataSource(DbEndpoint dbEndpoint) { hikariConfig.addDataSourceProperty("prepStmtCacheSize", "250"); hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); hikariConfig.addDataSourceProperty("useServerPrepStmts", "true"); - if (!config.transactionIsolationLevel.equals(TransactionIsolationLevel.TRANSACTION_NONE)) { - hikariConfig.setTransactionIsolation(config.transactionIsolationLevel.name()); - } + configureIsolation(hikariConfig, config.transactionIsolationLevel, + config.honorRetirementFence && dbEndpoint.isWriteable()); hikariConfig.setMetricRegistry(metricRegistry); return new HikariDataSource(hikariConfig); } + + static void configureIsolation(HikariConfig pool, TransactionIsolationLevel isolation, boolean fenceAwareWriter) { + if (fenceAwareWriter) { + if (isolation != TransactionIsolationLevel.TRANSACTION_NONE + && isolation != TransactionIsolationLevel.TRANSACTION_REPEATABLE_READ) { + throw new IllegalArgumentException("Fence-aware writer pools require TRANSACTION_REPEATABLE_READ"); + } + pool.setTransactionIsolation(TransactionIsolationLevel.TRANSACTION_REPEATABLE_READ.name()); + // Hikari can skip its JDBC setter when the session default matches, leaving a one-transaction override intact. + pool.setConnectionInitSql("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + } else if (isolation != TransactionIsolationLevel.TRANSACTION_NONE) { + pool.setTransactionIsolation(isolation.name()); + } + } } diff --git a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbFactoryTest.java b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbFactoryTest.java new file mode 100644 index 0000000000..af79d1f481 --- /dev/null +++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbFactoryTest.java @@ -0,0 +1,30 @@ +/* + * Copyright 2026 LinkedIn Corp. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package com.github.ambry.named; + +import com.zaxxer.hikari.HikariConfig; +import org.junit.Test; + +import static org.junit.Assert.*; + + +public class MySqlNamedBlobDbFactoryTest { + @Test + public void testFlagOffPreservesConfiguredIsolation() { + HikariConfig pool = new HikariConfig(); + MySqlNamedBlobDbFactory.configureIsolation(pool, TransactionIsolationLevel.TRANSACTION_NONE, false); + assertNull(pool.getTransactionIsolation()); + assertNull(pool.getConnectionInitSql()); + MySqlNamedBlobDbFactory.configureIsolation(pool, TransactionIsolationLevel.TRANSACTION_READ_COMMITTED, false); + assertEquals("TRANSACTION_READ_COMMITTED", pool.getTransactionIsolation()); + assertNull(pool.getConnectionInitSql()); + } + + @Test(expected = IllegalArgumentException.class) + public void testFenceAwareWriterRejectsExplicitReadCommitted() { + MySqlNamedBlobDbFactory.configureIsolation(new HikariConfig(), TransactionIsolationLevel.TRANSACTION_READ_COMMITTED, + true); + } +} 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 bb89f0b2c1..8f01378b43 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,11 @@ import com.github.ambry.rest.RestServiceException; import com.github.ambry.utils.TestUtils; import com.github.ambry.utils.Utils; +import com.mysql.cj.NativeSession; +import com.mysql.cj.jdbc.ConnectionImpl; +import com.mysql.cj.jdbc.JdbcConnection; +import com.mysql.cj.jdbc.JdbcPropertySetImpl; +import com.mysql.cj.protocol.ServerSession; import com.zaxxer.hikari.HikariDataSource; import java.io.IOException; import java.sql.Connection; @@ -42,6 +47,7 @@ import java.sql.SQLException; import java.sql.SQLNonTransientConnectionException; import java.sql.SQLTransientConnectionException; +import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; @@ -126,6 +132,73 @@ public void testRetryDeleteNamedBlob() throws Exception { checkErrorCode(() -> namedBlobDb.delete(account.getName(), container.getName(), "blobName"), RestServiceErrorCode.NotFound); } + @Test + public void testFenceAwarePutRetriesOnlyConfirmedDeadlocksOnce() throws Exception { + Properties props = new Properties(); + props.setProperty(MySqlNamedBlobDbConfig.DB_INFO, buildSmallPoolConfig(1, 1, 1).dbInfo); + props.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, "true"); + DataSource source = mock(DataSource.class); + Connection connection = mock(Connection.class); + PreparedStatement insert = mock(PreparedStatement.class); + Statement probe = mock(Statement.class); + ResultSet settings = mock(ResultSet.class); + ConnectionImpl driver = mock(ConnectionImpl.class); + NativeSession session = mock(NativeSession.class); + when(driver.getSession()).thenReturn(session); + when(session.getServerSession()).thenReturn(mock(ServerSession.class)); + when(connection.unwrap(JdbcConnection.class)).thenReturn(driver); + when(driver.getPropertySet()).thenReturn(new JdbcPropertySetImpl()); + when(source.getConnection()).thenReturn(connection); + when(connection.createStatement()).thenReturn(probe); + when(probe.executeQuery(startsWith("SELECT"))).thenReturn(settings); + when(settings.next()).thenReturn(true); + when(settings.getBoolean(1)).thenReturn(true); + when(settings.getString(2)).thenReturn("REPEATABLE-READ"); + when(connection.prepareStatement(startsWith("INSERT"))).thenReturn(insert); + SQLException lostReply = new SQLException("Connection lost waiting for INSERT reply", "08S01"); + SQLException timeout = new SQLException("Lock wait timeout", "40001", 1205); + SQLException deadlock = new SQLException("Deadlock victim", "40001", 1213); + when(insert.executeUpdate()).thenThrow(lostReply, timeout, deadlock, deadlock, deadlock).thenReturn(0); + Metrics metrics = new Metrics(new MetricRegistry(), ""); + try (MySqlNamedBlobDb db = new MySqlNamedBlobDb(accountService, + new MySqlNamedBlobDbConfig(new VerifiableProperties(props)), endpoint -> source, localDatacenter, + metrics)) { + NamedBlobRecord record = NamedBlobRecord.forPut(account.getName(), container.getName(), "name", id, -1, 1); + for (SQLException original : Arrays.asList(lostReply, timeout)) { + TestUtils.assertException(ExecutionException.class, () -> db.put(record, NamedBlobState.READY, true) + .get(5, TimeUnit.SECONDS), e -> assertSame(original, e.getCause())); + } + verify(insert, times(2)).executeUpdate(); + TestUtils.assertException(ExecutionException.class, () -> db.put(record, NamedBlobState.READY, true) + .get(5, TimeUnit.SECONDS), e -> { + RestServiceException unavailable = (RestServiceException) e.getCause(); + assertEquals(RestServiceErrorCode.ServiceUnavailable, unavailable.getErrorCode()); + assertSame(deadlock, unavailable.getCause()); + }); + verify(insert, times(4)).executeUpdate(); + assertEquals(3, metrics.namedBlobDBInsertErrorCount.getCount()); + checkErrorCode(() -> db.put(record, NamedBlobState.READY, true), RestServiceErrorCode.ServiceUnavailable); + assertEquals(1, metrics.fenceAwarePutVersionRejectedCount.getCount()); + when(settings.getString(2)).thenReturn("READ-COMMITTED"); + SQLException discardFailure = new SQLException("Connection abort failed"); + doThrow(discardFailure).when(connection).abort(any()); + TestUtils.assertException(ExecutionException.class, () -> db.put(record, NamedBlobState.READY, true) + .get(5, TimeUnit.SECONDS), e -> { + assertEquals(RestServiceErrorCode.ServiceUnavailable, ((RestServiceException) e.getCause()).getErrorCode()); + assertArrayEquals(new Throwable[]{discardFailure}, e.getCause().getSuppressed()); + }); + verify(connection).abort(any()); + verify(connection, times(4)).close(); + verify(connection, never()).setAutoCommit(true); + assertEquals(1, metrics.connectionCloseErrorCount.getCount()); + verify(insert, times(6)).executeUpdate(); + verify(source, times(5)).getConnection(); + assertEquals(3, metrics.namedBlobDBInsertErrorCount.getCount()); + assertEquals(3, metrics.fenceAwarePutDeadlockCount.getCount()); + assertEquals(1, metrics.fenceAwarePutSessionRejectedCount.getCount()); + } + } + @Test public void testHardDeleteReturnsVersionsWhenPoolReturnFails() throws Exception { Connection connection = mock(Connection.class); From d81c87a9de0ba1cdf5fa7043f82f7e09027f3661 Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Tue, 1 Dec 2026 11:54:49 -0800 Subject: [PATCH 2/2] Use atomic retirement in fence-aware serving tests Replace the staging fixtures with direct publication while keeping transaction control in the concurrent PUT test. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../NamedBlobManifestStoreIntegrationTest.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) 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 e203e54c44..1b8e20e6c5 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 @@ -142,8 +142,7 @@ public void testFenceAwareGetWithSlowFrontend() throws Exception { long expires = now + TimeUnit.DAYS.toMillis(1); long fence = writer.put(NamedBlobRecord.forPut("account", "container", NAME, root.getID(), expires, 1), NamedBlobState.READY, false).get(10, TimeUnit.SECONDS).getInsertedRecord().getVersion(); - retire(writer, Collections.singletonList(stage(writer, NAME, fence, root, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()))); + retireOne(writer, fence, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); // A lower-version insert after publication must not become the visible root. insertNamed(db, 6, blob(BlobId.BlobDataType.METADATA), NamedBlobState.READY); MockTime frontend = new MockTime(now - TimeUnit.SECONDS.toMillis(5)); @@ -545,9 +544,11 @@ public void testNameReuseDoesNotConsumeRetirementLimit() throws Exception { public void testFenceAwarePutDuringPublication() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); - insertNamed(db, 100, root, NamedBlobState.READY); - List jobs = Collections.singletonList(stage(named, NAME, 100, root, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); + long retiringVersion = 100; + insertNamed(db, retiringVersion, root, NamedBlobState.READY); + Map pending = Collections.singletonMap(retiringVersion, + new NamedBlobManifestStore.PendingVersion(root, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); NamedBlobRecord lower = new NamedBlobRecord("account", "container", NAME, root.getID(), -1, 50); Properties props = new Properties(); props.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, "true"); @@ -559,7 +560,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, jobs); + NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, 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); @@ -620,8 +621,7 @@ public void testFenceAwarePutChecksServerInsteadOfCachedSessionSettings() throws physical.setUseConfigs("maxPerformance"); BlobId root = blob(BlobId.BlobDataType.METADATA); insertNamed(db, 7, root, NamedBlobState.READY); - String job = stage(named, NAME, 7, root, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); sql(db, "CREATE TABLE eviction_sentinel (id INT PRIMARY KEY) ENGINE=InnoDB"); Properties props = new Properties(); props.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, "true"); @@ -649,7 +649,7 @@ public void testFenceAwarePutChecksServerInsteadOfCachedSessionSettings() throws assertNotEquals(rejectedId, scalar(next, "SELECT CONNECTION_ID()")); } } - retire(named, Collections.singletonList(job)); + retireOne(named, 7, root, 1, Collections.singletonList(child).iterator()); try { writer.get("account", "container", NAME).get(10, TimeUnit.SECONDS); fail("A subsequent GET must not reuse a pre-retirement snapshot");