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..51422af30c --- /dev/null +++ b/ambry-named-mysql/README.md @@ -0,0 +1,120 @@ +# Named delete manifests + +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. 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. + +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. +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. 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`. 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 +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 + +**Defer production DDL until the activation prerequisites below are ready.** Nothing installs automatically, but once +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` +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' +``` + +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" --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 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 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 +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 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. +- 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 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 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..6fb6a89282 --- /dev/null +++ b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java @@ -0,0 +1,947 @@ +/* + * 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.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; +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"; + // 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 { + 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"); + install(ddl, "/NamedBlobManifestTupleGuardInsertV1.sql"); + install(ddl, "/NamedBlobManifestTupleGuardUpdateV1.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(), "")); + } + + /** + * 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.retireWithManifests("account", "container", name, pending).get(10, TimeUnit.SECONDS); + } catch (ExecutionException e) { + 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); + List children = new ArrayList<>(); + for (int i = 0; i < 65; i++) { + children.add(blob(BlobId.BlobDataType.DATACHUNK)); + } + List ids = children.stream().map(BlobId::getID).collect(Collectors.toList()); + insertNamed(db, 7, old, NamedBlobState.READY); + insertNamed(db, 8, replacement, NamedBlobState.IN_PROGRESS); + NamedBlobManifestStore writer = new NamedBlobManifestStore(db); + + // Retirement only ever covers a contiguous prefix of the unfenced range: an unrequested, still-live version + // blocks retiring an older one, exactly as it did before capture and retire were merged. + 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")); + + 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("Conflicting manifest for named version", + () -> retireOne(named, 7, old, reordered.size(), reordered.iterator())); + + 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); + retireOne(named, 7, old, children.size(), children.iterator()); + // isPublished resolves a lost commit reply from the exact content-bound intent, not merely the version set. + assertTrue(writer.isPublished(NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, NAME, + Collections.singletonMap(7L, new NamedBlobManifestStore.PendingVersion(old, children.size(), + children.iterator()))))); + 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( + "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(ACCOUNT, CONTAINER, NAME, 7); + assertEquals(old.getID(), recovered.root); + assertEquals(7L, recovered.version); + // 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); + fail("A valid header checkout must not authorize a dirty payload 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(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. + 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")); + + 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=?" + + " 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)); + } + + @Test + public void testStaleSnapshotRetireReplayObservesCommittedPublication() 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)); + } + 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(); + } + }); + } + + @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); + 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()); + 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"); + } 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")); + 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); + 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")); + }); + } + + @Test + public void testRetirementLocksGapForReplacement() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 7, root, NamedBlobState.READY); + 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, 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)"; + 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)); + } + // 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")); + }); + } + + @Test + public void testPublicationRollsBackWhenNameMutationFails() throws Exception { + withDatabase((db, named) -> { + 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); + 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); + 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 { + 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")); + } + // 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"); + 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, + pendingFor(reversed, roots, childrenByVersion)); + try { + 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", + () -> retireMany(named, pendingFor(jobs.subList(0, 1), roots, childrenByVersion))); + }); + } + + @Test + public void testWaitingTtlCannotReviveRetiredVersion() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 7, root, NamedBlobState.READY); + 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(); + 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, 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); + 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(); + } + }); + } + + /** + * 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 testDirectReinsertAfterPhysicalRemovalRejectsReuse() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId impostor = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 7, root, NamedBlobState.READY); + 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 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()) + "'")); + }); + } + + /** + * 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 testOrdinaryStateUpdateIgnoresExistingManifest() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 7, root, NamedBlobState.READY); + 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")); + }); + } + + /** + * 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) -> { + 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()); + } + 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()); + } + 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); + }); + } + + /** + * 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 testConcurrentRetireBlocksRacingDirectReplaceThenRejectsReuse() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId impostor = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 7, root, NamedBlobState.READY); + List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); + try (Connection retiring = db.getConnection(); Connection replacing = db.getConnection(); + Statement replace = replacing.createStatement()) { + retiring.setAutoCommit(false); + NamedBlobManifestStore.retire(retiring, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(7L, + 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 retire"); + } catch (SQLException blocked) { + assertEquals(1205, blocked.getErrorCode()); + } + retiring.commit(); + replace.executeUpdate("DELETE FROM named_blobs_v2 WHERE version=7"); + expectSqlRejection("Named version is reserved", () -> insertNamed(db, 7, impostor, NamedBlobState.READY)); + expectSqlRejection("Named version is reserved", () -> insertNamed(db, 7, root, NamedBlobState.READY)); + } + }); + } + + 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)); + } + } + + /** + * 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); + 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; + } + + @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(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 per-version cap must be rejected before any descriptor is read. */ + @Test + 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", + () -> retireOne(named, 1, root, MAX_CHILDREN + 1, poisonIterator())); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + }); + } + + /** + * 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 { + 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"); + // Mirror production's Hikari useServerPrepStmts=true so large-payload tests exercise the same statement mode. + db.setUseServerPrepStmts(true); + 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); + } + + /** 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.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..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 @@ -493,6 +493,48 @@ public CompletableFuture updateBlobTtlAndStateToReady(NamedBlobRecord }, null, this.metricsRecoder.namedBlobDBUpdateErrorCount); } + /** + * Validate, publish and fence this exact set of named versions in one transaction. Never returns IDs for a + * router cascade. There is no separate staging step: a version's descriptors are supplied and consumed in the + * same call that retires it. Everything is validated and every iterator is fully consumed into an immutable + * {@link NamedBlobManifestStore.PreparedRetirement} synchronously, before this is handed to the background + * transaction thread: the thread never sees {@code pendingVersions} itself, so the caller mutating or clearing + * that map after this call returns cannot change what gets published. + */ + CompletableFuture retireWithManifests(String accountName, String containerName, String blobName, + Map pendingVersions) { + 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, prepared); + 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..9ebab8f921 --- /dev/null +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java @@ -0,0 +1,546 @@ +/* + * 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.sql.SQLIntegrityConstraintViolationException; +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 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. 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. {@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 + * 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 { + // 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 = 262144; + private static final int MAX_VERSIONS = 32; + 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; + + 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"); + } + } + + /** 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; + + PendingVersion(BlobId root, int expected, Iterator descriptors) { + this.root = Objects.requireNonNull(root, "root"); + this.expected = expected; + this.descriptors = Objects.requireNonNull(descriptors, "descriptors"); + } + } + + /** + * 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(); + 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); + } + 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 { + bindKey(s, account, container, name, version, 1); + } + + private static void bindKey(PreparedStatement s, short account, short container, String name, long version, int at) + throws SQLException { + s.setInt(at, account); + s.setInt(at + 1, container); + s.setString(at + 2, name); + s.setLong(at + 3, version); + } + + static void checkManifestCount(List versions) { + if (versions == null || versions.isEmpty() || versions.size() > MAX_VERSIONS) { + throw new IllegalArgumentException("Invalid number of manifests"); + } + } + + static List canonicalVersions(List versions) { + checkManifestCount(versions); + TreeSet sorted = new TreeSet<>(); + for (Long version : versions) { + if (version == null || !sorted.add(version)) { + throw new IllegalArgumentException("Expected distinct canonical manifest versions"); + } + } + return new ArrayList<>(sorted); + } + + /** + * 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 PreparedRetirement prepare(short account, short container, String name, Map pending) + throws SQLException { + if (name == null || name.isEmpty()) { + throw new SQLDataException("Unsupported named composite capture"); + } + Objects.requireNonNull(pending, "pending"); + List requested = canonicalVersions(new ArrayList<>(pending.keySet())); + + long totalDeclared = 0; + Map counts = new LinkedHashMap<>(); + for (long version : requested) { + PendingVersion p = pending.get(version); + if (p == null) { + throw new IllegalArgumentException("Missing pending descriptors for version " + version); + } + BlobId root = p.root; + if (p.expected < 1 || p.expected > MAX_CHILDREN || root.sizeInBytes() < 1 || root.sizeInBytes() > 50 + || root.getAccountId() != account || root.getContainerId() != container + || root.getBlobDataType() != BlobId.BlobDataType.METADATA) { + throw new SQLDataException("Unsupported named composite capture"); + } + counts.put(version, p.expected); + totalDeclared += p.expected; + } + if (totalDeclared > MAX_CHILDREN) { + throw new SQLDataException("Mixed or oversized publication"); + } + + // Only now, with the whole request's declared size already bounded, consume each iterator and encode its body. + Map rootBytes = new LinkedHashMap<>(); + Map rootIds = new LinkedHashMap<>(); + Map bodies = new LinkedHashMap<>(); + Map rowHashes = new LinkedHashMap<>(); + for (long version : requested) { + PendingVersion p = pending.get(version); + byte[] rb = p.root.toBytes(); + rootBytes.put(version, rb); + String rootId = Base64.getUrlEncoder().withoutPadding().encodeToString(rb); + rootIds.put(version, rootId); + byte[] body = encode(p.descriptors, p.expected, rb); + bodies.put(version, body); + rowHashes.put(version, hash(account, container, name, version, p.expected, rootId, body)); + } + + 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 + // 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<>(); + // An unrequested, still-live row blocks a fresh publish -- retirement only ever covers a contiguous prefix of + // 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, 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 || !p.name.equals(r.getString(1))) { + throw new SQLDataException("Unsupported named version range"); + } + long version = r.getLong(2); + if (!p.counts.containsKey(version)) { + if (r.getBoolean(5)) { + history.add(version); + } else { + unrequestedLiveVersion = true; + } + continue; + } + boolean eligible = r.getInt(4) == NamedBlobState.READY.ordinal() && !r.getBoolean(5) + && Arrays.equals(r.getBytes(3), p.rootBytes.get(version)); + liveMatch.put(version, eligible); + } + } + } + + // 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"); + } + 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"); + } + } catch (SQLIntegrityConstraintViolationException duplicate) { + if (duplicate.getErrorCode() != 1062) { + throw duplicate; + } + confirmExistingMatches(c, p, version); + } + } + } + + if (freshlyPublished.isEmpty()) { + return; + } + if (freshlyPublished.size() != p.requested.size()) { + throw new SQLDataException("Partial manifest set"); + } + 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. 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. + try (ResultSet r = fence.executeQuery()) { + if (!r.next()) { + throw new SQLDataException("Named retirement fence is not installed"); + } + } + } + } + } + + /** + * 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; + final String name; + final long version; + final String root; + final int count; + final byte[] publicationKey; + + private Manifest(ResultSet r) throws SQLException { + 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: " + name + "/" + version); + } + + } + } + + /** + * 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 an exact, content-bound intent, without reading the name. */ + boolean isPublished(PreparedRetirement p) throws SQLException { + try (Connection c = db.getConnection()) { + requireCommittedReads(c); + return fullyMatches(c, p); + } + } + + /** + * Recover a known publication by its exact tuple, without resolving the name or reading the original root. Every + * row in this table is published by construction, so existence alone is sufficient. + */ + Manifest getPublished(short account, short container, String name, long version) throws SQLException { + String sql = "SELECT " + HEADER_COLUMNS + " FROM " + TABLE + " WHERE " + KEY; + try (Connection c = db.getConnection()) { + requireCommittedReads(c); + try (PreparedStatement s = c.prepareStatement(sql)) { + bindKey(s, account, container, Objects.requireNonNull(name, "name"), version); + try (ResultSet r = s.executeQuery()) { + 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 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()) { + requireCommittedReads(c); + 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 published manifest: " + m.name + "/" + m.version); + } + byte[] payload = r.getBytes(1); + byte[] payloadHash = r.getBytes(2); + 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); + 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 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 published manifest"); + } + return Collections.unmodifiableList(ids); + } + + private static byte[] hash(short account, short container, String name, long version, int count, String root, + byte[] body) { + MessageDigest d = sha256(); + 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); + } + + 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/NamedBlobManifestTupleGuardInsertV1.sql b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql new file mode 100644 index 0000000000..ec37fdcec0 --- /dev/null +++ b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardInsertV1.sql @@ -0,0 +1,17 @@ +CREATE TRIGGER named_blob_manifest_tuple_guard_ins_v1 +AFTER INSERT ON named_blobs_v2 +FOR EACH ROW +BEGIN + DECLARE existing_root VARBINARY(50); + -- 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; + 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 new file mode 100644 index 0000000000..75c252f20d --- /dev/null +++ b/ambry-named-mysql/src/main/resources/NamedBlobManifestTupleGuardUpdateV1.sql @@ -0,0 +1,19 @@ +CREATE TRIGGER named_blob_manifest_tuple_guard_upd_v1 +AFTER UPDATE ON named_blobs_v2 +FOR EACH ROW +BEGIN + DECLARE existing_root VARBINARY(50); + -- 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 + 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 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 new file mode 100644 index 0000000000..66b6d54c39 --- /dev/null +++ b/ambry-named-mysql/src/main/resources/NamedBlobManifestV1.ddl @@ -0,0 +1,20 @@ +CREATE TABLE named_blob_manifests_v1 ( + 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 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; + +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..debd4ee353 --- /dev/null +++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java @@ -0,0 +1,67 @@ +/* + * 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.ArrayList; +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((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")); + } + verify(connection, never()).setTransactionIsolation(anyInt()); + verify(connection, never()).prepareStatement(anyString()); + verify(connection).close(); + } + + @Test + public void testPublicationUsesADistinctOrderIndependentSet() { + assertEquals(Arrays.asList(1L, 2L), NamedBlobManifestStore.canonicalVersions(Arrays.asList(2L, 1L))); + for (List invalid : Arrays.asList(Arrays.asList(1L, 1L), Collections.singletonList(null), + Collections.emptyList())) { + try { + NamedBlobManifestStore.canonicalVersions(invalid); + fail("Invalid publication set accepted: " + invalid); + } catch (IllegalArgumentException expected) { + // Reject before acquiring database locks. + } + } + } + + @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()); + } + } +}