From 45fb3693f3e38e3805a0af3c5574e34a86d849fb Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Tue, 24 Nov 2026 19:38:17 -0800 Subject: [PATCH 1/5] Persist exact-version manifests for recoverable named soft deletes Stage ordered child IDs for each immutable root. Publish the exact manifest set and soft-retire its named versions in one transaction, so a retry does not resolve a replacement name. Published pages can be read by manifest ID without fetching the root. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/github-actions.yml | 12 + ambry-named-mysql/README.md | 98 ++++ .../MySqlNamedBlobDbIntegrationTest.java | 6 +- ...NamedBlobManifestStoreIntegrationTest.java | 504 ++++++++++++++++++ .../github/ambry/named/MySqlNamedBlobDb.java | 25 + .../ambry/named/NamedBlobManifestStore.java | 418 +++++++++++++++ .../main/resources/NamedBlobManifestV1.ddl | 29 + .../resources/NamedBlobRetirementFenceV1.sql | 20 + .../named/NamedBlobManifestStoreTest.java | 54 ++ 9 files changed, 1161 insertions(+), 5 deletions(-) create mode 100644 ambry-named-mysql/README.md create mode 100644 ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java create mode 100644 ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java create mode 100644 ambry-named-mysql/src/main/resources/NamedBlobManifestV1.ddl create mode 100644 ambry-named-mysql/src/main/resources/NamedBlobRetirementFenceV1.sql create mode 100644 ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java diff --git a/.github/workflows/github-actions.yml b/.github/workflows/github-actions.yml index 297fa38359..db7de69e6b 100644 --- a/.github/workflows/github-actions.yml +++ b/.github/workflows/github-actions.yml @@ -199,6 +199,18 @@ jobs: arguments: --scan --warning-mode=summary intTest -x :ambry-server:intTest codeCoverageReport gradle-version: wrapper + - name: Verify named manifest migration tests ran + run: | + python3 - <<'PY' + from pathlib import Path + from xml.etree import ElementTree + report, = Path("ambry-named-mysql/build/test-results/intTest").glob("TEST-*.NamedBlobManifestStoreIntegrationTest.xml") + suite = ElementTree.parse(report).getroot() + if int(suite.attrib["tests"]) == 0 or int(suite.attrib["skipped"]) != 0: + raise SystemExit(f"Migration suite did not fully execute: {suite.attrib}") + print(f'{suite.attrib["tests"]} manifest migration tests executed; none skipped') + PY + - name: Upload coverage to Codecov uses: codecov/codecov-action@v4 env: diff --git a/ambry-named-mysql/README.md b/ambry-named-mysql/README.md new file mode 100644 index 0000000000..372c9915ee --- /dev/null +++ b/ambry-named-mysql/README.md @@ -0,0 +1,98 @@ +# Named delete manifests + +`stageDeleteManifest` stores ordered child IDs from one immutable metadata blob in pages of 64. The caller must supply +descriptors from that exact root. Staging does not lock or retire the name or expose the manifest to recovery readers. +`retireWithManifests` validates the sealed pages and the locked name versions, then publishes the supplied +manifest set in the same transaction that soft-deletes those versions. If the commit outcome is unknown, retry with +the same manifest IDs. Do not resolve the name again or fall back to the router's ordinary delete. + +A reader with a saved manifest ID can look up that published manifest and read its pages by offset after a restart, +without fetching the original root. Configure the reader data source for `READ COMMITTED` or stronger on every checkout. +A pool shared with the publisher must use `REPEATABLE READ`; readers do not change its isolation. Distinct roots can +reference the same child; finding its ID does not authorize deletion. + +## Compatibility and limits + +These package-private methods have no frontend caller. They require one authoritative InnoDB writer for the name range, +soft deletes, and `REPEATABLE READ` during publication. They do not coordinate independent active-active writers. +Publication locks the indexed range of unfenced versions, including the gap for new inserts. Every live version needs a +matching manifest and must be READY. An elapsed legacy tombstone or expiry needs no manifest: the same transaction +preserves its timestamp and fences it against TTL finalization, without publishing cleanup work for it. Fenced rows no +longer count toward the limit of 32 unfenced versions per name. A name above that limit, or with an unrepresented live +version, fails without changing any row. Exclude such names from rollout until their history has been safely reconciled; +retrying unchanged input will not help. Publication also limits total children to 131,072. + +## Installing or resuming the migration + +**Defer production DDL until the activation prerequisites below are ready.** Nothing installs automatically, but once +installed the trigger fires on every update, even on unfenced rows with manifests disabled. If its definer disappears +or loses privileges, ordinary TTL finalization and soft deletes can fail. + +From `ambry-named-mysql/src/main/resources`, set `DB` to the approved writer's named-blob schema. Use separate mysql +options files: `MYSQL_CNF` for schema DDL and `DEFINER_CNF` for the durable service account that will own the trigger. +The trigger file uses MySQL's implicit `DEFINER=CURRENT_USER`. Before installation, confirm the matched `user@host` +is the intended permanent account, **not** a personal or temporary migration identity. Have the DBA verify on every +writer and promotion candidate that this account exists and retains `TRIGGER`, `SELECT` and `UPDATE` on `named_blobs_v2` +for the trigger's lifetime. Use the approved trigger-install process for the server's binary logging configuration. + +```sh +mysql --defaults-file="$DEFINER_CNF" --database="$DB" -e 'SELECT CURRENT_USER(), DATABASE(); SHOW GRANTS' +``` + +On a fresh installation, check each result before continuing. The column addition is `INSTANT`; even the `INPLACE`, +`LOCK=NONE` index build needs a metadata lock to finish. Schedule a rollout window and monitor lock waits and replica +lag. Bound each metadata-lock wait, not the index build duration, with a five-second **session** timeout. Use the same +timeout for every retry. Do not use a table-copy fallback. + +```sh +mysql --defaults-file="$MYSQL_CNF" --database="$DB" --init-command='SET SESSION lock_wait_timeout=5' \ + < NamedBlobManifestV1.ddl +mysql --defaults-file="$DEFINER_CNF" --database="$DB" --init-command='SET SESSION lock_wait_timeout=5' \ + --delimiter='//' -e 'SOURCE NamedBlobRetirementFenceV1.sql' +mysql --defaults-file="$DEFINER_CNF" --database="$DB" -e 'SHOW CREATE TRIGGER named_blob_retirement_fence_v1\G' +``` + +The delimiter keeps the compound trigger intact in the mysql client; JDBC installers send the entire trigger file as +one statement. Verify the installed `BEFORE UPDATE` body and the exact `DEFINER` on each writer and before promotion. +On each writer, connect **as the application account** and smoke-test an unfenced update: in one transaction, insert +an approved disposable named version, finalize its TTL using its exact primary key, verify one row changed to READY +with `deleted_ts IS NULL`, and roll back. Verify the fixture row is absent afterward. Do not use a customer row. Stop +on any error; a successful install by the DDL operator is not evidence that application writes still work. + +**On any error or lost connection, do not rerun the file.** Each successful DDL statement has already committed. +Wait for any in-flight DDL to finish. Inspect `SHOW CREATE TABLE` for both manifest tables and `named_blobs_v2`, and +`SHOW CREATE TRIGGER` if the trigger exists. Compare definitions in installation order: manifest header table, page +table and foreign key, fence column, ordered unfenced-version index, then trigger and definer. Stop on any conflicting +definition. Fix the cause, resume at the first missing statement using the timeout above, and run only the missing +steps in order. An index build can finish scanning the table and still time out waiting for its final metadata lock. +If the column exists but the index does not, have the owners finish any long-running transactions holding the lock +before retrying `ALTER TABLE ... ADD INDEX`; each retry rebuilds the index. Then install the trigger, recheck the +definitions, and run the application smoke test. + +## Before enabling a caller + +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. +- Before permitting failover, verify each promotion candidate has applied all acknowledged retirement transactions + (receipts, pages and fenced rows), not just the schema and trigger. Do not promote or serve from a candidate whose + applied position cannot be proven sufficient. +- 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. +- Give the worker indexed discovery of committed publications or durably record the exact manifest IDs before + retirement. A process-local list of IDs is lost on restart; a saved ID is actionable only after publication. + +Before staging the first manifest, route all frontend and direct named DELETE callers away from legacy DELETE for the +enabled namespace, or reject those requests. Also exclude its account or container from `NamedBlobsCleanupRunner` on +every runner, for both stale cleanup and purge. Drain in-flight requests, cleaner batches already selected, and their +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 staging and 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. + +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/MySqlNamedBlobDbIntegrationTest.java b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/MySqlNamedBlobDbIntegrationTest.java index 28a01c154f..0e9e293080 100644 --- a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/MySqlNamedBlobDbIntegrationTest.java +++ b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/MySqlNamedBlobDbIntegrationTest.java @@ -168,7 +168,6 @@ public void testPutWithVersion() throws Exception { @Test public void testPutWithDigest() throws Exception { - List records = new ArrayList<>(); Account account = accountService.getAllAccounts().iterator().next(); Container container = account.getAllContainers().iterator().next(); String blobId = getBlobId(account, container); @@ -178,10 +177,7 @@ public void testPutWithDigest() throws Exception { NamedBlobRecord record = new NamedBlobRecord(account.getName(), container.getName(), blobName, blobId, expirationTime, time.milliseconds(), blobSize, Hex.encodeHexString(TestUtils.getRandomBytes(32))); - namedBlobDb.put(record); - records.add(record); - time.sleep(1000); - + namedBlobDb.put(record).get(10, TimeUnit.SECONDS); NamedBlobRecord recordFromStore = namedBlobDb.get(record.getAccountName(), record.getContainerName(), record.getBlobName()).get(); 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 new file mode 100644 index 0000000000..cc8ff36c83 --- /dev/null +++ b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java @@ -0,0 +1,504 @@ +/* + * Copyright 2026 LinkedIn Corp. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package com.github.ambry.named; + +import static org.junit.Assert.*; +import static org.mockito.AdditionalAnswers.delegatesTo; +import static org.mockito.Mockito.*; + +import java.io.InputStream; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLDataException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Properties; +import java.util.Scanner; +import java.util.UUID; +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.stream.Collectors; +import javax.sql.DataSource; +import org.junit.Test; +import com.codahale.metrics.MetricRegistry; +import com.github.ambry.account.Account; +import com.github.ambry.account.AccountBuilder; +import com.github.ambry.account.Container; +import com.github.ambry.account.ContainerBuilder; +import com.github.ambry.account.InMemAccountService; +import com.github.ambry.clustermap.MockPartitionId; +import com.github.ambry.commons.BlobId; +import com.github.ambry.config.MySqlNamedBlobDbConfig; +import com.github.ambry.config.VerifiableProperties; +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.mysql.cj.jdbc.MysqlDataSource; + +public class NamedBlobManifestStoreIntegrationTest { + private static final short ACCOUNT = 17; + private static final short CONTAINER = 4; + private static final String NAME = "folder/MixedCase"; + + @Test + public void testDetachedRecoveryAcrossReplacement() throws Exception { + withDatabase(NamedBlobManifestStoreIntegrationTest::exercise); + } + + private interface Scenario { + void run(DataSource source, MySqlNamedBlobDb named) throws Exception; + } + + private static void withDatabase(Scenario scenario) throws Exception { + withDatabase(null, scenario); + } + + private interface BeforeMigration { + void seed(DataSource source) throws Exception; + } + + private static void withDatabase(BeforeMigration before, Scenario scenario) throws Exception { + String schema = "ambry_manifest_test_" + UUID.randomUUID().toString().replace("-", ""); + MysqlDataSource admin = source(""); + try (Connection c = admin.getConnection(); Statement s = c.createStatement()) { + // No IF NOT EXISTS: never adopt, mutate, or drop an existing database. + s.executeUpdate("CREATE DATABASE " + schema + " CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"); + try { + MysqlDataSource db = source(schema); + try (Connection setup = db.getConnection(); Statement ddl = setup.createStatement()) { + install(ddl, "/NamedBlobsSchema.ddl"); + if (before != null) { + before.seed(db); + } + install(ddl, "/NamedBlobManifestV1.ddl"); + install(ddl, "/NamedBlobRetirementFenceV1.sql"); + } + try (MySqlNamedBlobDb named = namedDb(db)) { + scenario.run(db, named); + } + } finally { + s.executeUpdate("DROP DATABASE " + schema); + } + } + } + + private static MySqlNamedBlobDb namedDb(DataSource db) 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(), "")); + } + + private static String stage(MySqlNamedBlobDb db, String name, long version, BlobId root, int count, + Iterator children) throws Exception { + try { + return db.stageDeleteManifest("account", "container", name, version, root, count, children) + .get(10, TimeUnit.SECONDS); + } catch (ExecutionException e) { + if (e.getCause() instanceof SQLDataException) { + throw (SQLDataException) e.getCause(); + } + throw e; + } + } + + private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Exception { + BlobId old = blob(BlobId.BlobDataType.METADATA); + BlobId replacement = blob(BlobId.BlobDataType.METADATA); + List children = new ArrayList<>(); + for (int i = 0; i <= NamedBlobManifestStore.PAGE_SIZE; i++) { + children.add(blob(BlobId.BlobDataType.DATACHUNK)); + } + List ids = children.stream().map(BlobId::getID).collect(Collectors.toList()); + int boundary = NamedBlobManifestStore.PAGE_SIZE; + insertNamed(db, 7, old, NamedBlobState.READY); + insertNamed(db, 8, replacement, NamedBlobState.IN_PROGRESS); + NamedBlobManifestStore writer = new NamedBlobManifestStore(db); + + expectDataError("No matching live READY", () -> + stage(named, NAME, 8, replacement, children.size(), children.iterator())); + expectDataError("No matching live READY", () -> + stage(named, NAME + " ", 7, old, children.size(), children.iterator())); + expectDataError("No matching live READY", () -> + stage(named, NAME, 7, replacement, children.size(), children.iterator())); + expectDataError("Missing or unsupported child", () -> + stage(named, NAME, 7, old, children.size(), children.subList(0, boundary).iterator())); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + + String job = stage(named, NAME, 7, old, children.size(), children.iterator()); + assertEquals(job, stage(named, NAME, 7, old, children.size(), children.iterator())); + List reordered = new ArrayList<>(children); + Collections.swap(reordered, 0, 1); + expectDataError("Capture retry disagrees", () -> + stage(named, NAME, 7, old, reordered.size(), reordered.iterator())); + + assertNull("Staging alone does not publish work", writer.getPublished(job)); + expectDataError("Unrepresented or ineligible", () -> retire(named, Collections.singletonList(job))); + sql(db, "DELETE FROM named_blobs_v2 WHERE version=8"); + retire(named, Collections.singletonList(job)); + insertNamed(db, 8, replacement, NamedBlobState.READY); + retire(named, Collections.singletonList(job)); + 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( + "DELETE FROM named_blobs_v2 WHERE account_id=? AND container_id=? AND blob_name=? AND version=7 AND blob_id=?")) { + remove.setShort(1, ACCOUNT); + remove.setShort(2, CONTAINER); + remove.setString(3, NAME); + remove.setBytes(4, old.toBytes()); + assertEquals(1, remove.executeUpdate()); + } + + DataSource readers = mock(DataSource.class); + when(readers.getConnection()).thenAnswer(invocation -> { + Connection c = mock(Connection.class, delegatesTo(db.getConnection())); + doThrow(new AssertionError("Reader changed pool isolation")).when(c).setTransactionIsolation(anyInt()); + return c; + }); + NamedBlobManifestStore worker = new NamedBlobManifestStore(readers); + NamedBlobManifestStore.Manifest recovered = worker.getPublished(job); + assertEquals(job, recovered.id); + assertEquals(old.getID(), recovered.root); + assertEquals(7L, recovered.version); + assertEquals(ids.subList(0, boundary), worker.read(recovered, 0)); + + try (Connection dirty = db.getConnection()) { + dirty.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); + doReturn(dirty).when(readers).getConnection(); + try { + worker.read(recovered, 0); + fail("A valid header checkout must not authorize a dirty page checkout"); + } catch (IllegalStateException expected) { + assertTrue(expected.getMessage(), expected.getMessage().contains("READ COMMITTED")); + } + assertTrue(dirty.isClosed()); + } + + NamedBlobManifestStore restarted = new NamedBlobManifestStore(db); + NamedBlobManifestStore.Manifest again = restarted.getPublished(job); + assertEquals(job, again.id); + assertEquals(ids.subList(0, boundary), restarted.read(again, 0)); + assertEquals(ids.subList(boundary, ids.size()), restarted.read(again, boundary)); + assertNull(restarted.getPublished(UUID.randomUUID().toString())); + + // A second root can legitimately reference the same child. Both records remain evidence. + String other = stage(named, NAME, 8, replacement, 1, + Collections.singletonList(children.get(0)).iterator()); + assertNotEquals(job, other); + retire(named, Collections.singletonList(other)); + NamedBlobManifestStore.Manifest second = restarted.getPublished(other); + assertEquals(other, second.id); + assertEquals(replacement.getID(), second.root); + assertEquals(Collections.singletonList(ids.get(0)), restarted.read(second, 0)); + assertEquals(2, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1 WHERE publication_key IS NOT NULL")); + + try (Connection c = db.getConnection(); PreparedStatement s = c.prepareStatement( + "UPDATE named_blob_manifest_pages_v1 SET payload=X'00' WHERE manifest_id=? AND first_child=0")) { + s.setString(1, other); + assertEquals(1, s.executeUpdate()); + } + expectDataError("Manifest checksum mismatch", () -> restarted.read(second, 0)); + } + + @Test + public void testDuplicateCaptureReadsBeyondItsSnapshot() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); + insertNamed(db, 1, root, NamedBlobState.READY); + try (Connection loser = db.getConnection(); Statement snapshot = loser.createStatement()) { + loser.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + loser.setAutoCommit(false); + try (ResultSet rows = snapshot.executeQuery("SELECT COUNT(*) FROM named_blob_manifests_v1")) { + assertTrue(rows.next()); + assertEquals(0, rows.getInt(1)); + } + String winner = stage(named, NAME, 1, root, 1, children.iterator()); + assertEquals(winner, NamedBlobManifestStore.capture(loser, ACCOUNT, CONTAINER, NAME, 1, root, 1, + children.iterator())); + expectDataError("Capture retry disagrees", () -> NamedBlobManifestStore.capture(loser, ACCOUNT, CONTAINER, + NAME, 1, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); + loser.rollback(); + } + }); + } + + @Test + public void testMigrationPreservesLegacyTtlUntilRetirement() throws Exception { + BlobId root = blob(BlobId.BlobDataType.METADATA); + withDatabase(db -> { + insertNamed(db, 1, blob(BlobId.BlobDataType.METADATA), NamedBlobState.READY); + insertNamed(db, 2, blob(BlobId.BlobDataType.METADATA), NamedBlobState.IN_PROGRESS); + insertNamed(db, 3, root, NamedBlobState.IN_PROGRESS); + sql(db, "UPDATE named_blobs_v2 SET deleted_ts='2000-01-01'"); + }, (db, named) -> { + NamedBlobRecord newest = NamedBlobRecord.forUpdate("account", "container", NAME, 3); + named.updateBlobTtlAndStateToReady(newest).get(10, TimeUnit.SECONDS); + assertEquals(root.getID(), named.get("account", "container", NAME).get(10, TimeUnit.SECONDS).getBlobId()); + String job = stage(named, NAME, 3, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)) + .iterator()); + retire(named, Collections.singletonList(job)); + try { + named.get("account", "container", NAME).get(10, TimeUnit.SECONDS); + fail("Ordinary GET must report Deleted after retirement"); + } catch (ExecutionException e) { + assertTrue(e.getCause() instanceof RestServiceException); + assertEquals(RestServiceErrorCode.Deleted, ((RestServiceException) e.getCause()).getErrorCode()); + } + NamedBlobRecord deleted = named.get("account", "container", NAME, GetOption.Include_Deleted_Blobs, false) + .get(10, TimeUnit.SECONDS); + assertEquals(root.getID(), deleted.getBlobId()); + assertEquals(3L, deleted.getVersion()); + assertEquals(2, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version<3 AND retirement_fenced=TRUE" + + " AND deleted_ts='2000-01-01'")); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1 WHERE publication_key IS NOT NULL")); + try { + named.updateBlobTtlAndStateToReady(NamedBlobRecord.forUpdate("account", "container", NAME, 2)) + .get(10, TimeUnit.SECONDS); + fail("TTL must not revive fenced history"); + } catch (ExecutionException e) { + assertTrue(e.getCause() instanceof SQLException); + assertEquals("45000", ((SQLException) e.getCause()).getSQLState()); + } + }); + } + + @Test + public void testNameReuseDoesNotConsumeRetirementLimit() throws Exception { + withDatabase((db, named) -> { + for (int version = 1; version <= 33; version++) { + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, version, root, NamedBlobState.READY); + retire(named, Collections.singletonList(stage(named, NAME, version, root, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()))); + } + assertEquals(33, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE retirement_fenced=TRUE")); + }); + } + + @Test + public void testRetirementLocksGapForReplacement() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 7, root, NamedBlobState.READY); + List jobs = Collections.singletonList(stage(named, NAME, 7, root, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); + try (Connection publisher = db.getConnection(); Connection replacement = db.getConnection(); + Statement insert = replacement.createStatement()) { + publisher.setAutoCommit(false); + NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, NAME, jobs); + 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)" + + " VALUES (17,4,'folder/MixedCase',8,X'AB',1)"; + try { + insert.executeUpdate(put); + fail("A new version must wait for retirement"); + } catch (SQLException e) { + assertEquals("InnoDB lock wait timeout", 1205, e.getErrorCode()); + } + publisher.commit(); + assertEquals(1, insert.executeUpdate(put)); + } + retire(named, jobs); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=8 AND retirement_fenced=FALSE" + + " AND deleted_ts IS NULL")); + }); + } + + @Test + public void testPublicationRollsBackWhenNameMutationFails() throws Exception { + withDatabase((db, named) -> { + List jobs = new ArrayList<>(); + for (int version = 1; version <= 2; version++) { + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, version, root, NamedBlobState.READY); + jobs.add(stage(named, NAME, version, root, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); + } + // The transaction mutates these versions in manifest-ID order, not version order. + int lastVersion = jobs.indexOf(Collections.max(jobs)) + 1; + sql(db, "CREATE TRIGGER reject_retirement AFTER UPDATE ON named_blobs_v2 FOR EACH ROW BEGIN" + + " IF NEW.version=" + lastVersion + + " THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='fixture rejection'; END IF; END"); + try { + retire(named, jobs); + fail("Expected mutation to fail"); + } catch (SQLException expected) { + assertEquals("45000", expected.getSQLState()); + assertTrue(expected.getMessage(), expected.getMessage().contains("fixture rejection")); + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1 WHERE publication_key IS NOT NULL")); + assertEquals(2, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE deleted_ts IS NULL" + + " AND retirement_fenced=FALSE")); + sql(db, "DROP TRIGGER reject_retirement"); + retire(named, jobs); + jobs.sort(Collections.reverseOrder()); + try (Connection replay = db.getConnection()) { + replay.setAutoCommit(false); + NamedBlobManifestStore.retire(replay, ACCOUNT, CONTAINER, NAME, jobs); + try { + NamedBlobManifestStore.retire(replay, ACCOUNT, CONTAINER, NAME, Collections.emptyList()); + fail("An empty set is not a publication receipt"); + } catch (IllegalArgumentException expected) { + assertEquals("Invalid number of manifests", expected.getMessage()); + } + replay.commit(); + } + expectDataError("Manifest belongs to a different publication", () -> retire(named, jobs.subList(0, 1))); + }); + } + + @Test + public void testWaitingTtlCannotReviveRetiredVersion() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 7, root, NamedBlobState.READY); + List jobs = Collections.singletonList(stage(named, NAME, 7, root, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); + String ttlSql = "UPDATE named_blobs_v2 SET blob_state=1, deleted_ts=NULL WHERE account_id=17" + + " AND container_id=4 AND blob_name='folder/MixedCase' AND version="; + ExecutorService executor = Executors.newSingleThreadExecutor(); + try (Connection publisher = db.getConnection(); Connection ttl = db.getConnection(); + Statement lock = publisher.createStatement(); Statement update = ttl.createStatement()) { + publisher.setAutoCommit(false); + try (ResultSet rows = lock.executeQuery("SELECT version FROM named_blobs_v2 WHERE account_id=17" + + " AND container_id=4 AND blob_name='folder/MixedCase' FOR UPDATE")) { + assertTrue(rows.next()); + } + long connectionId; + try (ResultSet self = update.executeQuery("SELECT CONNECTION_ID()")) { + assertTrue(self.next()); + connectionId = self.getLong(1); + } + Future blocked = executor.submit(() -> { + try { + update.executeUpdate(ttlSql + "7"); + return "updated"; + } catch (SQLException failure) { + return failure.getSQLState(); + } + }); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (scalar(db, "SELECT COUNT(*) FROM information_schema.processlist WHERE id=" + connectionId + + " 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, jobs); + publisher.commit(); + assertEquals("45000", blocked.get(10, TimeUnit.SECONDS)); + insertNamed(db, 8, blob(BlobId.BlobDataType.METADATA), NamedBlobState.IN_PROGRESS); + sql(db, "UPDATE named_blobs_v2 SET deleted_ts='2000-01-01' WHERE version=8"); + assertEquals(1, update.executeUpdate(ttlSql + "8")); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=7 AND retirement_fenced=TRUE" + + " AND deleted_ts IS NOT NULL")); + } finally { + executor.shutdownNow(); + } + }); + } + + private static void retire(MySqlNamedBlobDb db, List jobs) throws Exception { + try { + db.retireWithManifests("account", "container", NAME, jobs).get(10, TimeUnit.SECONDS); + } catch (ExecutionException e) { + if (e.getCause() instanceof SQLException) { + throw (SQLException) e.getCause(); + } + throw e; + } + } + + private static int scalar(DataSource db, String sql) throws SQLException { + try (Connection c = db.getConnection(); Statement s = c.createStatement(); ResultSet r = s.executeQuery(sql)) { + assertTrue(r.next()); + return r.getInt(1); + } + } + + private static void sql(DataSource db, String sql) throws SQLException { + try (Connection c = db.getConnection(); Statement s = c.createStatement()) { + s.execute(sql); + } + } + + private static MysqlDataSource source(String schema) throws SQLException { + MysqlDataSource db = new MysqlDataSource(); + String port = System.getenv("AMBRY_MANIFEST_TEST_PORT"); + if (port == null) { + // Same loopback MySQL fixture and user as the named-DB integration suite. + db.setUser("travis"); + db.setPassword(""); + } else { + db.setServerName("[::1]"); + db.setPort(Integer.parseInt(port)); + db.setUser("ambry_manifest_test"); + db.setPassword(System.getenv("AMBRY_MANIFEST_TEST_PASSWORD")); + } + db.setDatabaseName(schema); + db.setServerTimezone("UTC"); + return db; + } + + private static void install(Statement statement, String resource) throws SQLException { + InputStream input = NamedBlobManifestStoreIntegrationTest.class.getResourceAsStream(resource); + assertNotNull(resource, input); + try (Scanner ddl = new Scanner(input, "UTF-8")) { + ddl.useDelimiter(resource.endsWith(".sql") ? "\\A" : ";"); + while (ddl.hasNext()) { + String sql = ddl.next().trim(); + if (!sql.isEmpty()) { + statement.execute(sql); + } + } + } + } + + private static BlobId blob(BlobId.BlobDataType type) { + return new BlobId(BlobId.BLOB_ID_V6, BlobId.BlobIdType.NATIVE, (byte) 0, ACCOUNT, CONTAINER, + new MockPartitionId(), false, type); + } + + private static void insertNamed(DataSource db, long version, BlobId root, NamedBlobState state) throws SQLException { + try (Connection c = db.getConnection(); 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); + s.setShort(2, CONTAINER); + s.setString(3, NAME); + s.setLong(4, version); + s.setBytes(5, root.toBytes()); + s.setInt(6, state.ordinal()); + assertEquals(1, s.executeUpdate()); + } + } + + private interface SqlAction { + void run() throws Exception; + } + + private static void expectDataError(String reason, SqlAction action) throws Exception { + try { + action.run(); + fail("Expected rejection: " + reason); + } catch (SQLDataException expected) { + assertTrue(expected.getMessage(), expected.getMessage().startsWith(reason)); + } + } +} 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 1ff933229e..3dd5480e7f 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 @@ -22,6 +22,7 @@ import com.github.ambry.account.Account; import com.github.ambry.account.AccountService; import com.github.ambry.account.Container; +import com.github.ambry.commons.BlobId; import com.github.ambry.commons.Callback; import com.github.ambry.commons.RetryExecutor; import com.github.ambry.commons.RetryPolicies; @@ -33,6 +34,7 @@ import com.github.ambry.protocol.NamedBlobState; import com.github.ambry.rest.RestServiceErrorCode; import com.github.ambry.rest.RestServiceException; +import com.github.ambry.store.StoreKey; import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.Time; import com.github.ambry.utils.Utils; @@ -53,6 +55,7 @@ import java.util.Deque; import java.util.HashSet; import java.util.IdentityHashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -493,6 +496,28 @@ public CompletableFuture updateBlobTtlAndStateToReady(NamedBlobRecord }, null, this.metricsRecoder.namedBlobDBUpdateErrorCount); } + /** Stages descriptors decoded from a single immutable metadata blob without locking or deleting its name. */ + CompletableFuture stageDeleteManifest(String accountName, String containerName, String blobName, long version, + BlobId root, int childCount, Iterator children) { + return executeTransactionAsync(accountName, containerName, false, + (account, container, connection) -> NamedBlobManifestStore.capture(connection, account, container, blobName, + version, root, childCount, children), null, metricsRecoder.namedBlobDBDeleteErrorCount); + } + + /** Publish this exact sealed manifest set atomically with soft retirement. Never returns IDs for a router cascade. */ + CompletableFuture retireWithManifests(String accountName, String containerName, String blobName, + List manifestIds) { + NamedBlobManifestStore.checkManifestCount(manifestIds); + List ids = new ArrayList<>(manifestIds); + return executeTransactionAsync(accountName, containerName, false, (account, container, connection) -> { + if (config.enableHardDelete) { + throw new UnsupportedOperationException("Manifest retirement requires named soft delete"); + } + NamedBlobManifestStore.retire(connection, account, container, blobName, ids); + return null; + }, null, metricsRecoder.namedBlobDBDeleteErrorCount); + } + @Override public CompletableFuture delete(String accountName, String containerName, String blobName) { return executeTransactionAsync(accountName, containerName, false, (accountId, containerId, connection) -> { 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 new file mode 100644 index 0000000000..b241d3d5ef --- /dev/null +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java @@ -0,0 +1,418 @@ +/* + * Copyright 2026 LinkedIn Corp. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package com.github.ambry.named; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLDataException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.TreeSet; +import java.util.UUID; +import javax.sql.DataSource; +import com.github.ambry.commons.BlobId; +import com.github.ambry.protocol.NamedBlobState; +import com.github.ambry.store.StoreKey; + +/** + * Detached evidence for one immutable root at one named version. Seal means that all declared + * descriptors were captured. Neither seal nor inspection grants permission to delete anything. + * The reader data source must consistently supply connections to the same database at READ COMMITTED or stronger. + */ +final class NamedBlobManifestStore { + // V1 page format: up to 64 entries, each an unsigned length byte followed by 1..127 blob ID bytes. + static final int PAGE_SIZE = 64; + private static final int MAX_ID_BYTES = 127; + private static final int MAX_CHILDREN = 131072; + private static final int MAX_VERSIONS = 32; + private static final String HEADS = "named_blob_manifests_v1"; + private static final String PAGES = "named_blob_manifest_pages_v1"; + private static final String COLUMNS = + "manifest_id,account_id,container_id,blob_name,version,root_id,child_count,publication_key"; + private static final String KEY = "account_id=? AND container_id=? AND blob_name=? AND version=?"; + + private final DataSource db; + + NamedBlobManifestStore(DataSource db) { + this.db = Objects.requireNonNull(db, "db"); + } + + private static void requireCommittedReads(Connection c) throws SQLException { + int isolation = c.getTransactionIsolation(); + if (isolation != Connection.TRANSACTION_READ_COMMITTED && isolation != Connection.TRANSACTION_REPEATABLE_READ + && isolation != Connection.TRANSACTION_SERIALIZABLE) { + throw new IllegalStateException("Manifest readers require READ COMMITTED or stronger"); + } + } + + /** + * The caller must supply the ordered descriptors decoded from this exact root, not from a name + * lookup. The live-row check is a nonlocking eligibility check, not a publication or TTL fence. + * A concurrent replacement can leave an unpublished manifest; it cannot redirect its pages. + */ + static String capture(Connection c, short account, short container, String name, long version, BlobId root, int expected, + Iterator descriptors) throws SQLException { + Objects.requireNonNull(root, "root"); + Objects.requireNonNull(descriptors, "descriptors"); + if (name == null || name.isEmpty() || expected < 1 || 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"); + } + if (c.getAutoCommit()) { + throw new IllegalStateException("Capture requires a caller-owned transaction"); + } + byte[] rootBytes = root.toBytes(); + try (PreparedStatement s = c.prepareStatement("SELECT blob_name FROM named_blobs_v2 WHERE " + KEY + + " AND blob_id=? AND blob_state=? AND (deleted_ts IS NULL OR deleted_ts > UTC_TIMESTAMP(6))")) { + bindKey(s, account, container, name, version); + s.setBytes(5, rootBytes); + s.setInt(6, NamedBlobState.READY.ordinal()); + try (ResultSet r = s.executeQuery()) { + // utf8mb4_bin on VARCHAR can compare names equal despite trailing spaces. + if (!r.next() || !name.equals(r.getString(1))) { + throw new SQLDataException("No matching live READY named version"); + } + } + } + + String candidate = UUID.randomUUID().toString(); + try (PreparedStatement s = c.prepareStatement("INSERT INTO " + HEADS + + " (account_id,container_id,blob_name,version,root_id,child_count,manifest_id)" + + " VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE manifest_id=manifest_id")) { + bindKey(s, account, container, name, version); + s.setBytes(5, rootBytes); + s.setInt(6, expected); + s.setString(7, candidate); + s.executeUpdate(); + } + Manifest m; + // The eligibility read may have established a snapshot before a competing capture committed. + try (PreparedStatement s = c.prepareStatement("SELECT " + COLUMNS + " FROM " + HEADS + " WHERE " + KEY + + " FOR UPDATE")) { + bindKey(s, account, container, name, version); + try (ResultSet r = s.executeQuery()) { + if (!r.next()) { + throw new SQLDataException("No manifest for the requested named version"); + } + m = new Manifest(r); + } + } + if (!m.name.equals(name) || !m.root.equals(root.getID()) || m.count != expected) { + throw new SQLDataException("Conflicting manifest for named version"); + } + + boolean creating = candidate.equals(m.id); + try (PreparedStatement insert = c.prepareStatement("INSERT INTO " + PAGES + + " (manifest_id,first_child,payload,page_hash) VALUES (?,?,?,?)")) { + for (int first = 0; first < expected; first += PAGE_SIZE) { + int n = Math.min(PAGE_SIZE, expected - first); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (int i = 0; i < n; i++) { + StoreKey key = descriptors.hasNext() ? descriptors.next() : null; + if (!(key instanceof BlobId) || key.sizeInBytes() < 1 || key.sizeInBytes() > MAX_ID_BYTES) { + throw new SQLDataException("Missing or unsupported child descriptor"); + } + byte[] bytes = key.toBytes(); + if (bytes.length != key.sizeInBytes() || Arrays.equals(bytes, rootBytes)) { + throw new SQLDataException("Invalid child descriptor"); + } + out.write(bytes.length); + out.write(bytes, 0, bytes.length); + } + byte[] body = out.toByteArray(); + if (creating) { + insert.setString(1, m.id); + insert.setInt(2, first); + insert.setBytes(3, body); + insert.setBytes(4, hash(m, first, body)); + insert.executeUpdate(); + } else if (!Arrays.equals(body, readPayload(c, m, first, true))) { + throw new SQLDataException("Capture retry disagrees with sealed page"); + } + } + if (descriptors.hasNext()) { + throw new SQLDataException("More child descriptors than declared"); + } + } + return m.id; + } + + private static void bindKey(PreparedStatement s, short account, short container, String name, long version) + throws SQLException { + s.setInt(1, account); + s.setInt(2, container); + s.setString(3, name); + s.setLong(4, version); + } + + static void checkManifestCount(List ids) { + if (ids == null || ids.isEmpty() || ids.size() > MAX_VERSIONS) { + throw new IllegalArgumentException("Invalid number of manifests"); + } + } + + static List canonicalIds(List ids) { + checkManifestCount(ids); + TreeSet sorted = new TreeSet<>(); + for (String id : ids) { + if (id == null || !UUID.fromString(id).toString().equals(id) || !sorted.add(id)) { + throw new IllegalArgumentException("Expected distinct canonical manifest IDs"); + } + } + return new ArrayList<>(sorted); + } + + static void retire(Connection c, short account, short container, String name, List manifestIds) + throws SQLException { + if (c.getAutoCommit() || c.getTransactionIsolation() != Connection.TRANSACTION_REPEATABLE_READ) { + throw new IllegalStateException("Publication requires an InnoDB REPEATABLE READ transaction"); + } + List ids = canonicalIds(manifestIds); + byte[] receipt = sha256().digest(String.join(",", ids).getBytes(StandardCharsets.US_ASCII)); + Map versions = new LinkedHashMap<>(); + int published = 0; + int totalChildren = 0; + try (PreparedStatement s = c.prepareStatement("SELECT " + COLUMNS + " FROM " + HEADS + + " WHERE manifest_id=? FOR UPDATE")) { + for (String id : ids) { + s.setString(1, id); + try (ResultSet r = s.executeQuery()) { + if (!r.next()) { + throw new SQLDataException("Unknown manifest"); + } + Manifest m = new Manifest(r); + if (!id.equals(m.id) || m.account != account || m.container != container || !m.name.equals(name) + || versions.put(m.version, m) != null) { + throw new SQLDataException("Manifest does not match the requested named version"); + } + if (m.publicationKey != null) { + if (!Arrays.equals(receipt, m.publicationKey)) { + throw new SQLDataException("Manifest belongs to a different publication"); + } + published++; + } + totalChildren += m.count; + } + } + } + // On replay do not even resolve the name: it may already refer to a different root. + if (published == versions.size()) { + return; + } + if (published != 0 || totalChildren > MAX_CHILDREN) { + throw new SQLDataException("Mixed or oversized publication"); + } + for (Manifest m : versions.values()) { + verifySealed(c, m); + } + List history = new ArrayList<>(); + int matches = 0; + // At REPEATABLE READ this range also locks the gap where a new, initially unfenced version must be inserted. + try (PreparedStatement s = c.prepareStatement("SELECT blob_name,version,blob_id,blob_state," + + "(deleted_ts IS NOT NULL AND deleted_ts<=UTC_TIMESTAMP(6)) FROM named_blobs_v2" + + " FORCE INDEX (named_blob_unfenced_versions) WHERE account_id=? AND container_id=? AND blob_name=?" + + " AND retirement_fenced=FALSE ORDER BY version LIMIT ? FOR UPDATE")) { + s.setInt(1, account); + s.setInt(2, container); + s.setString(3, name); + s.setInt(4, MAX_VERSIONS + 1); + try (ResultSet r = s.executeQuery()) { + int rows = 0; + while (r.next()) { + if (++rows > MAX_VERSIONS || !name.equals(r.getString(1))) { + throw new SQLDataException("Unsupported named version range"); + } + Manifest m = versions.get(r.getLong(2)); + if (m == null && r.getBoolean(5)) { + history.add(r.getLong(2)); + continue; + } + if (m == null || r.getInt(4) != NamedBlobState.READY.ordinal() || r.getBoolean(5) + || !m.root.equals(Base64.getUrlEncoder().withoutPadding().encodeToString(r.getBytes(3)))) { + throw new SQLDataException("Unrepresented or ineligible named version"); + } + matches++; + } + } + } + if (matches != versions.size()) { + throw new SQLDataException("Expected named version is absent"); + } + try (PreparedStatement publish = c.prepareStatement("UPDATE " + HEADS + + " SET publication_key=? WHERE manifest_id=? AND publication_key IS NULL"); + PreparedStatement retire = c.prepareStatement("UPDATE named_blobs_v2 SET retirement_fenced=TRUE,deleted_ts=NULL" + + " WHERE retirement_fenced=FALSE AND " + KEY); + PreparedStatement fence = c.prepareStatement("SELECT 1 FROM named_blobs_v2 WHERE retirement_fenced=TRUE" + + " AND deleted_ts<=UTC_TIMESTAMP(6) AND " + KEY + " FOR UPDATE")) { + for (Manifest m : versions.values()) { + publish.setBytes(1, receipt); + publish.setString(2, m.id); + if (publish.executeUpdate() != 1) { + throw new SQLDataException("Cannot publish sealed manifest"); + } + } + // History needs the TTL fence, not a fabricated cleanup manifest. All versions are still locked. + history.addAll(versions.keySet()); + for (long version : history) { + bindKey(retire, account, container, name, version); + bindKey(fence, account, container, name, version); + if (retire.executeUpdate() != 1) { + throw new SQLDataException("Named version is no longer eligible"); + } + // Only the installed fence turns the explicit NULL into a delete timestamp. + try (ResultSet r = fence.executeQuery()) { + if (!r.next()) { + throw new SQLDataException("Named retirement fence is not installed"); + } + } + } + } + } + + private static void verifySealed(Connection c, Manifest m) throws SQLException { + try (PreparedStatement s = c.prepareStatement("SELECT first_child,payload,page_hash FROM " + PAGES + + " WHERE manifest_id=? ORDER BY first_child FOR UPDATE")) { + s.setString(1, m.id); + s.setFetchSize(Integer.MIN_VALUE); // Connector/J streams rows instead of buffering the manifest. + try (ResultSet r = s.executeQuery()) { + int first = 0; + while (r.next()) { + if (first >= m.count || r.getInt(1) != first + || !MessageDigest.isEqual(r.getBytes(3), hash(m, first, r.getBytes(2)))) { + throw new SQLDataException("Invalid sealed page"); + } + first += Math.min(PAGE_SIZE, m.count - first); + } + if (first != m.count) { + throw new SQLDataException("Missing sealed page"); + } + } + } + } + + static final class Manifest { + final String id; + final short account; + final short container; + final String name; + final long version; + final String root; + final int count; + final byte[] publicationKey; + + private Manifest(ResultSet r) throws SQLException { + id = r.getString(1); + account = r.getShort(2); + container = r.getShort(3); + name = r.getString(4); + version = r.getLong(5); + root = Base64.getUrlEncoder().withoutPadding().encodeToString(r.getBytes(6)); + count = r.getInt(7); + publicationKey = r.getBytes(8); + if (count < 1 || count > MAX_CHILDREN) { + throw new SQLDataException("Invalid manifest bounds: " + id); + } + } + } + + /** Recover a known publication without resolving the name. Unknown and unpublished IDs return null. */ + Manifest getPublished(String manifestId) throws SQLException { + String sql = "SELECT " + COLUMNS + " FROM " + HEADS + " WHERE manifest_id=? AND publication_key IS NOT NULL"; + try (Connection c = db.getConnection()) { + requireCommittedReads(c); + try (PreparedStatement s = c.prepareStatement(sql)) { + s.setString(1, Objects.requireNonNull(manifestId, "manifestId")); + try (ResultSet r = s.executeQuery()) { + return r.next() ? new Manifest(r) : null; + } + } + } + } + + /** Read one immutable page; the caller owns any inspection progress. */ + List read(Manifest m, int first) throws SQLException { + byte[] body; + try (Connection c = db.getConnection()) { + requireCommittedReads(c); + body = readPayload(c, m, first, false); + } + ByteBuffer in = ByteBuffer.wrap(body); + int n = Math.min(PAGE_SIZE, m.count - first); + List ids = new ArrayList<>(n); + for (int i = 0; i < n; i++) { + int length = in.hasRemaining() ? Byte.toUnsignedInt(in.get()) : 0; + if (length == 0 || length > MAX_ID_BYTES || length > in.remaining()) { + throw new SQLDataException("Invalid sealed child descriptor"); + } + byte[] bytes = new byte[length]; + in.get(bytes); + ids.add(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)); + } + if (in.hasRemaining()) { + throw new SQLDataException("Trailing bytes on sealed page"); + } + return Collections.unmodifiableList(ids); + } + + private static byte[] readPayload(Connection c, Manifest m, int first, boolean currentRead) throws SQLException { + if (first < 0 || first >= m.count || first % PAGE_SIZE != 0) { + throw new SQLDataException("Invalid manifest page offset"); + } + try (PreparedStatement s = c.prepareStatement( + "SELECT payload,page_hash FROM " + PAGES + " WHERE manifest_id=? AND first_child=?" + + (currentRead ? " FOR UPDATE" : ""))) { + s.setString(1, m.id); + s.setInt(2, first); + try (ResultSet r = s.executeQuery()) { + if (!r.next()) { + throw new SQLDataException("Missing sealed page: " + m.id + "/" + first); + } + byte[] body = r.getBytes(1); + byte[] checksum = r.getBytes(2); + if (!MessageDigest.isEqual(checksum, hash(m, first, body))) { + throw new SQLDataException("Manifest checksum mismatch: " + m.id + "/" + first); + } + return body; + } + } + } + + private static byte[] hash(Manifest m, int first, byte[] body) { + MessageDigest d = sha256(); + byte[] name = m.name.getBytes(StandardCharsets.UTF_8); + d.update(m.id.getBytes(StandardCharsets.US_ASCII)); + d.update(ByteBuffer.allocate(2 * Short.BYTES + Long.BYTES + 3 * Integer.BYTES) + .putShort(m.account).putShort(m.container).putLong(m.version) + .putInt(m.count).putInt(first).putInt(name.length).array()); + d.update(name); + d.update(m.root.getBytes(StandardCharsets.US_ASCII)); + d.update((byte) 0); + return d.digest(body); + } + + private static MessageDigest sha256() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } +} diff --git a/ambry-named-mysql/src/main/resources/NamedBlobManifestV1.ddl b/ambry-named-mysql/src/main/resources/NamedBlobManifestV1.ddl new file mode 100644 index 0000000000..1867754864 --- /dev/null +++ b/ambry-named-mysql/src/main/resources/NamedBlobManifestV1.ddl @@ -0,0 +1,29 @@ +CREATE TABLE named_blob_manifests_v1 ( + manifest_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + account_id INT NOT NULL, + container_id INT NOT NULL, + blob_name VARCHAR(350) NOT NULL, + version BIGINT NOT NULL, + root_id VARBINARY(50) NOT NULL, + child_count INT NOT NULL, + publication_key BINARY(32) DEFAULT NULL, + PRIMARY KEY (manifest_id), + UNIQUE KEY manifest_named_version (account_id, container_id, blob_name, version) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; + +CREATE TABLE named_blob_manifest_pages_v1 ( + manifest_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + first_child INT NOT NULL, + payload VARBINARY(8192) NOT NULL, + page_hash BINARY(32) NOT NULL, + PRIMARY KEY (manifest_id, first_child), + FOREIGN KEY (manifest_id) REFERENCES named_blob_manifests_v1 (manifest_id) +) ENGINE=InnoDB; + +ALTER TABLE named_blobs_v2 + ADD COLUMN retirement_fenced BOOLEAN NOT NULL DEFAULT FALSE, + ALGORITHM=INSTANT; + +ALTER TABLE named_blobs_v2 + ADD INDEX named_blob_unfenced_versions (account_id, container_id, blob_name, retirement_fenced, version), + ALGORITHM=INPLACE, LOCK=NONE; diff --git a/ambry-named-mysql/src/main/resources/NamedBlobRetirementFenceV1.sql b/ambry-named-mysql/src/main/resources/NamedBlobRetirementFenceV1.sql new file mode 100644 index 0000000000..8f158f5337 --- /dev/null +++ b/ambry-named-mysql/src/main/resources/NamedBlobRetirementFenceV1.sql @@ -0,0 +1,20 @@ +CREATE TRIGGER named_blob_retirement_fence_v1 +BEFORE UPDATE ON named_blobs_v2 +FOR EACH ROW +BEGIN + IF OLD.retirement_fenced THEN + IF NEW.deleted_ts IS NULL + OR NEW.retirement_fenced <> OLD.retirement_fenced + OR NEW.account_id <> OLD.account_id + OR NEW.container_id <> OLD.container_id + OR BINARY NEW.blob_name <> BINARY OLD.blob_name + OR NEW.version <> OLD.version + OR NEW.blob_id <> OLD.blob_id + OR NEW.blob_state <> OLD.blob_state THEN + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Named version is durably retired'; + END IF; + SET NEW.deleted_ts = OLD.deleted_ts; + ELSEIF NEW.retirement_fenced THEN + SET NEW.deleted_ts = LEAST(COALESCE(OLD.deleted_ts, UTC_TIMESTAMP(6)), UTC_TIMESTAMP(6)); + END IF; +END 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 new file mode 100644 index 0000000000..4b940f1f6b --- /dev/null +++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java @@ -0,0 +1,54 @@ +/* + * Copyright 2026 LinkedIn Corp. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package com.github.ambry.named; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import javax.sql.DataSource; +import org.junit.Test; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + + +public class NamedBlobManifestStoreTest { + @Test + public void testReaderRejectsDirtyReadsWithoutChangingPoolIsolation() throws SQLException { + DataSource db = mock(DataSource.class); + Connection connection = mock(Connection.class); + when(db.getConnection()).thenReturn(connection); + when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_READ_UNCOMMITTED); + NamedBlobManifestStore store = new NamedBlobManifestStore(db); + verify(db, never()).getConnection(); + try { + store.getPublished("00000000-0000-0000-0000-000000000001"); + fail("A reader could observe a publication that rolls back"); + } catch (IllegalStateException e) { + assertTrue(e.getMessage(), e.getMessage().contains("READ COMMITTED")); + } + verify(connection, never()).setTransactionIsolation(anyInt()); + verify(connection, never()).prepareStatement(anyString()); + verify(connection).close(); + } + + @Test + public void testPublicationUsesADistinctOrderIndependentSet() { + String first = "00000000-0000-0000-0000-000000000001"; + String second = "00000000-0000-0000-0000-000000000002"; + assertEquals(Arrays.asList(first, second), NamedBlobManifestStore.canonicalIds(Arrays.asList(second, first))); + for (List invalid : Arrays.asList(Arrays.asList(first, first), Collections.singletonList("0-0-0-0-1"), + Collections.emptyList())) { + try { + NamedBlobManifestStore.canonicalIds(invalid); + fail("Invalid publication set accepted: " + invalid); + } catch (IllegalArgumentException expected) { + // Reject before acquiring database locks. + } + } + } +} From caff434565cad7f0c7dbd32ad1329f4cdd360efc Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Fri, 27 Nov 2026 09:54:30 -0800 Subject: [PATCH 2/5] Store the ordered named-delete manifest in one exact-version row Use the named version tuple for recovery and reserve it against root substitution. Validate bounded payload size, transaction rollback, locking and restart recovery on MySQL. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ambry-named-mysql/README.md | 47 ++- ...NamedBlobManifestStoreIntegrationTest.java | 283 +++++++++++++--- .../github/ambry/named/MySqlNamedBlobDb.java | 19 +- .../ambry/named/NamedBlobManifestStore.java | 304 +++++++++--------- .../NamedBlobManifestTupleGuardInsertV1.sql | 13 + .../NamedBlobManifestTupleGuardUpdateV1.sql | 16 + .../main/resources/NamedBlobManifestV1.ddl | 15 +- .../named/NamedBlobManifestStoreTest.java | 27 +- 8 files changed, 470 insertions(+), 254 deletions(-) create mode 100644 ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql create mode 100644 ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardUpdateV1.sql diff --git a/ambry-named-mysql/README.md b/ambry-named-mysql/README.md index 372c9915ee..080646e89f 100644 --- a/ambry-named-mysql/README.md +++ b/ambry-named-mysql/README.md @@ -1,13 +1,13 @@ # Named delete manifests -`stageDeleteManifest` stores ordered child IDs from one immutable metadata blob in pages of 64. The caller must supply -descriptors from that exact root. Staging does not lock or retire the name or expose the manifest to recovery readers. -`retireWithManifests` validates the sealed pages and the locked name versions, then publishes the supplied -manifest set in the same transaction that soft-deletes those versions. If the commit outcome is unknown, retry with -the same manifest IDs. Do not resolve the name again or fall back to the router's ordinary delete. - -A reader with a saved manifest ID can look up that published manifest and read its pages by offset after a restart, -without fetching the original root. Configure the reader data source for `READ COMMITTED` or stronger on every checkout. +Each manifest stores the ordered child IDs of one immutable metadata blob in a single MySQL row. Its primary key is +`(account_id, container_id, blob_name, version)`, the same key that identifies the named version. The root ID identifies +the source of the list; repeated child IDs retain their positions. Publication and retirement commit together. If the +commit outcome is unknown, retry the same exact versions, roots and lists. Do not resolve the latest version of the +name or fall back to 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. A pool shared with the publisher must use `REPEATABLE READ`; readers do not change its isolation. Distinct roots can reference the same child; finding its ID does not authorize deletion. @@ -20,7 +20,14 @@ matching manifest and must be READY. An elapsed legacy tombstone or expiry needs preserves its timestamp and fences it against TTL finalization, without publishing cleanup work for it. Fenced rows no longer count toward the limit of 32 unfenced versions per name. A name above that limit, or with an unrepresented live version, fails without changing any row. Exclude such names from rollout until their history has been safely reconciled; -retrying unchanged input will not help. Publication also limits total children to 131,072. +retrying unchanged input will not help. A publication supports at most 262,144 children across its versions (1 TiB at +4 MiB per child). Each descriptor has a one-byte length and at most 127 ID bytes: the largest encoded list is 32 MiB, +which requires `LONGBLOB` rather than `MEDIUMBLOB`. Before enabling publication, round-trip a maximum-size binary +payload through the deployed JDBC connection and check `@@session.max_allowed_packet` on writers and failover targets. +Connector/J 8.0.21 with client-side prepared statements rejected a synthetic 32 MiB body at a 64 MiB packet limit: +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. ## Installing or resuming the migration @@ -49,20 +56,26 @@ mysql --defaults-file="$MYSQL_CNF" --database="$DB" --init-command='SET SESSION < NamedBlobManifestV1.ddl mysql --defaults-file="$DEFINER_CNF" --database="$DB" --init-command='SET SESSION lock_wait_timeout=5' \ --delimiter='//' -e 'SOURCE NamedBlobRetirementFenceV1.sql' +mysql --defaults-file="$DEFINER_CNF" --database="$DB" --init-command='SET SESSION lock_wait_timeout=5' \ + --delimiter='//' -e 'SOURCE NamedBlobManifestTupleGuardInsertV1.sql' +mysql --defaults-file="$DEFINER_CNF" --database="$DB" --init-command='SET SESSION lock_wait_timeout=5' \ + --delimiter='//' -e 'SOURCE NamedBlobManifestTupleGuardUpdateV1.sql' mysql --defaults-file="$DEFINER_CNF" --database="$DB" -e 'SHOW CREATE TRIGGER named_blob_retirement_fence_v1\G' ``` -The delimiter keeps the compound trigger intact in the mysql client; JDBC installers send the entire trigger file as -one statement. Verify the installed `BEFORE UPDATE` body and the exact `DEFINER` on each writer and before promotion. +The delimiter keeps each compound trigger intact in the mysql client; JDBC installers send each trigger file as +one statement. Verify all three trigger bodies and definers. The tuple guards need locking-read privileges on +`named_blob_manifests_v1`; rehearse using the deployed MySQL version and roles. Every insert checks the manifest +primary key, even when no caller is enabled. Rehearse normal PUT concurrency and watch lock waits before rollout. On each writer, connect **as the application account** and smoke-test an unfenced update: in one transaction, insert an approved disposable named version, finalize its TTL using its exact primary key, verify one row changed to READY with `deleted_ts IS NULL`, and roll back. Verify the fixture row is absent afterward. Do not use a customer row. Stop on any error; a successful install by the DDL operator is not evidence that application writes still work. **On any error or lost connection, do not rerun the file.** Each successful DDL statement has already committed. -Wait for any in-flight DDL to finish. Inspect `SHOW CREATE TABLE` for both manifest tables and `named_blobs_v2`, and -`SHOW CREATE TRIGGER` if the trigger exists. Compare definitions in installation order: manifest header table, page -table and foreign key, fence column, ordered unfenced-version index, then trigger and definer. Stop on any conflicting +Wait for any in-flight DDL to finish. Inspect `SHOW CREATE TABLE` for the manifest table and `named_blobs_v2`, and +`SHOW CREATE TRIGGER` if the trigger exists. Compare definitions in installation order: manifest table and composite +primary key, fence column, ordered unfenced-version index, then trigger and definer. Stop on any conflicting definition. Fix the cause, resume at the first missing statement using the timeout above, and run only the missing steps in order. An index build can finish scanning the table and still time out waiting for its final metadata lock. If the column exists but the index does not, have the owners finish any long-running transactions holding the lock @@ -77,13 +90,13 @@ The database operations alone are not safe to activate. In addition to the DELET 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. - Before permitting failover, verify each promotion candidate has applied all acknowledged retirement transactions - (receipts, pages and fenced rows), not just the schema and trigger. Do not promote or serve from a candidate whose + (manifest rows and fenced named versions), not just the schema and trigger. Do not promote or serve from a candidate whose applied position cannot be proven sufficient. - 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. -- Give the worker indexed discovery of committed publications or durably record the exact manifest IDs before - retirement. A process-local list of IDs is lost on restart; a saved ID is actionable only after publication. +- Give the worker indexed discovery of committed publications or durably record the exact tuples before retirement. + A process-local list is lost on restart; a saved tuple is actionable only after publication. Before staging the first manifest, route all frontend and direct named DELETE callers away from legacy DELETE for the enabled namespace, or reject those requests. Also exclude its account or container from `NamedBlobsCleanupRunner` on 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 cc8ff36c83..92ff78a81b 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 @@ -50,6 +50,8 @@ public class NamedBlobManifestStoreIntegrationTest { private static final short ACCOUNT = 17; private static final short CONTAINER = 4; private static final String NAME = "folder/MixedCase"; + // The declared per-manifest and aggregate-publish child cap; exercised at full scale below. + private static final int MAX_CHILDREN = 262_144; @Test public void testDetachedRecoveryAcrossReplacement() throws Exception { @@ -83,6 +85,8 @@ private static void withDatabase(BeforeMigration before, Scenario scenario) thro } install(ddl, "/NamedBlobManifestV1.ddl"); install(ddl, "/NamedBlobRetirementFenceV1.sql"); + install(ddl, "/NamedBlobManifestTupleGuardInsertV1.sql"); + install(ddl, "/NamedBlobManifestTupleGuardUpdateV1.sql"); } try (MySqlNamedBlobDb named = namedDb(db)) { scenario.run(db, named); @@ -106,11 +110,12 @@ private static MySqlNamedBlobDb namedDb(DataSource db) throws Exception { endpoint -> db, "local", new Metrics(new MetricRegistry(), "")); } - private static String stage(MySqlNamedBlobDb db, String name, long version, BlobId root, int count, + /** Stage descriptors for one named version; the sealed row is keyed only by the (account, container, name, + * version) tuple, so nothing is returned to identify it afterward. */ + private static void stage(MySqlNamedBlobDb db, String name, long version, BlobId root, int count, Iterator children) throws Exception { try { - return db.stageDeleteManifest("account", "container", name, version, root, count, children) - .get(10, TimeUnit.SECONDS); + db.stageDeleteManifest("account", "container", name, version, root, count, children).get(10, TimeUnit.SECONDS); } catch (ExecutionException e) { if (e.getCause() instanceof SQLDataException) { throw (SQLDataException) e.getCause(); @@ -123,11 +128,10 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep BlobId old = blob(BlobId.BlobDataType.METADATA); BlobId replacement = blob(BlobId.BlobDataType.METADATA); List children = new ArrayList<>(); - for (int i = 0; i <= NamedBlobManifestStore.PAGE_SIZE; i++) { + for (int i = 0; i < 65; i++) { children.add(blob(BlobId.BlobDataType.DATACHUNK)); } List ids = children.stream().map(BlobId::getID).collect(Collectors.toList()); - int boundary = NamedBlobManifestStore.PAGE_SIZE; insertNamed(db, 7, old, NamedBlobState.READY); insertNamed(db, 8, replacement, NamedBlobState.IN_PROGRESS); NamedBlobManifestStore writer = new NamedBlobManifestStore(db); @@ -139,22 +143,23 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep expectDataError("No matching live READY", () -> stage(named, NAME, 7, replacement, children.size(), children.iterator())); expectDataError("Missing or unsupported child", () -> - stage(named, NAME, 7, old, children.size(), children.subList(0, boundary).iterator())); + stage(named, NAME, 7, old, children.size(), children.subList(0, children.size() - 1).iterator())); assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); - String job = stage(named, NAME, 7, old, children.size(), children.iterator()); - assertEquals(job, stage(named, NAME, 7, old, children.size(), children.iterator())); + stage(named, NAME, 7, old, children.size(), children.iterator()); + // A retry against the already-sealed row is idempotent: it must not re-seal or fail. + stage(named, NAME, 7, old, children.size(), children.iterator()); List reordered = new ArrayList<>(children); Collections.swap(reordered, 0, 1); expectDataError("Capture retry disagrees", () -> stage(named, NAME, 7, old, reordered.size(), reordered.iterator())); - assertNull("Staging alone does not publish work", writer.getPublished(job)); - expectDataError("Unrepresented or ineligible", () -> retire(named, Collections.singletonList(job))); + assertNull("Staging alone does not publish work", writer.getPublished(ACCOUNT, CONTAINER, NAME, 7)); + expectDataError("Unrepresented or ineligible", () -> retire(named, Collections.singletonList(7L))); sql(db, "DELETE FROM named_blobs_v2 WHERE version=8"); - retire(named, Collections.singletonList(job)); + retire(named, Collections.singletonList(7L)); insertNamed(db, 8, replacement, NamedBlobState.READY); - retire(named, Collections.singletonList(job)); + retire(named, Collections.singletonList(7L)); 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( @@ -173,18 +178,18 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep return c; }); NamedBlobManifestStore worker = new NamedBlobManifestStore(readers); - NamedBlobManifestStore.Manifest recovered = worker.getPublished(job); - assertEquals(job, recovered.id); + NamedBlobManifestStore.Manifest recovered = worker.getPublished(ACCOUNT, CONTAINER, NAME, 7); assertEquals(old.getID(), recovered.root); assertEquals(7L, recovered.version); - assertEquals(ids.subList(0, boundary), worker.read(recovered, 0)); + // The worker recovered the exact tuple without resolving the name or reading the original root. + assertEquals(ids, worker.read(recovered)); try (Connection dirty = db.getConnection()) { dirty.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); doReturn(dirty).when(readers).getConnection(); try { - worker.read(recovered, 0); - fail("A valid header checkout must not authorize a dirty page checkout"); + worker.read(recovered); + fail("A valid header checkout must not authorize a dirty payload checkout"); } catch (IllegalStateException expected) { assertTrue(expected.getMessage(), expected.getMessage().contains("READ COMMITTED")); } @@ -192,29 +197,31 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep } NamedBlobManifestStore restarted = new NamedBlobManifestStore(db); - NamedBlobManifestStore.Manifest again = restarted.getPublished(job); - assertEquals(job, again.id); - assertEquals(ids.subList(0, boundary), restarted.read(again, 0)); - assertEquals(ids.subList(boundary, ids.size()), restarted.read(again, boundary)); - assertNull(restarted.getPublished(UUID.randomUUID().toString())); - - // A second root can legitimately reference the same child. Both records remain evidence. - String other = stage(named, NAME, 8, replacement, 1, - Collections.singletonList(children.get(0)).iterator()); - assertNotEquals(job, other); - retire(named, Collections.singletonList(other)); - NamedBlobManifestStore.Manifest second = restarted.getPublished(other); - assertEquals(other, second.id); + NamedBlobManifestStore.Manifest again = restarted.getPublished(ACCOUNT, CONTAINER, NAME, 7); + assertEquals(ids, restarted.read(again)); + assertNull(restarted.getPublished(ACCOUNT, CONTAINER, NAME, 999)); + assertNull(restarted.getPublished(ACCOUNT, CONTAINER, NAME + " ", 7)); + + // A second root can legitimately reference the same child. Both rows remain evidence, each keyed by its + // own tuple: a worker that saved (name, version=8) trusts that row directly, independent of the root at + // version 7 or any other version. + stage(named, NAME, 8, replacement, 1, Collections.singletonList(children.get(0)).iterator()); + retire(named, Collections.singletonList(8L)); + NamedBlobManifestStore.Manifest second = restarted.getPublished(ACCOUNT, CONTAINER, NAME, 8); assertEquals(replacement.getID(), second.root); - assertEquals(Collections.singletonList(ids.get(0)), restarted.read(second, 0)); + assertEquals(Collections.singletonList(ids.get(0)), restarted.read(second)); assertEquals(2, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1 WHERE publication_key IS NOT NULL")); try (Connection c = db.getConnection(); PreparedStatement s = c.prepareStatement( - "UPDATE named_blob_manifest_pages_v1 SET payload=X'00' WHERE manifest_id=? AND first_child=0")) { - s.setString(1, other); + "UPDATE named_blob_manifests_v1 SET payload=X'00' WHERE account_id=? AND container_id=? AND blob_name=?" + + " AND version=?")) { + s.setShort(1, ACCOUNT); + s.setShort(2, CONTAINER); + s.setString(3, NAME); + s.setLong(4, 8); assertEquals(1, s.executeUpdate()); } - expectDataError("Manifest checksum mismatch", () -> restarted.read(second, 0)); + expectDataError("Manifest checksum mismatch", () -> restarted.read(second)); } @Test @@ -230,9 +237,10 @@ public void testDuplicateCaptureReadsBeyondItsSnapshot() throws Exception { assertTrue(rows.next()); assertEquals(0, rows.getInt(1)); } - String winner = stage(named, NAME, 1, root, 1, children.iterator()); - assertEquals(winner, NamedBlobManifestStore.capture(loser, ACCOUNT, CONTAINER, NAME, 1, root, 1, - children.iterator())); + stage(named, NAME, 1, root, 1, children.iterator()); + // A racer whose snapshot predates the winner's commit must still see the sealed row when it checks out + // the row FOR UPDATE: that read is not snapshot-isolated, so the retry is idempotent rather than blind. + NamedBlobManifestStore.capture(loser, ACCOUNT, CONTAINER, NAME, 1, root, 1, children.iterator()); expectDataError("Capture retry disagrees", () -> NamedBlobManifestStore.capture(loser, ACCOUNT, CONTAINER, NAME, 1, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); loser.rollback(); @@ -252,9 +260,8 @@ public void testMigrationPreservesLegacyTtlUntilRetirement() throws Exception { NamedBlobRecord newest = NamedBlobRecord.forUpdate("account", "container", NAME, 3); named.updateBlobTtlAndStateToReady(newest).get(10, TimeUnit.SECONDS); assertEquals(root.getID(), named.get("account", "container", NAME).get(10, TimeUnit.SECONDS).getBlobId()); - String job = stage(named, NAME, 3, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)) - .iterator()); - retire(named, Collections.singletonList(job)); + stage(named, NAME, 3, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); + retire(named, Collections.singletonList(3L)); try { named.get("account", "container", NAME).get(10, TimeUnit.SECONDS); fail("Ordinary GET must report Deleted after retirement"); @@ -286,8 +293,9 @@ public void testNameReuseDoesNotConsumeRetirementLimit() throws Exception { for (int version = 1; version <= 33; version++) { BlobId root = blob(BlobId.BlobDataType.METADATA); insertNamed(db, version, root, NamedBlobState.READY); - retire(named, Collections.singletonList(stage(named, NAME, version, root, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()))); + stage(named, NAME, version, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)) + .iterator()); + retire(named, Collections.singletonList((long) version)); } assertEquals(33, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE retirement_fenced=TRUE")); }); @@ -298,8 +306,8 @@ public void testRetirementLocksGapForReplacement() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); insertNamed(db, 7, root, NamedBlobState.READY); - List jobs = Collections.singletonList(stage(named, NAME, 7, root, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); + stage(named, NAME, 7, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); + List jobs = Collections.singletonList(7L); try (Connection publisher = db.getConnection(); Connection replacement = db.getConnection(); Statement insert = replacement.createStatement()) { publisher.setAutoCommit(false); @@ -325,15 +333,17 @@ public void testRetirementLocksGapForReplacement() throws Exception { @Test public void testPublicationRollsBackWhenNameMutationFails() throws Exception { withDatabase((db, named) -> { - List jobs = new ArrayList<>(); + List jobs = new ArrayList<>(); for (int version = 1; version <= 2; version++) { BlobId root = blob(BlobId.BlobDataType.METADATA); insertNamed(db, version, root, NamedBlobState.READY); - jobs.add(stage(named, NAME, version, root, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); + stage(named, NAME, version, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)) + .iterator()); + jobs.add((long) version); } - // The transaction mutates these versions in manifest-ID order, not version order. - int lastVersion = jobs.indexOf(Collections.max(jobs)) + 1; + // Publication processes the canonical (ascending-by-version) order; make the trigger fail on the last + // version in that order so the test still proves the earlier publish within the same transaction rolls back. + long lastVersion = Collections.max(jobs); sql(db, "CREATE TRIGGER reject_retirement AFTER UPDATE ON named_blobs_v2 FOR EACH ROW BEGIN" + " IF NEW.version=" + lastVersion + " THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='fixture rejection'; END IF; END"); @@ -370,8 +380,8 @@ public void testWaitingTtlCannotReviveRetiredVersion() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); insertNamed(db, 7, root, NamedBlobState.READY); - List jobs = Collections.singletonList(stage(named, NAME, 7, root, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); + stage(named, NAME, 7, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); + List jobs = Collections.singletonList(7L); String ttlSql = "UPDATE named_blobs_v2 SET blob_state=1, deleted_ts=NULL WHERE account_id=17" + " AND container_id=4 AND blob_name='folder/MixedCase' AND version="; ExecutorService executor = Executors.newSingleThreadExecutor(); @@ -414,9 +424,176 @@ public void testWaitingTtlCannotReviveRetiredVersion() throws Exception { }); } - private static void retire(MySqlNamedBlobDb db, List jobs) throws Exception { + /** + * The concretely reported gap: capture/retire only re-validate root and count when {@code capture} itself is + * called again. Neither fences a direct SQL write to named_blobs_v2, so once a cleanup job physically removes + * the retired row, nothing used to stop a fresh INSERT from rebinding the same tuple to a different root while + * the published manifest still names the original. Also confirms what must still be permitted: recreating the + * identical row, and writing an entirely different version, are both untouched by the guard. + */ + @Test + public void testDirectReinsertAfterPhysicalRemovalRejectsDifferentRoot() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId impostor = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 7, root, NamedBlobState.READY); + stage(named, NAME, 7, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); + retire(named, Collections.singletonList(7L)); + sql(db, "DELETE FROM named_blobs_v2 WHERE version=7"); + + expectSqlRejection("Named tuple already has a manifest for a different root", + () -> insertNamed(db, 7, impostor, NamedBlobState.READY)); + + // Recreating the exact same row the manifest already names is the documented recovery path and must + // still work after the guard rejects an impostor for the same tuple. + insertNamed(db, 7, root, NamedBlobState.READY); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=7 AND blob_id=X'" + + bytesToHex(root.toBytes()) + "'")); + // A different version was never part of this manifest's key and must be entirely unaffected. + insertNamed(db, 9, impostor, NamedBlobState.READY); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=9 AND blob_id=X'" + + bytesToHex(impostor.toBytes()) + "'")); + }); + } + + /** + * Same prohibition, reached through UPDATE instead of INSERT: a direct rebind of blob_id while the row is still + * live (not yet purged, not even retired) must be rejected exactly like the post-purge INSERT case, while an + * ordinary state-only update (the TTL path) is untouched. + */ + @Test + public void testDirectUpdateRejectsDifferentRootWhileManifestExists() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId impostor = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 7, root, NamedBlobState.READY); + stage(named, NAME, 7, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); + + expectSqlRejection("Named tuple already has a manifest for a different root", () -> { + try (Connection c = db.getConnection(); PreparedStatement s = c.prepareStatement( + "UPDATE named_blobs_v2 SET blob_id=? WHERE account_id=? AND container_id=? AND blob_name=? AND version=7")) { + s.setBytes(1, impostor.toBytes()); + s.setShort(2, ACCOUNT); + s.setShort(3, CONTAINER); + s.setString(4, NAME); + s.executeUpdate(); + } + }); + + // An ordinary state-only update (no blob_id change) never consults the manifest table and must still work. + sql(db, "UPDATE named_blobs_v2 SET blob_state=" + NamedBlobState.READY.ordinal() + " WHERE version=7"); + retire(named, Collections.singletonList(7L)); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=7 AND retirement_fenced=TRUE")); + }); + } + + /** + * The actual race the guard exists for: a capture that has reserved (but not yet committed) a manifest row must + * block a concurrent direct replace for the same tuple, not merely a replace that starts after capture commits. + */ + @Test + public void testConcurrentInFlightCaptureBlocksRacingDirectReplace() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId impostor = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 7, root, NamedBlobState.READY); + try (Connection capturing = db.getConnection(); Connection replacing = db.getConnection(); + Statement replace = replacing.createStatement()) { + capturing.setAutoCommit(false); + // Reserve the manifest row without committing: this is the in-flight window the guard must defend. + NamedBlobManifestStore.capture(capturing, ACCOUNT, CONTAINER, NAME, 7, root, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); + + replace.execute("SET SESSION innodb_lock_wait_timeout=1"); + try { + replace.executeUpdate("DELETE FROM named_blobs_v2 WHERE version=7"); + fail("Purge must wait for an in-flight capture"); + } catch (SQLException blocked) { + assertEquals(1205, blocked.getErrorCode()); + } + capturing.commit(); + replace.executeUpdate("DELETE FROM named_blobs_v2 WHERE version=7"); + try { + insertNamed(db, 7, impostor, NamedBlobState.READY); + fail("A committed reservation must reject replacement"); + } catch (SQLException conflict) { + assertEquals("45000", conflict.getSQLState()); + } + } + // After capture's committed root loses the race to no one, the same tuple can still be recreated with the + // root the manifest actually names. + sql(db, "DELETE FROM named_blobs_v2 WHERE version=7"); + insertNamed(db, 7, root, NamedBlobState.READY); + retire(named, Collections.singletonList(7L)); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=7 AND retirement_fenced=TRUE")); + }); + } + + private static String bytesToHex(byte[] bytes) { + StringBuilder sb = new StringBuilder(bytes.length * 2); + for (byte b : bytes) { + sb.append(String.format("%02X", b)); + } + return sb.toString(); + } + + private static void expectSqlRejection(String reason, SqlAction action) throws Exception { + try { + action.run(); + fail("Expected rejection: " + reason); + } catch (SQLException expected) { + assertEquals("45000", expected.getSQLState()); + assertTrue(expected.getMessage(), expected.getMessage().contains(reason)); + } + } + + /** + * Captures, publishes and reads back the declared cap of real child descriptors in a single manifest row, and + * asserts the full ordered list survives exactly, under the same JDBC settings as every other case in this suite + * (no streaming fetch size, no paging). Check the stored byte length as well as the decoded IDs. + */ + @Test + public void testFullScaleManifestRoundTripAtTheDeclaredChildCap() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 1, root, NamedBlobState.READY); + List children = new ArrayList<>(MAX_CHILDREN); + for (int i = 0; i < MAX_CHILDREN; i++) { + children.add(blob(BlobId.BlobDataType.DATACHUNK)); + } + List ids = children.stream().map(BlobId::getID).collect(Collectors.toList()); + + stage(named, NAME, 1, root, children.size(), children.iterator()); + retire(named, Collections.singletonList(1L)); + + NamedBlobManifestStore worker = new NamedBlobManifestStore(db); + NamedBlobManifestStore.Manifest manifest = worker.getPublished(ACCOUNT, CONTAINER, NAME, 1); + assertEquals(MAX_CHILDREN, manifest.count); + + List recovered = worker.read(manifest); + + assertEquals(ids, recovered); + assertEquals(children.stream().mapToInt(child -> 1 + child.sizeInBytes()).sum(), + scalar(db, "SELECT OCTET_LENGTH(payload) FROM named_blob_manifests_v1")); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1 WHERE publication_key IS NOT NULL")); + }); + } + + /** One more than the declared cap must be rejected immediately, before any descriptor is read or any row written. */ + @Test + public void testCaptureRejectsOneMoreThanTheDeclaredChildCap() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 1, root, NamedBlobState.READY); + expectDataError("Unsupported named composite capture", () -> + stage(named, NAME, 1, root, MAX_CHILDREN + 1, Collections.emptyIterator())); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + }); + } + + private static void retire(MySqlNamedBlobDb db, List versions) throws Exception { try { - db.retireWithManifests("account", "container", NAME, jobs).get(10, TimeUnit.SECONDS); + db.retireWithManifests("account", "container", NAME, versions).get(10, TimeUnit.SECONDS); } catch (ExecutionException e) { if (e.getCause() instanceof SQLException) { throw (SQLException) e.getCause(); 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 3dd5480e7f..211490a39c 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 @@ -496,24 +496,25 @@ public CompletableFuture updateBlobTtlAndStateToReady(NamedBlobRecord }, null, this.metricsRecoder.namedBlobDBUpdateErrorCount); } - /** Stages descriptors decoded from a single immutable metadata blob without locking or deleting its name. */ - CompletableFuture stageDeleteManifest(String accountName, String containerName, String blobName, long version, + /** Stage descriptors for the exact live root without retiring its named version. */ + CompletableFuture stageDeleteManifest(String accountName, String containerName, String blobName, long version, BlobId root, int childCount, Iterator children) { - return executeTransactionAsync(accountName, containerName, false, - (account, container, connection) -> NamedBlobManifestStore.capture(connection, account, container, blobName, - version, root, childCount, children), null, metricsRecoder.namedBlobDBDeleteErrorCount); + return executeTransactionAsync(accountName, containerName, false, (account, container, connection) -> { + NamedBlobManifestStore.capture(connection, account, container, blobName, version, root, childCount, children); + return null; + }, null, metricsRecoder.namedBlobDBDeleteErrorCount); } /** Publish this exact sealed manifest set atomically with soft retirement. Never returns IDs for a router cascade. */ CompletableFuture retireWithManifests(String accountName, String containerName, String blobName, - List manifestIds) { - NamedBlobManifestStore.checkManifestCount(manifestIds); - List ids = new ArrayList<>(manifestIds); + List manifestVersions) { + NamedBlobManifestStore.checkManifestCount(manifestVersions); + List versions = new ArrayList<>(manifestVersions); return executeTransactionAsync(accountName, containerName, false, (account, container, connection) -> { if (config.enableHardDelete) { throw new UnsupportedOperationException("Manifest retirement requires named soft delete"); } - NamedBlobManifestStore.retire(connection, account, container, blobName, ids); + NamedBlobManifestStore.retire(connection, account, container, blobName, versions); return null; }, null, metricsRecoder.namedBlobDBDeleteErrorCount); } 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 b241d3d5ef..b11c60a613 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.Map; import java.util.Objects; import java.util.TreeSet; -import java.util.UUID; +import java.util.stream.Collectors; import javax.sql.DataSource; import com.github.ambry.commons.BlobId; import com.github.ambry.protocol.NamedBlobState; @@ -34,17 +34,21 @@ * Detached evidence for one immutable root at one named version. Seal means that all declared * descriptors were captured. Neither seal nor inspection grants permission to delete anything. * The reader data source must consistently supply connections to the same database at READ COMMITTED or stronger. + * + *

Each named version has exactly one row, keyed by the same {@code (account_id, container_id, blob_name, + * version)} tuple that identifies it in {@code named_blobs_v2}. The ordered child list is stored as that row's own + * payload; there is no surrogate manifest ID and no separate page table. A worker that has saved the exact tuple can + * recover the published list directly, without resolving the latest version or fetching the original root. */ final class NamedBlobManifestStore { - // V1 page format: up to 64 entries, each an unsigned length byte followed by 1..127 blob ID bytes. - static final int PAGE_SIZE = 64; + // Length-prefixed child descriptors: an unsigned length byte followed by 1..127 blob ID bytes, repeated for every + // declared child. The maximum encoded body is 32 MiB before driver and protocol overhead. private static final int MAX_ID_BYTES = 127; - private static final int MAX_CHILDREN = 131072; + private static final int MAX_CHILDREN = 262144; private static final int MAX_VERSIONS = 32; - private static final String HEADS = "named_blob_manifests_v1"; - private static final String PAGES = "named_blob_manifest_pages_v1"; - private static final String COLUMNS = - "manifest_id,account_id,container_id,blob_name,version,root_id,child_count,publication_key"; + private static final String TABLE = "named_blob_manifests_v1"; + private static final String HEADER_COLUMNS = + "account_id,container_id,blob_name,version,root_id,child_count,publication_key"; private static final String KEY = "account_id=? AND container_id=? AND blob_name=? AND version=?"; private final DataSource db; @@ -64,9 +68,9 @@ private static void requireCommittedReads(Connection c) throws SQLException { /** * The caller must supply the ordered descriptors decoded from this exact root, not from a name * lookup. The live-row check is a nonlocking eligibility check, not a publication or TTL fence. - * A concurrent replacement can leave an unpublished manifest; it cannot redirect its pages. + * A concurrent replacement can leave an unpublished manifest row; it cannot redirect it to a different root. */ - static String capture(Connection c, short account, short container, String name, long version, BlobId root, int expected, + static void capture(Connection c, short account, short container, String name, long version, BlobId root, int expected, Iterator descriptors) throws SQLException { Objects.requireNonNull(root, "root"); Objects.requireNonNull(descriptors, "descriptors"); @@ -81,7 +85,7 @@ static String capture(Connection c, short account, short container, String name, } byte[] rootBytes = root.toBytes(); try (PreparedStatement s = c.prepareStatement("SELECT blob_name FROM named_blobs_v2 WHERE " + KEY - + " AND blob_id=? AND blob_state=? AND (deleted_ts IS NULL OR deleted_ts > UTC_TIMESTAMP(6))")) { + + " AND blob_id=? AND blob_state=? AND (deleted_ts IS NULL OR deleted_ts > UTC_TIMESTAMP(6)) FOR UPDATE")) { bindKey(s, account, container, name, version); s.setBytes(5, rootBytes); s.setInt(6, NamedBlobState.READY.ordinal()); @@ -93,116 +97,133 @@ static String capture(Connection c, short account, short container, String name, } } - String candidate = UUID.randomUUID().toString(); - try (PreparedStatement s = c.prepareStatement("INSERT INTO " + HEADS - + " (account_id,container_id,blob_name,version,root_id,child_count,manifest_id)" - + " VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE manifest_id=manifest_id")) { + // Reserve the row without touching an existing payload: a concurrent racer for the same tuple must observe + // whatever this statement establishes, not silently reset a sealed manifest. + try (PreparedStatement s = c.prepareStatement("INSERT INTO " + TABLE + + " (account_id,container_id,blob_name,version,root_id,child_count)" + + " VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE account_id=account_id")) { bindKey(s, account, container, name, version); s.setBytes(5, rootBytes); s.setInt(6, expected); - s.setString(7, candidate); s.executeUpdate(); } Manifest m; + byte[] existingPayload; // The eligibility read may have established a snapshot before a competing capture committed. - try (PreparedStatement s = c.prepareStatement("SELECT " + COLUMNS + " FROM " + HEADS + " WHERE " + KEY - + " FOR UPDATE")) { + try (PreparedStatement s = c.prepareStatement( + "SELECT " + HEADER_COLUMNS + ",payload FROM " + TABLE + " WHERE " + KEY + " FOR UPDATE")) { bindKey(s, account, container, name, version); try (ResultSet r = s.executeQuery()) { if (!r.next()) { throw new SQLDataException("No manifest for the requested named version"); } m = new Manifest(r); + existingPayload = r.getBytes(8); } } if (!m.name.equals(name) || !m.root.equals(root.getID()) || m.count != expected) { + // A residual row for a different root must never be mistaken for this capture: the tuple cannot be reused + // for a different root while any manifest or cleanup job may still depend on the original. throw new SQLDataException("Conflicting manifest for named version"); } - boolean creating = candidate.equals(m.id); - try (PreparedStatement insert = c.prepareStatement("INSERT INTO " + PAGES - + " (manifest_id,first_child,payload,page_hash) VALUES (?,?,?,?)")) { - for (int first = 0; first < expected; first += PAGE_SIZE) { - int n = Math.min(PAGE_SIZE, expected - first); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for (int i = 0; i < n; i++) { - StoreKey key = descriptors.hasNext() ? descriptors.next() : null; - if (!(key instanceof BlobId) || key.sizeInBytes() < 1 || key.sizeInBytes() > MAX_ID_BYTES) { - throw new SQLDataException("Missing or unsupported child descriptor"); - } - byte[] bytes = key.toBytes(); - if (bytes.length != key.sizeInBytes() || Arrays.equals(bytes, rootBytes)) { - throw new SQLDataException("Invalid child descriptor"); - } - out.write(bytes.length); - out.write(bytes, 0, bytes.length); - } - byte[] body = out.toByteArray(); - if (creating) { - insert.setString(1, m.id); - insert.setInt(2, first); - insert.setBytes(3, body); - insert.setBytes(4, hash(m, first, body)); - insert.executeUpdate(); - } else if (!Arrays.equals(body, readPayload(c, m, first, true))) { - throw new SQLDataException("Capture retry disagrees with sealed page"); + byte[] body = encode(descriptors, expected, rootBytes); + if (existingPayload == null) { + try (PreparedStatement update = c.prepareStatement( + "UPDATE " + TABLE + " SET payload=?,payload_hash=? WHERE " + KEY + " AND payload IS NULL")) { + update.setBytes(1, body); + update.setBytes(2, hash(account, container, name, version, m.count, m.root, body)); + bindKey(update, account, container, name, version, 3); + if (update.executeUpdate() != 1) { + throw new SQLDataException("Concurrent capture already sealed this manifest"); } } - if (descriptors.hasNext()) { - throw new SQLDataException("More child descriptors than declared"); + } else if (!Arrays.equals(body, existingPayload)) { + throw new SQLDataException("Capture retry disagrees with sealed manifest"); + } + } + + private static byte[] encode(Iterator descriptors, int expected, byte[] rootBytes) + throws SQLException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (int i = 0; i < expected; i++) { + StoreKey key = descriptors.hasNext() ? descriptors.next() : null; + if (!(key instanceof BlobId) || key.sizeInBytes() < 1 || key.sizeInBytes() > MAX_ID_BYTES) { + throw new SQLDataException("Missing or unsupported child descriptor"); + } + byte[] bytes = key.toBytes(); + if (bytes.length != key.sizeInBytes() || Arrays.equals(bytes, rootBytes)) { + throw new SQLDataException("Invalid child descriptor"); } + out.write(bytes.length); + out.write(bytes, 0, bytes.length); } - return m.id; + if (descriptors.hasNext()) { + throw new SQLDataException("More child descriptors than declared"); + } + return out.toByteArray(); } private static void bindKey(PreparedStatement s, short account, short container, String name, long version) throws SQLException { - s.setInt(1, account); - s.setInt(2, container); - s.setString(3, name); - s.setLong(4, version); + 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 ids) { - if (ids == null || ids.isEmpty() || ids.size() > MAX_VERSIONS) { + static void checkManifestCount(List versions) { + if (versions == null || versions.isEmpty() || versions.size() > MAX_VERSIONS) { throw new IllegalArgumentException("Invalid number of manifests"); } } - static List canonicalIds(List ids) { - checkManifestCount(ids); - TreeSet sorted = new TreeSet<>(); - for (String id : ids) { - if (id == null || !UUID.fromString(id).toString().equals(id) || !sorted.add(id)) { - throw new IllegalArgumentException("Expected distinct canonical manifest IDs"); + 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); } - static void retire(Connection c, short account, short container, String name, List manifestIds) + static void retire(Connection c, short account, short container, String name, List manifestVersions) throws SQLException { if (c.getAutoCommit() || c.getTransactionIsolation() != Connection.TRANSACTION_REPEATABLE_READ) { throw new IllegalStateException("Publication requires an InnoDB REPEATABLE READ transaction"); } - List ids = canonicalIds(manifestIds); - byte[] receipt = sha256().digest(String.join(",", ids).getBytes(StandardCharsets.US_ASCII)); - Map versions = new LinkedHashMap<>(); + List requested = canonicalVersions(manifestVersions); + byte[] receipt = + sha256().digest(requested.stream().map(String::valueOf).collect(Collectors.joining(",")).getBytes( + StandardCharsets.US_ASCII)); + Map manifests = new LinkedHashMap<>(); int published = 0; int totalChildren = 0; - try (PreparedStatement s = c.prepareStatement("SELECT " + COLUMNS + " FROM " + HEADS - + " WHERE manifest_id=? FOR UPDATE")) { - for (String id : ids) { - s.setString(1, id); + try (PreparedStatement s = c.prepareStatement( + "SELECT " + HEADER_COLUMNS + ",payload,payload_hash FROM " + TABLE + " WHERE " + KEY + " FOR UPDATE")) { + for (long version : requested) { + bindKey(s, account, container, name, version); try (ResultSet r = s.executeQuery()) { if (!r.next()) { throw new SQLDataException("Unknown manifest"); } Manifest m = new Manifest(r); - if (!id.equals(m.id) || m.account != account || m.container != container || !m.name.equals(name) - || versions.put(m.version, m) != null) { - throw new SQLDataException("Manifest does not match the requested named version"); + byte[] payload = r.getBytes(8); + byte[] payloadHash = r.getBytes(9); + if (payload == null || payloadHash == null) { + throw new SQLDataException("Manifest is not sealed"); } + if (!MessageDigest.isEqual(payloadHash, hash(account, container, name, version, m.count, m.root, payload))) { + throw new SQLDataException("Invalid sealed manifest"); + } + manifests.put(version, m); if (m.publicationKey != null) { if (!Arrays.equals(receipt, m.publicationKey)) { throw new SQLDataException("Manifest belongs to a different publication"); @@ -214,15 +235,12 @@ static void retire(Connection c, short account, short container, String name, Li } } // On replay do not even resolve the name: it may already refer to a different root. - if (published == versions.size()) { + if (published == manifests.size()) { return; } if (published != 0 || totalChildren > MAX_CHILDREN) { throw new SQLDataException("Mixed or oversized publication"); } - for (Manifest m : versions.values()) { - verifySealed(c, m); - } List history = new ArrayList<>(); int matches = 0; // At REPEATABLE READ this range also locks the gap where a new, initially unfenced version must be inserted. @@ -240,7 +258,7 @@ static void retire(Connection c, short account, short container, String name, Li if (++rows > MAX_VERSIONS || !name.equals(r.getString(1))) { throw new SQLDataException("Unsupported named version range"); } - Manifest m = versions.get(r.getLong(2)); + Manifest m = manifests.get(r.getLong(2)); if (m == null && r.getBoolean(5)) { history.add(r.getLong(2)); continue; @@ -253,24 +271,24 @@ static void retire(Connection c, short account, short container, String name, Li } } } - if (matches != versions.size()) { + if (matches != manifests.size()) { throw new SQLDataException("Expected named version is absent"); } - try (PreparedStatement publish = c.prepareStatement("UPDATE " + HEADS - + " SET publication_key=? WHERE manifest_id=? AND publication_key IS NULL"); + try (PreparedStatement publish = c.prepareStatement("UPDATE " + TABLE + + " SET publication_key=? WHERE " + KEY + " AND publication_key IS NULL"); PreparedStatement retire = c.prepareStatement("UPDATE named_blobs_v2 SET retirement_fenced=TRUE,deleted_ts=NULL" + " WHERE retirement_fenced=FALSE AND " + KEY); PreparedStatement fence = c.prepareStatement("SELECT 1 FROM named_blobs_v2 WHERE retirement_fenced=TRUE" + " AND deleted_ts<=UTC_TIMESTAMP(6) AND " + KEY + " FOR UPDATE")) { - for (Manifest m : versions.values()) { + for (Manifest m : manifests.values()) { publish.setBytes(1, receipt); - publish.setString(2, m.id); + bindKey(publish, account, container, name, m.version, 2); if (publish.executeUpdate() != 1) { throw new SQLDataException("Cannot publish sealed manifest"); } } // History needs the TTL fence, not a fabricated cleanup manifest. All versions are still locked. - history.addAll(versions.keySet()); + history.addAll(manifests.keySet()); for (long version : history) { bindKey(retire, account, container, name, version); bindKey(fence, account, container, name, version); @@ -287,29 +305,7 @@ static void retire(Connection c, short account, short container, String name, Li } } - private static void verifySealed(Connection c, Manifest m) throws SQLException { - try (PreparedStatement s = c.prepareStatement("SELECT first_child,payload,page_hash FROM " + PAGES - + " WHERE manifest_id=? ORDER BY first_child FOR UPDATE")) { - s.setString(1, m.id); - s.setFetchSize(Integer.MIN_VALUE); // Connector/J streams rows instead of buffering the manifest. - try (ResultSet r = s.executeQuery()) { - int first = 0; - while (r.next()) { - if (first >= m.count || r.getInt(1) != first - || !MessageDigest.isEqual(r.getBytes(3), hash(m, first, r.getBytes(2)))) { - throw new SQLDataException("Invalid sealed page"); - } - first += Math.min(PAGE_SIZE, m.count - first); - } - if (first != m.count) { - throw new SQLDataException("Missing sealed page"); - } - } - } - } - static final class Manifest { - final String id; final short account; final short container; final String name; @@ -319,45 +315,65 @@ static final class Manifest { final byte[] publicationKey; private Manifest(ResultSet r) throws SQLException { - id = r.getString(1); - account = r.getShort(2); - container = r.getShort(3); - name = r.getString(4); - version = r.getLong(5); - root = Base64.getUrlEncoder().withoutPadding().encodeToString(r.getBytes(6)); - count = r.getInt(7); - publicationKey = r.getBytes(8); + account = r.getShort(1); + container = r.getShort(2); + name = r.getString(3); + version = r.getLong(4); + root = Base64.getUrlEncoder().withoutPadding().encodeToString(r.getBytes(5)); + count = r.getInt(6); + publicationKey = r.getBytes(7); if (count < 1 || count > MAX_CHILDREN) { - throw new SQLDataException("Invalid manifest bounds: " + id); + throw new SQLDataException("Invalid manifest bounds: " + name + "/" + version); } } } - /** Recover a known publication without resolving the name. Unknown and unpublished IDs return null. */ - Manifest getPublished(String manifestId) throws SQLException { - String sql = "SELECT " + COLUMNS + " FROM " + HEADS + " WHERE manifest_id=? AND publication_key IS NOT NULL"; + /** Recover a known publication by its exact tuple, without resolving the name or reading the original root. */ + Manifest getPublished(short account, short container, String name, long version) throws SQLException { + String sql = "SELECT " + HEADER_COLUMNS + " FROM " + TABLE + " WHERE " + KEY + " AND publication_key IS NOT NULL"; try (Connection c = db.getConnection()) { requireCommittedReads(c); try (PreparedStatement s = c.prepareStatement(sql)) { - s.setString(1, Objects.requireNonNull(manifestId, "manifestId")); + bindKey(s, account, container, Objects.requireNonNull(name, "name"), version); try (ResultSet r = s.executeQuery()) { - return r.next() ? new Manifest(r) : null; + if (!r.next()) { + return null; + } + Manifest manifest = new Manifest(r); + // The named table's VARCHAR key uses a PAD SPACE collation. + return name.equals(manifest.name) ? manifest : null; } } } } - /** Read one immutable page; the caller owns any inspection progress. */ - List read(Manifest m, int first) throws SQLException { + /** Read the full ordered child list for one sealed manifest row; the caller owns any inspection progress. */ + List read(Manifest m) throws SQLException { byte[] body; try (Connection c = db.getConnection()) { requireCommittedReads(c); - body = readPayload(c, m, first, false); + try (PreparedStatement s = c.prepareStatement("SELECT payload,payload_hash FROM " + TABLE + " WHERE " + KEY)) { + bindKey(s, m.account, m.container, m.name, m.version); + try (ResultSet r = s.executeQuery()) { + if (!r.next()) { + throw new SQLDataException("Missing sealed manifest: " + m.name + "/" + m.version); + } + byte[] payload = r.getBytes(1); + byte[] payloadHash = r.getBytes(2); + if (payload == null || payloadHash == null) { + throw new SQLDataException("Manifest is not sealed: " + m.name + "/" + m.version); + } + if (!MessageDigest.isEqual(payloadHash, hash(m.account, m.container, m.name, m.version, m.count, m.root, + payload))) { + throw new SQLDataException("Manifest checksum mismatch: " + m.name + "/" + m.version); + } + body = payload; + } + } } ByteBuffer in = ByteBuffer.wrap(body); - int n = Math.min(PAGE_SIZE, m.count - first); - List ids = new ArrayList<>(n); - for (int i = 0; i < n; i++) { + List ids = new ArrayList<>(m.count); + for (int i = 0; i < m.count; i++) { int length = in.hasRemaining() ? Byte.toUnsignedInt(in.get()) : 0; if (length == 0 || length > MAX_ID_BYTES || length > in.remaining()) { throw new SQLDataException("Invalid sealed child descriptor"); @@ -367,43 +383,19 @@ List read(Manifest m, int first) throws SQLException { ids.add(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)); } if (in.hasRemaining()) { - throw new SQLDataException("Trailing bytes on sealed page"); + throw new SQLDataException("Trailing bytes on sealed manifest"); } return Collections.unmodifiableList(ids); } - private static byte[] readPayload(Connection c, Manifest m, int first, boolean currentRead) throws SQLException { - if (first < 0 || first >= m.count || first % PAGE_SIZE != 0) { - throw new SQLDataException("Invalid manifest page offset"); - } - try (PreparedStatement s = c.prepareStatement( - "SELECT payload,page_hash FROM " + PAGES + " WHERE manifest_id=? AND first_child=?" - + (currentRead ? " FOR UPDATE" : ""))) { - s.setString(1, m.id); - s.setInt(2, first); - try (ResultSet r = s.executeQuery()) { - if (!r.next()) { - throw new SQLDataException("Missing sealed page: " + m.id + "/" + first); - } - byte[] body = r.getBytes(1); - byte[] checksum = r.getBytes(2); - if (!MessageDigest.isEqual(checksum, hash(m, first, body))) { - throw new SQLDataException("Manifest checksum mismatch: " + m.id + "/" + first); - } - return body; - } - } - } - - private static byte[] hash(Manifest m, int first, byte[] body) { + private static byte[] hash(short account, short container, String name, long version, int count, String root, + byte[] body) { MessageDigest d = sha256(); - byte[] name = m.name.getBytes(StandardCharsets.UTF_8); - d.update(m.id.getBytes(StandardCharsets.US_ASCII)); - d.update(ByteBuffer.allocate(2 * Short.BYTES + Long.BYTES + 3 * Integer.BYTES) - .putShort(m.account).putShort(m.container).putLong(m.version) - .putInt(m.count).putInt(first).putInt(name.length).array()); - d.update(name); - d.update(m.root.getBytes(StandardCharsets.US_ASCII)); + byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8); + d.update(ByteBuffer.allocate(2 * Short.BYTES + Long.BYTES + 2 * Integer.BYTES) + .putShort(account).putShort(container).putLong(version).putInt(count).putInt(nameBytes.length).array()); + d.update(nameBytes); + d.update(root.getBytes(StandardCharsets.US_ASCII)); d.update((byte) 0); return d.digest(body); } diff --git a/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql new file mode 100644 index 0000000000..dd9b4f8441 --- /dev/null +++ b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER named_blob_manifest_tuple_guard_ins_v1 +BEFORE INSERT ON named_blobs_v2 +FOR EACH ROW +BEGIN + DECLARE existing_root VARBINARY(50); + SELECT root_id INTO existing_root FROM named_blob_manifests_v1 + WHERE account_id = NEW.account_id AND container_id = NEW.container_id + AND blob_name = NEW.blob_name AND version = NEW.version + FOR UPDATE; + IF existing_root IS NOT NULL AND existing_root <> NEW.blob_id THEN + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Named tuple already has a manifest for a different root'; + END IF; +END diff --git a/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardUpdateV1.sql b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardUpdateV1.sql new file mode 100644 index 0000000000..8822197daf --- /dev/null +++ b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardUpdateV1.sql @@ -0,0 +1,16 @@ +CREATE TRIGGER named_blob_manifest_tuple_guard_upd_v1 +BEFORE UPDATE ON named_blobs_v2 +FOR EACH ROW +BEGIN + DECLARE existing_root VARBINARY(50); + IF NEW.blob_id <> OLD.blob_id OR NEW.account_id <> OLD.account_id OR NEW.container_id <> OLD.container_id + OR BINARY NEW.blob_name <> BINARY OLD.blob_name OR NEW.version <> OLD.version THEN + SELECT root_id INTO existing_root FROM named_blob_manifests_v1 + WHERE account_id = NEW.account_id AND container_id = NEW.container_id + AND blob_name = NEW.blob_name AND version = NEW.version + FOR UPDATE; + IF existing_root IS NOT NULL AND existing_root <> NEW.blob_id THEN + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Named tuple already has a manifest for a different root'; + END IF; + END IF; +END diff --git a/ambry-named-mysql/src/main/resources/NamedBlobManifestV1.ddl b/ambry-named-mysql/src/main/resources/NamedBlobManifestV1.ddl index 1867754864..9c1b2cd8e4 100644 --- a/ambry-named-mysql/src/main/resources/NamedBlobManifestV1.ddl +++ b/ambry-named-mysql/src/main/resources/NamedBlobManifestV1.ddl @@ -1,25 +1,16 @@ CREATE TABLE named_blob_manifests_v1 ( - manifest_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, account_id INT NOT NULL, container_id INT NOT NULL, blob_name VARCHAR(350) NOT NULL, version BIGINT NOT NULL, root_id VARBINARY(50) NOT NULL, child_count INT NOT NULL, + payload LONGBLOB DEFAULT NULL, + payload_hash BINARY(32) DEFAULT NULL, publication_key BINARY(32) DEFAULT NULL, - PRIMARY KEY (manifest_id), - UNIQUE KEY manifest_named_version (account_id, container_id, blob_name, version) + PRIMARY KEY (account_id, container_id, blob_name, version) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; -CREATE TABLE named_blob_manifest_pages_v1 ( - manifest_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, - first_child INT NOT NULL, - payload VARBINARY(8192) NOT NULL, - page_hash BINARY(32) NOT NULL, - PRIMARY KEY (manifest_id, first_child), - FOREIGN KEY (manifest_id) REFERENCES named_blob_manifests_v1 (manifest_id) -) ENGINE=InnoDB; - ALTER TABLE named_blobs_v2 ADD COLUMN retirement_fenced BOOLEAN NOT NULL DEFAULT FALSE, ALGORITHM=INSTANT; 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 4b940f1f6b..debd4ee353 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,6 +6,7 @@ import java.sql.Connection; import java.sql.SQLException; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -26,7 +27,7 @@ public void testReaderRejectsDirtyReadsWithoutChangingPoolIsolation() throws SQL NamedBlobManifestStore store = new NamedBlobManifestStore(db); verify(db, never()).getConnection(); try { - store.getPublished("00000000-0000-0000-0000-000000000001"); + store.getPublished((short) 17, (short) 4, "folder/MixedCase", 1); fail("A reader could observe a publication that rolls back"); } catch (IllegalStateException e) { assertTrue(e.getMessage(), e.getMessage().contains("READ COMMITTED")); @@ -38,17 +39,29 @@ public void testReaderRejectsDirtyReadsWithoutChangingPoolIsolation() throws SQL @Test public void testPublicationUsesADistinctOrderIndependentSet() { - String first = "00000000-0000-0000-0000-000000000001"; - String second = "00000000-0000-0000-0000-000000000002"; - assertEquals(Arrays.asList(first, second), NamedBlobManifestStore.canonicalIds(Arrays.asList(second, first))); - for (List invalid : Arrays.asList(Arrays.asList(first, first), Collections.singletonList("0-0-0-0-1"), - Collections.emptyList())) { + 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.canonicalIds(invalid); + NamedBlobManifestStore.canonicalVersions(invalid); fail("Invalid publication set accepted: " + invalid); } catch (IllegalArgumentException expected) { // Reject before acquiring database locks. } } } + + @Test + public void testPublicationRejectsMoreThanTheDeclaredVersionCap() { + List tooMany = new ArrayList<>(); + for (long version = 1; version <= 33; version++) { + tooMany.add(version); + } + try { + NamedBlobManifestStore.checkManifestCount(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()); + } + } } From 5295e3d878bbb8a163c54cabd9dfe1fe10f8cd5b Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Fri, 27 Nov 2026 14:50:44 -0800 Subject: [PATCH 3/5] Publish complete manifests in the exact retirement transaction Eliminate durable staging. Bound request size before reading chunk iterators and use exact version-set receipts for lost commit replies. Reject reinsertions of published tuples even when the root matches. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ambry-named-mysql/README.md | 22 +- ...NamedBlobManifestStoreIntegrationTest.java | 405 +++++++++++------- .../github/ambry/named/MySqlNamedBlobDb.java | 25 +- .../ambry/named/NamedBlobManifestStore.java | 338 ++++++++------- .../NamedBlobManifestTupleGuardInsertV1.sql | 15 +- .../NamedBlobManifestTupleGuardUpdateV1.sql | 12 +- .../main/resources/NamedBlobManifestV1.ddl | 6 +- 7 files changed, 490 insertions(+), 333 deletions(-) diff --git a/ambry-named-mysql/README.md b/ambry-named-mysql/README.md index 080646e89f..b0a66a2ef8 100644 --- a/ambry-named-mysql/README.md +++ b/ambry-named-mysql/README.md @@ -2,9 +2,10 @@ Each manifest stores the ordered child IDs of one immutable metadata blob in a single MySQL row. Its primary key is `(account_id, container_id, blob_name, version)`, the same key that identifies the named version. The root ID identifies -the source of the list; repeated child IDs retain their positions. Publication and retirement commit together. If the -commit outcome is unknown, retry the same exact versions, roots and lists. Do not resolve the latest version of the -name or fall back to the router's ordinary delete. +the source of the list; repeated child IDs retain their positions. Prepare the lists in memory. Persist every complete +manifest and retire the named versions in one transaction. A crash before commit leaves neither a manifest nor a +retirement. If the commit reply is lost, check the exact version set on the authoritative writer. If not committed, +retry from the original exact inputs. Never resolve a replacement name or fall back to 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. @@ -22,7 +23,9 @@ longer count toward the limit of 32 unfenced versions per name. A name above tha version, fails without changing any row. Exclude such names from rollout until their history has been safely reconciled; retrying unchanged input will not help. A publication supports at most 262,144 children across its versions (1 TiB at 4 MiB per child). Each descriptor has a one-byte length and at most 127 ID bytes: the largest encoded list is 32 MiB, -which requires `LONGBLOB` rather than `MEDIUMBLOB`. Before enabling publication, round-trip a maximum-size binary +which requires `LONGBLOB` rather than `MEDIUMBLOB`. At the child-count limit, 34-byte V6 IDs yield 8.75 MiB and +58-byte V5 IDs with canonical UUIDs yield 14.75 MiB. The accepted V5 string form can reach 127 bytes per ID; 32 MiB +is the format limit, not a typical Liquid payload. Before enabling publication, round-trip a maximum-size binary payload through the deployed JDBC connection and check `@@session.max_allowed_packet` on writers and failover targets. Connector/J 8.0.21 with client-side prepared statements rejected a synthetic 32 MiB body at a 64 MiB packet limit: the measured query exceeded 64 MiB before transmission. The same bytes round-tripped with server-side prepared @@ -32,15 +35,16 @@ production settings. Check the client limit as well as MySQL and replication lim ## Installing or resuming the migration **Defer production DDL until the activation prerequisites below are ready.** Nothing installs automatically, but once -installed the trigger fires on every update, even on unfenced rows with manifests disabled. If its definer disappears -or loses privileges, ordinary TTL finalization and soft deletes can fail. +installed the triggers run on ordinary writes even with manifests disabled. A missing definer or missing privileges +can break named PUT, TTL finalization and soft DELETE. From `ambry-named-mysql/src/main/resources`, set `DB` to the approved writer's named-blob schema. Use separate mysql options files: `MYSQL_CNF` for schema DDL and `DEFINER_CNF` for the durable service account that will own the trigger. The trigger file uses MySQL's implicit `DEFINER=CURRENT_USER`. Before installation, confirm the matched `user@host` is the intended permanent account, **not** a personal or temporary migration identity. Have the DBA verify on every writer and promotion candidate that this account exists and retains `TRIGGER`, `SELECT` and `UPDATE` on `named_blobs_v2` -for the trigger's lifetime. Use the approved trigger-install process for the server's binary logging configuration. +and the privileges required for locking reads on `named_blob_manifests_v1` for the triggers' lifetime. +Use the approved trigger-install process for the server's binary logging configuration. ```sh mysql --defaults-file="$DEFINER_CNF" --database="$DB" -e 'SELECT CURRENT_USER(), DATABASE(); SHOW GRANTS' @@ -98,13 +102,13 @@ The database operations alone are not safe to activate. In addition to the DELET - Give the worker indexed discovery of committed publications or durably record the exact tuples before retirement. A process-local list is lost on restart; a saved tuple is actionable only after publication. -Before staging the first manifest, route all frontend and direct named DELETE callers away from legacy DELETE for the +Before publishing the first manifest, route all frontend and direct named DELETE callers away from legacy DELETE for the enabled namespace, or reject those requests. Also exclude its account or container from `NamedBlobsCleanupRunner` on every runner, for both stale cleanup and purge. Drain in-flight requests, cleaner batches already selected, and their 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 staging and publication but retain the DELETE gate, cleaner exclusion, database fence, index, and +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. This store does not retire raw parent IDs, establish exclusive ownership of chunks, schedule cleanup, or reclaim space. 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 92ff78a81b..5de92e387a 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 @@ -16,9 +16,12 @@ import java.sql.SQLDataException; import java.sql.Statement; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Properties; import java.util.Scanner; import java.util.UUID; @@ -52,6 +55,10 @@ public class NamedBlobManifestStoreIntegrationTest { private static final String NAME = "folder/MixedCase"; // The declared per-manifest and aggregate-publish child cap; exercised at full scale below. private static final int MAX_CHILDREN = 262_144; + // sizeInBytes() for a V1-V5 BlobId is VERSION(2)+FLAG(1)+DATACENTER(1)+ACCOUNT(2)+CONTAINER(2) + // + MockPartitionId.getBytes().length(10) + length-prefix(4) + uuidStr.length(). 8+10+4=22 fixed bytes, so a + // 105-character ASCII uuid reaches exactly the declared 127-byte cap through a genuine BlobId instance. + private static final int MAX_ID_UUID_LENGTH = 105; @Test public void testDetachedRecoveryAcrossReplacement() throws Exception { @@ -110,20 +117,64 @@ private static MySqlNamedBlobDb namedDb(DataSource db) throws Exception { endpoint -> db, "local", new Metrics(new MetricRegistry(), "")); } - /** Stage descriptors for one named version; the sealed row is keyed only by the (account, container, name, - * version) tuple, so nothing is returned to identify it afterward. */ - private static void stage(MySqlNamedBlobDb db, String name, long version, BlobId root, int count, + /** + * 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. + */ + private static void retireOne(MySqlNamedBlobDb db, long version, BlobId root, int count, + Iterator children) throws Exception { + retireOneNamed(db, NAME, version, root, count, children); + } + + private static void retireOneNamed(MySqlNamedBlobDb db, String name, long version, BlobId root, int count, Iterator children) throws Exception { + retireMany(db, name, + Collections.singletonMap(version, new NamedBlobManifestStore.PendingVersion(root, count, children))); + } + + private static void retireMany(MySqlNamedBlobDb db, Map pending) + throws Exception { + retireMany(db, NAME, pending); + } + + private static void retireMany(MySqlNamedBlobDb db, String name, + Map pending) throws Exception { try { - db.stageDeleteManifest("account", "container", name, version, root, count, children).get(10, TimeUnit.SECONDS); + db.retireWithManifests("account", "container", name, pending).get(10, TimeUnit.SECONDS); } catch (ExecutionException e) { - if (e.getCause() instanceof SQLDataException) { - throw (SQLDataException) e.getCause(); + if (e.getCause() instanceof SQLException) { + throw (SQLException) e.getCause(); } throw e; } } + private static Map pendingFor(List versions, + Map roots, Map> childrenByVersion) { + Map pending = new LinkedHashMap<>(); + for (long version : versions) { + List children = childrenByVersion.get(version); + pending.put(version, + new NamedBlobManifestStore.PendingVersion(roots.get(version), children.size(), children.iterator())); + } + return pending; + } + + /** An iterator that must never be consumed: used to prove a rejection happens before any descriptor is read. */ + private static Iterator poisonIterator() { + return new Iterator() { + @Override + public boolean hasNext() { + throw new AssertionError("An oversized request must be rejected before any iterator is touched"); + } + + @Override + public BlobId next() { + throw new AssertionError("An oversized request must be rejected before any iterator is touched"); + } + }; + } + private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Exception { BlobId old = blob(BlobId.BlobDataType.METADATA); BlobId replacement = blob(BlobId.BlobDataType.METADATA); @@ -136,30 +187,43 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep insertNamed(db, 8, replacement, NamedBlobState.IN_PROGRESS); NamedBlobManifestStore writer = new NamedBlobManifestStore(db); - expectDataError("No matching live READY", () -> - stage(named, NAME, 8, replacement, children.size(), children.iterator())); - expectDataError("No matching live READY", () -> - stage(named, NAME + " ", 7, old, children.size(), children.iterator())); - expectDataError("No matching live READY", () -> - stage(named, NAME, 7, replacement, children.size(), children.iterator())); - expectDataError("Missing or unsupported child", () -> - stage(named, NAME, 7, old, children.size(), children.subList(0, children.size() - 1).iterator())); + // 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. + expectDataError("Unrepresented or ineligible", + () -> retireOne(named, 7, old, children.size(), children.iterator())); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + + sql(db, "DELETE FROM named_blobs_v2 WHERE version=8"); + + expectDataError("Unrepresented or ineligible", + () -> retireOne(named, 8, replacement, children.size(), children.iterator())); + expectDataError("Unsupported named version range", + () -> retireOneNamed(named, NAME + " ", 7, old, children.size(), children.iterator())); + expectDataError("Unrepresented or ineligible", + () -> retireOne(named, 7, replacement, children.size(), children.iterator())); + expectDataError("Missing or unsupported child", () -> retireOne(named, 7, old, children.size(), + children.subList(0, children.size() - 1).iterator())); assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); - stage(named, NAME, 7, old, children.size(), children.iterator()); - // A retry against the already-sealed row is idempotent: it must not re-seal or fail. - stage(named, NAME, 7, old, children.size(), children.iterator()); + retireOne(named, 7, old, children.size(), children.iterator()); + // A retry with the same exact tuple, root and content is idempotent: it must not fail or re-publish. + retireOne(named, 7, old, children.size(), children.iterator()); List reordered = new ArrayList<>(children); Collections.swap(reordered, 0, 1); - expectDataError("Capture retry disagrees", () -> - stage(named, NAME, 7, old, reordered.size(), reordered.iterator())); + expectDataError("Conflicting manifest for named version", + () -> retireOne(named, 7, old, reordered.size(), reordered.iterator())); - assertNull("Staging alone does not publish work", writer.getPublished(ACCOUNT, CONTAINER, NAME, 7)); - expectDataError("Unrepresented or ineligible", () -> retire(named, Collections.singletonList(7L))); - sql(db, "DELETE FROM named_blobs_v2 WHERE version=8"); - retire(named, Collections.singletonList(7L)); + try { + named.get("account", "container", NAME).get(10, TimeUnit.SECONDS); + fail("Ordinary GET must report Deleted after retirement"); + } catch (ExecutionException e) { + assertTrue(e.getCause() instanceof RestServiceException); + assertEquals(RestServiceErrorCode.Deleted, ((RestServiceException) e.getCause()).getErrorCode()); + } insertNamed(db, 8, replacement, NamedBlobState.READY); - retire(named, Collections.singletonList(7L)); + retireOne(named, 7, old, children.size(), children.iterator()); + assertTrue(writer.isPublished(ACCOUNT, CONTAINER, NAME, Collections.singletonList(7L))); + assertFalse(writer.isPublished(ACCOUNT, CONTAINER, NAME, Arrays.asList(7L, 8L))); 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( @@ -205,12 +269,11 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep // A second root can legitimately reference the same child. Both rows remain evidence, each keyed by its // own tuple: a worker that saved (name, version=8) trusts that row directly, independent of the root at // version 7 or any other version. - stage(named, NAME, 8, replacement, 1, Collections.singletonList(children.get(0)).iterator()); - retire(named, Collections.singletonList(8L)); + retireOne(named, 8, replacement, 1, Collections.singletonList(children.get(0)).iterator()); NamedBlobManifestStore.Manifest second = restarted.getPublished(ACCOUNT, CONTAINER, NAME, 8); assertEquals(replacement.getID(), second.root); assertEquals(Collections.singletonList(ids.get(0)), restarted.read(second)); - assertEquals(2, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1 WHERE publication_key IS NOT NULL")); + assertEquals(2, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); try (Connection c = db.getConnection(); PreparedStatement s = c.prepareStatement( "UPDATE named_blob_manifests_v1 SET payload=X'00' WHERE account_id=? AND container_id=? AND blob_name=?" @@ -225,7 +288,7 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep } @Test - public void testDuplicateCaptureReadsBeyondItsSnapshot() throws Exception { + public void testStaleSnapshotRetireReplayObservesCommittedPublication() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); @@ -237,12 +300,15 @@ public void testDuplicateCaptureReadsBeyondItsSnapshot() throws Exception { assertTrue(rows.next()); assertEquals(0, rows.getInt(1)); } - stage(named, NAME, 1, root, 1, children.iterator()); - // A racer whose snapshot predates the winner's commit must still see the sealed row when it checks out - // the row FOR UPDATE: that read is not snapshot-isolated, so the retry is idempotent rather than blind. - NamedBlobManifestStore.capture(loser, ACCOUNT, CONTAINER, NAME, 1, root, 1, children.iterator()); - expectDataError("Capture retry disagrees", () -> NamedBlobManifestStore.capture(loser, ACCOUNT, CONTAINER, - NAME, 1, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); + 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, + new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); + expectDataError("Conflicting manifest for named version", + () -> NamedBlobManifestStore.retire(loser, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())))); loser.rollback(); } }); @@ -260,8 +326,7 @@ public void testMigrationPreservesLegacyTtlUntilRetirement() throws Exception { NamedBlobRecord newest = NamedBlobRecord.forUpdate("account", "container", NAME, 3); named.updateBlobTtlAndStateToReady(newest).get(10, TimeUnit.SECONDS); assertEquals(root.getID(), named.get("account", "container", NAME).get(10, TimeUnit.SECONDS).getBlobId()); - stage(named, NAME, 3, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); - retire(named, Collections.singletonList(3L)); + retireOne(named, 3, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); try { named.get("account", "container", NAME).get(10, TimeUnit.SECONDS); fail("Ordinary GET must report Deleted after retirement"); @@ -275,7 +340,7 @@ public void testMigrationPreservesLegacyTtlUntilRetirement() throws Exception { assertEquals(3L, deleted.getVersion()); assertEquals(2, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version<3 AND retirement_fenced=TRUE" + " AND deleted_ts='2000-01-01'")); - assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1 WHERE publication_key IS NOT NULL")); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); try { named.updateBlobTtlAndStateToReady(NamedBlobRecord.forUpdate("account", "container", NAME, 2)) .get(10, TimeUnit.SECONDS); @@ -293,9 +358,7 @@ public void testNameReuseDoesNotConsumeRetirementLimit() throws Exception { for (int version = 1; version <= 33; version++) { BlobId root = blob(BlobId.BlobDataType.METADATA); insertNamed(db, version, root, NamedBlobState.READY); - stage(named, NAME, version, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)) - .iterator()); - retire(named, Collections.singletonList((long) version)); + retireOne(named, version, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); } assertEquals(33, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE retirement_fenced=TRUE")); }); @@ -306,12 +369,12 @@ public void testRetirementLocksGapForReplacement() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); insertNamed(db, 7, root, NamedBlobState.READY); - stage(named, NAME, 7, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); - List jobs = Collections.singletonList(7L); + List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); try (Connection publisher = db.getConnection(); Connection replacement = db.getConnection(); Statement insert = replacement.createStatement()) { publisher.setAutoCommit(false); - NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, NAME, jobs); + NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, 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)" + " VALUES (17,4,'folder/MixedCase',8,X'AB',1)"; @@ -324,7 +387,8 @@ public void testRetirementLocksGapForReplacement() throws Exception { publisher.commit(); assertEquals(1, insert.executeUpdate(put)); } - retire(named, jobs); + // Replay after commit, via the high-level API, with the same exact content: still idempotent. + retireOne(named, 7, root, 1, children.iterator()); assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=8 AND retirement_fenced=FALSE" + " AND deleted_ts IS NULL")); }); @@ -333,14 +397,15 @@ public void testRetirementLocksGapForReplacement() throws Exception { @Test public void testPublicationRollsBackWhenNameMutationFails() throws Exception { withDatabase((db, named) -> { - List jobs = new ArrayList<>(); - for (int version = 1; version <= 2; version++) { + Map roots = new LinkedHashMap<>(); + Map> childrenByVersion = new LinkedHashMap<>(); + for (long version = 1; version <= 2; version++) { BlobId root = blob(BlobId.BlobDataType.METADATA); insertNamed(db, version, root, NamedBlobState.READY); - stage(named, NAME, version, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)) - .iterator()); - jobs.add((long) version); + roots.put(version, root); + childrenByVersion.put(version, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK))); } + List jobs = new ArrayList<>(roots.keySet()); // Publication processes the canonical (ascending-by-version) order; make the trigger fail on the last // version in that order so the test still proves the earlier publish within the same transaction rolls back. long lastVersion = Collections.max(jobs); @@ -348,30 +413,35 @@ public void testPublicationRollsBackWhenNameMutationFails() throws Exception { + " IF NEW.version=" + lastVersion + " THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='fixture rejection'; END IF; END"); try { - retire(named, jobs); + retireMany(named, pendingFor(jobs, roots, childrenByVersion)); fail("Expected mutation to fail"); } catch (SQLException expected) { assertEquals("45000", expected.getSQLState()); assertTrue(expected.getMessage(), expected.getMessage().contains("fixture rejection")); } - assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1 WHERE publication_key IS NOT NULL")); + // The whole transaction -- including the manifest rows this retire would have inserted -- rolled back: there + // is no durable pre-publication row left behind, and no fence was applied either. + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); assertEquals(2, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE deleted_ts IS NULL" + " AND retirement_fenced=FALSE")); sql(db, "DROP TRIGGER reject_retirement"); - retire(named, jobs); - jobs.sort(Collections.reverseOrder()); + retireMany(named, pendingFor(jobs, roots, childrenByVersion)); + List reversed = new ArrayList<>(jobs); + reversed.sort(Collections.reverseOrder()); try (Connection replay = db.getConnection()) { replay.setAutoCommit(false); - NamedBlobManifestStore.retire(replay, ACCOUNT, CONTAINER, NAME, jobs); + NamedBlobManifestStore.retire(replay, ACCOUNT, CONTAINER, NAME, + pendingFor(reversed, roots, childrenByVersion)); try { - NamedBlobManifestStore.retire(replay, ACCOUNT, CONTAINER, NAME, Collections.emptyList()); + NamedBlobManifestStore.retire(replay, ACCOUNT, CONTAINER, NAME, Collections.emptyMap()); fail("An empty set is not a publication receipt"); } catch (IllegalArgumentException expected) { assertEquals("Invalid number of manifests", expected.getMessage()); } replay.commit(); } - expectDataError("Manifest belongs to a different publication", () -> retire(named, jobs.subList(0, 1))); + expectDataError("Manifest belongs to a different publication", + () -> retireMany(named, pendingFor(jobs.subList(0, 1), roots, childrenByVersion))); }); } @@ -380,8 +450,7 @@ public void testWaitingTtlCannotReviveRetiredVersion() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); insertNamed(db, 7, root, NamedBlobState.READY); - stage(named, NAME, 7, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); - List jobs = Collections.singletonList(7L); + List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); String ttlSql = "UPDATE named_blobs_v2 SET blob_state=1, deleted_ts=NULL WHERE account_id=17" + " AND container_id=4 AND blob_name='folder/MixedCase' AND version="; ExecutorService executor = Executors.newSingleThreadExecutor(); @@ -410,7 +479,8 @@ 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, jobs); + NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(7L, + new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); publisher.commit(); assertEquals("45000", blocked.get(10, TimeUnit.SECONDS)); insertNamed(db, 8, blob(BlobId.BlobDataType.METADATA), NamedBlobState.IN_PROGRESS); @@ -425,107 +495,104 @@ public void testWaitingTtlCannotReviveRetiredVersion() throws Exception { } /** - * The concretely reported gap: capture/retire only re-validate root and count when {@code capture} itself is - * called again. Neither fences a direct SQL write to named_blobs_v2, so once a cleanup job physically removes - * the retired row, nothing used to stop a fresh INSERT from rebinding the same tuple to a different root while - * the published manifest still names the original. Also confirms what must still be permitted: recreating the - * identical row, and writing an entirely different version, are both untouched by the guard. + * The concretely reported gap: a retire only re-validates root and content when retire itself is called again. + * Nothing used to fence a direct SQL write to named_blobs_v2, so once a cleanup job physically removes the + * retired row, nothing stopped a fresh INSERT from rebinding the same tuple -- even to its own original root -- + * while the published manifest still exists. A published tuple can never go live again. */ @Test - public void testDirectReinsertAfterPhysicalRemovalRejectsDifferentRoot() throws Exception { + public void testDirectReinsertAfterPhysicalRemovalRejectsReuse() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); BlobId impostor = blob(BlobId.BlobDataType.METADATA); insertNamed(db, 7, root, NamedBlobState.READY); - stage(named, NAME, 7, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); - retire(named, Collections.singletonList(7L)); + List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); + retireOne(named, 7, root, 1, children.iterator()); sql(db, "DELETE FROM named_blobs_v2 WHERE version=7"); - expectSqlRejection("Named tuple already has a manifest for a different root", - () -> insertNamed(db, 7, impostor, NamedBlobState.READY)); - - // Recreating the exact same row the manifest already names is the documented recovery path and must - // still work after the guard rejects an impostor for the same tuple. - insertNamed(db, 7, root, NamedBlobState.READY); - assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=7 AND blob_id=X'" - + bytesToHex(root.toBytes()) + "'")); + expectSqlRejection("Named version is reserved", () -> insertNamed(db, 7, impostor, NamedBlobState.READY)); + expectSqlRejection("Named version is reserved", () -> insertNamed(db, 7, root, NamedBlobState.READY)); + // A replay against the purged row still succeeds: the published manifest is proof enough on its own. + retireOne(named, 7, root, 1, children.iterator()); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=7")); // A different version was never part of this manifest's key and must be entirely unaffected. insertNamed(db, 9, impostor, NamedBlobState.READY); + expectSqlRejection("Named version is reserved", () -> sql(db, "UPDATE named_blobs_v2 SET version=7," + + "blob_id=X'" + bytesToHex(root.toBytes()) + "' WHERE version=9")); assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=9 AND blob_id=X'" + bytesToHex(impostor.toBytes()) + "'")); }); } /** - * Same prohibition, reached through UPDATE instead of INSERT: a direct rebind of blob_id while the row is still - * live (not yet purged, not even retired) must be rejected exactly like the post-purge INSERT case, while an - * ordinary state-only update (the TTL path) is untouched. + * An ordinary state-only update (no identity column change, e.g. the TTL path) never consults the manifest + * table and must succeed even on a row that already carries a published manifest and is already fenced. */ @Test - public void testDirectUpdateRejectsDifferentRootWhileManifestExists() throws Exception { + public void testOrdinaryStateUpdateIgnoresExistingManifest() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); - BlobId impostor = blob(BlobId.BlobDataType.METADATA); insertNamed(db, 7, root, NamedBlobState.READY); - stage(named, NAME, 7, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); - - expectSqlRejection("Named tuple already has a manifest for a different root", () -> { - try (Connection c = db.getConnection(); PreparedStatement s = c.prepareStatement( - "UPDATE named_blobs_v2 SET blob_id=? WHERE account_id=? AND container_id=? AND blob_name=? AND version=7")) { - s.setBytes(1, impostor.toBytes()); - s.setShort(2, ACCOUNT); - s.setShort(3, CONTAINER); - s.setString(4, NAME); - s.executeUpdate(); - } - }); - - // An ordinary state-only update (no blob_id change) never consults the manifest table and must still work. - sql(db, "UPDATE named_blobs_v2 SET blob_state=" + NamedBlobState.READY.ordinal() + " WHERE version=7"); - retire(named, Collections.singletonList(7L)); + retireOne(named, 7, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); + sql(db, "UPDATE named_blobs_v2 SET modified_ts=UTC_TIMESTAMP(6) WHERE version=7"); assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=7 AND retirement_fenced=TRUE")); }); } + @Test + public void testConcurrentUnrelatedNamedPutsDoNotContendOnTheGuardTrigger() throws Exception { + withDatabase((db, named) -> { + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + List> futures = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + String name = NAME + "/" + i; + BlobId root = blob(BlobId.BlobDataType.METADATA); + futures.add(executor.submit(() -> { + insertNamed(db, name, 1, root, NamedBlobState.READY); + return null; + })); + } + for (Future f : futures) { + // Each future would time out here if the AFTER trigger introduced cross-name contention: it only ever + // locks its own tuple, and only after the base row's own insert lock already landed. + f.get(10, TimeUnit.SECONDS); + } + } finally { + executor.shutdownNow(); + } + }); + } + /** - * The actual race the guard exists for: a capture that has reserved (but not yet committed) a manifest row must - * block a concurrent direct replace for the same tuple, not merely a replace that starts after capture commits. + * 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, + * reinsertion is rejected regardless of which root the racer uses. */ @Test - public void testConcurrentInFlightCaptureBlocksRacingDirectReplace() throws Exception { + public void testConcurrentRetireBlocksRacingDirectReplaceThenRejectsReuse() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); BlobId impostor = blob(BlobId.BlobDataType.METADATA); insertNamed(db, 7, root, NamedBlobState.READY); - try (Connection capturing = db.getConnection(); Connection replacing = db.getConnection(); + List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); + try (Connection retiring = db.getConnection(); Connection replacing = db.getConnection(); Statement replace = replacing.createStatement()) { - capturing.setAutoCommit(false); - // Reserve the manifest row without committing: this is the in-flight window the guard must defend. - NamedBlobManifestStore.capture(capturing, ACCOUNT, CONTAINER, NAME, 7, root, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); - + retiring.setAutoCommit(false); + NamedBlobManifestStore.retire(retiring, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(7L, + new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); replace.execute("SET SESSION innodb_lock_wait_timeout=1"); try { replace.executeUpdate("DELETE FROM named_blobs_v2 WHERE version=7"); - fail("Purge must wait for an in-flight capture"); + fail("Purge must wait for an in-flight retire"); } catch (SQLException blocked) { assertEquals(1205, blocked.getErrorCode()); } - capturing.commit(); + retiring.commit(); replace.executeUpdate("DELETE FROM named_blobs_v2 WHERE version=7"); - try { - insertNamed(db, 7, impostor, NamedBlobState.READY); - fail("A committed reservation must reject replacement"); - } catch (SQLException conflict) { - assertEquals("45000", conflict.getSQLState()); - } + expectSqlRejection("Named version is reserved", () -> insertNamed(db, 7, impostor, NamedBlobState.READY)); + expectSqlRejection("Named version is reserved", () -> insertNamed(db, 7, root, NamedBlobState.READY)); } - // After capture's committed root loses the race to no one, the same tuple can still be recreated with the - // root the manifest actually names. - sql(db, "DELETE FROM named_blobs_v2 WHERE version=7"); - insertNamed(db, 7, root, NamedBlobState.READY); - retire(named, Collections.singletonList(7L)); - assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=7 AND retirement_fenced=TRUE")); }); } @@ -548,58 +615,82 @@ private static void expectSqlRejection(String reason, SqlAction action) throws E } /** - * Captures, publishes and reads back the declared cap of real child descriptors in a single manifest row, and - * asserts the full ordered list survives exactly, under the same JDBC settings as every other case in this suite - * (no streaming fetch size, no paging). Check the stored byte length as well as the decoded IDs. + * Retires and reads back the declared cap of real child descriptors in a single manifest row, at the declared + * 127-byte-per-child bound, and asserts the full ordered list survives exactly -- including repeats, since + * only two distinct BlobId instances are reused across the whole cap to bound test heap -- under the same JDBC + * settings and server-side prepared-statement mode as production. */ @Test public void testFullScaleManifestRoundTripAtTheDeclaredChildCap() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); insertNamed(db, 1, root, NamedBlobState.READY); - List children = new ArrayList<>(MAX_CHILDREN); - for (int i = 0; i < MAX_CHILDREN; i++) { - children.add(blob(BlobId.BlobDataType.DATACHUNK)); - } - List ids = children.stream().map(BlobId::getID).collect(Collectors.toList()); + BlobId even = maxSizedBlob(BlobId.BlobDataType.DATACHUNK, 'A'); + BlobId odd = maxSizedBlob(BlobId.BlobDataType.DATACHUNK, 'B'); + assertEquals(127, even.sizeInBytes()); + assertEquals(127, odd.sizeInBytes()); + Iterator children = new Iterator() { + int produced = 0; + + @Override + public boolean hasNext() { + return produced < MAX_CHILDREN; + } - stage(named, NAME, 1, root, children.size(), children.iterator()); - retire(named, Collections.singletonList(1L)); + @Override + public BlobId next() { + return (produced++ % 2 == 0) ? even : odd; + } + }; + + retireOne(named, 1, root, MAX_CHILDREN, children); NamedBlobManifestStore worker = new NamedBlobManifestStore(db); NamedBlobManifestStore.Manifest manifest = worker.getPublished(ACCOUNT, CONTAINER, NAME, 1); assertEquals(MAX_CHILDREN, manifest.count); List recovered = worker.read(manifest); - - assertEquals(ids, recovered); - assertEquals(children.stream().mapToInt(child -> 1 + child.sizeInBytes()).sum(), - scalar(db, "SELECT OCTET_LENGTH(payload) FROM named_blob_manifests_v1")); - assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1 WHERE publication_key IS NOT NULL")); + assertEquals(MAX_CHILDREN, recovered.size()); + for (int i = 0; i < MAX_CHILDREN; i++) { + assertEquals("Mismatch at index " + i, (i % 2 == 0) ? even.getID() : odd.getID(), recovered.get(i)); + } + // 262144 * (1 length byte + 127 id bytes) = 33,554,432 bytes = 32 MiB exactly. + assertEquals(MAX_CHILDREN * (1 + 127), scalar(db, "SELECT OCTET_LENGTH(payload) FROM named_blob_manifests_v1")); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); }); } - /** One more than the declared cap must be rejected immediately, before any descriptor is read or any row written. */ + /** One more than the declared per-version cap must be rejected before any descriptor is read. */ @Test - public void testCaptureRejectsOneMoreThanTheDeclaredChildCap() throws Exception { + public void testRetireRejectsOneVersionOverTheDeclaredChildCapBeforeReadingDescriptors() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); insertNamed(db, 1, root, NamedBlobState.READY); - expectDataError("Unsupported named composite capture", () -> - stage(named, NAME, 1, root, MAX_CHILDREN + 1, Collections.emptyIterator())); + expectDataError("Unsupported named composite capture", + () -> retireOne(named, 1, root, MAX_CHILDREN + 1, poisonIterator())); assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); }); } - private static void retire(MySqlNamedBlobDb db, List versions) throws Exception { - try { - db.retireWithManifests("account", "container", NAME, versions).get(10, TimeUnit.SECONDS); - } catch (ExecutionException e) { - if (e.getCause() instanceof SQLException) { - throw (SQLException) e.getCause(); - } - throw e; - } + /** + * Each individual version's declared count is within the per-version cap, but the request's aggregate count + * across both versions is not; the rejection must happen purely from the declared counts, before either + * version's iterator is ever touched. + */ + @Test + public void testRetireRejectsOversizedAggregateBeforeReadingAnyIterator() throws Exception { + withDatabase((db, named) -> { + BlobId rootA = blob(BlobId.BlobDataType.METADATA); + BlobId rootB = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 1, rootA, NamedBlobState.READY); + insertNamed(db, 2, rootB, NamedBlobState.READY); + int perVersion = (MAX_CHILDREN / 2) + 1; + Map pending = new LinkedHashMap<>(); + pending.put(1L, new NamedBlobManifestStore.PendingVersion(rootA, perVersion, poisonIterator())); + pending.put(2L, new NamedBlobManifestStore.PendingVersion(rootB, perVersion, poisonIterator())); + expectDataError("Mixed or oversized publication", () -> retireMany(named, pending)); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + }); } private static int scalar(DataSource db, String sql) throws SQLException { @@ -630,6 +721,8 @@ private static MysqlDataSource source(String schema) throws SQLException { } db.setDatabaseName(schema); db.setServerTimezone("UTC"); + // Mirror production's Hikari useServerPrepStmts=true so large-payload tests exercise the same statement mode. + db.setUseServerPrepStmts(true); return db; } @@ -652,13 +745,27 @@ private static BlobId blob(BlobId.BlobDataType type) { new MockPartitionId(), false, type); } - private static void insertNamed(DataSource db, long version, BlobId root, NamedBlobState state) throws SQLException { + /** A V5 BlobId whose uuid string is long enough to reach the declared 127-byte-per-child cap exactly. */ + private static BlobId maxSizedBlob(BlobId.BlobDataType type, char marker) { + char[] uuidChars = new char[MAX_ID_UUID_LENGTH]; + Arrays.fill(uuidChars, marker); + return new BlobId(BlobId.BLOB_ID_V5, BlobId.BlobIdType.NATIVE, (byte) 0, ACCOUNT, CONTAINER, + new MockPartitionId(), false, type, new String(uuidChars)); + } + + private static void insertNamed(DataSource db, long version, BlobId root, NamedBlobState state) + throws SQLException { + insertNamed(db, NAME, version, root, state); + } + + 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( "INSERT INTO named_blobs_v2 (account_id,container_id,blob_name,version,blob_id,blob_state)" + " VALUES (?,?,?,?,?,?)")) { s.setShort(1, ACCOUNT); s.setShort(2, CONTAINER); - s.setString(3, NAME); + s.setString(3, name); s.setLong(4, version); s.setBytes(5, root.toBytes()); s.setInt(6, state.ordinal()); 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 211490a39c..99058e485a 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 @@ -22,7 +22,6 @@ import com.github.ambry.account.Account; import com.github.ambry.account.AccountService; import com.github.ambry.account.Container; -import com.github.ambry.commons.BlobId; import com.github.ambry.commons.Callback; import com.github.ambry.commons.RetryExecutor; import com.github.ambry.commons.RetryPolicies; @@ -34,7 +33,6 @@ import com.github.ambry.protocol.NamedBlobState; import com.github.ambry.rest.RestServiceErrorCode; import com.github.ambry.rest.RestServiceException; -import com.github.ambry.store.StoreKey; import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.Time; import com.github.ambry.utils.Utils; @@ -55,7 +53,6 @@ import java.util.Deque; import java.util.HashSet; import java.util.IdentityHashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -496,25 +493,19 @@ public CompletableFuture updateBlobTtlAndStateToReady(NamedBlobRecord }, null, this.metricsRecoder.namedBlobDBUpdateErrorCount); } - /** Stage descriptors for the exact live root without retiring its named version. */ - CompletableFuture stageDeleteManifest(String accountName, String containerName, String blobName, long version, - BlobId root, int childCount, Iterator children) { - return executeTransactionAsync(accountName, containerName, false, (account, container, connection) -> { - NamedBlobManifestStore.capture(connection, account, container, blobName, version, root, childCount, children); - return null; - }, null, metricsRecoder.namedBlobDBDeleteErrorCount); - } - - /** Publish this exact sealed manifest set atomically with soft retirement. Never returns IDs for a router cascade. */ + /** + * 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. + */ CompletableFuture retireWithManifests(String accountName, String containerName, String blobName, - List manifestVersions) { - NamedBlobManifestStore.checkManifestCount(manifestVersions); - List versions = new ArrayList<>(manifestVersions); + Map pendingVersions) { + NamedBlobManifestStore.checkManifestCount(new ArrayList<>(pendingVersions.keySet())); return executeTransactionAsync(accountName, containerName, false, (account, container, connection) -> { if (config.enableHardDelete) { throw new UnsupportedOperationException("Manifest retirement requires named soft delete"); } - NamedBlobManifestStore.retire(connection, account, container, blobName, versions); + NamedBlobManifestStore.retire(connection, account, container, blobName, pendingVersions); return null; }, null, metricsRecoder.namedBlobDBDeleteErrorCount); } 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 b11c60a613..07b4bd8f96 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 @@ -31,9 +31,12 @@ import com.github.ambry.store.StoreKey; /** - * Detached evidence for one immutable root at one named version. Seal means that all declared - * descriptors were captured. Neither seal nor inspection grants permission to delete anything. - * The reader data source must consistently supply connections to the same database at READ COMMITTED or stronger. + * Detached evidence for one immutable root at one named version. A row in {@code named_blob_manifests_v1} exists + * only once it is fully formed: there is no durable pre-publication staging state, no nullable seal column, and no + * separate capture transaction whose result another transaction later publishes. The single entry point below + * validates the entire requested set, locks the named range, locks the manifest tuples, and -- only once every + * check has passed -- inserts the rows and fences their history in one transaction. Neither a row's existence nor + * its publication grants permission to delete anything. * *

Each named version has exactly one row, keyed by the same {@code (account_id, container_id, blob_name, * version)} tuple that identifies it in {@code named_blobs_v2}. The ordered child list is stored as that row's own @@ -65,81 +68,16 @@ private static void requireCommittedReads(Connection c) throws SQLException { } } - /** - * The caller must supply the ordered descriptors decoded from this exact root, not from a name - * lookup. The live-row check is a nonlocking eligibility check, not a publication or TTL fence. - * A concurrent replacement can leave an unpublished manifest row; it cannot redirect it to a different root. - */ - static void capture(Connection c, short account, short container, String name, long version, BlobId root, int expected, - Iterator descriptors) throws SQLException { - Objects.requireNonNull(root, "root"); - Objects.requireNonNull(descriptors, "descriptors"); - if (name == null || name.isEmpty() || expected < 1 || 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"); - } - if (c.getAutoCommit()) { - throw new IllegalStateException("Capture requires a caller-owned transaction"); - } - byte[] rootBytes = root.toBytes(); - try (PreparedStatement s = c.prepareStatement("SELECT blob_name FROM named_blobs_v2 WHERE " + KEY - + " AND blob_id=? AND blob_state=? AND (deleted_ts IS NULL OR deleted_ts > UTC_TIMESTAMP(6)) FOR UPDATE")) { - bindKey(s, account, container, name, version); - s.setBytes(5, rootBytes); - s.setInt(6, NamedBlobState.READY.ordinal()); - try (ResultSet r = s.executeQuery()) { - // utf8mb4_bin on VARCHAR can compare names equal despite trailing spaces. - if (!r.next() || !name.equals(r.getString(1))) { - throw new SQLDataException("No matching live READY named version"); - } - } - } + /** One requested version's immutable inputs: the caller must supply descriptors decoded from this exact root. */ + static final class PendingVersion { + final BlobId root; + final int expected; + final Iterator descriptors; - // Reserve the row without touching an existing payload: a concurrent racer for the same tuple must observe - // whatever this statement establishes, not silently reset a sealed manifest. - try (PreparedStatement s = c.prepareStatement("INSERT INTO " + TABLE - + " (account_id,container_id,blob_name,version,root_id,child_count)" - + " VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE account_id=account_id")) { - bindKey(s, account, container, name, version); - s.setBytes(5, rootBytes); - s.setInt(6, expected); - s.executeUpdate(); - } - Manifest m; - byte[] existingPayload; - // The eligibility read may have established a snapshot before a competing capture committed. - try (PreparedStatement s = c.prepareStatement( - "SELECT " + HEADER_COLUMNS + ",payload FROM " + TABLE + " WHERE " + KEY + " FOR UPDATE")) { - bindKey(s, account, container, name, version); - try (ResultSet r = s.executeQuery()) { - if (!r.next()) { - throw new SQLDataException("No manifest for the requested named version"); - } - m = new Manifest(r); - existingPayload = r.getBytes(8); - } - } - if (!m.name.equals(name) || !m.root.equals(root.getID()) || m.count != expected) { - // A residual row for a different root must never be mistaken for this capture: the tuple cannot be reused - // for a different root while any manifest or cleanup job may still depend on the original. - throw new SQLDataException("Conflicting manifest for named version"); - } - - byte[] body = encode(descriptors, expected, rootBytes); - if (existingPayload == null) { - try (PreparedStatement update = c.prepareStatement( - "UPDATE " + TABLE + " SET payload=?,payload_hash=? WHERE " + KEY + " AND payload IS NULL")) { - update.setBytes(1, body); - update.setBytes(2, hash(account, container, name, version, m.count, m.root, body)); - bindKey(update, account, container, name, version, 3); - if (update.executeUpdate() != 1) { - throw new SQLDataException("Concurrent capture already sealed this manifest"); - } - } - } else if (!Arrays.equals(body, existingPayload)) { - throw new SQLDataException("Capture retry disagrees with sealed manifest"); + PendingVersion(BlobId root, int expected, Iterator descriptors) { + this.root = Objects.requireNonNull(root, "root"); + this.expected = expected; + this.descriptors = Objects.requireNonNull(descriptors, "descriptors"); } } @@ -194,56 +132,68 @@ static List canonicalVersions(List versions) { return new ArrayList<>(sorted); } - static void retire(Connection c, short account, short container, String name, List manifestVersions) + /** + * Validate, publish and fence an entire set of named versions in one transaction. 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 statement is issued: a + * doomed oversized request never reads or hashes a byte under lock. The named row range is then locked ahead of + * the manifest table, the same order an ordinary named PUT's own AFTER INSERT/UPDATE guard uses, so the two can + * never deadlock against each other. A replay that already carries this exact receipt, root and content for every + * requested version returns successfully without resolving the name; 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 { if (c.getAutoCommit() || c.getTransactionIsolation() != Connection.TRANSACTION_REPEATABLE_READ) { throw new IllegalStateException("Publication requires an InnoDB REPEATABLE READ transaction"); } - List requested = canonicalVersions(manifestVersions); - byte[] receipt = - sha256().digest(requested.stream().map(String::valueOf).collect(Collectors.joining(",")).getBytes( - StandardCharsets.US_ASCII)); - Map manifests = new LinkedHashMap<>(); - int published = 0; - int totalChildren = 0; - try (PreparedStatement s = c.prepareStatement( - "SELECT " + HEADER_COLUMNS + ",payload,payload_hash FROM " + TABLE + " WHERE " + KEY + " FOR UPDATE")) { - for (long version : requested) { - bindKey(s, account, container, name, version); - try (ResultSet r = s.executeQuery()) { - if (!r.next()) { - throw new SQLDataException("Unknown manifest"); - } - Manifest m = new Manifest(r); - byte[] payload = r.getBytes(8); - byte[] payloadHash = r.getBytes(9); - if (payload == null || payloadHash == null) { - throw new SQLDataException("Manifest is not sealed"); - } - if (!MessageDigest.isEqual(payloadHash, hash(account, container, name, version, m.count, m.root, payload))) { - throw new SQLDataException("Invalid sealed manifest"); - } - manifests.put(version, m); - if (m.publicationKey != null) { - if (!Arrays.equals(receipt, m.publicationKey)) { - throw new SQLDataException("Manifest belongs to a different publication"); - } - published++; - } - totalChildren += m.count; - } - } + if (name == null || name.isEmpty()) { + throw new SQLDataException("Unsupported named composite capture"); } - // On replay do not even resolve the name: it may already refer to a different root. - if (published == manifests.size()) { - return; + Objects.requireNonNull(pending, "pending"); + List requested = canonicalVersions(new ArrayList<>(pending.keySet())); + + long totalDeclared = 0; + for (long version : requested) { + PendingVersion p = pending.get(version); + if (p == null) { + throw new IllegalArgumentException("Missing pending descriptors for version " + version); + } + 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"); + } + totalDeclared += p.expected; } - if (published != 0 || totalChildren > MAX_CHILDREN) { + if (totalDeclared > MAX_CHILDREN) { throw new SQLDataException("Mixed or oversized publication"); } + + byte[] receipt = receipt(requested); + + // Only now, with the whole request's declared size already bounded, consume each iterator and encode its body. + Map rootBytes = new LinkedHashMap<>(); + Map bodies = new LinkedHashMap<>(); + Map rootIds = new LinkedHashMap<>(); + for (long version : requested) { + PendingVersion p = pending.get(version); + byte[] rb = p.root.toBytes(); + rootBytes.put(version, rb); + rootIds.put(version, Base64.getUrlEncoder().withoutPadding().encodeToString(rb)); + bodies.put(version, encode(p.descriptors, p.expected, rb)); + } + + // Lock the named row range first: this is the same order (named_blobs_v2, then named_blob_manifests_v1) an + // ordinary PUT's own trigger uses. At REPEATABLE READ this range also locks the gap where a new, initially + // unfenced version must be inserted. + Map liveMatch = new LinkedHashMap<>(); List history = new ArrayList<>(); - int matches = 0; - // At REPEATABLE READ this range also locks the gap where a new, initially unfenced version must be inserted. + // An unrequested, still-live row blocks a fresh publish -- retirement only ever covers a contiguous prefix of + // the unfenced range -- but a pure replay never needs to resolve the name at all, so this is recorded rather + // than thrown here and is only enforced once the manifest lookup below has ruled out a full replay. + boolean unrequestedLiveVersion = false; try (PreparedStatement s = c.prepareStatement("SELECT blob_name,version,blob_id,blob_state," + "(deleted_ts IS NOT NULL AND deleted_ts<=UTC_TIMESTAMP(6)) FROM named_blobs_v2" + " FORCE INDEX (named_blob_unfenced_versions) WHERE account_id=? AND container_id=? AND blob_name=?" @@ -258,37 +208,95 @@ static void retire(Connection c, short account, short container, String name, Li if (++rows > MAX_VERSIONS || !name.equals(r.getString(1))) { throw new SQLDataException("Unsupported named version range"); } - Manifest m = manifests.get(r.getLong(2)); - if (m == null && r.getBoolean(5)) { - history.add(r.getLong(2)); + long version = r.getLong(2); + if (!pending.containsKey(version)) { + if (r.getBoolean(5)) { + history.add(version); + } else { + unrequestedLiveVersion = true; + } continue; } - if (m == null || r.getInt(4) != NamedBlobState.READY.ordinal() || r.getBoolean(5) - || !m.root.equals(Base64.getUrlEncoder().withoutPadding().encodeToString(r.getBytes(3)))) { - throw new SQLDataException("Unrepresented or ineligible named version"); + boolean eligible = r.getInt(4) == NamedBlobState.READY.ordinal() && !r.getBoolean(5) + && Arrays.equals(r.getBytes(3), rootBytes.get(version)); + liveMatch.put(version, eligible); + } + } + } + + // Pure exact-receipt lookup by tuple, independent of whatever the range above found: a prior commit's manifest + // row is proof enough on its own, even if the named row it refers to was since purged entirely. + int published = 0; + try (PreparedStatement s = c.prepareStatement( + "SELECT root_id,child_count,payload,payload_hash,publication_key FROM " + TABLE + " WHERE " + KEY + + " FOR UPDATE")) { + for (long version : requested) { + bindKey(s, account, container, name, version); + try (ResultSet r = s.executeQuery()) { + if (!r.next()) { + continue; + } + byte[] storedRoot = r.getBytes(1); + int storedCount = r.getInt(2); + byte[] storedPayload = r.getBytes(3); + byte[] storedHash = r.getBytes(4); + byte[] storedKey = r.getBytes(5); + boolean sameInputs = Arrays.equals(storedRoot, rootBytes.get(version)) && storedCount == pending.get( + version).expected && Arrays.equals(storedPayload, bodies.get(version)) && MessageDigest.isEqual( + storedHash, hash(account, container, name, version, storedCount, rootIds.get(version), storedPayload)); + if (!sameInputs) { + throw new SQLDataException("Conflicting manifest for named version"); } - matches++; + if (!MessageDigest.isEqual(storedKey, receipt)) { + throw new SQLDataException("Manifest belongs to a different publication"); + } + published++; } } } - if (matches != manifests.size()) { - throw new SQLDataException("Expected named version is absent"); + // Never report success for only part of the requested set: either every version already carries this exact + // receipt, root and content, or none of them may. + if (published == requested.size()) { + return; } - try (PreparedStatement publish = c.prepareStatement("UPDATE " + TABLE - + " SET publication_key=? WHERE " + KEY + " AND publication_key IS NULL"); - PreparedStatement retire = c.prepareStatement("UPDATE named_blobs_v2 SET retirement_fenced=TRUE,deleted_ts=NULL" - + " WHERE retirement_fenced=FALSE AND " + KEY); - PreparedStatement fence = c.prepareStatement("SELECT 1 FROM named_blobs_v2 WHERE retirement_fenced=TRUE" - + " AND deleted_ts<=UTC_TIMESTAMP(6) AND " + KEY + " FOR UPDATE")) { - for (Manifest m : manifests.values()) { - publish.setBytes(1, receipt); - bindKey(publish, account, container, name, m.version, 2); - if (publish.executeUpdate() != 1) { + if (published != 0) { + throw new SQLDataException("Mixed or oversized publication"); + } + if (unrequestedLiveVersion) { + throw new SQLDataException("Unrepresented or ineligible named version"); + } + for (long version : requested) { + if (!Boolean.TRUE.equals(liveMatch.get(version))) { + throw new SQLDataException("Unrepresented or ineligible named version"); + } + } + + try (PreparedStatement insert = c.prepareStatement( + "INSERT INTO " + TABLE + " (" + HEADER_COLUMNS + ",payload,payload_hash) VALUES (?,?,?,?,?,?,?,?,?)")) { + for (long version : requested) { + PendingVersion p = pending.get(version); + byte[] body = bodies.get(version); + insert.setInt(1, account); + insert.setInt(2, container); + insert.setString(3, name); + insert.setLong(4, version); + insert.setBytes(5, rootBytes.get(version)); + insert.setInt(6, p.expected); + insert.setBytes(7, receipt); + insert.setBytes(8, body); + insert.setBytes(9, hash(account, container, name, version, p.expected, rootIds.get(version), body)); + if (insert.executeUpdate() != 1) { throw new SQLDataException("Cannot publish sealed manifest"); } } + } + + try (PreparedStatement retire = c.prepareStatement( + "UPDATE named_blobs_v2 SET retirement_fenced=TRUE,deleted_ts=NULL WHERE retirement_fenced=FALSE AND " + KEY); + PreparedStatement fence = c.prepareStatement("SELECT 1 FROM named_blobs_v2 WHERE retirement_fenced=TRUE" + + " AND deleted_ts<=UTC_TIMESTAMP(6) AND " + KEY + " FOR UPDATE")) { // History needs the TTL fence, not a fabricated cleanup manifest. All versions are still locked. - history.addAll(manifests.keySet()); + history.addAll(requested); for (long version : history) { bindKey(retire, account, container, name, version); bindKey(fence, account, container, name, version); @@ -325,12 +333,51 @@ private Manifest(ResultSet r) throws SQLException { if (count < 1 || count > MAX_CHILDREN) { throw new SQLDataException("Invalid manifest bounds: " + name + "/" + version); } + + } + } + + private static byte[] receipt(List orderedVersions) { + return sha256().digest(orderedVersions.stream().map(String::valueOf).collect(Collectors.joining(",")) + .getBytes(StandardCharsets.US_ASCII)); + } + + /** Resolve a lost commit reply from immutable receipts on the authoritative writer, without reading the name. */ + boolean isPublished(short account, short container, String name, List versions) throws SQLException { + List requested = canonicalVersions(versions); + byte[] key = receipt(requested); + String placeholders = String.join(",", Collections.nCopies(requested.size(), "?")); + String sql = "SELECT blob_name,publication_key FROM " + TABLE + + " WHERE account_id=? AND container_id=? AND blob_name=? AND version IN (" + placeholders + ")"; + try (Connection c = db.getConnection()) { + requireCommittedReads(c); + try (PreparedStatement s = c.prepareStatement(sql)) { + s.setInt(1, account); + s.setInt(2, container); + s.setString(3, name); + for (int i = 0; i < requested.size(); i++) { + s.setLong(i + 4, requested.get(i)); + } + try (ResultSet r = s.executeQuery()) { + int count = 0; + while (r.next()) { + if (!name.equals(r.getString(1)) || !MessageDigest.isEqual(key, r.getBytes(2))) { + return false; + } + count++; + } + return count == requested.size(); + } + } } } - /** Recover a known publication by its exact tuple, without resolving the name or reading the original root. */ + /** + * 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. + */ Manifest getPublished(short account, short container, String name, long version) throws SQLException { - String sql = "SELECT " + HEADER_COLUMNS + " FROM " + TABLE + " WHERE " + KEY + " AND publication_key IS NOT NULL"; + String sql = "SELECT " + HEADER_COLUMNS + " FROM " + TABLE + " WHERE " + KEY; try (Connection c = db.getConnection()) { requireCommittedReads(c); try (PreparedStatement s = c.prepareStatement(sql)) { @@ -347,7 +394,7 @@ Manifest getPublished(short account, short container, String name, long version) } } - /** Read the full ordered child list for one sealed manifest row; the caller owns any inspection progress. */ + /** Read the full ordered child list for one published manifest row; the caller owns any inspection progress. */ List read(Manifest m) throws SQLException { byte[] body; try (Connection c = db.getConnection()) { @@ -356,13 +403,10 @@ List read(Manifest m) throws SQLException { bindKey(s, m.account, m.container, m.name, m.version); try (ResultSet r = s.executeQuery()) { if (!r.next()) { - throw new SQLDataException("Missing sealed manifest: " + m.name + "/" + m.version); + throw new SQLDataException("Missing published manifest: " + m.name + "/" + m.version); } byte[] payload = r.getBytes(1); byte[] payloadHash = r.getBytes(2); - if (payload == null || payloadHash == null) { - throw new SQLDataException("Manifest is not sealed: " + m.name + "/" + m.version); - } if (!MessageDigest.isEqual(payloadHash, hash(m.account, m.container, m.name, m.version, m.count, m.root, payload))) { throw new SQLDataException("Manifest checksum mismatch: " + m.name + "/" + m.version); @@ -376,14 +420,14 @@ List read(Manifest m) throws SQLException { for (int i = 0; i < m.count; i++) { int length = in.hasRemaining() ? Byte.toUnsignedInt(in.get()) : 0; if (length == 0 || length > MAX_ID_BYTES || length > in.remaining()) { - throw new SQLDataException("Invalid sealed child descriptor"); + throw new SQLDataException("Invalid published child descriptor"); } byte[] bytes = new byte[length]; in.get(bytes); ids.add(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)); } if (in.hasRemaining()) { - throw new SQLDataException("Trailing bytes on sealed manifest"); + throw new SQLDataException("Trailing bytes on published manifest"); } return Collections.unmodifiableList(ids); } diff --git a/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql index dd9b4f8441..1af3e0a20f 100644 --- a/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql +++ b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql @@ -1,13 +1,20 @@ CREATE TRIGGER named_blob_manifest_tuple_guard_ins_v1 -BEFORE INSERT ON named_blobs_v2 +AFTER INSERT ON named_blobs_v2 FOR EACH ROW BEGIN DECLARE existing_root VARBINARY(50); - SELECT root_id INTO existing_root FROM named_blob_manifests_v1 + DECLARE existing_name VARBINARY(1400); + -- A manifest row is only ever inserted fully formed, in the same transaction that retires its named version: + -- its mere existence means the tuple is published, regardless of root. Running after the base row lands + -- means an ordinary named PUT locks named_blobs_v2 first and this table second, the same order retire uses, + -- so the two never wait on each other in opposite directions. + SELECT root_id,blob_name INTO existing_root,existing_name FROM named_blob_manifests_v1 WHERE account_id = NEW.account_id AND container_id = NEW.container_id AND blob_name = NEW.blob_name AND version = NEW.version FOR UPDATE; - IF existing_root IS NOT NULL AND existing_root <> NEW.blob_id THEN - SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Named tuple already has a manifest for a different root'; + -- utf8mb4_bin on VARCHAR still compares under PAD SPACE rules, so an index match can hide a trailing-space + -- alias; compare the stored name byte-for-byte before trusting the lookup. + IF existing_root IS NOT NULL OR existing_name <> BINARY NEW.blob_name THEN + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Named version is reserved'; END IF; END diff --git a/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardUpdateV1.sql b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardUpdateV1.sql index 8822197daf..4915140745 100644 --- a/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardUpdateV1.sql +++ b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardUpdateV1.sql @@ -1,16 +1,20 @@ CREATE TRIGGER named_blob_manifest_tuple_guard_upd_v1 -BEFORE UPDATE ON named_blobs_v2 +AFTER UPDATE ON named_blobs_v2 FOR EACH ROW BEGIN DECLARE existing_root VARBINARY(50); + DECLARE existing_name VARBINARY(1400); + -- Only an identity-moving update (root or any key column) needs to consult the manifest table at all: the + -- retirement fence's own update only ever touches retirement_fenced/deleted_ts, so it never takes this path + -- or this table's lock, in either trigger. IF NEW.blob_id <> OLD.blob_id OR NEW.account_id <> OLD.account_id OR NEW.container_id <> OLD.container_id OR BINARY NEW.blob_name <> BINARY OLD.blob_name OR NEW.version <> OLD.version THEN - SELECT root_id INTO existing_root FROM named_blob_manifests_v1 + SELECT root_id,blob_name INTO existing_root,existing_name FROM named_blob_manifests_v1 WHERE account_id = NEW.account_id AND container_id = NEW.container_id AND blob_name = NEW.blob_name AND version = NEW.version FOR UPDATE; - IF existing_root IS NOT NULL AND existing_root <> NEW.blob_id THEN - SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Named tuple already has a manifest for a different root'; + IF existing_root IS NOT NULL OR existing_name <> BINARY NEW.blob_name THEN + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Named version is reserved'; END IF; END IF; END diff --git a/ambry-named-mysql/src/main/resources/NamedBlobManifestV1.ddl b/ambry-named-mysql/src/main/resources/NamedBlobManifestV1.ddl index 9c1b2cd8e4..66b6d54c39 100644 --- a/ambry-named-mysql/src/main/resources/NamedBlobManifestV1.ddl +++ b/ambry-named-mysql/src/main/resources/NamedBlobManifestV1.ddl @@ -5,9 +5,9 @@ CREATE TABLE named_blob_manifests_v1 ( version BIGINT NOT NULL, root_id VARBINARY(50) NOT NULL, child_count INT NOT NULL, - payload LONGBLOB DEFAULT NULL, - payload_hash BINARY(32) DEFAULT NULL, - publication_key BINARY(32) DEFAULT NULL, + payload LONGBLOB NOT NULL, + payload_hash BINARY(32) NOT NULL, + publication_key BINARY(32) NOT NULL, PRIMARY KEY (account_id, container_id, blob_name, version) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; From 288c35749082ed363dded2b6aabc8f0df616f38a Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Fri, 27 Nov 2026 15:25:07 -0800 Subject: [PATCH 4/5] Bind named retirement replay to immutable content and avoid gap locks on missing manifests Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...NamedBlobManifestStoreIntegrationTest.java | 195 +++++++++- .../github/ambry/named/MySqlNamedBlobDb.java | 33 +- .../ambry/named/NamedBlobManifestStore.java | 338 +++++++++++------- .../NamedBlobManifestTupleGuardInsertV1.sql | 15 +- .../NamedBlobManifestTupleGuardUpdateV1.sql | 5 +- 5 files changed, 429 insertions(+), 157 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 5de92e387a..6fb6a89282 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 @@ -222,8 +222,15 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep } insertNamed(db, 8, replacement, NamedBlobState.READY); retireOne(named, 7, old, children.size(), children.iterator()); - assertTrue(writer.isPublished(ACCOUNT, CONTAINER, NAME, Collections.singletonList(7L))); - assertFalse(writer.isPublished(ACCOUNT, CONTAINER, NAME, Arrays.asList(7L, 8L))); + // 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()))))); + 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))); 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( @@ -314,6 +321,27 @@ public void testStaleSnapshotRetireReplayObservesCommittedPublication() throws E }); } + @Test + public void testLegacyOperationsAcrossMigration() throws Exception { + BlobId root = blob(BlobId.BlobDataType.METADATA); + withDatabase(db -> { + try (MySqlNamedBlobDb legacy = namedDb(db)) { + legacyPutAndFinalize(legacy, "before", root); + } + }, (db, named) -> { + assertEquals(root.getID(), named.get("account", "container", "before").get(10, TimeUnit.SECONDS).getBlobId()); + legacyPutAndFinalize(named, "after", root); + }); + } + + private static void legacyPutAndFinalize(MySqlNamedBlobDb named, String name, BlobId root) throws Exception { + NamedBlobRecord record = new NamedBlobRecord("account", "container", name, root.getID(), -1, 1); + named.put(record, NamedBlobState.IN_PROGRESS, true).get(10, TimeUnit.SECONDS); + named.updateBlobTtlAndStateToReady(NamedBlobRecord.forUpdate("account", "container", name, 1)) + .get(10, TimeUnit.SECONDS); + assertEquals(root.getID(), named.get("account", "container", name).get(10, TimeUnit.SECONDS).getBlobId()); + } + @Test public void testMigrationPreservesLegacyTtlUntilRetirement() throws Exception { BlobId root = blob(BlobId.BlobDataType.METADATA); @@ -539,28 +567,159 @@ public void testOrdinaryStateUpdateIgnoresExistingManifest() throws Exception { }); } + /** + * Deterministically proves non-contention rather than merely hoping two threads race: the first PUT's own AFTER + * INSERT trigger has already run and its transaction is deliberately left open (uncommitted) while a second PUT + * for an unrelated name is attempted. A bounded lock-wait timeout on the second connection turns a reintroduced + * cross-name gap lock into a prompt test failure instead of a hang. + */ @Test public void testConcurrentUnrelatedNamedPutsDoNotContendOnTheGuardTrigger() throws Exception { withDatabase((db, named) -> { - ExecutorService executor = Executors.newFixedThreadPool(2); - try { - List> futures = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - String name = NAME + "/" + i; - BlobId root = blob(BlobId.BlobDataType.METADATA); - futures.add(executor.submit(() -> { - insertNamed(db, name, 1, root, NamedBlobState.READY); - return null; - })); + String nameA = NAME + "/A"; + String nameB = NAME + "/B"; + BlobId rootA = blob(BlobId.BlobDataType.METADATA); + BlobId rootB = blob(BlobId.BlobDataType.METADATA); + try (Connection first = db.getConnection(); Connection second = db.getConnection()) { + first.setAutoCommit(false); + try (PreparedStatement insert = first.prepareStatement( + "INSERT INTO named_blobs_v2 (account_id,container_id,blob_name,version,blob_id,blob_state)" + + " VALUES (?,?,?,?,?,?)")) { + insert.setShort(1, ACCOUNT); + insert.setShort(2, CONTAINER); + insert.setString(3, nameA); + insert.setLong(4, 1); + insert.setBytes(5, rootA.toBytes()); + insert.setInt(6, NamedBlobState.READY.ordinal()); + assertEquals(1, insert.executeUpdate()); } - for (Future f : futures) { - // Each future would time out here if the AFTER trigger introduced cross-name contention: it only ever - // locks its own tuple, and only after the base row's own insert lock already landed. - f.get(10, TimeUnit.SECONDS); + try (Statement bound = second.createStatement(); + PreparedStatement insert = second.prepareStatement( + "INSERT INTO named_blobs_v2 (account_id,container_id,blob_name,version,blob_id,blob_state)" + + " VALUES (?,?,?,?,?,?)")) { + bound.execute("SET SESSION innodb_lock_wait_timeout=2"); + insert.setShort(1, ACCOUNT); + insert.setShort(2, CONTAINER); + insert.setString(3, nameB); + insert.setLong(4, 1); + insert.setBytes(5, rootB.toBytes()); + insert.setInt(6, NamedBlobState.READY.ordinal()); + // This would fail with InnoDB lock wait timeout (1205) here if the AFTER trigger introduced cross-name + // contention: it only ever locks its own tuple, and only after the base row's own insert lock landed. + assertEquals(1, insert.executeUpdate()); } - } finally { - executor.shutdownNow(); + first.commit(); + } + }); + } + + /** + * The concretely reported hazard: two unrelated publishers' locking reads against absent manifest keys could + * land in the same InnoDB index gap and deadlock (MySQL error 1213), even though they never touch the same + * name. retire() never takes a locking read against a key that might not exist -- it inserts directly, and only + * locks a key once a duplicate-key signal proves it exists -- so two fresh, concurrent publications for + * different names must both complete without waiting on each other. + */ + @Test + public void testTwoUnrelatedFreshPublicationsDoNotContendOnTheManifestTable() throws Exception { + withDatabase((db, named) -> { + String nameA = NAME + "/A"; + String nameB = NAME + "/B"; + BlobId rootA = blob(BlobId.BlobDataType.METADATA); + BlobId rootB = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, nameA, 1, rootA, NamedBlobState.READY); + insertNamed(db, nameB, 1, rootB, NamedBlobState.READY); + List childrenA = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); + List childrenB = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); + try (Connection first = db.getConnection(); Connection second = db.getConnection()) { + first.setAutoCommit(false); + second.setAutoCommit(false); + try (Statement bound = second.createStatement()) { + bound.execute("SET SESSION innodb_lock_wait_timeout=2"); + } + // 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, + new NamedBlobManifestStore.PendingVersion(rootA, 1, childrenA.iterator()))); + NamedBlobManifestStore.retire(second, ACCOUNT, CONTAINER, nameB, Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(rootB, 1, childrenB.iterator()))); + first.commit(); + second.commit(); + } + assertEquals(2, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + }); + } + + /** + * The concretely reported gap: a valid exact replay used to fail once the named range accumulated more unrelated, + * unfenced replacement versions than a fresh publish could ever tolerate, even though the originally requested + * tuple was already fully published. The non-locking replay check runs first and never touches named_blobs_v2 at + * all, so it is never subject to that cap. + */ + @Test + public void testExactReplaySucceedsDespiteNamedRangeExceedingTheVersionCap() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 1, root, NamedBlobState.READY); + List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); + retireOne(named, 1, root, 1, children.iterator()); + // Pile up far more unrelated, unfenced replacement versions than a fresh publish could ever tolerate. + for (long version = 2; version <= 40; version++) { + insertNamed(db, version, blob(BlobId.BlobDataType.METADATA), NamedBlobState.READY); } + // Replay the original, already-complete publication with the exact same content: it must still succeed. + retireOne(named, 1, root, 1, children.iterator()); + }); + } + + /** + * The concretely reported gap: isPublished and a replay used to confirm only a coarse version-set digest, so a + * second intent with a different root for the same version could falsely confirm the first intent as committed. + * Both the fast, non-locking replay path and the authoritative duplicate-key path bind content -- not just the + * version set -- so a different root is rejected rather than silently confirmed. + */ + @Test + public void testDifferentRootForTheSameVersionCannotImpersonateAPublishedIntent() throws Exception { + withDatabase((db, named) -> { + BlobId publishedRoot = blob(BlobId.BlobDataType.METADATA); + BlobId impostorRoot = blob(BlobId.BlobDataType.METADATA); + 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()))))); + 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 { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId decoy = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 1, root, NamedBlobState.READY); + 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); + NamedBlobManifestStore worker = new NamedBlobManifestStore(db); + NamedBlobManifestStore.Manifest manifest = worker.getPublished(ACCOUNT, CONTAINER, NAME, 1); + assertEquals(root.getID(), manifest.root); }); } 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 99058e485a..0efe6d5e5f 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 @@ -496,16 +496,41 @@ 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. + * 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. */ CompletableFuture retireWithManifests(String accountName, String containerName, String blobName, Map pendingVersions) { - NamedBlobManifestStore.checkManifestCount(new ArrayList<>(pendingVersions.keySet())); - return executeTransactionAsync(accountName, containerName, false, (account, container, connection) -> { + Account account = accountService.getAccountByName(accountName); + if (account == null) { + CompletableFuture failed = new CompletableFuture<>(); + failed.completeExceptionally( + new RestServiceException("Account not found: " + accountName, RestServiceErrorCode.NotFound)); + return failed; + } + Container container = account.getContainerByName(containerName); + if (container == null) { + CompletableFuture failed = new CompletableFuture<>(); + failed.completeExceptionally( + new RestServiceException("Container not found: " + containerName, RestServiceErrorCode.NotFound)); + return failed; + } + NamedBlobManifestStore.PreparedRetirement prepared; + try { + prepared = NamedBlobManifestStore.prepare((short) account.getId(), (short) container.getId(), blobName, + pendingVersions); + } catch (SQLException e) { + CompletableFuture failed = new CompletableFuture<>(); + failed.completeExceptionally(e); + return failed; + } + return executeTransactionAsync(accountName, containerName, false, (ignoredAccount, ignoredContainer, connection) -> { if (config.enableHardDelete) { throw new UnsupportedOperationException("Manifest retirement requires named soft delete"); } - NamedBlobManifestStore.retire(connection, account, container, blobName, pendingVersions); + NamedBlobManifestStore.retire(connection, prepared); return null; }, null, metricsRecoder.namedBlobDBDeleteErrorCount); } 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 07b4bd8f96..9ebab8f921 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 @@ -14,6 +14,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLDataException; +import java.sql.SQLIntegrityConstraintViolationException; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; @@ -24,7 +25,6 @@ import java.util.Map; import java.util.Objects; import java.util.TreeSet; -import java.util.stream.Collectors; import javax.sql.DataSource; import com.github.ambry.commons.BlobId; import com.github.ambry.protocol.NamedBlobState; @@ -33,10 +33,11 @@ /** * Detached evidence for one immutable root at one named version. A row in {@code named_blob_manifests_v1} exists * only once it is fully formed: there is no durable pre-publication staging state, no nullable seal column, and no - * separate capture transaction whose result another transaction later publishes. The single entry point below - * validates the entire requested set, locks the named range, locks the manifest tuples, and -- only once every - * check has passed -- inserts the rows and fences their history in one transaction. Neither a row's existence nor - * its publication grants permission to delete anything. + * separate capture transaction whose result another transaction later publishes. {@link #prepare} validates an + * entire requested set and consumes every iterator into an immutable {@link PreparedRetirement} before any + * connection is touched; {@link #retire(Connection, PreparedRetirement)} then locks the named range, locks the + * manifest tuples it needs, and -- only once every check has passed -- inserts the rows and fences their history + * in that one transaction. Neither a row's existence nor its publication grants permission to delete anything. * *

Each named version has exactly one row, keyed by the same {@code (account_id, container_id, blob_name, * version)} tuple that identifies it in {@code named_blobs_v2}. The ordered child list is stored as that row's own @@ -81,6 +82,40 @@ 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. + */ + 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 byte[] intentToken; + + private PreparedRetirement(short account, short container, String name, List requested, + Map rootBytes, Map rootIds, Map counts, Map bodies, + Map rowHashes, byte[] intentToken) { + 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; + } + } + private static byte[] encode(Iterator descriptors, int expected, byte[] rootBytes) throws SQLException { ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -133,20 +168,15 @@ static List canonicalVersions(List versions) { } /** - * Validate, publish and fence an entire set of named versions in one transaction. 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 statement is issued: a - * doomed oversized request never reads or hashes a byte under lock. The named row range is then locked ahead of - * the manifest table, the same order an ordinary named PUT's own AFTER INSERT/UPDATE guard uses, so the two can - * never deadlock against each other. A replay that already carries this exact receipt, root and content for every - * requested version returns successfully without resolving the name; anything less than all of them matching is - * rejected rather than partially honored. + * Validate the entire requested set and consume every iterator up front, producing an immutable description of + * 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. */ - static void retire(Connection c, short account, short container, String name, Map pending) + static PreparedRetirement prepare(short account, short container, String name, Map pending) throws SQLException { - if (c.getAutoCommit() || c.getTransactionIsolation() != Connection.TRANSACTION_REPEATABLE_READ) { - throw new IllegalStateException("Publication requires an InnoDB REPEATABLE READ transaction"); - } if (name == null || name.isEmpty()) { throw new SQLDataException("Unsupported named composite capture"); } @@ -154,6 +184,7 @@ static void retire(Connection c, short account, short container, String name, Ma 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) { @@ -165,24 +196,60 @@ static void retire(Connection c, short account, short container, String name, Ma || root.getBlobDataType() != BlobId.BlobDataType.METADATA) { throw new SQLDataException("Unsupported named composite capture"); } + counts.put(version, p.expected); totalDeclared += p.expected; } if (totalDeclared > MAX_CHILDREN) { throw new SQLDataException("Mixed or oversized publication"); } - byte[] receipt = receipt(requested); - // Only now, with the whole request's declared size already bounded, consume each iterator and encode its body. Map rootBytes = new LinkedHashMap<>(); - Map bodies = 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); - rootIds.put(version, Base64.getUrlEncoder().withoutPadding().encodeToString(rb)); - bodies.put(version, encode(p.descriptors, p.expected, 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)); + } + + 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)); + } + + /** + * 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. + */ + 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)) { + return; } // Lock the named row range first: this is the same order (named_blobs_v2, then named_blob_manifests_v1) an @@ -191,25 +258,25 @@ static void retire(Connection c, short account, short container, String name, Ma Map liveMatch = new LinkedHashMap<>(); List history = new ArrayList<>(); // An unrequested, still-live row blocks a fresh publish -- retirement only ever covers a contiguous prefix of - // the unfenced range -- but a pure replay never needs to resolve the name at all, so this is recorded rather - // than thrown here and is only enforced once the manifest lookup below has ruled out a full replay. + // the unfenced range -- but never blocks a version that is already published, since that is already-settled + // history regardless of what else now sits above it. boolean unrequestedLiveVersion = false; try (PreparedStatement s = c.prepareStatement("SELECT blob_name,version,blob_id,blob_state," + "(deleted_ts IS NOT NULL AND deleted_ts<=UTC_TIMESTAMP(6)) FROM named_blobs_v2" + " FORCE INDEX (named_blob_unfenced_versions) WHERE account_id=? AND container_id=? AND blob_name=?" + " AND retirement_fenced=FALSE ORDER BY version LIMIT ? FOR UPDATE")) { - s.setInt(1, account); - s.setInt(2, container); - s.setString(3, name); + s.setInt(1, p.account); + s.setInt(2, p.container); + s.setString(3, p.name); s.setInt(4, MAX_VERSIONS + 1); try (ResultSet r = s.executeQuery()) { int rows = 0; while (r.next()) { - if (++rows > MAX_VERSIONS || !name.equals(r.getString(1))) { + if (++rows > MAX_VERSIONS || !p.name.equals(r.getString(1))) { throw new SQLDataException("Unsupported named version range"); } long version = r.getLong(2); - if (!pending.containsKey(version)) { + if (!p.counts.containsKey(version)) { if (r.getBoolean(5)) { history.add(version); } else { @@ -218,89 +285,65 @@ static void retire(Connection c, short account, short container, String name, Ma continue; } boolean eligible = r.getInt(4) == NamedBlobState.READY.ordinal() && !r.getBoolean(5) - && Arrays.equals(r.getBytes(3), rootBytes.get(version)); + && Arrays.equals(r.getBytes(3), p.rootBytes.get(version)); liveMatch.put(version, eligible); } } } - // Pure exact-receipt lookup by tuple, independent of whatever the range above found: a prior commit's manifest - // row is proof enough on its own, even if the named row it refers to was since purged entirely. - int published = 0; - try (PreparedStatement s = c.prepareStatement( - "SELECT root_id,child_count,payload,payload_hash,publication_key FROM " + TABLE + " WHERE " + KEY - + " FOR UPDATE")) { - for (long version : requested) { - bindKey(s, account, container, name, version); - try (ResultSet r = s.executeQuery()) { - if (!r.next()) { - continue; + // Publish every requested version by a plain insert, never by a locking read against a key that may not exist: + // only a genuine duplicate-key signal -- never snapshot-isolated in InnoDB -- proves a row already exists, and + // only then is a locking read issued against that now-known-existing key. + List freshlyPublished = new ArrayList<>(); + try (PreparedStatement insert = c.prepareStatement( + "INSERT INTO " + TABLE + " (" + HEADER_COLUMNS + ",payload,payload_hash) VALUES (?,?,?,?,?,?,?,?,?)")) { + for (long version : p.requested) { + 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(7, p.intentToken); + insert.setBytes(8, p.bodies.get(version)); + insert.setBytes(9, p.rowHashes.get(version)); + try { + if (insert.executeUpdate() != 1) { + throw new SQLDataException("Cannot publish sealed manifest"); } - byte[] storedRoot = r.getBytes(1); - int storedCount = r.getInt(2); - byte[] storedPayload = r.getBytes(3); - byte[] storedHash = r.getBytes(4); - byte[] storedKey = r.getBytes(5); - boolean sameInputs = Arrays.equals(storedRoot, rootBytes.get(version)) && storedCount == pending.get( - version).expected && Arrays.equals(storedPayload, bodies.get(version)) && MessageDigest.isEqual( - storedHash, hash(account, container, name, version, storedCount, rootIds.get(version), storedPayload)); - if (!sameInputs) { - throw new SQLDataException("Conflicting manifest for named version"); + if (!unrequestedLiveVersion && Boolean.TRUE.equals(liveMatch.get(version))) { + freshlyPublished.add(version); + } else { + // The whole transaction -- including this uncommitted insert -- is rolled back by the caller. + throw new SQLDataException("Unrepresented or ineligible named version"); } - if (!MessageDigest.isEqual(storedKey, receipt)) { - throw new SQLDataException("Manifest belongs to a different publication"); + } catch (SQLIntegrityConstraintViolationException duplicate) { + if (duplicate.getErrorCode() != 1062) { + throw duplicate; } - published++; + confirmExistingMatches(c, p, version); } } } - // Never report success for only part of the requested set: either every version already carries this exact - // receipt, root and content, or none of them may. - if (published == requested.size()) { + + if (freshlyPublished.isEmpty()) { return; } - if (published != 0) { - throw new SQLDataException("Mixed or oversized publication"); - } - if (unrequestedLiveVersion) { - throw new SQLDataException("Unrepresented or ineligible named version"); - } - for (long version : requested) { - if (!Boolean.TRUE.equals(liveMatch.get(version))) { - throw new SQLDataException("Unrepresented or ineligible named version"); - } - } - - try (PreparedStatement insert = c.prepareStatement( - "INSERT INTO " + TABLE + " (" + HEADER_COLUMNS + ",payload,payload_hash) VALUES (?,?,?,?,?,?,?,?,?)")) { - for (long version : requested) { - PendingVersion p = pending.get(version); - byte[] body = bodies.get(version); - insert.setInt(1, account); - insert.setInt(2, container); - insert.setString(3, name); - insert.setLong(4, version); - insert.setBytes(5, rootBytes.get(version)); - insert.setInt(6, p.expected); - insert.setBytes(7, receipt); - insert.setBytes(8, body); - insert.setBytes(9, hash(account, container, name, version, p.expected, rootIds.get(version), body)); - if (insert.executeUpdate() != 1) { - throw new SQLDataException("Cannot publish sealed manifest"); - } - } + if (freshlyPublished.size() != p.requested.size()) { + throw new SQLDataException("Partial manifest set"); } - - try (PreparedStatement retire = c.prepareStatement( + try (PreparedStatement retireRow = c.prepareStatement( "UPDATE named_blobs_v2 SET retirement_fenced=TRUE,deleted_ts=NULL WHERE retirement_fenced=FALSE AND " + KEY); PreparedStatement fence = c.prepareStatement("SELECT 1 FROM named_blobs_v2 WHERE retirement_fenced=TRUE" + " AND deleted_ts<=UTC_TIMESTAMP(6) AND " + KEY + " FOR UPDATE")) { - // History needs the TTL fence, not a fabricated cleanup manifest. All versions are still locked. - history.addAll(requested); - for (long version : history) { - bindKey(retire, account, container, name, version); - bindKey(fence, account, container, name, version); - if (retire.executeUpdate() != 1) { + // History needs the TTL fence, not a fabricated cleanup manifest. All versions are still locked. A version + // matched by confirmExistingMatches was already fenced by whoever published it and is deliberately excluded. + List toFence = new ArrayList<>(freshlyPublished); + toFence.addAll(history); + for (long version : toFence) { + bindKey(retireRow, p.account, p.container, p.name, version); + bindKey(fence, p.account, p.container, p.name, version); + if (retireRow.executeUpdate() != 1) { throw new SQLDataException("Named version is no longer eligible"); } // Only the installed fence turns the explicit NULL into a delete timestamp. @@ -313,6 +356,64 @@ static void retire(Connection c, short account, short container, String name, Ma } } + /** + * 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 { + 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); + try (ResultSet r = s.executeQuery()) { + if (!r.next()) { + throw new SQLDataException("Manifest belongs to a different publication"); + } + if (!MessageDigest.isEqual(r.getBytes(1), p.rowHashes.get(version))) { + throw new SQLDataException("Conflicting manifest for named version"); + } + if (!MessageDigest.isEqual(r.getBytes(2), p.intentToken)) { + throw new SQLDataException("Manifest belongs to a different publication"); + } + } + } + } + + /** + * 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. + */ + private static boolean fullyMatches(Connection c, PreparedRetirement p) throws SQLException { + String placeholders = String.join(",", Collections.nCopies(p.requested.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)); + } + try (ResultSet r = s.executeQuery()) { + int matched = 0; + while (r.next()) { + if (!p.name.equals(r.getString(1))) { + return false; + } + long version = r.getLong(2); + if (!MessageDigest.isEqual(r.getBytes(3), p.rowHashes.get(version)) || !MessageDigest.isEqual( + r.getBytes(4), p.intentToken)) { + return false; + } + matched++; + } + return matched == p.requested.size(); + } + } + } + static final class Manifest { final short account; final short container; @@ -337,38 +438,29 @@ private Manifest(ResultSet r) throws SQLException { } } - private static byte[] receipt(List orderedVersions) { - return sha256().digest(orderedVersions.stream().map(String::valueOf).collect(Collectors.joining(",")) - .getBytes(StandardCharsets.US_ASCII)); + /** + * Binds the name and, for every requested version in canonical order, that version's content hash (root, count + * and body, already bound together by {@link #hash}). Any difference in content, or in which versions are + * 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) { + 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)); + } + return d.digest(); } - /** Resolve a lost commit reply from immutable receipts on the authoritative writer, without reading the name. */ - boolean isPublished(short account, short container, String name, List versions) throws SQLException { - List requested = canonicalVersions(versions); - byte[] key = receipt(requested); - String placeholders = String.join(",", Collections.nCopies(requested.size(), "?")); - String sql = "SELECT blob_name,publication_key FROM " + TABLE - + " WHERE account_id=? AND container_id=? AND blob_name=? AND version IN (" + placeholders + ")"; + /** 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); - try (PreparedStatement s = c.prepareStatement(sql)) { - s.setInt(1, account); - s.setInt(2, container); - s.setString(3, name); - for (int i = 0; i < requested.size(); i++) { - s.setLong(i + 4, requested.get(i)); - } - try (ResultSet r = s.executeQuery()) { - int count = 0; - while (r.next()) { - if (!name.equals(r.getString(1)) || !MessageDigest.isEqual(key, r.getBytes(2))) { - return false; - } - count++; - } - return count == requested.size(); - } - } + return fullyMatches(c, p); } } diff --git a/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql index 1af3e0a20f..ec37fdcec0 100644 --- a/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql +++ b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql @@ -3,18 +3,15 @@ AFTER INSERT ON named_blobs_v2 FOR EACH ROW BEGIN DECLARE existing_root VARBINARY(50); - DECLARE existing_name VARBINARY(1400); - -- A manifest row is only ever inserted fully formed, in the same transaction that retires its named version: - -- its mere existence means the tuple is published, regardless of root. Running after the base row lands - -- means an ordinary named PUT locks named_blobs_v2 first and this table second, the same order retire uses, - -- so the two never wait on each other in opposite directions. - SELECT root_id,blob_name INTO existing_root,existing_name FROM named_blob_manifests_v1 + -- A manifest row is only ever inserted fully formed, in the same transaction that retires its named version, + -- and root_id is never NULL in any stored row: existence alone is sufficient, independent of root. Running + -- after the base row lands means an ordinary named PUT locks named_blobs_v2 first and this table second, the + -- same order retire uses. + SELECT root_id INTO existing_root FROM named_blob_manifests_v1 WHERE account_id = NEW.account_id AND container_id = NEW.container_id AND blob_name = NEW.blob_name AND version = NEW.version FOR UPDATE; - -- utf8mb4_bin on VARCHAR still compares under PAD SPACE rules, so an index match can hide a trailing-space - -- alias; compare the stored name byte-for-byte before trusting the lookup. - IF existing_root IS NOT NULL OR existing_name <> BINARY NEW.blob_name THEN + IF existing_root IS NOT NULL THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Named version is reserved'; END IF; END diff --git a/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardUpdateV1.sql b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardUpdateV1.sql index 4915140745..75c252f20d 100644 --- a/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardUpdateV1.sql +++ b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardUpdateV1.sql @@ -3,17 +3,16 @@ AFTER UPDATE ON named_blobs_v2 FOR EACH ROW BEGIN DECLARE existing_root VARBINARY(50); - DECLARE existing_name VARBINARY(1400); -- Only an identity-moving update (root or any key column) needs to consult the manifest table at all: the -- retirement fence's own update only ever touches retirement_fenced/deleted_ts, so it never takes this path -- or this table's lock, in either trigger. IF NEW.blob_id <> OLD.blob_id OR NEW.account_id <> OLD.account_id OR NEW.container_id <> OLD.container_id OR BINARY NEW.blob_name <> BINARY OLD.blob_name OR NEW.version <> OLD.version THEN - SELECT root_id,blob_name INTO existing_root,existing_name FROM named_blob_manifests_v1 + SELECT root_id INTO existing_root FROM named_blob_manifests_v1 WHERE account_id = NEW.account_id AND container_id = NEW.container_id AND blob_name = NEW.blob_name AND version = NEW.version FOR UPDATE; - IF existing_root IS NOT NULL OR existing_name <> BINARY NEW.blob_name THEN + IF existing_root IS NOT NULL THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Named version is reserved'; END IF; END IF; From 3a5e4218db0049c8e24246bd367a4b433cf415da Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Fri, 27 Nov 2026 16:58:46 -0800 Subject: [PATCH 5/5] Clarify retirement recovery and replica promotion before reclamation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ambry-named-mysql/README.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/ambry-named-mysql/README.md b/ambry-named-mysql/README.md index b0a66a2ef8..51422af30c 100644 --- a/ambry-named-mysql/README.md +++ b/ambry-named-mysql/README.md @@ -4,8 +4,12 @@ Each manifest stores the ordered child IDs of one immutable metadata blob in a s `(account_id, container_id, blob_name, version)`, the same key that identifies the named version. The root ID identifies the source of the list; repeated child IDs retain their positions. Prepare the lists in memory. Persist every complete manifest and retire the named versions in one transaction. A crash before commit leaves neither a manifest nor a -retirement. If the commit reply is lost, check the exact version set on the authoritative writer. If not committed, -retry from the original exact inputs. Never resolve a replacement name or fall back to the router's ordinary delete. +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. 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. @@ -93,9 +97,10 @@ The database operations alone are not safe to activate. In addition to the DELET - 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. -- Before permitting failover, verify each promotion candidate has applied all acknowledged retirement transactions - (manifest rows and fenced named versions), not just the schema and trigger. Do not promote or serve from a candidate whose - applied position cannot be proven sufficient. +- 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. - 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.