From 51f11ab135dbef24f9840e7857dd01608e73473a Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Wed, 2 Dec 2026 17:32:54 -0800 Subject: [PATCH 1/4] Wire single-object named DELETE to bounded retirement Include the bounded writer and gate native and S3 named DELETE by namespace and fence-aware serving. Read bounded root descriptors, publish the exact versions, and resolve a lost commit reply against the same receipt without invoking router DELETE. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../github/ambry/config/FrontendConfig.java | 10 + .../com/github/ambry/named/NamedBlobDb.java | 19 + .../java/com/github/ambry/rest/RestUtils.java | 1 + .../github/ambry/router/GetBlobOptions.java | 50 +- .../ambry/router/GetBlobOptionsBuilder.java | 28 +- .../ambry/router/GetBlobOptionsTest.java | 24 + .../S3NamedBlobRetirementIntegrationTest.java | 176 ++++++ .../ambry/frontend/DeleteBlobHandler.java | 29 +- .../ambry/frontend/DeleteDatasetHandler.java | 1 + .../frontend/FrontendRestRequestService.java | 10 +- .../frontend/NamedBlobRetirementHandler.java | 152 +++++ .../frontend/s3/S3BatchDeleteHandler.java | 3 +- .../frontend/NamedBlobDeleteHandlerTest.java | 136 +++++ .../frontend/S3BatchDeleteHandlerTest.java | 37 ++ .../messageformat/MessageFormatRecord.java | 26 +- .../messageformat/MetadataContentSerDe.java | 41 +- .../MessageFormatRecordTest.java | 17 + ambry-named-mysql/README.md | 54 +- ...NamedBlobManifestStoreIntegrationTest.java | 522 ++++++++++++++++-- .../github/ambry/named/MySqlNamedBlobDb.java | 290 ++++++++-- .../ambry/named/NamedBlobManifestStore.java | 276 +++++---- .../named/NamedBlobManifestStoreTest.java | 34 +- .../github/ambry/router/GetBlobOperation.java | 64 ++- .../ambry/router/NonBlockingRouter.java | 2 +- .../ambry/router/S3NonBlockingRouterTest.java | 24 + 25 files changed, 1731 insertions(+), 295 deletions(-) create mode 100644 ambry-frontend/src/integration-test/java/com/github/ambry/frontend/S3NamedBlobRetirementIntegrationTest.java create mode 100644 ambry-frontend/src/main/java/com/github/ambry/frontend/NamedBlobRetirementHandler.java diff --git a/ambry-api/src/main/java/com/github/ambry/config/FrontendConfig.java b/ambry-api/src/main/java/com/github/ambry/config/FrontendConfig.java index cca2adb943..38a04f5a31 100644 --- a/ambry-api/src/main/java/com/github/ambry/config/FrontendConfig.java +++ b/ambry-api/src/main/java/com/github/ambry/config/FrontendConfig.java @@ -42,6 +42,7 @@ public class FrontendConfig { public static final String MAX_JSON_REQUEST_SIZE_BYTES_KEY = PREFIX + "max.json.request.size.bytes"; public static final String ENABLE_UNDELETE = PREFIX + "enable.undelete"; public static final String NAMED_BLOB_DB_FACTORY = PREFIX + "named.blob.db.factory"; + public static final String NAMED_BLOB_RETIREMENT_NAMESPACE = PREFIX + "named.blob.retirement.namespace"; public static final String CONTAINER_METRICS_EXCLUDED_ACCOUNTS = PREFIX + "container.metrics.excluded.accounts"; public static final String CONTAINER_METRICS_AGGREGATED_ACCOUNTS = PREFIX + "container.metrics.aggregated.accounts"; public static final String INVALID_ASCII_BLOB_NAME_CHARS = PREFIX + "invalid.ascii.blob.name.chars"; @@ -335,6 +336,11 @@ public class FrontendConfig { @Default("null") public final String namedBlobDbFactory; + /** One account/container for single-object named DELETE retirement. Empty disables it. */ + @Config(NAMED_BLOB_RETIREMENT_NAMESPACE) + @Default("") + public final String namedBlobRetirementNamespace; + /** * The comma separated list of account names for which container metrics should not be generated. */ @@ -451,6 +457,10 @@ public FrontendConfig(VerifiableProperties verifiableProperties) { accountStatsStoreFactory = verifiableProperties.getString(ACCOUNT_STATS_STORE_FACTORY, DEFAULT_ACCOUNT_STATS_STORE_FACTORY); namedBlobDbFactory = verifiableProperties.getString(NAMED_BLOB_DB_FACTORY, null); + namedBlobRetirementNamespace = verifiableProperties.getString(NAMED_BLOB_RETIREMENT_NAMESPACE, ""); + if (!namedBlobRetirementNamespace.isEmpty() && !namedBlobRetirementNamespace.matches("[^/]+/[^/]+")) { + throw new IllegalArgumentException(NAMED_BLOB_RETIREMENT_NAMESPACE + " must be empty or account/container"); + } containerMetricsExcludedAccounts = Utils.splitString(verifiableProperties.getString(CONTAINER_METRICS_EXCLUDED_ACCOUNTS, ""), ","); containerMetricsAggregatedAccounts = diff --git a/ambry-api/src/main/java/com/github/ambry/named/NamedBlobDb.java b/ambry-api/src/main/java/com/github/ambry/named/NamedBlobDb.java index a26ab5ecb3..a812c6c1b3 100644 --- a/ambry-api/src/main/java/com/github/ambry/named/NamedBlobDb.java +++ b/ambry-api/src/main/java/com/github/ambry/named/NamedBlobDb.java @@ -18,6 +18,10 @@ import com.github.ambry.frontend.Page; import com.github.ambry.protocol.GetOption; import com.github.ambry.protocol.NamedBlobState; +import com.github.ambry.rest.RestServiceErrorCode; +import com.github.ambry.rest.RestServiceException; +import com.github.ambry.store.StoreKey; +import com.github.ambry.store.StoreKeyFactory; import java.io.Closeable; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -108,6 +112,21 @@ default CompletableFuture put(NamedBlobRecord record) { */ CompletableFuture delete(String accountName, String containerName, String blobName); + /** + * Retire the unfenced versions of the authorized name without deleting data. Blocks on the caller's worker. + * The loader must return the full ordered child list of the exact root, decoding at most the supplied limit. + * A publication is successful only after commit or positive confirmation of the original intent. + */ + default void retire(Container container, String blobName, StoreKeyFactory keyFactory, RetirementLoader loader) + throws Exception { + throw new RestServiceException("Named retirement is unavailable", RestServiceErrorCode.ServiceUnavailable); + } + + @FunctionalInterface + interface RetirementLoader { + List load(StoreKey root, int maxChildren) throws Exception; + } + /** * Pull the stale blobs that need to be cleaned up */ diff --git a/ambry-api/src/main/java/com/github/ambry/rest/RestUtils.java b/ambry-api/src/main/java/com/github/ambry/rest/RestUtils.java index 8627092767..5ceec8ffad 100644 --- a/ambry-api/src/main/java/com/github/ambry/rest/RestUtils.java +++ b/ambry-api/src/main/java/com/github/ambry/rest/RestUtils.java @@ -523,6 +523,7 @@ public static final class InternalKeys { * The internal header to determine if the delete request is coming from a dataset deletion. */ public static final String DATASET_DELETE_ENABLED = KEY_PREFIX + "dataset-delete-enabled"; + public static final String S3_BATCH_DELETE_SUBREQUEST = KEY_PREFIX + "s3-batch-delete-subrequest"; /** diff --git a/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptions.java b/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptions.java index e78459200c..02ab585667 100644 --- a/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptions.java +++ b/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptions.java @@ -34,6 +34,9 @@ public class GetBlobOptions { private final boolean rawMode; private final int blobSegmentIdx; private final RestRequest restRequest; + private final int maxChunkIds; + private final boolean bypassNotFoundCache; + static final int NO_CHUNK_ID_LIMIT = -1; public static final int NO_BLOB_SEGMENT_IDX_SPECIFIED = -1; /** @@ -51,6 +54,13 @@ public class GetBlobOptions { */ public GetBlobOptions(OperationType operationType, GetOption getOption, ByteRange range, boolean resolveRangeOnEmptyBlob, boolean rawMode, int blobSegmentIdx, RestRequest restRequest) { + this(operationType, getOption, range, resolveRangeOnEmptyBlob, rawMode, blobSegmentIdx, restRequest, + NO_CHUNK_ID_LIMIT, false); + } + + GetBlobOptions(OperationType operationType, GetOption getOption, ByteRange range, + boolean resolveRangeOnEmptyBlob, boolean rawMode, int blobSegmentIdx, RestRequest restRequest, int maxChunkIds, + boolean bypassNotFoundCache) { if (operationType == null || getOption == null) { throw new IllegalArgumentException("operationType and getOption must be defined"); } @@ -60,6 +70,12 @@ public GetBlobOptions(OperationType operationType, GetOption getOption, ByteRang if (rawMode && operationType != OperationType.All) { throw new IllegalArgumentException("Raw mode can be used only with OperationType.ALL"); } + if (maxChunkIds != NO_CHUNK_ID_LIMIT && (operationType != OperationType.BlobChunkIds || range != null + || blobSegmentIdx != NO_BLOB_SEGMENT_IDX_SPECIFIED)) { + throw new IllegalArgumentException("maxChunkIds requires BlobChunkIds without a range or segment"); + } + this.maxChunkIds = maxChunkIds; + this.bypassNotFoundCache = bypassNotFoundCache; this.operationType = operationType; this.getOption = getOption; this.range = range; @@ -126,10 +142,33 @@ public RestRequest getRestRequest() { return restRequest; } + /** + * @return whether the caller supplied a chunk ID limit. + */ + public boolean hasMaxChunkIds() { + return maxChunkIds != NO_CHUNK_ID_LIMIT; + } + + /** + * @return the maximum number of child IDs to decode, or {@code -1} if no limit was supplied. + */ + public int getMaxChunkIds() { + return maxChunkIds; + } + + /** + * @return whether the router should query storage despite a cached not-found result. + */ + public boolean shouldBypassNotFoundCache() { + return bypassNotFoundCache; + } + @Override public String toString() { return "GetBlobOptions{operationType=" + operationType + ", getOption=" + getOption + ", range=" + range - + ", rawMode=" + rawMode + ", blobSegmentIdx=" + blobSegmentIdx + ", restRequest=" + restRequest + '}'; + + ", rawMode=" + rawMode + ", blobSegmentIdx=" + blobSegmentIdx + ", restRequest=" + restRequest + + (hasMaxChunkIds() ? ", maxChunkIds=" + maxChunkIds : "") + + (bypassNotFoundCache ? ", bypassNotFoundCache=true" : "") + '}'; } @Override @@ -141,14 +180,17 @@ public boolean equals(Object o) { return false; } GetBlobOptions that = (GetBlobOptions) o; - return resolveRangeOnEmptyBlob == that.resolveRangeOnEmptyBlob && rawMode == that.rawMode - && blobSegmentIdx == that.blobSegmentIdx && operationType == that.operationType && getOption == that.getOption + return maxChunkIds == that.maxChunkIds && bypassNotFoundCache == that.bypassNotFoundCache + && resolveRangeOnEmptyBlob == that.resolveRangeOnEmptyBlob + && rawMode == that.rawMode && blobSegmentIdx == that.blobSegmentIdx && operationType == that.operationType + && getOption == that.getOption && Objects.equals(range, that.range) && Objects.equals(restRequest, that.restRequest); } @Override public int hashCode() { - return Objects.hash(operationType, getOption, range, resolveRangeOnEmptyBlob, rawMode, blobSegmentIdx, restRequest); + return Objects.hash(operationType, getOption, range, resolveRangeOnEmptyBlob, rawMode, blobSegmentIdx, restRequest, + maxChunkIds, bypassNotFoundCache); } /** diff --git a/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptionsBuilder.java b/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptionsBuilder.java index e2f5d8a7e6..7cef3954d8 100644 --- a/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptionsBuilder.java +++ b/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptionsBuilder.java @@ -32,6 +32,8 @@ public class GetBlobOptionsBuilder { private boolean rawMode = false; private RestRequest restRequest = null; private int blobSegmentIdx = NO_BLOB_SEGMENT_IDX_SPECIFIED; + private int maxChunkIds = NO_CHUNK_ID_LIMIT; + private boolean bypassNotFoundCache; /** * @param operationType the {@link GetBlobOptions.OperationType} for this request. @@ -100,11 +102,35 @@ public GetBlobOptionsBuilder blobSegment(int blobSegmentIdx) { return this; } + /** + * Limit an exact, whole-blob {@link GetBlobOptions.OperationType#BlobChunkIds} request. + * The request returns no data channel and fails with {@link RouterErrorCode#BlobTooLarge} if the metadata + * declares more child IDs than the limit. A limit of zero permits blobs with no child IDs. + * @param maxChunkIds the nonnegative remaining child ID budget. + * @return this builder + */ + public GetBlobOptionsBuilder maxChunkIds(int maxChunkIds) { + if (maxChunkIds < 0) { + throw new IllegalArgumentException("maxChunkIds must be nonnegative"); + } + this.maxChunkIds = maxChunkIds; + return this; + } + + /** + * @param bypassNotFoundCache whether to ignore cached not-found results when starting the GET. + * @return this builder + */ + public GetBlobOptionsBuilder bypassNotFoundCache(boolean bypassNotFoundCache) { + this.bypassNotFoundCache = bypassNotFoundCache; + return this; + } + /** * @return the {@link GetBlobOptions} built. */ public GetBlobOptions build() { return new GetBlobOptions(operationType, getOption, range, resolveRangeOnEmptyBlob, rawMode, blobSegmentIdx, - restRequest); + restRequest, maxChunkIds, bypassNotFoundCache); } } diff --git a/ambry-api/src/test/java/com/github/ambry/router/GetBlobOptionsTest.java b/ambry-api/src/test/java/com/github/ambry/router/GetBlobOptionsTest.java index a3fc03d2e4..901be0ac04 100644 --- a/ambry-api/src/test/java/com/github/ambry/router/GetBlobOptionsTest.java +++ b/ambry-api/src/test/java/com/github/ambry/router/GetBlobOptionsTest.java @@ -99,6 +99,30 @@ public void testRawModeWithInvalidCombinations() throws Exception { TestUtils.assertException(IllegalArgumentException.class, () -> options.build(), null); } + @Test + public void testMaxChunkIdsOption() throws Exception { + assertFalse(new GetBlobOptionsBuilder().build().hasMaxChunkIds()); + GetBlobOptionsBuilder options = new GetBlobOptionsBuilder(); + TestUtils.assertException(IllegalArgumentException.class, () -> options.maxChunkIds(-1), null); + for (GetBlobOptions.OperationType type : GetBlobOptions.OperationType.values()) { + if (type != GetBlobOptions.OperationType.BlobChunkIds) { + TestUtils.assertException(IllegalArgumentException.class, + () -> options.operationType(type).maxChunkIds(0).build(), null); + } + } + options.operationType(GetBlobOptions.OperationType.BlobChunkIds); + GetBlobOptions unbounded = + new GetBlobOptionsBuilder().operationType(GetBlobOptions.OperationType.BlobChunkIds).build(); + GetBlobOptions bounded = options.maxChunkIds(0).build(); + assertTrue(bounded.hasMaxChunkIds()); + assertEquals(0, bounded.getMaxChunkIds()); + assertOptionsAreDistinct(unbounded, bounded); + assertOptionsAreDistinct(bounded, options.maxChunkIds(1).build()); + TestUtils.assertException(IllegalArgumentException.class, + () -> options.range(ByteRanges.fromLastNBytes(1)).build(), null); + TestUtils.assertException(IllegalArgumentException.class, () -> options.range(null).blobSegment(0).build(), null); + } + /** * Test toString, equals, and hashCode methods. */ diff --git a/ambry-frontend/src/integration-test/java/com/github/ambry/frontend/S3NamedBlobRetirementIntegrationTest.java b/ambry-frontend/src/integration-test/java/com/github/ambry/frontend/S3NamedBlobRetirementIntegrationTest.java new file mode 100644 index 0000000000..a4c11e0c7f --- /dev/null +++ b/ambry-frontend/src/integration-test/java/com/github/ambry/frontend/S3NamedBlobRetirementIntegrationTest.java @@ -0,0 +1,176 @@ +/* + * Copyright 2026 LinkedIn Corp. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + */ +package com.github.ambry.frontend; + +import com.codahale.metrics.MetricRegistry; +import com.github.ambry.account.Account; +import com.github.ambry.account.AccountService; +import com.github.ambry.account.AccountServiceFactory; +import com.github.ambry.account.Container; +import com.github.ambry.account.InMemAccountService; +import com.github.ambry.clustermap.MockClusterMap; +import com.github.ambry.commons.BlobId; +import com.github.ambry.commons.LoggingNotificationSystem; +import com.github.ambry.config.FrontendConfig; +import com.github.ambry.config.VerifiableProperties; +import com.github.ambry.named.NamedBlobDb; +import com.github.ambry.named.NamedBlobDbFactory; +import com.github.ambry.quota.QuotaResourceType; +import com.github.ambry.rest.NettyClient; +import com.github.ambry.rest.RestServer; +import com.github.ambry.rest.RestServiceErrorCode; +import com.github.ambry.rest.RestServiceException; +import io.netty.handler.codec.http.DefaultFullHttpRequest; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpResponse; +import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.handler.codec.http.HttpVersion; +import io.netty.util.ReferenceCountUtil; +import java.util.Properties; +import java.util.concurrent.TimeUnit; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + + +/** Exercises S3 DELETE over HTTP with a real frontend and in-memory router, and injected named DB outcomes. */ +public class S3NamedBlobRetirementIntegrationTest { + private static final String KEY = "object"; + private static final InMemAccountService ACCOUNTS = new InMemAccountService(false, false); + private static final NamedBlobDb DB = mock(NamedBlobDb.class); + private static MockClusterMap clusterMap; + private static RestServer server; + private static Container container; + private static String objectPath; + private static BlobId missingRoot; + + @ClassRule + public static final TemporaryFolder TEMP = new TemporaryFolder(); + + @BeforeClass + public static void startServer() throws Exception { + Account account = ACCOUNTS.createAndAddRandomAccount(QuotaResourceType.ACCOUNT); + container = account.getAllContainers().iterator().next(); + String namespace = account.getName() + "/" + container.getName(); + objectPath = "/s3/" + namespace + "/" + KEY; + Properties extraProps = new Properties(); + extraProps.setProperty(FrontendConfig.NAMED_BLOB_RETIREMENT_NAMESPACE, namespace); + extraProps.setProperty("rest.server.account.service.factory", TestAccountServiceFactory.class.getName()); + extraProps.setProperty("netty.server.enable.ssl", "false"); + Properties props = S3IntegrationTest.buildFrontendVProps(TEMP.newFile("truststore.jks"), + TestNamedBlobDbFactory.class.getName(), extraProps); + clusterMap = new MockClusterMap(); + missingRoot = new BlobId(BlobId.BLOB_ID_V6, BlobId.BlobIdType.NATIVE, clusterMap.getLocalDatacenterId(), + account.getId(), container.getId(), clusterMap.getWritablePartitionIds(null).get(0), false, + BlobId.BlobDataType.METADATA); + server = new RestServer(new VerifiableProperties(props), clusterMap, new LoggingNotificationSystem(), null); + server.start(); + } + + @AfterClass + public static void stopServer() { + try { + if (server != null) { + server.shutdown(); + } + } finally { + if (clusterMap != null) { + clusterMap.close(); + } + } + } + + @Before + public void resetDb() { + reset(DB); + } + + @Test + public void testSuccessfulRetirementReturnsNoContent() throws Exception { + doNothing().when(DB).retire(eq(container), eq(KEY), any(), any()); + assertDelete(objectPath, HttpResponseStatus.NO_CONTENT, true); + } + + @Test + public void testAbsentNameReturnsNoContent() throws Exception { + doThrow(new RestServiceException("Name is absent", RestServiceErrorCode.NotFound)).when(DB) + .retire(eq(container), eq(KEY), any(), any()); + assertDelete(objectPath, HttpResponseStatus.NO_CONTENT, true); + } + + @Test + public void testMissingStorageRootReturnsServiceUnavailable() throws Exception { + doAnswer(call -> { + NamedBlobDb.RetirementLoader loader = call.getArgument(3); + loader.load(missingRoot, 1); + return null; + }).when(DB).retire(eq(container), eq(KEY), any(), any()); + assertDelete(objectPath, HttpResponseStatus.SERVICE_UNAVAILABLE, true); + } + + @Test + public void testUnconfirmedPublicationReturnsServiceUnavailable() throws Exception { + doThrow(new RestServiceException("Retirement was not confirmed", RestServiceErrorCode.ServiceUnavailable)) + .when(DB).retire(eq(container), eq(KEY), any(), any()); + assertDelete(objectPath, HttpResponseStatus.SERVICE_UNAVAILABLE, true); + } + + @Test + public void testVersionIdDoesNotEnterEitherDeletePath() throws Exception { + assertDelete(objectPath + "?versionId=1", HttpResponseStatus.METHOD_NOT_ALLOWED, false); + } + + private void assertDelete(String path, HttpResponseStatus expected, boolean expectRetirement) throws Exception { + try (NettyClient client = new NettyClient("::1", FrontendIntegrationTestBase.PLAINTEXT_SERVER_PORT, null)) { + DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.DELETE, path); + NettyClient.ResponseParts parts = client.sendRequest(request, null, null).get(10, TimeUnit.SECONDS); + try { + assertEquals(expected, ((HttpResponse) parts.queue.element()).status()); + } finally { + parts.queue.forEach(ReferenceCountUtil::release); + } + } + if (expectRetirement) { + verify(DB).retire(eq(container), eq(KEY), any(), any()); + } + verifyNoMoreInteractions(DB); + } + + public static class TestAccountServiceFactory implements AccountServiceFactory { + public TestAccountServiceFactory(VerifiableProperties properties, MetricRegistry metrics) { + } + + @Override + public AccountService getAccountService() { + return ACCOUNTS; + } + } + + public static class TestNamedBlobDbFactory implements NamedBlobDbFactory { + public TestNamedBlobDbFactory(VerifiableProperties properties, MetricRegistry metrics, AccountService accounts) { + } + + @Override + public NamedBlobDb getNamedBlobDb() { + return DB; + } + } +} diff --git a/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteBlobHandler.java b/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteBlobHandler.java index ba0b0556b6..06b3ac4138 100644 --- a/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteBlobHandler.java +++ b/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteBlobHandler.java @@ -36,6 +36,7 @@ import com.github.ambry.router.Router; import com.github.ambry.utils.Pair; import java.io.IOException; +import java.util.Collections; import java.util.GregorianCalendar; import java.util.Map; import org.slf4j.Logger; @@ -63,10 +64,19 @@ public class DeleteBlobHandler { private final QuotaManager quotaManager; private final AccountService accountService; private final IdSigningService idSigningService; + private final NamedBlobRetirementHandler retirementHandler; DeleteBlobHandler(Router router, SecurityService securityService, IdConverter idConverter, AccountAndContainerInjector accountAndContainerInjector, FrontendMetrics metrics, ClusterMap clusterMap, QuotaManager quotaManager, AccountService accountService, IdSigningService idSigningService) { + this(router, securityService, idConverter, accountAndContainerInjector, metrics, clusterMap, quotaManager, + accountService, idSigningService, null); + } + + DeleteBlobHandler(Router router, SecurityService securityService, IdConverter idConverter, + AccountAndContainerInjector accountAndContainerInjector, FrontendMetrics metrics, ClusterMap clusterMap, + QuotaManager quotaManager, AccountService accountService, IdSigningService idSigningService, + NamedBlobRetirementHandler retirementHandler) { this.router = router; this.securityService = securityService; this.idConverter = idConverter; @@ -76,6 +86,14 @@ public class DeleteBlobHandler { this.quotaManager = quotaManager; this.accountService = accountService; this.idSigningService = idSigningService; + this.retirementHandler = retirementHandler; + } + + void rejectDatasetRetirement(RestRequest request) throws RestServiceException { + if (retirementHandler != null && retirementHandler.matchesAuthorizedNamespace(request)) { + throw new RestServiceException("Dataset DELETE is unsupported in the retirement namespace", + RestServiceErrorCode.NotAllowed); + } } public void handle(RestRequest restRequest, RestResponseChannel restResponseChannel, Callback callback) @@ -145,13 +163,22 @@ private Callback securityProcessRequestCallback() { private Callback securityPostProcessRequestCallback() { return buildCallback(metrics.deleteBlobSecurityPostProcessRequestMetrics, result -> { String serviceId = RestUtils.getHeader(restRequest.getArgs(), RestUtils.Headers.SERVICE_ID, false); + RequestPath requestPath = getRequestPath(restRequest); + if (retirementHandler != null && requestPath.matchesOperation(NAMED_BLOB)) { + // Resolve the target from the same path the legacy DELETE converter would use, not from a header. + NamedBlobPath path = NamedBlobPath.parse(requestPath, Collections.emptyMap()); + if (retirementHandler.matches(path.getAccountName(), path.getContainerName()) + || retirementHandler.matchesAuthorizedNamespace(restRequest)) { + retirementHandler.handle(restRequest, path, routerCallback()); + return; + } + } if (RestUtils.isDatasetVersionQueryEnabled(restRequest.getArgs())) { accountAndContainerInjector.injectDatasetForNamedBlob(restRequest); String datasetVersionPathString = getRequestPath(restRequest).getOperationOrBlobId(false); DatasetVersionRecord datasetVersionRecord = getDatasetVersionHelper(restRequest, datasetVersionPathString, accountService, metrics); if (datasetVersionRecord.getRenameFrom() != null) { - RequestPath requestPath = getRequestPath(restRequest); RequestPath newRequestPath = reconstructRequestPath(datasetVersionRecord, requestPath, ((Account) restRequest.getArgs().get(InternalKeys.TARGET_ACCOUNT_KEY)).getName(), ((Container) restRequest.getArgs().get(InternalKeys.TARGET_CONTAINER_KEY)).getName()); diff --git a/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteDatasetHandler.java b/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteDatasetHandler.java index 7a74888f1f..1c870d4d02 100644 --- a/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteDatasetHandler.java +++ b/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteDatasetHandler.java @@ -126,6 +126,7 @@ private Callback securityProcessRequestCallback() { */ private Callback securityPostProcessRequestCallback() { return buildCallback(frontendMetrics.deleteDatasetsSecurityPostProcessRequestMetrics, securityCheckResult -> { + deleteBlobHandler.rejectDatasetRetirement(restRequest); deleteDataset(); }, uri, LOGGER, finalCallback); } diff --git a/ambry-frontend/src/main/java/com/github/ambry/frontend/FrontendRestRequestService.java b/ambry-frontend/src/main/java/com/github/ambry/frontend/FrontendRestRequestService.java index b05ea3240c..ef6238084b 100644 --- a/ambry-frontend/src/main/java/com/github/ambry/frontend/FrontendRestRequestService.java +++ b/ambry-frontend/src/main/java/com/github/ambry/frontend/FrontendRestRequestService.java @@ -106,6 +106,7 @@ class FrontendRestRequestService implements RestRequestService, RestRequestMetri private TtlUpdateHandler ttlUpdateHandler; private CopyDatasetVersionHandler copyDatasetVersionHandler; private DeleteBlobHandler deleteBlobHandler; + private NamedBlobRetirementHandler retirementHandler; private DeleteDatasetHandler deleteDatasetHandler; private HeadBlobHandler headBlobHandler; private UndeleteHandler undeleteHandler; @@ -212,9 +213,13 @@ public void start() throws InstantiationException { clusterMap, quotaManager, namedBlobDb, accountService); copyDatasetVersionHandler = new CopyDatasetVersionHandler(securityService, accountService, frontendMetrics, accountAndContainerInjector); + if (!frontendConfig.namedBlobRetirementNamespace.isEmpty()) { + retirementHandler = new NamedBlobRetirementHandler(frontendConfig.namedBlobRetirementNamespace, namedBlobDb, + router, clusterMap, quotaManager); + } deleteBlobHandler = new DeleteBlobHandler(router, securityService, idConverter, accountAndContainerInjector, frontendMetrics, - clusterMap, quotaManager, accountService, idSigningService); + clusterMap, quotaManager, accountService, idSigningService, retirementHandler); deleteDatasetHandler = new DeleteDatasetHandler(securityService, accountService, frontendMetrics, accountAndContainerInjector, deleteBlobHandler); @@ -297,6 +302,9 @@ public void start() throws InstantiationException { public void shutdown() { long shutdownBeginTime = System.currentTimeMillis(); isUp = false; + if (retirementHandler != null) { + retirementHandler.close(); + } try { if (quotaManager != null) { quotaManager.shutdown(); diff --git a/ambry-frontend/src/main/java/com/github/ambry/frontend/NamedBlobRetirementHandler.java b/ambry-frontend/src/main/java/com/github/ambry/frontend/NamedBlobRetirementHandler.java new file mode 100644 index 0000000000..fcfb86d28f --- /dev/null +++ b/ambry-frontend/src/main/java/com/github/ambry/frontend/NamedBlobRetirementHandler.java @@ -0,0 +1,152 @@ +/* + * Copyright 2026 LinkedIn Corp. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + */ +package com.github.ambry.frontend; + +import com.github.ambry.account.Account; +import com.github.ambry.account.Container; +import com.github.ambry.clustermap.ClusterMap; +import com.github.ambry.commons.BlobIdFactory; +import com.github.ambry.commons.Callback; +import com.github.ambry.named.NamedBlobDb; +import com.github.ambry.protocol.GetOption; +import com.github.ambry.quota.QuotaChargeCallback; +import com.github.ambry.quota.QuotaManager; +import com.github.ambry.quota.QuotaUtils; +import com.github.ambry.rest.RestMethod; +import com.github.ambry.rest.RestRequest; +import com.github.ambry.rest.RestServiceErrorCode; +import com.github.ambry.rest.RestServiceException; +import com.github.ambry.rest.RestUtils; +import com.github.ambry.router.GetBlobOptions; +import com.github.ambry.router.GetBlobOptionsBuilder; +import com.github.ambry.router.GetBlobResult; +import com.github.ambry.router.Router; +import com.github.ambry.router.RouterErrorCode; +import com.github.ambry.router.RouterException; +import com.github.ambry.store.StoreKey; +import com.github.ambry.utils.Utils; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import static com.github.ambry.rest.RestUtils.InternalKeys.*; + +/** Performs metadata-only DELETE retirement after request authorization. */ +final class NamedBlobRetirementHandler implements AutoCloseable { + private final String namespace; + private final NamedBlobDb namedBlobDb; + private final Router router; + private final BlobIdFactory keyFactory; + private final QuotaManager quotaManager; + private final ThreadPoolExecutor worker = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, + new SynchronousQueue<>(), new Utils.SchedulerThreadFactory("NamedBlobRetirement", true)); + + NamedBlobRetirementHandler(String namespace, NamedBlobDb namedBlobDb, Router router, ClusterMap clusterMap, + QuotaManager quotaManager) { + this.namespace = namespace; + this.namedBlobDb = namedBlobDb; + this.router = router; + this.keyFactory = new BlobIdFactory(clusterMap); + this.quotaManager = quotaManager; + } + + boolean matches(String account, String container) { + return namespace.equals(account + "/" + container); + } + + boolean matchesAuthorizedNamespace(RestRequest request) { + Account account = (Account) request.getArgs().get(TARGET_ACCOUNT_KEY); + Container container = (Container) request.getArgs().get(TARGET_CONTAINER_KEY); + return account != null && container != null && matches(account.getName(), container.getName()); + } + + void handle(RestRequest request, NamedBlobPath path, Callback callback) throws RestServiceException { + if (!matches(path.getAccountName(), path.getContainerName()) || !matchesAuthorizedNamespace(request) + || request.getArgs().containsKey(RestUtils.Headers.BLOB_ID)) { + throw new RestServiceException("Named DELETE path does not match the authorized retirement target", + RestServiceErrorCode.BadRequest); + } + if (request.getRestMethod() != RestMethod.DELETE || request.getArgs().containsKey(S3_BATCH_DELETE_SUBREQUEST) + || request.getArgs().containsKey(DATASET_DELETE_ENABLED) || RestUtils.isDatasetVersionQueryEnabled(request.getArgs()) + || (RestUtils.isS3Request(request) && request.getArgs().containsKey("versionId"))) { + throw new RestServiceException("Only single-object named DELETE is supported in the retirement namespace", + RestServiceErrorCode.NotAllowed); + } + if (namedBlobDb == null) { + throw new RestServiceException("Named retirement is unavailable", RestServiceErrorCode.ServiceUnavailable); + } + Container container = (Container) request.getArgs().get(TARGET_CONTAINER_KEY); + try { + worker.execute(() -> { + Exception failure = null; + try { + QuotaChargeCallback charge = QuotaUtils.buildQuotaChargeCallback(request, quotaManager, false); + namedBlobDb.retire(container, path.getBlobName(), keyFactory, + (root, limit) -> loadChildren(root, limit, request, charge)); + } catch (Exception e) { + failure = e; + } + callback.onCompletion(null, failure); + }); + } catch (RejectedExecutionException e) { + throw new RestServiceException("Named retirement worker is busy or stopped", e, + RestServiceErrorCode.ServiceUnavailable); + } + } + + private List loadChildren(StoreKey root, int limit, RestRequest request, QuotaChargeCallback charge) + throws Exception { + GetBlobOptions options = new GetBlobOptionsBuilder().operationType(GetBlobOptions.OperationType.BlobChunkIds) + .maxChunkIds(limit).bypassNotFoundCache(true).getOption(GetOption.Include_Expired_Blobs).restRequest(request) + .build(); + // The raw-ID overload cannot resolve the name again or invoke named DELETE conversion. + Future read = router.getBlob(root.getID(), options, null, charge); + try { + GetBlobResult result = read.get(); + if (result != null && result.getBlobDataChannel() != null) { + result.getBlobDataChannel().close(); + throw new RestServiceException("Named retirement requires metadata only", RestServiceErrorCode.Conflict); + } + return result == null ? null : result.getBlobChunkIds(); + } catch (ExecutionException e) { + Throwable failure = e.getCause(); + if (failure instanceof RouterException) { + RouterErrorCode code = ((RouterException) failure).getErrorCode(); + if (code == RouterErrorCode.BlobTooLarge) { + throw new RestServiceException("Named retirement exceeds its child limit", failure, + RestServiceErrorCode.Conflict); + } + if (code == RouterErrorCode.TooManyRequests) { + throw new RestServiceException("Named retirement metadata read exceeded quota", failure, + RestServiceErrorCode.TooManyRequests); + } + } + // Storage absence does not prove that the name is absent (S3 maps NotFound to success). + throw new RestServiceException("Cannot read named retirement root", failure, + RestServiceErrorCode.ServiceUnavailable); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw e; + } + } + + @Override + public void close() { + worker.shutdown(); + } +} diff --git a/ambry-frontend/src/main/java/com/github/ambry/frontend/s3/S3BatchDeleteHandler.java b/ambry-frontend/src/main/java/com/github/ambry/frontend/s3/S3BatchDeleteHandler.java index 7e2488fb85..bab40ce558 100644 --- a/ambry-frontend/src/main/java/com/github/ambry/frontend/s3/S3BatchDeleteHandler.java +++ b/ambry-frontend/src/main/java/com/github/ambry/frontend/s3/S3BatchDeleteHandler.java @@ -47,7 +47,7 @@ import static com.github.ambry.rest.RestUtils.*; public class S3BatchDeleteHandler extends S3BaseHandler { - private static DeleteBlobHandler deleteBlobHandler; + private final DeleteBlobHandler deleteBlobHandler; private final XmlMapper xmlMapper; private FrontendMetrics metrics; private static final Logger logger = LoggerFactory.getLogger(S3BatchDeleteHandler.class); @@ -145,6 +145,7 @@ private Callback parseRequestBodyAndDeleteCallback(RetainingAsyncWritableC WrappedRestRequest singleDeleteRequest = new WrappedRestRequest(restRequest); singleDeleteRequest.setArg(InternalKeys.REQUEST_PATH, newRequestPath); singleDeleteRequest.removeArg(BATCH_DELETE_QUERY_PARAM); + singleDeleteRequest.setArg(InternalKeys.S3_BATCH_DELETE_SUBREQUEST, true); NoOpResponseChannel noOpResponseChannel = new NoOpResponseChannel(); CompletableFuture future = new CompletableFuture<>(); diff --git a/ambry-frontend/src/test/java/com/github/ambry/frontend/NamedBlobDeleteHandlerTest.java b/ambry-frontend/src/test/java/com/github/ambry/frontend/NamedBlobDeleteHandlerTest.java index acb754759c..bbc5a43848 100644 --- a/ambry-frontend/src/test/java/com/github/ambry/frontend/NamedBlobDeleteHandlerTest.java +++ b/ambry-frontend/src/test/java/com/github/ambry/frontend/NamedBlobDeleteHandlerTest.java @@ -29,16 +29,27 @@ import com.github.ambry.config.VerifiableProperties; import com.github.ambry.named.NamedBlobDb; import com.github.ambry.named.NamedBlobDbFactory; +import com.github.ambry.protocol.GetOption; +import com.github.ambry.quota.QuotaChargeCallback; +import com.github.ambry.quota.QuotaManager; import com.github.ambry.quota.QuotaTestUtils; import com.github.ambry.rest.MockRestResponseChannel; import com.github.ambry.rest.RequestPath; import com.github.ambry.rest.RestMethod; +import com.github.ambry.rest.ResponseStatus; import com.github.ambry.rest.RestRequest; import com.github.ambry.rest.RestResponseChannel; +import com.github.ambry.rest.RestServiceErrorCode; import com.github.ambry.rest.RestServiceException; import com.github.ambry.rest.RestUtils; import com.github.ambry.router.FutureResult; +import com.github.ambry.router.GetBlobOptions; +import com.github.ambry.router.GetBlobResult; import com.github.ambry.router.InMemoryRouter; +import com.github.ambry.router.Router; +import com.github.ambry.router.RouterErrorCode; +import com.github.ambry.router.RouterException; +import com.github.ambry.store.StoreKey; import com.github.ambry.utils.MockTime; import com.github.ambry.utils.TestUtils; import java.io.UnsupportedEncodingException; @@ -50,11 +61,15 @@ import java.util.LinkedList; import java.util.List; import java.util.Properties; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.json.JSONObject; import org.junit.Test; import static org.junit.Assert.*; +import static org.mockito.Mockito.*; /** @@ -165,6 +180,127 @@ public void deleteMultipleVersionsTest() throws Exception { } } + @Test + public void testRetirementReadsExactRootAndWaitsForPublication() throws Exception { + NamedBlobDb db = mock(NamedBlobDb.class); + Router exactRouter = mock(Router.class); + StoreKey root = mock(StoreKey.class); + StoreKey child = mock(StoreKey.class); + when(root.getID()).thenReturn("exact-root"); + when(exactRouter.getBlob(eq("exact-root"), any(GetBlobOptions.class), isNull(), any(QuotaChargeCallback.class))) + .thenAnswer(call -> { + GetBlobOptions options = call.getArgument(1); + assertEquals(GetBlobOptions.OperationType.BlobChunkIds, options.getOperationType()); + assertEquals(GetOption.Include_Expired_Blobs, options.getGetOption()); + assertEquals(17, options.getMaxChunkIds()); + assertTrue(options.shouldBypassNotFoundCache()); + return CompletableFuture.completedFuture(new GetBlobResult(null, null, Collections.singletonList(child))); + }); + CountDownLatch loaded = new CountDownLatch(1); + CountDownLatch publish = new CountDownLatch(1); + Thread caller = Thread.currentThread(); + doAnswer(call -> { + assertNotSame(caller, Thread.currentThread()); + NamedBlobDb.RetirementLoader loader = call.getArgument(3); + assertEquals(Collections.singletonList(child), loader.load(root, 17)); + loaded.countDown(); + assertTrue(publish.await(TIMEOUT_SECS, TimeUnit.SECONDS)); + return null; + }).when(db).retire(eq(REF_CONTAINER), eq(BLOBNAME), any(), any()); + try (NamedBlobRetirementHandler retirement = retirement(db, exactRouter)) { + DeleteBlobHandler handler = withRetirement(retirement, exactRouter); + MockRestResponseChannel response = new MockRestResponseChannel(); + CompletableFuture first = delete(handler, getDeleteRestRequest(new JSONObject(), request_path), response); + try { + assertTrue(loaded.await(TIMEOUT_SECS, TimeUnit.SECONDS)); + assertFalse(first.isDone()); + assertDeleteError(RestServiceErrorCode.ServiceUnavailable, + delete(handler, getDeleteRestRequest(new JSONObject(), request_path), new MockRestResponseChannel())); + } finally { + publish.countDown(); + } + first.get(TIMEOUT_SECS, TimeUnit.SECONDS); + assertEquals(ResponseStatus.Accepted, response.getStatus()); + verify(db).retire(eq(REF_CONTAINER), eq(BLOBNAME), any(), any()); + verify(exactRouter).getBlob(eq("exact-root"), any(GetBlobOptions.class), isNull(), + any(QuotaChargeCallback.class)); + verifyNoMoreInteractions(db, exactRouter); + } + } + + @Test + public void testRetirementRejectsUnsupportedDeleteShapesWithoutLegacyDelete() throws Exception { + NamedBlobDb db = mock(NamedBlobDb.class); + Router unusedRouter = mock(Router.class); + try (NamedBlobRetirementHandler retirement = retirement(db, unusedRouter)) { + DeleteBlobHandler handler = withRetirement(retirement, unusedRouter); + for (String marker : Arrays.asList(RestUtils.InternalKeys.S3_BATCH_DELETE_SUBREQUEST, + RestUtils.InternalKeys.DATASET_DELETE_ENABLED)) { + RestRequest request = getDeleteRestRequest(new JSONObject(), request_path); + request.setArg(marker, true); + assertDeleteError(RestServiceErrorCode.NotAllowed, delete(handler, request, new MockRestResponseChannel())); + } + verifyNoInteractions(db, unusedRouter); + } + } + + @Test + public void testRetirementDoesNotTreatMissingStorageAsMissingName() throws Exception { + NamedBlobDb db = mock(NamedBlobDb.class); + Router exactRouter = mock(Router.class); + StoreKey root = mock(StoreKey.class); + when(root.getID()).thenReturn("missing-root"); + CompletableFuture missing = new CompletableFuture<>(); + missing.completeExceptionally(new RouterException("Missing root", RouterErrorCode.BlobDoesNotExist)); + when(exactRouter.getBlob(eq("missing-root"), any(GetBlobOptions.class), isNull(), any(QuotaChargeCallback.class))) + .thenReturn(missing); + doAnswer(call -> { + ((NamedBlobDb.RetirementLoader) call.getArgument(3)).load(root, 1); + return null; + }).when(db).retire(eq(REF_CONTAINER), eq(BLOBNAME), any(), any()); + try (NamedBlobRetirementHandler retirement = retirement(db, exactRouter)) { + assertDeleteError(RestServiceErrorCode.ServiceUnavailable, delete(withRetirement(retirement, exactRouter), + getDeleteRestRequest(new JSONObject(), request_path), new MockRestResponseChannel())); + verify(exactRouter).getBlob(eq("missing-root"), any(GetBlobOptions.class), isNull(), + any(QuotaChargeCallback.class)); + verifyNoMoreInteractions(exactRouter); + } + } + + private NamedBlobRetirementHandler retirement(NamedBlobDb db, Router retirementRouter) { + return new NamedBlobRetirementHandler(REF_ACCOUNT.getName() + "/" + REF_CONTAINER.getName(), db, + retirementRouter, CLUSTER_MAP, QuotaTestUtils.createDummyQuotaManager()); + } + + private DeleteBlobHandler withRetirement(NamedBlobRetirementHandler retirement, Router retirementRouter) { + QuotaManager quota = QuotaTestUtils.createDummyQuotaManager(); + return new DeleteBlobHandler(retirementRouter, securityServiceFactory.getSecurityService(), + idConverterFactory.getIdConverter(), injector, metrics, CLUSTER_MAP, quota, ACCOUNT_SERVICE, idSigningService, + retirement); + } + + private static CompletableFuture delete(DeleteBlobHandler handler, RestRequest request, + RestResponseChannel response) throws RestServiceException { + CompletableFuture future = new CompletableFuture<>(); + handler.handle(request, response, (result, failure) -> { + if (failure == null) { + future.complete(result); + } else { + future.completeExceptionally(failure); + } + }); + return future; + } + + private static void assertDeleteError(RestServiceErrorCode code, CompletableFuture future) throws Exception { + try { + future.get(TIMEOUT_SECS, TimeUnit.SECONDS); + fail("Expected " + code); + } catch (ExecutionException failure) { + assertEquals(code, ((RestServiceException) failure.getCause()).getErrorCode()); + } + } + /** * Upload a new version for this named blob and return the blob id. * @return The blob id for the new version diff --git a/ambry-frontend/src/test/java/com/github/ambry/frontend/S3BatchDeleteHandlerTest.java b/ambry-frontend/src/test/java/com/github/ambry/frontend/S3BatchDeleteHandlerTest.java index 751c3410a9..c9e0918148 100644 --- a/ambry-frontend/src/test/java/com/github/ambry/frontend/S3BatchDeleteHandlerTest.java +++ b/ambry-frontend/src/test/java/com/github/ambry/frontend/S3BatchDeleteHandlerTest.java @@ -41,6 +41,7 @@ import com.github.ambry.rest.RestMethod; import com.github.ambry.rest.RestRequest; import com.github.ambry.rest.RestResponseChannel; +import com.github.ambry.rest.RestServiceErrorCode; import com.github.ambry.rest.RestUtils; import com.github.ambry.router.FutureResult; import com.github.ambry.router.InMemoryRouter; @@ -52,6 +53,7 @@ import java.util.Collections; import java.util.LinkedList; import java.util.Properties; +import java.util.concurrent.TimeUnit; import org.json.JSONObject; import org.junit.After; import org.junit.Before; @@ -59,6 +61,7 @@ import static com.github.ambry.frontend.s3.S3Constants.*; import static org.junit.Assert.*; +import static org.mockito.Mockito.*; public class S3BatchDeleteHandlerTest { @@ -142,6 +145,40 @@ public void deleteObjectTest() throws Exception { assertEquals("Mismatch on status", ResponseStatus.Ok, restResponseChannel.getStatus()); } + @Test + public void testBatchDeleteDoesNotRetireOrDeleteSelectedNamespace() throws Exception { + MockClusterMap clusterMap = new MockClusterMap(); + NamedBlobDb db = mock(NamedBlobDb.class); + InMemoryRouter router = mock(InMemoryRouter.class); + AccountAndContainerInjector injector = new AccountAndContainerInjector(ACCOUNT_SERVICE, metrics, frontendConfig); + SecurityService security = new FrontendTestSecurityServiceFactory().getSecurityService(); + try (NamedBlobRetirementHandler retirement = new NamedBlobRetirementHandler( + account.getName() + "/" + container.getName(), db, router, clusterMap, + QuotaTestUtils.createDummyQuotaManager())) { + DeleteBlobHandler delete = new DeleteBlobHandler(router, security, null, injector, metrics, clusterMap, + QuotaTestUtils.createDummyQuotaManager(), ACCOUNT_SERVICE, null, retirement); + S3BatchDeleteHandler batch = new S3BatchDeleteHandler(delete, metrics); + String uri = String.format("/s3/%s/%s", account.getName(), container.getName()); + byte[] body = ("" + KEY_NAME + "") + .getBytes(StandardCharsets.UTF_8); + RestRequest request = FrontendRestRequestServiceTest.createRestRequest(RestMethod.POST, uri, new JSONObject(), + new LinkedList<>(Arrays.asList(ByteBuffer.wrap(body), null))); + request.setArg(RestUtils.InternalKeys.REQUEST_PATH, + RequestPath.parse(request, frontendConfig.pathPrefixesToRemove, CLUSTER_NAME)); + FutureResult future = new FutureResult<>(); + batch.handle(request, new MockRestResponseChannel(), future::done); + try (ReadableStreamChannel response = future.get(5, TimeUnit.SECONDS)) { + ByteBuffer xml = ((ByteBufferReadableStreamChannel) response).getContent(); + S3MessagePayload.DeleteResult result = new XmlMapper().readValue(xml.array(), S3MessagePayload.DeleteResult.class); + assertTrue(result.getDeleted() == null || result.getDeleted().isEmpty()); + assertEquals(1, result.getErrors().size()); + assertEquals(new S3MessagePayload.S3ErrorObject(KEY_NAME, RestServiceErrorCode.NotAllowed.toString()).toString(), + result.getErrors().get(0).toString()); + } + verifyNoInteractions(db, router); + } + } + @Test public void testConsumeContentAsBytesReleasesBuffer() { // Arrange: Create a ByteBuf with some data diff --git a/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MessageFormatRecord.java b/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MessageFormatRecord.java index d2a6a59914..1e55460bcb 100644 --- a/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MessageFormatRecord.java +++ b/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MessageFormatRecord.java @@ -1912,10 +1912,24 @@ public static void serializeMetadataContentRecord(ByteBuffer outputBuffer, int c */ public static CompositeBlobInfo deserializeMetadataContentRecord(DataInputStream stream, StoreKeyFactory storeKeyFactory) throws IOException { - List keys = new ArrayList(); + return deserializeMetadataContentRecord(stream, storeKeyFactory, MetadataContentSerDe.NO_CHUNK_ID_LIMIT); + } + + static CompositeBlobInfo deserializeMetadataContentRecord(DataInputStream stream, StoreKeyFactory storeKeyFactory, + int maxChunkIds) throws IOException { int chunkSize = stream.readInt(); long totalSize = stream.readLong(); - long numberOfKeys = (totalSize + chunkSize - 1) / chunkSize; + long numberOfKeys; + if (maxChunkIds == MetadataContentSerDe.NO_CHUNK_ID_LIMIT) { + numberOfKeys = (totalSize + chunkSize - 1) / chunkSize; + } else { + if (chunkSize <= 0 || totalSize <= 0) { + throw new IOException("Invalid V2 metadata chunk or total size"); + } + numberOfKeys = 1 + (totalSize - 1) / chunkSize; + MetadataContentSerDe.checkChunkCount(numberOfKeys, maxChunkIds); + } + List keys = new ArrayList<>(); for (int i = 0; i < numberOfKeys; i++) { StoreKey storeKey = storeKeyFactory.getStoreKey(stream); keys.add(storeKey); @@ -1998,10 +2012,16 @@ public static void serializeMetadataContentRecord(ByteBuffer outputBuffer, long */ public static CompositeBlobInfo deserializeMetadataContentRecord(DataInputStream stream, StoreKeyFactory storeKeyFactory) throws IOException { - List> keysAndContentSizes = new ArrayList<>(); + return deserializeMetadataContentRecord(stream, storeKeyFactory, MetadataContentSerDe.NO_CHUNK_ID_LIMIT); + } + + static CompositeBlobInfo deserializeMetadataContentRecord(DataInputStream stream, StoreKeyFactory storeKeyFactory, + int maxChunkIds) throws IOException { long totalSize = stream.readLong(); long sum = 0; int numberOfKeys = stream.readInt(); + MetadataContentSerDe.checkChunkCount(numberOfKeys, maxChunkIds); + List> keysAndContentSizes = new ArrayList<>(); for (int i = 0; i < numberOfKeys; i++) { long contentSize = stream.readLong(); StoreKey storeKey = storeKeyFactory.getStoreKey(stream); diff --git a/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MetadataContentSerDe.java b/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MetadataContentSerDe.java index 22495f03a7..94b19fe995 100644 --- a/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MetadataContentSerDe.java +++ b/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MetadataContentSerDe.java @@ -27,6 +27,7 @@ * A class to serialize and deserialize MetadataContent which forms the content of a Metadata Blob. */ public class MetadataContentSerDe { + static final int NO_CHUNK_ID_LIMIT = -1; /** * Serialize the input list of keys that form the metadata content. @@ -70,17 +71,53 @@ public static ByteBuffer serializeMetadataContentV3(long totalSize, List maxChunkIds) { + throw new ChunkCountLimitExceededException(chunkCount, maxChunkIds); + } + } + } + + /** Indicates that a metadata record declares more child IDs than the request permits. */ + public static final class ChunkCountLimitExceededException extends IOException { + private ChunkCountLimitExceededException(long chunkCount, int maxChunkIds) { + super("Metadata declares " + chunkCount + " chunk IDs; limit is " + maxChunkIds); + } + } } diff --git a/ambry-messageformat/src/test/java/com/github/ambry/messageformat/MessageFormatRecordTest.java b/ambry-messageformat/src/test/java/com/github/ambry/messageformat/MessageFormatRecordTest.java index 21eae28896..14e8792b01 100644 --- a/ambry-messageformat/src/test/java/com/github/ambry/messageformat/MessageFormatRecordTest.java +++ b/ambry-messageformat/src/test/java/com/github/ambry/messageformat/MessageFormatRecordTest.java @@ -564,6 +564,8 @@ public void testMetadataContentRecordV2() throws IOException, MessageFormatExcep long[] totalSizes = {(long) keys.size() * chunkSizes[0], ((long) keys.size() * chunkSizes[1]) - 11}; for (int i = 0; i < chunkSizes.length; i++) { ByteBuffer metadataContent = getSerializedMetadataContentV2(chunkSizes[i], totalSizes[i], keys); + assertEquals(keys, MetadataContentSerDe.deserializeMetadataContentRecord(metadataContent.duplicate(), + new MockIdFactory(), keys.size()).getKeys()); CompositeBlobInfo compositeBlobInfo = deserializeMetadataContentV2(metadataContent, new MockIdFactory()); Assert.assertEquals("Chunk size doesn't match", chunkSizes[i], compositeBlobInfo.getChunkSize()); Assert.assertEquals("Total size doesn't match", totalSizes[i], compositeBlobInfo.getTotalSize()); @@ -586,6 +588,8 @@ public void testMetadataContentRecordV3() throws IOException, MessageFormatExcep } ByteBuffer metadataContent = getSerializedMetadataContentV3(total, keysAndContentSizes); + assertEquals(keys, MetadataContentSerDe.deserializeMetadataContentRecord(metadataContent.duplicate(), + new MockIdFactory(), keys.size()).getKeys()); CompositeBlobInfo compositeBlobInfo = deserializeMetadataContentV3(metadataContent, new MockIdFactory()); Assert.assertEquals("Total size doesn't match", total, compositeBlobInfo.getTotalSize()); Assert.assertEquals("List of keys dont match", keys, compositeBlobInfo.getKeys()); @@ -600,6 +604,19 @@ public void testMetadataContentRecordV3() throws IOException, MessageFormatExcep } } + @Test + public void testRejectsOversizedMetadataBeforeReadingChildRecords() throws Exception { + ByteBuffer v2 = ByteBuffer.allocate(Short.BYTES + Integer.BYTES + Long.BYTES); + v2.putShort(Metadata_Content_Version_V2).putInt(2).putLong(Long.MAX_VALUE); + ByteBuffer v3 = ByteBuffer.allocate(Short.BYTES + Long.BYTES + Integer.BYTES); + v3.putShort(Metadata_Content_Version_V3).putLong(1).putInt(Integer.MAX_VALUE); + for (ByteBuffer header : new ByteBuffer[]{v2, v3}) { + header.flip(); + TestUtils.assertException(MetadataContentSerDe.ChunkCountLimitExceededException.class, + () -> MetadataContentSerDe.deserializeMetadataContentRecord(header, new MockIdFactory(), 1), null); + } + } + @Test public void testInvalidMetadataContentV2Fields() { List keys = getKeys(60, 5); diff --git a/ambry-named-mysql/README.md b/ambry-named-mysql/README.md index 919c88c07c..05633fd354 100644 --- a/ambry-named-mysql/README.md +++ b/ambry-named-mysql/README.md @@ -6,10 +6,25 @@ the source of the list; repeated child IDs retain their positions. Prepare the l manifest and retire the named versions in one transaction. A crash before commit leaves neither a manifest nor a retirement. -Before dispatch, retain the original named-version keys, each root ID, and its ordered child IDs. If the commit reply is -lost, check that exact request on the authoritative writer. A match confirms the commit; it does not authorize cleanup. -No match means the commit was not observed, not that it rolled back. Retry only the original request. If the inputs are -unavailable, stop. Never resolve the current name to reconstruct the request or fall back to the router's ordinary delete. +`prepareRetirement` resolves the account and container once and reserves one request per named DB instance before +invoking the descriptor supplier. Supply the exact named versions and roots, and defer descriptor work to the supplier. +Preparation, publication, and receipt checks block; run them off the event loop. There is no payload queue. Close the +handle on all paths: while it is open, a second request is rejected as unavailable. The 32 MiB limit is on encoded child +bytes, not peak heap: allow for encoding buffers, supplier memory, and JDBC packet buffers. Publication or confirmation +can also occupy one connection from the same pool as ordinary requests, outside the transaction executor. + +Use the same handle to publish, to check its receipt after an uncertain result, and to retry. Each call checks out an +idle, autocommit `REPEATABLE READ` session from the configured local writer pool and starts a fresh transaction. +Publication and confirmation require a fixed Connector/J connection with reconnect disabled. The retirement checkout +caps socket reads at five seconds and restores the previous timeout before returning a healthy connection. Do not set a +pool-wide `socketTimeout` for retirement. Socket or communications failures discard the checkout without a rollback +attempt; an interrupted commit is still an unknown outcome. Configure bounded pool checkout and descriptor fetches. +The read timeout is not an end-to-end deadline, and closing the handle does not interrupt an active call. + +A matching receipt confirms the commit; it does not authorize cleanup. No match means the commit was not observed, not +that it rolled back. A replay whose read snapshot predates a concurrent commit can still reject if replacements now +exceed the range cap; confirm again in a fresh transaction. If the original inputs are unavailable, stop. Never resolve +the current name to reconstruct the request or use the router's ordinary delete. A reader with a saved tuple can recover the published list after a restart without fetching the original root. Configure the reader data source for `READ COMMITTED` or stronger on every checkout. @@ -18,8 +33,8 @@ 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. +Retirement requires one authoritative InnoDB writer for the name range, soft deletes, and `REPEATABLE READ` during +publication. It does 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 @@ -114,10 +129,26 @@ before retrying `ALTER TABLE ... ADD INDEX`; each retry rebuilds the index. Afte version, finalize its TTL by exact primary key, verify one row changed to READY with `deleted_ts IS NULL`, and roll back. Verify the fixture row is absent afterward. Never use a customer row; stop on any error. -## Before enabling a caller +## Single-object named DELETE + +`frontend.named.blob.retirement.namespace` defaults to empty. If set to one `account/container`, authorized native and +S3 single-object named DELETEs for that namespace use retirement instead of the legacy named and router DELETEs. The +writer refuses publication unless `mysql.named.blob.honor.retirement.fence` is enabled. Batch, dataset, and S3 +`versionId` DELETEs are rejected for the selected namespace; multipart aborts and raw-ID DELETEs do not use this path. + +The frontend uses one worker with no queue. Under the DB's admission permit, it selects exact live versions from the +local writer, closes the selection transaction, and fetches only their root metadata by ID. The router bypasses its +negative cache and checks the remaining child budget before allocating the decoded list. Publication rechecks the full +name range under lock. If the commit reply is lost, the same request checks only its exact receipt. A missing or +unreadable receipt returns an error, not success. + +## Before enabling publication The database operations alone are not safe to activate. In addition to the DELETE and cleaner gates below: +- Provide a way to pause publication that rejects named DELETEs in the selected namespace. Clearing the namespace + setting restores legacy physical DELETE and is not a pause mechanism. Verify that clients and intermediaries will + not automatically replay ambiguous DELETEs: a new HTTP request may target a replacement. - After verifying the migration on every read endpoint, enable `mysql.named.blob.honor.retirement.fence` on every frontend before publishing any retirements. It defaults to `false`, so readers can run against the original schema. When enabled, ordinary and include-expired GET return `Deleted` for a fenced version even if the frontend clock is @@ -162,8 +193,9 @@ The database operations alone are not safe to activate. In addition to the DELET - 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 enabling reclamation, 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 @@ -175,5 +207,5 @@ On rollback, disable publication but retain fence-aware reads, the DELETE gate, 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. +This path does not retire raw parent IDs, establish exclusive ownership of chunks, schedule cleanup, or reclaim space. +Those are separate prerequisites for reclamation. diff --git a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java index 69c053e6c1..2d55165ae9 100644 --- a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java +++ b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java @@ -9,6 +9,7 @@ import static org.mockito.Mockito.*; import java.io.InputStream; +import java.net.SocketTimeoutException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -26,11 +27,13 @@ import java.util.Scanner; import java.util.UUID; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import javax.sql.DataSource; @@ -53,10 +56,12 @@ import com.github.ambry.protocol.NamedBlobState; import com.github.ambry.rest.RestServiceErrorCode; import com.github.ambry.rest.RestServiceException; +import com.github.ambry.store.StoreKeyFactory; import com.github.ambry.utils.MockTime; import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.Time; import com.mysql.cj.jdbc.MysqlDataSource; +import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; public class NamedBlobManifestStoreIntegrationTest { @@ -118,6 +123,12 @@ private static MySqlNamedBlobDb namedDb(DataSource db) throws Exception { return namedDb(db, new Properties(), SystemTime.getInstance()); } + private static MySqlNamedBlobDb namedDb(DataSource db, boolean hardDelete) throws Exception { + Properties properties = new Properties(); + properties.setProperty(MySqlNamedBlobDbConfig.ENABLE_HARD_DELETE, Boolean.toString(hardDelete)); + return namedDb(db, properties, SystemTime.getInstance()); + } + private static MySqlNamedBlobDb namedDb(DataSource db, Properties properties, Time time) throws Exception { properties.setProperty(MySqlNamedBlobDbConfig.DB_INFO, "[{\"url\":\"jdbc:mysql://[::1]\",\"datacenter\":\"local\",\"isWriteable\":true," @@ -134,6 +145,90 @@ private static InMemAccountService fixtureAccounts() throws Exception { return accounts; } + @Test + public void testWiredRetirementConfirmsLostReplyWithoutLoadingReplacement() throws Exception { + withDatabase((db, disabled) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId replacement = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + StoreKeyFactory keyFactory = mock(StoreKeyFactory.class); + when(keyFactory.getStoreKey(root.getID())).thenReturn(root); + Container container = fixtureAccounts().getAccountById(ACCOUNT).getContainerById(CONTAINER); + NamedBlobDb.RetirementLoader loader = mock(NamedBlobDb.RetirementLoader.class); + doReturn(Collections.singletonList(child)).when(loader).load(root, MAX_CHILDREN); + try { + disabled.retire(container, NAME, keyFactory, loader); + fail("Fence-aware reads are disabled"); + } catch (RestServiceException failure) { + assertEquals(RestServiceErrorCode.ServiceUnavailable, failure.getErrorCode()); + } + verifyNoInteractions(loader); + try (Connection physical = db.getConnection()) { + Connection lostReply = mock(Connection.class, delegatesTo(physical)); + doAnswer(call -> { + physical.commit(); + insertNamed(db, 2, replacement, NamedBlobState.READY); + throw new SQLException("Simulated lost commit reply", "S1000", new SocketTimeoutException()); + }).when(lostReply).commit(); + DataSource writer = mock(DataSource.class); + when(writer.getConnection()).thenAnswer(call -> db.getConnection()).thenReturn(lostReply) + .thenAnswer(call -> db.getConnection()); + try (MySqlNamedBlobDb named = fenceAwareWriter(writer)) { + named.retire(container, NAME, keyFactory, loader); + } + } + verify(loader).load(root, MAX_CHILDREN); + verifyNoMoreInteractions(loader); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1 WHERE version=1")); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=2 AND retirement_fenced=FALSE")); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1 WHERE version=2")); + }); + } + + @Test + public void testWiredRetirementRejectsReplacementAndUnsupportedRootsWithoutMutation() throws Exception { + withDatabase((db, unused) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId replacement = blob(BlobId.BlobDataType.SIMPLE); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + StoreKeyFactory keyFactory = mock(StoreKeyFactory.class); + when(keyFactory.getStoreKey(root.getID())).thenReturn(root); + when(keyFactory.getStoreKey(replacement.getID())).thenReturn(replacement); + Container container = fixtureAccounts().getAccountById(ACCOUNT).getContainerById(CONTAINER); + try (MySqlNamedBlobDb named = fenceAwareWriter(db)) { + try { + named.retire(container, NAME, keyFactory, (selected, limit) -> { + assertEquals(root, selected); + insertNamed(db, 2, replacement, NamedBlobState.READY); + return Collections.singletonList(child); + }); + fail("The original intent did not represent the replacement"); + } catch (RestServiceException failure) { + assertEquals(RestServiceErrorCode.ServiceUnavailable, failure.getErrorCode()); + } + try { + named.retire(container, NAME, keyFactory, (selected, limit) -> { + fail("All roots must be supported before reading any children"); + return Collections.emptyList(); + }); + fail("A simple root is not supported"); + } catch (RestServiceException failure) { + assertEquals(RestServiceErrorCode.Conflict, failure.getErrorCode()); + } + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + assertEquals(2, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE retirement_fenced=FALSE")); + }); + } + + private static MySqlNamedBlobDb fenceAwareWriter(DataSource writer) throws Exception { + Properties properties = new Properties(); + properties.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, "true"); + return namedDb(writer, properties, SystemTime.getInstance()); + } + @Test public void testFenceAwareGetWithSlowFrontend() throws Exception { withDatabase((db, writer) -> { @@ -266,8 +361,7 @@ private static void assertPage(MySqlNamedBlobDb reader, String prefix, String to } /** - * Validate, publish and fence one named version in one call; there is no separate staging step, so the - * descriptors are supplied and consumed in the same transaction that retires the version. + * Capture descriptors in memory, then publish the manifest and fence the named version in one transaction. */ private static void retireOne(MySqlNamedBlobDb db, long version, BlobId root, int count, Iterator children) throws Exception { @@ -287,16 +381,23 @@ private static void retireMany(MySqlNamedBlobDb db, Map pending) throws Exception { - try { - db.retireWithManifests("account", "container", name, pending).get(10, TimeUnit.SECONDS); - } catch (ExecutionException e) { - if (e.getCause() instanceof SQLException) { - throw (SQLException) e.getCause(); - } - throw e; + try (MySqlNamedBlobDb.Retirement retirement = db.prepareRetirement("account", "container", name, () -> pending)) { + retirement.publish(); } } + private static boolean isPublished(MySqlNamedBlobDb db, Map pending) + throws Exception { + try (MySqlNamedBlobDb.Retirement retirement = db.prepareRetirement("account", "container", NAME, () -> pending)) { + return retirement.isPublished(); + } + } + + private static void retireInTransaction(Connection c, String name, + Map pending) throws SQLException { + NamedBlobManifestStore.retire(c, NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, name, pending)); + } + private static Map pendingFor(List versions, Map roots, Map> childrenByVersion) { Map pending = new LinkedHashMap<>(); @@ -333,10 +434,8 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep List ids = children.stream().map(BlobId::getID).collect(Collectors.toList()); insertNamed(db, 7, old, NamedBlobState.READY); insertNamed(db, 8, replacement, NamedBlobState.IN_PROGRESS); - NamedBlobManifestStore writer = new NamedBlobManifestStore(db); - // Retirement only ever covers a contiguous prefix of the unfenced range: an unrequested, still-live version - // blocks retiring an older one, exactly as it did before capture and retire were merged. + // An unrequested, still-live version blocks retiring an older version of the same name. expectDataError("Unrepresented or ineligible", () -> retireOne(named, 7, old, children.size(), children.iterator())); assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); @@ -371,14 +470,13 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep insertNamed(db, 8, replacement, NamedBlobState.READY); retireOne(named, 7, old, children.size(), children.iterator()); // isPublished resolves a lost commit reply from the exact content-bound intent, not merely the version set. - assertTrue(writer.isPublished(NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, NAME, - Collections.singletonMap(7L, new NamedBlobManifestStore.PendingVersion(old, children.size(), - children.iterator()))))); + assertTrue(isPublished(named, Collections.singletonMap(7L, + new NamedBlobManifestStore.PendingVersion(old, children.size(), children.iterator())))); Map unpublishedPair = new LinkedHashMap<>(); unpublishedPair.put(7L, new NamedBlobManifestStore.PendingVersion(old, children.size(), children.iterator())); unpublishedPair.put(8L, new NamedBlobManifestStore.PendingVersion(replacement, 1, Collections.singletonList(children.get(0)).iterator())); - assertFalse(writer.isPublished(NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, NAME, unpublishedPair))); + assertFalse(isPublished(named, unpublishedPair)); assertEquals(replacement.getID(), named.get("account", "container", NAME).get(10, TimeUnit.SECONDS).getBlobId()); // Remove the retired fixture row entirely: a worker that resolves the source name cannot pass. try (Connection c = db.getConnection(); PreparedStatement remove = c.prepareStatement( @@ -458,10 +556,10 @@ public void testStaleSnapshotRetireReplayObservesCommittedPublication() throws E retireOne(named, 1, root, 1, children.iterator()); // A racer whose snapshot predates the winner's commit must still observe the published row when its own // locking read runs: that read is not snapshot-isolated, so the replay is idempotent rather than blind. - NamedBlobManifestStore.retire(loser, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(1L, + retireInTransaction(loser, NAME, Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); expectDataError("Conflicting manifest for named version", - () -> NamedBlobManifestStore.retire(loser, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(1L, + () -> retireInTransaction(loser, NAME, Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())))); loser.rollback(); @@ -560,7 +658,7 @@ public void testFenceAwarePutDuringPublication() throws Exception { rc.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); when(checkouts.getConnection()).thenReturn(rr, rc); publisher.setAutoCommit(false); - NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, NAME, pending); + retireInTransaction(publisher, NAME, pending); CompletableFuture waiting = writer.put(lower, NamedBlobState.READY, true); awaitCount(publisher, "SELECT COUNT(*) FROM performance_schema.data_lock_waits" + " WHERE BLOCKING_THREAD_ID=PS_CURRENT_THREAD_ID()", 1); @@ -866,7 +964,7 @@ public void testRetirementLocksGapForReplacement() throws Exception { try (Connection publisher = db.getConnection(); Connection replacement = db.getConnection(); Statement insert = replacement.createStatement()) { publisher.setAutoCommit(false); - NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(7L, + retireInTransaction(publisher, NAME, Collections.singletonMap(7L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); insert.execute("SET SESSION innodb_lock_wait_timeout=1"); String put = "INSERT INTO named_blobs_v2 (account_id,container_id,blob_name,version,blob_id,blob_state)" @@ -923,10 +1021,9 @@ public void testPublicationRollsBackWhenNameMutationFails() throws Exception { reversed.sort(Collections.reverseOrder()); try (Connection replay = db.getConnection()) { replay.setAutoCommit(false); - NamedBlobManifestStore.retire(replay, ACCOUNT, CONTAINER, NAME, - pendingFor(reversed, roots, childrenByVersion)); + retireInTransaction(replay, NAME, pendingFor(reversed, roots, childrenByVersion)); try { - NamedBlobManifestStore.retire(replay, ACCOUNT, CONTAINER, NAME, Collections.emptyMap()); + retireInTransaction(replay, NAME, Collections.emptyMap()); fail("An empty set is not a publication receipt"); } catch (IllegalArgumentException expected) { assertEquals("Invalid number of manifests", expected.getMessage()); @@ -972,7 +1069,7 @@ public void testWaitingTtlCannotReviveRetiredVersion() throws Exception { + " AND info LIKE 'UPDATE named_blobs_v2 SET blob_state=%'") == 0) { assertTrue("TTL statement never began", System.nanoTime() < deadline && !blocked.isDone()); } - NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(7L, + retireInTransaction(publisher, NAME, Collections.singletonMap(7L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); publisher.commit(); assertEquals("45000", blocked.get(10, TimeUnit.SECONDS)); @@ -1152,9 +1249,9 @@ public void testTwoUnrelatedFreshPublicationsDoNotContendOnTheManifestTable() th } // Both are genuinely fresh inserts into the same, otherwise empty manifest table; a preceding locking // read on either absent key would gap-lock the other, and the two inserts would then deadlock (1213). - NamedBlobManifestStore.retire(first, ACCOUNT, CONTAINER, nameA, Collections.singletonMap(1L, + retireInTransaction(first, nameA, Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(rootA, 1, childrenA.iterator()))); - NamedBlobManifestStore.retire(second, ACCOUNT, CONTAINER, nameB, Collections.singletonMap(1L, + retireInTransaction(second, nameB, Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(rootB, 1, childrenB.iterator()))); first.commit(); second.commit(); @@ -1199,23 +1296,16 @@ public void testDifferentRootForTheSameVersionCannotImpersonateAPublishedIntent( insertNamed(db, 1, publishedRoot, NamedBlobState.READY); List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); retireOne(named, 1, publishedRoot, 1, children.iterator()); - NamedBlobManifestStore writer = new NamedBlobManifestStore(db); - assertFalse(writer.isPublished(NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, NAME, - Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(impostorRoot, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()))))); + assertFalse(isPublished(named, Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(impostorRoot, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())))); expectDataError("Conflicting manifest for named version", () -> retireOne(named, 1, impostorRoot, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); }); } - /** - * The concretely reported gap: retireWithManifests used to capture the caller's own mutable map by reference - * into a lambda queued for a background thread. Everything is now validated and every iterator fully consumed - * into an immutable, caller-retainable description before that dispatch, so mutating or clearing the caller's - * map immediately after the call returns must not change what gets published. - */ @Test - public void testMutatingCallerMapAfterDispatchDoesNotAffectThePublishedContent() throws Exception { + public void testMutatingCallerMapAfterPreparationDoesNotAffectThePublishedContent() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); BlobId decoy = blob(BlobId.BlobDataType.METADATA); @@ -1223,19 +1313,351 @@ public void testMutatingCallerMapAfterDispatchDoesNotAffectThePublishedContent() List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); Map pending = new LinkedHashMap<>(); pending.put(1L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator())); - Future future = named.retireWithManifests("account", "container", NAME, pending); - // Mutate the caller's own map immediately after dispatch: a captured reference to this map would let this - // mutation race the background transaction and silently change what it publishes. - pending.clear(); - pending.put(1L, new NamedBlobManifestStore.PendingVersion(decoy, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); - future.get(10, TimeUnit.SECONDS); + try (MySqlNamedBlobDb.Retirement retirement = + named.prepareRetirement("account", "container", NAME, () -> pending)) { + pending.clear(); + pending.put(1L, new NamedBlobManifestStore.PendingVersion(decoy, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); + retirement.publish(); + } NamedBlobManifestStore worker = new NamedBlobManifestStore(db); NamedBlobManifestStore.Manifest manifest = worker.getPublished(ACCOUNT, CONTAINER, NAME, 1); assertEquals(root.getID(), manifest.root); }); } + @Test + public void testReplacementDuringEncodingCannotChangeValidatedVersion() throws Exception { + withDatabase((db, named) -> { + BlobId first = blob(BlobId.BlobDataType.METADATA); + BlobId second = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, first, NamedBlobState.READY); + insertNamed(db, 2, second, NamedBlobState.READY); + Map pending = new LinkedHashMap<>(); + pending.put(1L, new NamedBlobManifestStore.PendingVersion(first, 1, new Iterator() { + private boolean consumed; + + @Override + public boolean hasNext() { + return !consumed; + } + + @Override + public BlobId next() { + consumed = true; + pending.put(2L, new NamedBlobManifestStore.PendingVersion(first, MAX_CHILDREN, poisonIterator())); + return child; + } + })); + pending.put(2L, new NamedBlobManifestStore.PendingVersion(second, 1, Collections.singleton(child).iterator())); + retireMany(named, pending); + NamedBlobManifestStore store = new NamedBlobManifestStore(db); + NamedBlobManifestStore.Manifest manifest = store.getPublished(ACCOUNT, CONTAINER, NAME, 2); + assertEquals(second.getID(), manifest.root); + assertEquals(Collections.singletonList(child.getID()), store.read(manifest)); + }); + } + + @Test + public void testAdmissionCoversPreparationAndRecoveryAndReleasesOnFailure() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + ExecutorService preparer = Executors.newSingleThreadExecutor(); + CountDownLatch preparing = new CountDownLatch(1); + CountDownLatch resume = new CountDownLatch(1); + Future preparingFuture = preparer.submit( + () -> named.prepareRetirement("account", "container", NAME, () -> { + preparing.countDown(); + try { + assertTrue(resume.await(10, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError(e); + } + return Collections.emptyMap(); + })); + try { + assertTrue(preparing.await(10, TimeUnit.SECONDS)); + assertRetirementBusy(named); + } finally { + resume.countDown(); + preparer.shutdown(); + } + try { + preparingFuture.get(10, TimeUnit.SECONDS); + fail("No versions were supplied"); + } catch (ExecutionException e) { + assertTrue(e.getCause().toString(), e.getCause() instanceof IllegalArgumentException); + } + insertNamed(db, 1, root, NamedBlobState.READY); + try (MySqlNamedBlobDb.Retirement retirement = named.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + assertFalse(retirement.isPublished()); + retirement.publish(); + assertRetirementBusy(named); + } + retireOne(named, 1, root, 1, Collections.singleton(child).iterator()); + }); + } + + private static void assertRetirementBusy(MySqlNamedBlobDb named) throws Exception { + try { + named.prepareRetirement("account", "container", NAME, () -> { + throw new AssertionError("Rejected request must not fetch descriptors"); + }); + fail("Concurrent preparation was admitted"); + } catch (RestServiceException e) { + assertEquals(RestServiceErrorCode.ServiceUnavailable, e.getErrorCode()); + } + } + + @Test + public void testExactHandleConfirmsLostReplyAfterOverCapReplacement() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + try (Connection physical = db.getConnection()) { + Connection lostReply = mock(Connection.class, delegatesTo(physical)); + doAnswer(call -> { + physical.commit(); + throw new SQLException("Simulated lost commit reply", "S1000", new SocketTimeoutException()); + }).when(lostReply).commit(); + DataSource writer = mock(DataSource.class); + when(writer.getConnection()).thenReturn(lostReply).thenAnswer(call -> db.getConnection()); + try (MySqlNamedBlobDb withLostReply = namedDb(writer); + MySqlNamedBlobDb.Retirement retirement = withLostReply.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + assertLostReplyAndRecover(db, retirement, root, child); + } + verify(lostReply, never()).rollback(); + } + }); + } + + private static void assertLostReplyAndRecover(DataSource db, MySqlNamedBlobDb.Retirement retirement, BlobId root, + BlobId child) throws Exception { + try (Connection stale = db.getConnection(); Statement snapshot = stale.createStatement()) { + stale.setAutoCommit(false); + try (ResultSet rs = snapshot.executeQuery("SELECT COUNT(*) FROM named_blob_manifests_v1")) { + assertTrue(rs.next()); + assertEquals(0, rs.getInt(1)); + } + try { + retirement.publish(); + fail("Expected the commit reply to be lost"); + } catch (SQLException e) { + assertEquals("Simulated lost commit reply", e.getMessage()); + } + for (int version = 2; version <= 34; version++) { + insertNamed(db, version, blob(BlobId.BlobDataType.METADATA), NamedBlobState.READY); + } + expectDataError("Unsupported named version range", + () -> retireInTransaction(stale, NAME, Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))); + stale.rollback(); + } + assertTrue(retirement.isPublished()); + retirement.publish(); + assertEquals(33, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE retirement_fenced=FALSE")); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + } + + @Test + public void testRetirementRejectsActiveWriterTransactionWithoutCommittingIt() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + try (Connection writer = db.getConnection(); Statement sql = writer.createStatement()) { + sql.execute("START TRANSACTION"); + assertEquals(1, sql.executeUpdate("UPDATE named_blobs_v2 SET blob_size=123")); + assertTrue(writer.getAutoCommit()); + DataSource source = mock(DataSource.class); + when(source.getConnection()).thenReturn(writer); + try (MySqlNamedBlobDb unsafe = namedDb(source); + MySqlNamedBlobDb.Retirement retirement = unsafe.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + try { + retirement.publish(); + fail("Borrowed an active writer transaction"); + } catch (SQLException e) { + assertTrue(e.getMessage(), e.getMessage().contains("idle autocommit")); + } + } + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE blob_size=123 OR retirement_fenced")); + }); + } + + @Test + public void testPublishOverridesPendingReadCommittedAndLocksNamingGap() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + try (Connection physical = db.getConnection(); Statement setting = physical.createStatement(); + Connection competing = db.getConnection(); Statement limit = competing.createStatement()) { + setting.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + limit.execute("SET SESSION innodb_lock_wait_timeout=1"); + Connection writer = mock(Connection.class, delegatesTo(physical)); + doAnswer(call -> { + // Probe after the range was read but before any manifest or named-row write. + try { + insertNamed(competing, NAME, 2, blob(BlobId.BlobDataType.METADATA), NamedBlobState.READY); + fail("A replacement entered the name range before publication"); + } catch (SQLException expected) { + assertEquals(expected.getMessage(), 1205, expected.getErrorCode()); + } + return physical.prepareStatement(call.getArgument(0)); + }).when(writer).prepareStatement(startsWith("INSERT INTO named_blob_manifests_v1")); + DataSource checkout = mock(DataSource.class); + when(checkout.getConnection()).thenReturn(writer).thenAnswer(call -> db.getConnection()); + try (MySqlNamedBlobDb isolated = namedDb(checkout); + MySqlNamedBlobDb.Retirement retirement = isolated.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + retirement.publish(); + assertTrue(retirement.isPublished()); + } + verify(writer).prepareStatement(startsWith("INSERT INTO named_blob_manifests_v1")); + insertNamed(competing, NAME, 2, blob(BlobId.BlobDataType.METADATA), NamedBlobState.READY); + } + }); + } + + @Test + public void testRetirementRestoresPooledTimeoutAndEvictsAfterReadStall() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + MysqlDataSource source; + try (Connection connection = db.getConnection()) { + source = source(connection.getCatalog()); + } + source.setSocketTimeout(0); + HikariConfig config = new HikariConfig(); + config.setDataSource(source); + config.setMaximumPoolSize(1); + config.setConnectionInitSql("SET SESSION innodb_lock_wait_timeout=15"); + try (HikariDataSource pool = new HikariDataSource(config); + MySqlNamedBlobDb pooled = namedDb(pool); + MySqlNamedBlobDb.Retirement retirement = pooled.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + int originalId = ordinaryCheckout(pool, 0); + assertFalse(retirement.isPublished()); + assertEquals(originalId, ordinaryCheckout(pool, 0)); + + try (Connection blocker = db.getConnection(); Statement lock = blocker.createStatement()) { + blocker.setAutoCommit(false); + try (ResultSet locked = lock.executeQuery("SELECT version FROM named_blobs_v2 FOR UPDATE")) { + assertTrue(locked.next()); + } + try { + retirement.publish(); + fail("Published while another transaction held the row lock"); + } catch (SQLException expected) { + Throwable cause = expected; + while (cause != null && !(cause instanceof SocketTimeoutException)) { + cause = cause.getCause(); + } + assertNotNull(expected.toString(), cause); + } finally { + blocker.rollback(); + } + } + int replacementId = ordinaryCheckout(pool, 0); + assertNotEquals(originalId, replacementId); + assertFalse(retirement.isPublished()); + retirement.publish(); + assertTrue(retirement.isPublished()); + assertEquals(replacementId, ordinaryCheckout(pool, 0)); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + } + }); + } + + @Test + public void testRetirementPreservesCommitAndEvictsWhenTimeoutRestoreFails() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + long version = 1; + insertNamed(db, version, root, NamedBlobState.READY); + try (Connection physical = db.getConnection()) { + int originalTimeout = physical.getNetworkTimeout(); + AtomicBoolean committed = new AtomicBoolean(); + AtomicBoolean restoreFailed = new AtomicBoolean(); + Connection failingRestore = mock(Connection.class, delegatesTo(physical)); + doAnswer(call -> { + physical.commit(); + committed.set(true); + return null; + }).when(failingRestore).commit(); + doAnswer(call -> { + // Fail only the first restore so a later Hikari health check cannot mask a missing eviction. + if (committed.get() && restoreFailed.compareAndSet(false, true)) { + throw new SQLException("Socket timeout restore failed", "HY000"); + } + physical.setNetworkTimeout(call.getArgument(0), originalTimeout); + return null; + }).when(failingRestore).setNetworkTimeout(any(), eq(originalTimeout)); + DataSource checkout = mock(DataSource.class); + when(checkout.getConnection()).thenReturn(failingRestore).thenAnswer(call -> db.getConnection()); + HikariConfig config = new HikariConfig(); + config.setDataSource(checkout); + config.setMaximumPoolSize(1); + config.setConnectionTimeout(3000); + try (HikariDataSource pool = new HikariDataSource(config); + MySqlNamedBlobDb pooled = namedDb(pool); + MySqlNamedBlobDb.Retirement retirement = pooled.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(version, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + int originalId = ordinaryCheckout(pool, originalTimeout); + retirement.publish(); + assertTrue("Timeout restoration must fail after the real commit", restoreFailed.get()); + assertNotEquals("The next borrower must get a different physical connection", originalId, + ordinaryCheckout(pool, originalTimeout)); + assertTrue("The exact receipt must survive the cleanup failure", retirement.isPublished()); + } + } + }); + } + + private static int ordinaryCheckout(DataSource pool, int expectedTimeout) throws SQLException { + try (Connection c = pool.getConnection(); Statement s = c.createStatement(); + ResultSet rows = s.executeQuery("SELECT CONNECTION_ID()")) { + assertEquals(expectedTimeout, c.getNetworkTimeout()); + assertTrue(c.getAutoCommit()); + assertTrue(rows.next()); + return rows.getInt(1); + } + } + + @Test + public void testHardDeleteRejectsBeforeLoadingDescriptors() throws Exception { + withDatabase((db, named) -> { + try (MySqlNamedBlobDb hardDelete = namedDb(db, true)) { + try { + hardDelete.prepareRetirement("account", "container", NAME, () -> { + throw new AssertionError("Hard-delete mode must not fetch descriptors"); + }); + fail("Accepted manifest retirement in hard-delete mode"); + } catch (UnsupportedOperationException expected) { + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + } + } + }); + } + /** * The actual race the guard and the lock order exist for: a retire that has locked the named range (but not yet * committed its manifest insert) must block a concurrent direct replace for the same tuple. Once it commits, @@ -1251,7 +1673,7 @@ public void testConcurrentRetireBlocksRacingDirectReplaceThenRejectsReuse() thro try (Connection retiring = db.getConnection(); Connection replacing = db.getConnection(); Statement replace = replacing.createStatement()) { retiring.setAutoCommit(false); - NamedBlobManifestStore.retire(retiring, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(7L, + retireInTransaction(retiring, NAME, Collections.singletonMap(7L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); replace.execute("SET SESSION innodb_lock_wait_timeout=1"); try { @@ -1399,6 +1821,7 @@ private static MysqlDataSource source(String schema) throws SQLException { } db.setDatabaseName(schema); db.setServerTimezone("UTC"); + db.setSocketTimeout(15_000); // Mirror production's Hikari useServerPrepStmts=true so large-payload tests exercise the same statement mode. db.setUseServerPrepStmts(true); return db; @@ -1438,7 +1861,14 @@ private static void insertNamed(DataSource db, long version, BlobId root, NamedB private static void insertNamed(DataSource db, String name, long version, BlobId root, NamedBlobState state) throws SQLException { - try (Connection c = db.getConnection(); PreparedStatement s = c.prepareStatement( + try (Connection c = db.getConnection()) { + insertNamed(c, name, version, root, state); + } + } + + private static void insertNamed(Connection c, String name, long version, BlobId root, NamedBlobState state) + throws SQLException { + try (PreparedStatement s = c.prepareStatement( "INSERT INTO named_blobs_v2 (account_id,container_id,blob_name,version,blob_id,blob_state)" + " VALUES (?,?,?,?,?,?)")) { s.setShort(1, ACCOUNT); diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java index 463d0c5a21..17410d8ceb 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,8 @@ 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.store.StoreKeyFactory; import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.Time; import com.github.ambry.utils.Utils; @@ -41,10 +44,14 @@ import com.mysql.cj.jdbc.JdbcConnection; import com.zaxxer.hikari.HikariDataSource; import java.io.Closeable; +import java.io.EOFException; import java.io.IOException; +import java.net.SocketException; +import java.net.SocketTimeoutException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.SQLDataException; import java.sql.SQLException; import java.sql.SQLNonTransientConnectionException; import java.sql.SQLTransientConnectionException; @@ -57,6 +64,7 @@ import java.util.Deque; import java.util.HashSet; import java.util.IdentityHashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -64,8 +72,10 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.sql.DataSource; @@ -84,6 +94,7 @@ public class MySqlNamedBlobDb implements NamedBlobDb { private static final Logger logger = LoggerFactory.getLogger(MySqlNamedBlobDb.class); private static final int MAX_NUMBER_OF_VERSIONS_IN_DELETE = 1000; private static final int VERSION_BASE = 100000; + private static final int RETIREMENT_READ_TIMEOUT_MS = 5_000; private final Time time; private static final String MULTI_VERSION_PLACE_HOLDER = "MULTI_VERSION_PLACE_HOLDER"; @@ -189,6 +200,8 @@ public class MySqlNamedBlobDb implements NamedBlobDb { private final Map transactionExecutors; private final MySqlNamedBlobDbConfig config; private final Metrics metricsRecoder; + // Reserve one worst-case encoded request (32 MiB), including while its caller decides whether to retry. + private final Semaphore retirementSlot = new Semaphore(1); MySqlNamedBlobDb(AccountService accountService, MySqlNamedBlobDbConfig config, DataSourceFactory dataSourceFactory, String localDatacenter, Metrics metricRecorder, Time time) { @@ -467,45 +480,153 @@ public CompletableFuture updateBlobTtlAndStateToReady(NamedBlobRecord } /** - * Validate, publish and fence this exact set of named versions in one transaction. Never returns IDs for a - * router cascade. There is no separate staging step: a version's descriptors are supplied and consumed in the - * same call that retires it. Everything is validated and every iterator is fully consumed into an immutable - * {@link NamedBlobManifestStore.PreparedRetirement} synchronously, before this is handed to the background - * transaction thread: the thread never sees {@code pendingVersions} itself, so the caller mutating or clearing - * that map after this call returns cannot change what gets published. + * Admit and prepare one exact intent. The supplier must defer fetching descriptors until invoked. This blocks, + * as do the returned handle's methods; callers must run it off the event loop and close the handle on all paths. */ - CompletableFuture retireWithManifests(String accountName, String containerName, String blobName, - Map pendingVersions) { + Retirement prepareRetirement(String accountName, String containerName, String blobName, + Supplier> pendingVersions) throws RestServiceException, + SQLException { + if (config.enableHardDelete) { + throw new UnsupportedOperationException("Manifest retirement requires named soft delete"); + } Account account = accountService.getAccountByName(accountName); if (account == null) { - CompletableFuture failed = new CompletableFuture<>(); - failed.completeExceptionally( - new RestServiceException("Account not found: " + accountName, RestServiceErrorCode.NotFound)); - return failed; + throw new RestServiceException("Account not found: " + accountName, RestServiceErrorCode.NotFound); } Container container = account.getContainerByName(containerName); if (container == null) { - CompletableFuture failed = new CompletableFuture<>(); - failed.completeExceptionally( - new RestServiceException("Container not found: " + containerName, RestServiceErrorCode.NotFound)); - return failed; + throw new RestServiceException("Container not found: " + containerName, RestServiceErrorCode.NotFound); } - NamedBlobManifestStore.PreparedRetirement prepared; + return prepareRetirement(container, blobName, writer -> pendingVersions.get()); + } + + @FunctionalInterface + private interface RetirementInput { + Map load(TransactionExecutor writer) throws E; + } + + private Retirement prepareRetirement(Container container, String blobName, + RetirementInput input) throws RestServiceException, SQLException, E { + TransactionExecutor writer = transactionExecutors.get(localDatacenter); + if (writer == null || writer.executor.isShutdown()) { + throw new RestServiceException("Named retirement writer is unavailable", RestServiceErrorCode.ServiceUnavailable); + } + if (!retirementSlot.tryAcquire()) { + throw new RestServiceException("Named retirement already in progress", RestServiceErrorCode.ServiceUnavailable); + } + boolean prepared = false; try { - prepared = NamedBlobManifestStore.prepare((short) account.getId(), (short) container.getId(), blobName, - pendingVersions); - } catch (SQLException e) { - CompletableFuture failed = new CompletableFuture<>(); - failed.completeExceptionally(e); - return failed; + Retirement retirement = new Retirement(writer, + NamedBlobManifestStore.prepare(container.getParentAccountId(), container.getId(), blobName, + input.load(writer))); + prepared = true; + return retirement; + } finally { + if (!prepared) { + retirementSlot.release(); + } + } + } + + @Override + public void retire(Container container, String blobName, StoreKeyFactory keyFactory, RetirementLoader loader) + throws Exception { + if (!config.honorRetirementFence || config.enableHardDelete) { + throw new RestServiceException("Named retirement requires fence-aware soft delete", + RestServiceErrorCode.ServiceUnavailable); + } + short accountId = container.getParentAccountId(); + short containerId = container.getId(); + try (Retirement retirement = prepareRetirement(container, blobName, writer -> { + Map roots = writer.runRetirementTransaction( + connection -> NamedBlobManifestStore.selectRoots(connection, accountId, containerId, blobName, keyFactory)); + if (roots.isEmpty()) { + throw new RestServiceException("Named blob does not have a live version", RestServiceErrorCode.NotFound); + } + Map pending = new LinkedHashMap<>(); + int remaining = NamedBlobManifestStore.MAX_CHILDREN; + for (Map.Entry entry : roots.entrySet()) { + if (remaining == 0) { + throw new SQLDataException("Too many children for named retirement"); + } + List children = loader.load(entry.getValue(), remaining); + if (children == null || children.isEmpty() || children.size() > remaining) { + throw new SQLDataException("Invalid child list for named retirement"); + } + remaining -= children.size(); + pending.put(entry.getKey(), + new NamedBlobManifestStore.PendingVersion(entry.getValue(), children.size(), children.iterator())); + } + return pending; + })) { + try { + retirement.publish(); + } catch (Exception publishFailure) { + // Never rediscover the name after a failed publish: it could already point to a replacement. + try { + if (retirement.isPublished()) { + return; + } + } catch (Exception confirmationFailure) { + if (publishFailure != confirmationFailure) { + publishFailure.addSuppressed(confirmationFailure); + } + } + throw new RestServiceException("Named retirement was not confirmed", publishFailure, + RestServiceErrorCode.ServiceUnavailable); + } + } catch (SQLDataException unsupported) { + throw new RestServiceException("Named blob history cannot be retired", unsupported, RestServiceErrorCode.Conflict); + } + } + + /** Owns the admission slot and the encoded bytes until close. Never queues a payload. */ + final class Retirement implements AutoCloseable { + private final TransactionExecutor writer; + private NamedBlobManifestStore.PreparedRetirement prepared; + + private Retirement(TransactionExecutor writer, NamedBlobManifestStore.PreparedRetirement prepared) { + this.writer = writer; + this.prepared = prepared; + } + + synchronized void publish() throws Exception { + run(connection -> { + NamedBlobManifestStore.retire(connection, prepared); + return null; + }); + } + + /** A negative result means "not observed"; only a positive exact receipt confirms publication. */ + synchronized boolean isPublished() throws Exception { + return run(connection -> NamedBlobManifestStore.matchesReceipt(connection, prepared)); + } + + private T run(TransactionGeneric transaction) throws Exception { + if (prepared == null) { + throw new IllegalStateException("Named retirement is closed"); + } + if (writer.executor.isShutdown()) { + throw new RestServiceException("Named retirement writer is unavailable", RestServiceErrorCode.ServiceUnavailable); + } + try { + return writer.runRetirementTransaction(transaction); + } catch (Exception | Error e) { + writer.recordConnectionFailure(e); + if (e instanceof SQLException) { + metricsRecoder.namedBlobDBDeleteErrorCount.inc(); + } + throw e; + } } - return executeTransactionAsync(accountName, containerName, false, (ignoredAccount, ignoredContainer, connection) -> { - if (config.enableHardDelete) { - throw new UnsupportedOperationException("Manifest retirement requires named soft delete"); + + @Override + public synchronized void close() { + if (prepared != null) { + prepared = null; + retirementSlot.release(); } - NamedBlobManifestStore.retire(connection, prepared); - return null; - }, null, metricsRecoder.namedBlobDBDeleteErrorCount); + } } @Override @@ -735,7 +856,7 @@ private static class TransactionExecutor implements Closeable { /** * Whether the given throwable represents a JDBC connection failure (vs. any other SQL error). * - *

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

Positive signals include: *

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

The walk includes causes, chained SQL exceptions and suppressed cleanup failures. + * Connector/J can wrap a socket failure in a generic SQLException. * SQLSTATE "40*" (transaction rollback), "57*" (operator intervention), and other * adjacent classes are intentionally NOT counted — those are not connection failures. */ @@ -761,7 +883,8 @@ private static boolean isConnectionFailure(Throwable t) { if (!seen.add(cur)) { continue; } - if (cur instanceof SQLNonTransientConnectionException || cur instanceof SQLTransientConnectionException) { + if (cur instanceof SQLNonTransientConnectionException || cur instanceof SQLTransientConnectionException + || cur instanceof SocketTimeoutException || cur instanceof SocketException || cur instanceof EOFException) { return true; } if (cur instanceof SQLException) { @@ -789,6 +912,12 @@ void executeTransaction(Container container, boolean autoCommit, Transaction connection -> transaction.run(container.getParentAccountId(), container.getId(), connection), callback); } + private void recordConnectionFailure(Throwable failure) { + if (isConnectionFailure(failure)) { + connectionFailureCount.inc(); + } + } + void executeTransactionGeneric(boolean autoCommit, TransactionGeneric transaction, Callback callback) { final long enqueueTimeMs = System.currentTimeMillis(); try { @@ -796,11 +925,9 @@ void executeTransactionGeneric(boolean autoCommit, TransactionGeneric tra enqueueWaitTimeInMs.update(System.currentTimeMillis() - enqueueTimeMs); T result; try { - result = runTransaction(autoCommit, transaction); + result = runTransaction(autoCommit ? TransactionMode.AUTOCOMMIT : TransactionMode.EXPLICIT, transaction); } catch (Exception | Error e) { - if (isConnectionFailure(e)) { - connectionFailureCount.inc(); - } + recordConnectionFailure(e); callback.onCompletion(null, e instanceof Exception ? (Exception) e : new IllegalStateException(e)); return; } @@ -811,13 +938,51 @@ void executeTransactionGeneric(boolean autoCommit, TransactionGeneric tra } } - private T runTransaction(boolean autoCommit, TransactionGeneric transaction) throws Exception { + private enum TransactionMode { + AUTOCOMMIT, EXPLICIT, RETIREMENT + } + + private T runRetirementTransaction(TransactionGeneric transaction) throws Exception { + return runTransaction(TransactionMode.RETIREMENT, transaction); + } + + private T runTransaction(TransactionMode mode, TransactionGeneric transaction) throws Exception { + boolean autoCommit = mode == TransactionMode.AUTOCOMMIT; + boolean retirement = mode == TransactionMode.RETIREMENT; Connection connection = dataSource.getConnection(); + int timeoutToRestore = -1; + if (retirement) { + try { + JdbcConnection driver = requireFixedRetirementSession(connection); + int originalTimeout = connection.getNetworkTimeout(); + if (originalTimeout == 0 || originalTimeout > RETIREMENT_READ_TIMEOUT_MS) { + connection.setNetworkTimeout(Runnable::run, RETIREMENT_READ_TIMEOUT_MS); + timeoutToRestore = originalTimeout; + } + requireIdleRetirementSession(connection, driver); + } catch (Exception | Error failure) { + // This connection may contain someone else's transaction. Do not reset autocommit. + discardConnection(connection, failure); + throw failure; + } + } final T result; try { if (!autoCommit) { connection.setAutoCommit(false); } + if (retirement) { + try (Statement check = connection.createStatement(); + ResultSet settings = check.executeQuery("SELECT @@session.autocommit")) { + if (!settings.next() || settings.getBoolean(1)) { + throw new SQLException("Named retirement could not disable autocommit"); + } + } + // A per-transaction override is not visible in @@session.transaction_isolation. + try (Statement statement = connection.createStatement()) { + statement.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + } + } result = transaction.run(connection); if (!autoCommit) { connection.commit(); @@ -827,6 +992,10 @@ private T runTransaction(boolean autoCommit, TransactionGeneric transacti discardConnection(connection, failure); throw failure; } catch (Exception | Error failure) { + if (retirement && isConnectionFailure(failure)) { + discardConnection(connection, failure); + throw failure; + } if (!autoCommit) { try { connection.rollback(); @@ -839,31 +1008,56 @@ private T runTransaction(boolean autoCommit, TransactionGeneric transacti throw failure; } } - returnConnection(connection, autoCommit, failure); + returnConnection(connection, autoCommit, timeoutToRestore, failure); throw failure; } - returnConnection(connection, autoCommit, null); + returnConnection(connection, autoCommit, timeoutToRestore, null); return result; } - private void returnConnection(Connection connection, boolean autoCommit, Throwable operationFailure) { + private static JdbcConnection requireFixedRetirementSession(Connection connection) throws SQLException { + JdbcConnection driver = connection.unwrap(JdbcConnection.class); + if (!(driver instanceof ConnectionImpl) || driver.isProxySet() + || driver.getPropertySet().getBooleanProperty(PropertyKey.autoReconnect).getValue() + || driver.getPropertySet().getBooleanProperty(PropertyKey.autoReconnectForPools).getValue() + || driver.getPropertySet().getBooleanProperty(PropertyKey.reconnectAtTxEnd).getValue()) { + throw new SQLException("Named retirement requires a fixed physical MySQL session"); + } + return driver; + } + + private static void requireIdleRetirementSession(Connection connection, JdbcConnection driver) throws SQLException { + try (Statement check = connection.createStatement()) { + check.setFetchSize(0); + try (ResultSet settings = check.executeQuery("SELECT @@session.autocommit, @@session.transaction_isolation")) { + if (!settings.next() || !settings.getBoolean(1) || !"REPEATABLE-READ".equals(settings.getString(2)) + || driver.getSession().getServerSession().inTransactionOnServer()) { + throw new SQLException("Named retirement requires an idle autocommit REPEATABLE READ session"); + } + } + } + } + + private void returnConnection(Connection connection, boolean autoCommit, int timeoutToRestore, + Throwable operationFailure) { try { - if (!autoCommit) { - try { + try { + if (!autoCommit) { connection.setAutoCommit(true); - } catch (Exception | Error resetFailure) { - // Hikari can recycle a connection even when a reset inside close() fails. - discardConnection(connection, resetFailure); - throw resetFailure; } + if (timeoutToRestore >= 0) { + connection.setNetworkTimeout(Runnable::run, timeoutToRestore); + } + } catch (Exception | Error resetFailure) { + // Hikari can recycle a connection even when a reset inside close() fails. + discardConnection(connection, resetFailure); + throw resetFailure; } connection.close(); } catch (Exception | Error cleanupFailure) { metrics.connectionCloseErrorCount.inc(); if (operationFailure == null) { - if (isConnectionFailure(cleanupFailure)) { - connectionFailureCount.inc(); - } + recordConnectionFailure(cleanupFailure); } else if (operationFailure != cleanupFailure) { operationFailure.addSuppressed(cleanupFailure); } diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java index 9ebab8f921..e61788af75 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 @@ -4,6 +4,7 @@ */ package com.github.ambry.named; +import java.io.IOException; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -24,11 +25,12 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.TreeSet; +import java.util.TreeMap; import javax.sql.DataSource; import com.github.ambry.commons.BlobId; import com.github.ambry.protocol.NamedBlobState; import com.github.ambry.store.StoreKey; +import com.github.ambry.store.StoreKeyFactory; /** * Detached evidence for one immutable root at one named version. A row in {@code named_blob_manifests_v1} exists @@ -48,12 +50,16 @@ 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; + 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 static final String SELECT_UNFENCED = "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 ?"; private final DataSource db; @@ -61,6 +67,50 @@ final class NamedBlobManifestStore { this.db = Objects.requireNonNull(db, "db"); } + /** Read the same bounded range publication will validate under lock, without holding locks during router IO. */ + static Map selectRoots(Connection c, short account, short container, String name, + StoreKeyFactory keyFactory) throws SQLException, IOException { + Map roots = new LinkedHashMap<>(); + try (PreparedStatement s = c.prepareStatement(SELECT_UNFENCED)) { + bindUnfenced(s, account, container, name); + 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"); + } + if (r.getBoolean(5)) { + continue; + } + byte[] bytes = r.getBytes(3); + if (r.getInt(4) != NamedBlobState.READY.ordinal() || bytes == null || bytes.length == 0) { + throw new SQLDataException("Ineligible named version"); + } + StoreKey key = keyFactory.getStoreKey(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)); + if (!(key instanceof BlobId) || !Arrays.equals(bytes, key.toBytes()) + || !isCompositeRoot((BlobId) key, account, container)) { + throw new SQLDataException("Unsupported named composite capture"); + } + roots.put(r.getLong(2), (BlobId) key); + } + } + } + return roots; + } + + private static void bindUnfenced(PreparedStatement s, short account, short container, String name) + throws SQLException { + s.setInt(1, account); + s.setInt(2, container); + s.setString(3, name); + s.setInt(4, MAX_VERSIONS + 1); + } + + private static boolean isCompositeRoot(BlobId root, short account, short container) { + return root.sizeInBytes() >= 1 && root.sizeInBytes() <= 50 && root.getAccountId() == account + && root.getContainerId() == container && root.getBlobDataType() == BlobId.BlobDataType.METADATA; + } + private static void requireCommittedReads(Connection c) throws SQLException { int isolation = c.getTransactionIsolation(); if (isolation != Connection.TRANSACTION_READ_COMMITTED && isolation != Connection.TRANSACTION_REPEATABLE_READ @@ -83,36 +133,37 @@ static final class PendingVersion { } /** - * An entire publication request, fully validated and fully encoded: every iterator has already been consumed - * into an immutable {@code byte[]} body, and every bound (per-version and aggregate child count, root shape) has - * already been checked. It owns its own bytes rather than the caller's map or iterators, so it is safe to retain - * across an asynchronous dispatch boundary and hand to a background thread. + * An immutable publication request that owns its encoded bytes for publication, confirmation, and replay. */ static final class PreparedRetirement { final short account; final short container; final String name; - final List requested; - private final Map rootBytes; - private final Map rootIds; - private final Map counts; - private final Map bodies; - private final Map rowHashes; + private final Map versions; private final byte[] intentToken; - private PreparedRetirement(short account, short container, String name, List requested, - Map rootBytes, Map rootIds, Map counts, Map bodies, - Map rowHashes, byte[] intentToken) { + private PreparedRetirement(short account, short container, String name, Map versions) { this.account = account; this.container = container; this.name = name; - this.requested = Collections.unmodifiableList(requested); - this.rootBytes = Collections.unmodifiableMap(rootBytes); - this.rootIds = Collections.unmodifiableMap(rootIds); - this.counts = Collections.unmodifiableMap(counts); - this.bodies = Collections.unmodifiableMap(bodies); - this.rowHashes = Collections.unmodifiableMap(rowHashes); - this.intentToken = intentToken; + this.versions = Collections.unmodifiableMap(versions); + this.intentToken = intentToken(name, versions); + } + } + + private static final class PreparedVersion { + private final byte[] root; + private final int count; + private final byte[] body; + private final byte[] hash; + + private PreparedVersion(short account, short container, String name, long version, PendingVersion pending) + throws SQLException { + root = pending.root.toBytes(); + count = pending.expected; + body = encode(pending.descriptors, count, root); + hash = hash(account, container, name, version, count, + Base64.getUrlEncoder().withoutPadding().encodeToString(root), body); } } @@ -139,32 +190,10 @@ private static byte[] encode(Iterator descriptors, int expec private static void bindKey(PreparedStatement s, short account, short container, String name, long version) throws SQLException { - bindKey(s, account, container, name, version, 1); - } - - private static void bindKey(PreparedStatement s, short account, short container, String name, long version, int at) - throws SQLException { - s.setInt(at, account); - s.setInt(at + 1, container); - s.setString(at + 2, name); - s.setLong(at + 3, version); - } - - static void checkManifestCount(List versions) { - if (versions == null || versions.isEmpty() || versions.size() > MAX_VERSIONS) { - throw new IllegalArgumentException("Invalid number of manifests"); - } - } - - static List canonicalVersions(List versions) { - checkManifestCount(versions); - TreeSet sorted = new TreeSet<>(); - for (Long version : versions) { - if (version == null || !sorted.add(version)) { - throw new IllegalArgumentException("Expected distinct canonical manifest versions"); - } - } - return new ArrayList<>(sorted); + s.setInt(1, account); + s.setInt(2, container); + s.setString(3, name); + s.setLong(4, version); } /** @@ -172,8 +201,7 @@ static List canonicalVersions(List versions) { * exactly what will be published. Every declared bound -- per-version child count, aggregate child count across * the whole request, root shape -- is checked purely against caller-supplied values before a single iterator is * touched, a payload is encoded, or a connection is opened: a doomed oversized request never reads or hashes a - * byte. The result owns its own encoded bytes and holds no reference to {@code pending}, so it is safe to retain - * and hand to another thread for asynchronous publication. + * byte. The result holds no reference to {@code pending} or its iterators. */ static PreparedRetirement prepare(short account, short container, String name, Map pending) throws SQLException { @@ -181,22 +209,27 @@ static PreparedRetirement prepare(short account, short container, String name, M throw new SQLDataException("Unsupported named composite capture"); } Objects.requireNonNull(pending, "pending"); - List requested = canonicalVersions(new ArrayList<>(pending.keySet())); - - long totalDeclared = 0; - Map counts = new LinkedHashMap<>(); - for (long version : requested) { - PendingVersion p = pending.get(version); - if (p == null) { - throw new IllegalArgumentException("Missing pending descriptors for version " + version); + // Copy both key and value, not Map.Entry references that may continue to reflect changes to the caller's map. + Map captured = new TreeMap<>(); + for (Map.Entry entry : pending.entrySet()) { + Long version = entry.getKey(); + PendingVersion input = entry.getValue(); + if (captured.size() >= MAX_VERSIONS) { + throw new IllegalArgumentException("Invalid number of manifests"); + } + if (version == null || input == null || captured.putIfAbsent(version, input) != null) { + throw new IllegalArgumentException("Invalid pending manifest versions"); } + } + if (captured.isEmpty()) { + throw new IllegalArgumentException("Invalid number of manifests"); + } + long totalDeclared = 0; + for (PendingVersion p : captured.values()) { BlobId root = p.root; - if (p.expected < 1 || p.expected > MAX_CHILDREN || root.sizeInBytes() < 1 || root.sizeInBytes() > 50 - || root.getAccountId() != account || root.getContainerId() != container - || root.getBlobDataType() != BlobId.BlobDataType.METADATA) { + if (p.expected < 1 || p.expected > MAX_CHILDREN || !isCompositeRoot(root, account, container)) { throw new SQLDataException("Unsupported named composite capture"); } - counts.put(version, p.expected); totalDeclared += p.expected; } if (totalDeclared > MAX_CHILDREN) { @@ -204,51 +237,27 @@ static PreparedRetirement prepare(short account, short container, String name, M } // Only now, with the whole request's declared size already bounded, consume each iterator and encode its body. - Map rootBytes = new LinkedHashMap<>(); - Map rootIds = new LinkedHashMap<>(); - Map bodies = new LinkedHashMap<>(); - Map rowHashes = new LinkedHashMap<>(); - for (long version : requested) { - PendingVersion p = pending.get(version); - byte[] rb = p.root.toBytes(); - rootBytes.put(version, rb); - String rootId = Base64.getUrlEncoder().withoutPadding().encodeToString(rb); - rootIds.put(version, rootId); - byte[] body = encode(p.descriptors, p.expected, rb); - bodies.put(version, body); - rowHashes.put(version, hash(account, container, name, version, p.expected, rootId, body)); + Map versions = new LinkedHashMap<>(); + for (Map.Entry entry : captured.entrySet()) { + long version = entry.getKey(); + versions.put(version, new PreparedVersion(account, container, name, version, entry.getValue())); } - - return new PreparedRetirement(account, container, name, requested, rootBytes, rootIds, counts, bodies, rowHashes, - intentToken(name, requested, rowHashes)); - } - - /** - * Validate, publish and fence this exact set of named versions in one transaction. A replay that already carries - * this exact content for every requested version returns successfully without resolving the name or locking the - * named range; anything less than all of them matching is rejected rather than partially honored. - */ - static void retire(Connection c, short account, short container, String name, Map pending) - throws SQLException { - retire(c, prepare(account, container, name, pending)); + return new PreparedRetirement(account, container, name, versions); } /** * Publish and fence the given prepared request in one transaction. A pure, non-locking check for an already- - * complete publication runs first and never touches {@code named_blobs_v2} at all, so a legitimate replay is - * never blocked by the named range's own size cap, however many unrelated versions have since replaced it. Only - * when that check is incomplete does this lock the named range -- the same order (named_blobs_v2, then - * named_blob_manifests_v1) an ordinary named PUT's own AFTER INSERT/UPDATE guard uses, so neither ever waits on - * the other in the opposite order. Every requested version is then published by a plain {@code INSERT}, never by - * a locking read against a key that might not exist: only once a duplicate-key signal proves a row already - * exists is a locking read issued against that now-known-existing key. This keeps two unrelated publishers' - * concurrent inserts into the same manifest-table gap from contending on a shared gap lock at all. + * complete publication runs first and never touches {@code named_blobs_v2}, so a replay that sees its existing + * receipt is not blocked by the named range's size cap. If the receipt does not match, lock the named range before + * inserting manifests, in the same order as the named PUT's AFTER INSERT/UPDATE guard. Use a plain {@code INSERT} + * for each manifest and issue a locking read only on a duplicate key. This avoids gap locks from checking for a + * missing manifest and lets unrelated publishers insert into the same manifest-table gap. */ static void retire(Connection c, PreparedRetirement p) throws SQLException { if (c.getAutoCommit() || c.getTransactionIsolation() != Connection.TRANSACTION_REPEATABLE_READ) { throw new IllegalStateException("Publication requires an InnoDB REPEATABLE READ transaction"); } - if (fullyMatches(c, p)) { + if (matchesReceipt(c, p)) { return; } @@ -261,14 +270,8 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { // 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 (PreparedStatement s = c.prepareStatement(SELECT_UNFENCED + " FOR UPDATE")) { + bindUnfenced(s, p.account, p.container, p.name); try (ResultSet r = s.executeQuery()) { int rows = 0; while (r.next()) { @@ -276,7 +279,8 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { throw new SQLDataException("Unsupported named version range"); } long version = r.getLong(2); - if (!p.counts.containsKey(version)) { + PreparedVersion expected = p.versions.get(version); + if (expected == null) { if (r.getBoolean(5)) { history.add(version); } else { @@ -285,7 +289,7 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { continue; } boolean eligible = r.getInt(4) == NamedBlobState.READY.ordinal() && !r.getBoolean(5) - && Arrays.equals(r.getBytes(3), p.rootBytes.get(version)); + && Arrays.equals(r.getBytes(3), expected.root); liveMatch.put(version, eligible); } } @@ -297,16 +301,18 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { List freshlyPublished = new ArrayList<>(); try (PreparedStatement insert = c.prepareStatement( "INSERT INTO " + TABLE + " (" + HEADER_COLUMNS + ",payload,payload_hash) VALUES (?,?,?,?,?,?,?,?,?)")) { - for (long version : p.requested) { + for (Map.Entry entry : p.versions.entrySet()) { + long version = entry.getKey(); + PreparedVersion requested = entry.getValue(); insert.setInt(1, p.account); insert.setInt(2, p.container); insert.setString(3, p.name); insert.setLong(4, version); - insert.setBytes(5, p.rootBytes.get(version)); - insert.setInt(6, p.counts.get(version)); + insert.setBytes(5, requested.root); + insert.setInt(6, requested.count); insert.setBytes(7, p.intentToken); - insert.setBytes(8, p.bodies.get(version)); - insert.setBytes(9, p.rowHashes.get(version)); + insert.setBytes(8, requested.body); + insert.setBytes(9, requested.hash); try { if (insert.executeUpdate() != 1) { throw new SQLDataException("Cannot publish sealed manifest"); @@ -321,7 +327,7 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { if (duplicate.getErrorCode() != 1062) { throw duplicate; } - confirmExistingMatches(c, p, version); + confirmExistingMatches(c, p, version, requested); } } } @@ -329,7 +335,7 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { if (freshlyPublished.isEmpty()) { return; } - if (freshlyPublished.size() != p.requested.size()) { + if (freshlyPublished.size() != p.versions.size()) { throw new SQLDataException("Partial manifest set"); } try (PreparedStatement retireRow = c.prepareStatement( @@ -360,7 +366,8 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { * A row proven to already exist by a duplicate-key signal must carry exactly this request's content and this * request's intent, or the request is rejected rather than silently accepted or silently dropped. */ - private static void confirmExistingMatches(Connection c, PreparedRetirement p, long version) throws SQLException { + private static void confirmExistingMatches(Connection c, PreparedRetirement p, long version, + PreparedVersion requested) throws SQLException { try (PreparedStatement s = c.prepareStatement( "SELECT payload_hash,publication_key FROM " + TABLE + " WHERE " + KEY + " FOR UPDATE")) { bindKey(s, p.account, p.container, p.name, version); @@ -368,7 +375,7 @@ private static void confirmExistingMatches(Connection c, PreparedRetirement p, l if (!r.next()) { throw new SQLDataException("Manifest belongs to a different publication"); } - if (!MessageDigest.isEqual(r.getBytes(1), p.rowHashes.get(version))) { + if (!MessageDigest.isEqual(r.getBytes(1), requested.hash)) { throw new SQLDataException("Conflicting manifest for named version"); } if (!MessageDigest.isEqual(r.getBytes(2), p.intentToken)) { @@ -379,22 +386,21 @@ private static void confirmExistingMatches(Connection c, PreparedRetirement p, l } /** - * A pure, non-locking check for an already-complete publication: never touches {@code named_blobs_v2}, so it is - * never blocked by the named range's own size cap. This can under-report on a connection whose REPEATABLE READ - * snapshot predates a just-committed publication, but it can never over-report -- a plain read only ever shows - * what was truly committed -- so a false negative here only costs falling through to the slower, authoritative - * path below, never a wrongful success. + * Match the exact receipt visible to the supplied transaction without locking or reading {@code named_blobs_v2}. + * A transaction can see its own uncommitted writes, and an older snapshot can miss a committed receipt. + * To confirm publication, check in a fresh writer transaction before making any writes. */ - private static boolean fullyMatches(Connection c, PreparedRetirement p) throws SQLException { - String placeholders = String.join(",", Collections.nCopies(p.requested.size(), "?")); + static boolean matchesReceipt(Connection c, PreparedRetirement p) throws SQLException { + String placeholders = String.join(",", Collections.nCopies(p.versions.size(), "?")); String sql = "SELECT blob_name,version,payload_hash,publication_key FROM " + TABLE + " WHERE account_id=? AND container_id=? AND blob_name=? AND version IN (" + placeholders + ")"; try (PreparedStatement s = c.prepareStatement(sql)) { s.setInt(1, p.account); s.setInt(2, p.container); s.setString(3, p.name); - for (int i = 0; i < p.requested.size(); i++) { - s.setLong(i + 4, p.requested.get(i)); + int parameter = 4; + for (long version : p.versions.keySet()) { + s.setLong(parameter++, version); } try (ResultSet r = s.executeQuery()) { int matched = 0; @@ -403,13 +409,13 @@ private static boolean fullyMatches(Connection c, PreparedRetirement p) throws S return false; } long version = r.getLong(2); - if (!MessageDigest.isEqual(r.getBytes(3), p.rowHashes.get(version)) || !MessageDigest.isEqual( + if (!MessageDigest.isEqual(r.getBytes(3), p.versions.get(version).hash) || !MessageDigest.isEqual( r.getBytes(4), p.intentToken)) { return false; } matched++; } - return matched == p.requested.size(); + return matched == p.versions.size(); } } } @@ -444,26 +450,18 @@ private Manifest(ResultSet r) throws SQLException { * grouped into this request, changes the token: two intents cannot impersonate each other merely by sharing a * version set or merely by sharing content. */ - private static byte[] intentToken(String name, List orderedVersions, Map rowHashes) { + private static byte[] intentToken(String name, Map versions) { MessageDigest d = sha256(); byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8); d.update(ByteBuffer.allocate(Integer.BYTES).putInt(nameBytes.length).array()); d.update(nameBytes); - for (long version : orderedVersions) { - d.update(ByteBuffer.allocate(Long.BYTES).putLong(version).array()); - d.update(rowHashes.get(version)); + for (Map.Entry entry : versions.entrySet()) { + d.update(ByteBuffer.allocate(Long.BYTES).putLong(entry.getKey()).array()); + d.update(entry.getValue().hash); } return d.digest(); } - /** Resolve a lost commit reply from an exact, content-bound intent, without reading the name. */ - boolean isPublished(PreparedRetirement p) throws SQLException { - try (Connection c = db.getConnection()) { - requireCommittedReads(c); - return fullyMatches(c, p); - } - } - /** * Recover a known publication by its exact tuple, without resolving the name or reading the original root. Every * row in this table is published by construction, so existence alone is sufficient. diff --git a/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java b/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java index debd4ee353..97c40ff30a 100644 --- a/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java +++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java @@ -6,12 +6,12 @@ import java.sql.Connection; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; -import java.util.List; +import java.util.LinkedHashMap; +import java.util.Map; import javax.sql.DataSource; import org.junit.Test; +import com.github.ambry.commons.BlobId; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @@ -38,30 +38,30 @@ public void testReaderRejectsDirtyReadsWithoutChangingPoolIsolation() throws SQL } @Test - public void testPublicationUsesADistinctOrderIndependentSet() { - assertEquals(Arrays.asList(1L, 2L), NamedBlobManifestStore.canonicalVersions(Arrays.asList(2L, 1L))); - for (List invalid : Arrays.asList(Arrays.asList(1L, 1L), Collections.singletonList(null), - Collections.emptyList())) { - try { - NamedBlobManifestStore.canonicalVersions(invalid); - fail("Invalid publication set accepted: " + invalid); - } catch (IllegalArgumentException expected) { - // Reject before acquiring database locks. - } + public void testPublicationRejectsNullVersion() throws SQLException { + try { + NamedBlobManifestStore.prepare((short) 17, (short) 4, "name", + Collections.singletonMap(null, new NamedBlobManifestStore.PendingVersion(mock(BlobId.class), 1, + Collections.emptyList().iterator()))); + fail("Accepted a null version"); + } catch (IllegalArgumentException expected) { + assertEquals("Invalid pending manifest versions", expected.getMessage()); } } @Test - public void testPublicationRejectsMoreThanTheDeclaredVersionCap() { - List tooMany = new ArrayList<>(); + public void testPublicationRejectsMoreThanTheDeclaredVersionCap() throws SQLException { + Map tooMany = new LinkedHashMap<>(); + BlobId root = mock(BlobId.class); for (long version = 1; version <= 33; version++) { - tooMany.add(version); + tooMany.put(version, new NamedBlobManifestStore.PendingVersion(root, 1, Collections.emptyList().iterator())); } try { - NamedBlobManifestStore.checkManifestCount(tooMany); + NamedBlobManifestStore.prepare((short) 17, (short) 4, "name", tooMany); fail("More than the declared cap of distinct named versions was accepted in one publication"); } catch (IllegalArgumentException expected) { assertEquals("Invalid number of manifests", expected.getMessage()); } + verifyNoInteractions(root); } } diff --git a/ambry-router/src/main/java/com/github/ambry/router/GetBlobOperation.java b/ambry-router/src/main/java/com/github/ambry/router/GetBlobOperation.java index 685428634f..a1d845d9fb 100644 --- a/ambry-router/src/main/java/com/github/ambry/router/GetBlobOperation.java +++ b/ambry-router/src/main/java/com/github/ambry/router/GetBlobOperation.java @@ -32,6 +32,7 @@ import com.github.ambry.messageformat.MessageFormatRecord; import com.github.ambry.messageformat.MessageMetadata; import com.github.ambry.messageformat.MetadataContentSerDe; +import com.github.ambry.messageformat.MetadataContentSerDe.ChunkCountLimitExceededException; import com.github.ambry.network.Port; import com.github.ambry.network.RequestInfo; import com.github.ambry.network.ResponseInfo; @@ -47,6 +48,7 @@ import com.github.ambry.server.ServerErrorCode; import com.github.ambry.store.MessageInfo; import com.github.ambry.store.StoreKey; +import com.github.ambry.utils.NettyByteBufDataInputStream; import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.Time; import io.netty.buffer.ByteBuf; @@ -62,7 +64,6 @@ import java.util.List; import java.util.ListIterator; import java.util.Map; -import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @@ -321,7 +322,12 @@ private void onChunkOperationComplete(GetChunk chunk) { // GetManager remove this operation. setOperationCompleted(); List chunkIds = e == null && compositeBlobInfo != null ? compositeBlobInfo.getKeys() : null; - operationResult = new GetBlobResult(blobInfo, null, chunkIds); + if (e != null && options.getBlobOptions.hasMaxChunkIds()) { + operationResult = null; + routerMetrics.onGetBlobError(e, options, isEncrypted); + } else { + operationResult = new GetBlobResult(blobInfo, null, chunkIds); + } } else { // Complete the operation from the caller's perspective, so that the caller can start reading from the // channel if there is no exception. The operation will not be marked as complete internally as subsequent @@ -1200,6 +1206,11 @@ void handleResponse(ResponseInfo responseInfo, GetResponse getResponse) { } else { try { processGetBlobResponse(getRequestInfo, getResponse); + } catch (ChunkCountLimitExceededException e) { + // This is a request limit, not a bad replica response. Do not retry. + chunkException = buildChunkException("Metadata exceeds the requested chunk ID limit", e, + RouterErrorCode.BlobTooLarge); + chunkCompleted = true; } catch (IOException | MessageFormatException e) { // This should really not happen. Again, we do not notify the ResponseHandler responsible for failure // detection. @@ -1637,26 +1648,39 @@ void handleBody(InputStream payload, MessageMetadata messageMetadata, MessageInf encryptionKey = messageMetadata == null ? null : messageMetadata.getEncryptionKey(); } else { BlobAll blobAll = MessageFormatRecord.deserializeBlobAll(payload, blobIdFactory); - BlobInfo serverBlobInfo = blobAll.getBlobInfo(); - updateTtlIfRequired(serverBlobInfo.getBlobProperties(), messageInfo); - getOptions().ageAtAccessTracker.trackAgeAtAccess(serverBlobInfo.getBlobProperties().getCreationTimeInMs()); blobData = blobAll.getBlobData(); encryptionKey = blobAll.getBlobEncryptionKey(); - if (Objects.isNull(encryptionKey) || options.getChunkIdsOnly) { - // set blobInfo iff: - // 1. blob is not encrypted OR, - // 2. getChunkIdsOnly is set. - // If the blob is encrypted, then the user metadata is encrypted too. So in that case, - // maybeProcessCallbackAndComplete() will set the appropriate value for blobInfo after decryption. - // In the case of getChunkIdsOnly call, we don't need the user metadata but still need blob - // properties to evaluate if the metadata chunk is already updated for update requests. So we allow blobInfo - // to be set here. - blobInfo = serverBlobInfo; - blobInfo.setLifeVersion(messageInfo.getLifeVersion()); - } else { - serverBlobProperties = serverBlobInfo.getBlobProperties(); - lifeVersion = messageInfo.getLifeVersion(); - userMetadata = serverBlobInfo.getUserMetadata(); + boolean bounded = options.getBlobOptions.hasMaxChunkIds(); + try { + BlobInfo serverBlobInfo = blobAll.getBlobInfo(); + BlobProperties properties = serverBlobInfo.getBlobProperties(); + updateTtlIfRequired(properties, messageInfo); + getOptions().ageAtAccessTracker.trackAgeAtAccess(properties.getCreationTimeInMs()); + if (encryptionKey == null || options.getChunkIdsOnly) { + // Chunk-ID callers need properties, not decrypted user metadata. + blobInfo = serverBlobInfo; + blobInfo.setLifeVersion(messageInfo.getLifeVersion()); + } else { + serverBlobProperties = properties; + lifeVersion = messageInfo.getLifeVersion(); + userMetadata = serverBlobInfo.getUserMetadata(); + } + if (bounded) { + blobType = blobData.getBlobType(); + if (blobType == BlobType.MetadataBlob) { + compositeBlobInfo = MetadataContentSerDe.deserializeMetadataContentRecord(blobData.content().nioBuffer(), + blobIdFactory, options.getBlobOptions.getMaxChunkIds()); + } else { + totalSize = blobData.getSize(); + } + successfullyDeserialized = true; + return; + } + } finally { + // The metadata-only path keeps no response data. Release only copies, not borrowed Netty slices. + if (bounded && !(payload instanceof NettyByteBufDataInputStream)) { + blobData.release(); + } } } blobType = blobData.getBlobType(); diff --git a/ambry-router/src/main/java/com/github/ambry/router/NonBlockingRouter.java b/ambry-router/src/main/java/com/github/ambry/router/NonBlockingRouter.java index b3ae7ac395..1b2f91cc78 100644 --- a/ambry-router/src/main/java/com/github/ambry/router/NonBlockingRouter.java +++ b/ambry-router/src/main/java/com/github/ambry/router/NonBlockingRouter.java @@ -376,7 +376,7 @@ private void getBlobHelper(String blobIdStr, GetBlobOptions options, Callback chunkIds = getChunkResult.getBlobChunkIds(); + router.getNotFoundCache().put(blobID, Boolean.TRUE); + GetBlobOptionsBuilder bounded = + new GetBlobOptionsBuilder().operationType(GetBlobOptions.OperationType.BlobChunkIds); + assertException(ExecutionException.class, + () -> router.getBlob(blobID, bounded.maxChunkIds(chunkIds.size()).build()) + .get(AWAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS), + e -> Assert.assertEquals(RouterErrorCode.BlobDoesNotExist, ((RouterException) e.getCause()).getErrorCode())); + GetBlobResult fresh = router.getBlob(blobID, new GetBlobOptionsBuilder() + .operationType(GetBlobOptions.OperationType.BlobChunkIds).bypassNotFoundCache(true).build()) + .get(AWAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS); + Assert.assertEquals(chunkIds, fresh.getBlobChunkIds()); + bounded.bypassNotFoundCache(true); + assertException(ExecutionException.class, + () -> router.getBlob(blobID, bounded.maxChunkIds(chunkIds.size() - 1).build()) + .get(AWAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS), + e -> Assert.assertEquals(RouterErrorCode.BlobTooLarge, ((RouterException) e.getCause()).getErrorCode())); + GetBlobResult exact = router.getBlob(blobID, bounded.maxChunkIds(chunkIds.size()).build()) + .get(AWAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS); + Assert.assertEquals(chunkIds, exact.getBlobChunkIds()); + Assert.assertNull(exact.getBlobDataChannel()); + router.getNotFoundCache().invalidate(blobID); + // verify the content, one data chunk after another int chunkSize = maxPutChunkSize; for (int i = 0; i < chunkIds.size(); i++) { From 7ee8d5f5488d5640b066a30910aba6853b70e2a3 Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Thu, 3 Dec 2026 14:43:44 -0800 Subject: [PATCH 2/4] Isolate named retirement metrics and verify driver safeguards Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit f5b10bf57c0c2cb1d36e8773bfb5a5738d26a4e0) --- ambry-named-mysql/README.md | 6 +++ ...NamedBlobManifestStoreIntegrationTest.java | 39 ++++++++++++++++++- .../java/com/github/ambry/named/Metrics.java | 6 +++ .../github/ambry/named/MySqlNamedBlobDb.java | 30 +++++++------- .../ambry/named/MySqlNamedBlobDbTest.java | 9 +++++ 5 files changed, 74 insertions(+), 16 deletions(-) diff --git a/ambry-named-mysql/README.md b/ambry-named-mysql/README.md index 05633fd354..78cba59127 100644 --- a/ambry-named-mysql/README.md +++ b/ambry-named-mysql/README.md @@ -12,6 +12,7 @@ Preparation, publication, and receipt checks block; run them off the event loop. handle on all paths: while it is open, a second request is rejected as unavailable. The 32 MiB limit is on encoded child bytes, not peak heap: allow for encoding buffers, supplier memory, and JDBC packet buffers. Publication or confirmation can also occupy one connection from the same pool as ordinary requests, outside the transaction executor. +`RetirementWriterBusyCount` records admission rejections; use it with heap and writer load before changing concurrency. Use the same handle to publish, to check its receipt after an uncertain result, and to retry. Each call checks out an idle, autocommit `REPEATABLE READ` session from the configured local writer pool and starts a fresh transaction. @@ -20,6 +21,7 @@ caps socket reads at five seconds and restores the previous timeout before retur pool-wide `socketTimeout` for retirement. Socket or communications failures discard the checkout without a rollback attempt; an interrupted commit is still an unknown outcome. Configure bounded pool checkout and descriptor fetches. The read timeout is not an end-to-end deadline, and closing the handle does not interrupt an active call. +`RetirementConnectionFailureCount` tracks retirement transport failures separately from ordinary named DB connections. A matching receipt confirms the commit; it does not authorize cleanup. No match means the commit was not observed, not that it rolled back. A replay whose read snapshot predates a concurrent commit can still reject if replacements now @@ -50,6 +52,10 @@ Connector/J 8.0.21 with client-side prepared statements rejected a synthetic 32 the measured query exceeded 64 MiB before transmission. The same bytes round-tripped with server-side prepared statements at 64 MiB and with either mode at 128 MiB on local MySQL 8.0.46. These are tested configurations, not production settings. Check the client limit as well as MySQL and replication limits on each deployment. +Measure binlog growth, replica lag, transaction size and backup growth under a representative workload. A root ID and +hash cannot recover descriptors if the raw root expires or becomes unreadable. Storing descriptors separately would +require keeping that object available and reconciling its lifecycle with MySQL publication. There is no manifest purge +in this path; retention and safe removal must account for receipt recovery, replica progress and reclamation. ## Installing or resuming the migration diff --git a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java index 2d55165ae9..abc8603da7 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 @@ -130,11 +130,16 @@ private static MySqlNamedBlobDb namedDb(DataSource db, boolean hardDelete) throw } private static MySqlNamedBlobDb namedDb(DataSource db, Properties properties, Time time) throws Exception { + return namedDb(db, properties, time, new Metrics(new MetricRegistry(), "")); + } + + private static MySqlNamedBlobDb namedDb(DataSource db, Properties properties, Time time, Metrics metrics) + throws Exception { properties.setProperty(MySqlNamedBlobDbConfig.DB_INFO, "[{\"url\":\"jdbc:mysql://[::1]\",\"datacenter\":\"local\",\"isWriteable\":true," + "\"username\":\"unused\",\"password\":\"unused\",\"sslMode\":\"NONE\"}]"); return new MySqlNamedBlobDb(fixtureAccounts(), new MySqlNamedBlobDbConfig(new VerifiableProperties(properties)), - endpoint -> db, "local", new Metrics(new MetricRegistry(), ""), time); + endpoint -> db, "local", metrics, time); } private static InMemAccountService fixtureAccounts() throws Exception { @@ -1428,17 +1433,47 @@ public void testExactHandleConfirmsLostReplyAfterOverCapReplacement() throws Exc }).when(lostReply).commit(); DataSource writer = mock(DataSource.class); when(writer.getConnection()).thenReturn(lostReply).thenAnswer(call -> db.getConnection()); - try (MySqlNamedBlobDb withLostReply = namedDb(writer); + Metrics metrics = new Metrics(new MetricRegistry(), ""); + try (MySqlNamedBlobDb withLostReply = namedDb(writer, new Properties(), SystemTime.getInstance(), metrics); MySqlNamedBlobDb.Retirement retirement = withLostReply.prepareRetirement("account", "container", NAME, () -> Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { assertLostReplyAndRecover(db, retirement, root, child); + assertEquals(1, metrics.retirementConnectionFailureCount.getCount()); + assertEquals(0, metrics.getMetricRegistry().counter( + MetricRegistry.name(MySqlNamedBlobDb.class, "NamedBlobDBConnectionFailureCount.local")).getCount()); } verify(lostReply, never()).rollback(); } }); } + @Test + public void testRetirementRejectsConnectorJReconnectOptions() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + for (String option : Arrays.asList("autoReconnect", "autoReconnectForPools", "reconnectAtTxEnd")) { + MysqlDataSource unsafeSource = source(db.unwrap(MysqlDataSource.class).getDatabaseName()); + unsafeSource.setUrl(unsafeSource.getUrl() + "?" + option + "=true"); + try (MySqlNamedBlobDb unsafe = namedDb(unsafeSource); + MySqlNamedBlobDb.Retirement retirement = unsafe.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + try { + retirement.publish(); + fail("Accepted a writer with " + option); + } catch (SQLException e) { + assertTrue(e.getMessage(), e.getMessage().contains("fixed physical MySQL session")); + } + } + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE retirement_fenced")); + }); + } + private static void assertLostReplyAndRecover(DataSource db, MySqlNamedBlobDb.Retirement retirement, BlobId root, BlobId child) throws Exception { try (Connection stale = db.getConnection(); Statement snapshot = stale.createStatement()) { diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java index 4ef05b3e99..8471c18168 100644 --- a/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java @@ -66,6 +66,8 @@ public class Metrics { final Counter fenceAwarePutVersionRejectedCount; public final Counter namedBlobDBUpdateErrorCount; final Counter connectionCloseErrorCount; + final Counter retirementConnectionFailureCount; + final Counter retirementWriterBusyCount; /** * Constructor to create the Metrics. @@ -141,6 +143,10 @@ public Metrics(MetricRegistry metricRegistry, String prefix) { metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "NamedBlobDBUpdateErrorCount")); connectionCloseErrorCount = metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "ConnectionCloseErrorCount")); + retirementConnectionFailureCount = + metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "RetirementConnectionFailureCount")); + retirementWriterBusyCount = + metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "RetirementWriterBusyCount")); } /** diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java index 17410d8ceb..e7596035f0 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 @@ -512,6 +512,7 @@ private Retirement prepareRetirement(Container container, throw new RestServiceException("Named retirement writer is unavailable", RestServiceErrorCode.ServiceUnavailable); } if (!retirementSlot.tryAcquire()) { + metricsRecoder.retirementWriterBusyCount.inc(); throw new RestServiceException("Named retirement already in progress", RestServiceErrorCode.ServiceUnavailable); } boolean prepared = false; @@ -612,7 +613,7 @@ private T run(TransactionGeneric transaction) throws Exception { try { return writer.runRetirementTransaction(transaction); } catch (Exception | Error e) { - writer.recordConnectionFailure(e); + writer.recordConnectionFailure(e, true); if (e instanceof SQLException) { metricsRecoder.namedBlobDBDeleteErrorCount.inc(); } @@ -867,11 +868,11 @@ private static class TransactionExecutor implements Closeable { * * *

The walk includes causes, chained SQL exceptions and suppressed cleanup failures. - * Connector/J can wrap a socket failure in a generic SQLException. + * For retirement only, also recognize socket failures wrapped in a generic SQLException. * SQLSTATE "40*" (transaction rollback), "57*" (operator intervention), and other * adjacent classes are intentionally NOT counted — those are not connection failures. */ - private static boolean isConnectionFailure(Throwable t) { + private static boolean isConnectionFailure(Throwable t, boolean retirement) { if (t == null) { return false; } @@ -884,7 +885,8 @@ private static boolean isConnectionFailure(Throwable t) { continue; } if (cur instanceof SQLNonTransientConnectionException || cur instanceof SQLTransientConnectionException - || cur instanceof SocketTimeoutException || cur instanceof SocketException || cur instanceof EOFException) { + || (retirement && (cur instanceof SocketTimeoutException || cur instanceof SocketException + || cur instanceof EOFException))) { return true; } if (cur instanceof SQLException) { @@ -912,9 +914,9 @@ void executeTransaction(Container container, boolean autoCommit, Transaction connection -> transaction.run(container.getParentAccountId(), container.getId(), connection), callback); } - private void recordConnectionFailure(Throwable failure) { - if (isConnectionFailure(failure)) { - connectionFailureCount.inc(); + private void recordConnectionFailure(Throwable failure, boolean retirement) { + if (isConnectionFailure(failure, retirement)) { + (retirement ? metrics.retirementConnectionFailureCount : connectionFailureCount).inc(); } } @@ -927,7 +929,7 @@ void executeTransactionGeneric(boolean autoCommit, TransactionGeneric tra try { result = runTransaction(autoCommit ? TransactionMode.AUTOCOMMIT : TransactionMode.EXPLICIT, transaction); } catch (Exception | Error e) { - recordConnectionFailure(e); + recordConnectionFailure(e, false); callback.onCompletion(null, e instanceof Exception ? (Exception) e : new IllegalStateException(e)); return; } @@ -992,7 +994,7 @@ private T runTransaction(TransactionMode mode, TransactionGeneric transac discardConnection(connection, failure); throw failure; } catch (Exception | Error failure) { - if (retirement && isConnectionFailure(failure)) { + if (retirement && isConnectionFailure(failure, true)) { discardConnection(connection, failure); throw failure; } @@ -1008,10 +1010,10 @@ private T runTransaction(TransactionMode mode, TransactionGeneric transac throw failure; } } - returnConnection(connection, autoCommit, timeoutToRestore, failure); + returnConnection(connection, mode, timeoutToRestore, failure); throw failure; } - returnConnection(connection, autoCommit, timeoutToRestore, null); + returnConnection(connection, mode, timeoutToRestore, null); return result; } @@ -1038,11 +1040,11 @@ private static void requireIdleRetirementSession(Connection connection, JdbcConn } } - private void returnConnection(Connection connection, boolean autoCommit, int timeoutToRestore, + private void returnConnection(Connection connection, TransactionMode mode, int timeoutToRestore, Throwable operationFailure) { try { try { - if (!autoCommit) { + if (mode != TransactionMode.AUTOCOMMIT) { connection.setAutoCommit(true); } if (timeoutToRestore >= 0) { @@ -1057,7 +1059,7 @@ private void returnConnection(Connection connection, boolean autoCommit, int tim } catch (Exception | Error cleanupFailure) { metrics.connectionCloseErrorCount.inc(); if (operationFailure == null) { - recordConnectionFailure(cleanupFailure); + recordConnectionFailure(cleanupFailure, mode == TransactionMode.RETIREMENT); } else if (operationFailure != cleanupFailure) { operationFailure.addSuppressed(cleanupFailure); } diff --git a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java index 8f01378b43..b0610f8225 100644 --- a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java +++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java @@ -41,6 +41,7 @@ import com.mysql.cj.protocol.ServerSession; import com.zaxxer.hikari.HikariDataSource; import java.io.IOException; +import java.net.SocketTimeoutException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -521,6 +522,14 @@ public void testConnectionFailureCounterIncrementsOnSqlState08() throws Exceptio e -> Assert.assertEquals(nullState, e.getCause())); assertEquals("counter must not increment when SQLSTATE is null", 2L, counter.getCount()); + SQLException wrappedTimeout = new SQLException("generic driver error", "S1000", new SocketTimeoutException()); + dataSourceFactory.triggerQueryExecutionError(localDatacenter, wrappedTimeout); + TestUtils.assertException(ExecutionException.class, + () -> db.get(account.getName(), container.getName(), "blobName").get(5, TimeUnit.SECONDS), + e -> assertEquals(wrappedTimeout, e.getCause())); + assertEquals("legacy transactions must not count generic socket errors", 2L, counter.getCount()); + assertEquals(0, metrics.retirementConnectionFailureCount.getCount()); + // Direct SQLNonTransientConnectionException (mimics MySQL CommunicationsException) — counts via type. SQLException directNonTransient = new SQLNonTransientConnectionException("communications failure"); dataSourceFactory.triggerQueryExecutionError(localDatacenter, directNonTransient); From 8b98672275b332c20be9c408376676c0c6275f52 Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Thu, 3 Dec 2026 14:51:02 -0800 Subject: [PATCH 3/4] Validate retirement at startup and distinguish DELETE outcomes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../com/github/ambry/named/NamedBlobDb.java | 5 ++ .../frontend/FrontendRestRequestService.java | 14 ++++- .../frontend/NamedBlobRetirementHandler.java | 33 ++++++++++- .../frontend/NamedBlobDeleteHandlerTest.java | 5 +- .../frontend/S3BatchDeleteHandlerTest.java | 2 +- ambry-named-mysql/README.md | 19 ++++-- ...NamedBlobManifestStoreIntegrationTest.java | 58 ++++++++++++++++++- .../java/com/github/ambry/named/Metrics.java | 9 +++ .../github/ambry/named/MySqlNamedBlobDb.java | 42 ++++++++++++-- .../ambry/named/NamedBlobManifestStore.java | 27 +++++---- 10 files changed, 188 insertions(+), 26 deletions(-) diff --git a/ambry-api/src/main/java/com/github/ambry/named/NamedBlobDb.java b/ambry-api/src/main/java/com/github/ambry/named/NamedBlobDb.java index a812c6c1b3..196893b9f9 100644 --- a/ambry-api/src/main/java/com/github/ambry/named/NamedBlobDb.java +++ b/ambry-api/src/main/java/com/github/ambry/named/NamedBlobDb.java @@ -112,6 +112,11 @@ default CompletableFuture put(NamedBlobRecord record) { */ CompletableFuture delete(String accountName, String containerName, String blobName); + /** Check that the local writer supports retirement before starting an opted-in frontend. */ + default void validateRetirementWriter() throws Exception { + throw new IllegalStateException("Named retirement is unavailable"); + } + /** * Retire the unfenced versions of the authorized name without deleting data. Blocks on the caller's worker. * The loader must return the full ordered child list of the exact root, decoding at most the supplied limit. diff --git a/ambry-frontend/src/main/java/com/github/ambry/frontend/FrontendRestRequestService.java b/ambry-frontend/src/main/java/com/github/ambry/frontend/FrontendRestRequestService.java index ef6238084b..fdcf3c0526 100644 --- a/ambry-frontend/src/main/java/com/github/ambry/frontend/FrontendRestRequestService.java +++ b/ambry-frontend/src/main/java/com/github/ambry/frontend/FrontendRestRequestService.java @@ -188,6 +188,18 @@ public void start() throws InstantiationException { if (responseHandler == null) { throw new InstantiationException("ResponseHandler is not set."); } + if (!frontendConfig.namedBlobRetirementNamespace.isEmpty()) { + try { + if (namedBlobDb == null) { + throw new IllegalStateException("Named blob DB is not configured"); + } + namedBlobDb.validateRetirementWriter(); + } catch (Exception e) { + InstantiationException failure = new InstantiationException("Named retirement writer is not ready"); + failure.initCause(e); + throw failure; + } + } long startupBeginTime = System.currentTimeMillis(); try { quotaManager.init(); @@ -215,7 +227,7 @@ public void start() throws InstantiationException { new CopyDatasetVersionHandler(securityService, accountService, frontendMetrics, accountAndContainerInjector); if (!frontendConfig.namedBlobRetirementNamespace.isEmpty()) { retirementHandler = new NamedBlobRetirementHandler(frontendConfig.namedBlobRetirementNamespace, namedBlobDb, - router, clusterMap, quotaManager); + router, clusterMap, quotaManager, frontendMetrics.getMetricRegistry()); } deleteBlobHandler = new DeleteBlobHandler(router, securityService, idConverter, accountAndContainerInjector, frontendMetrics, diff --git a/ambry-frontend/src/main/java/com/github/ambry/frontend/NamedBlobRetirementHandler.java b/ambry-frontend/src/main/java/com/github/ambry/frontend/NamedBlobRetirementHandler.java index fcfb86d28f..cd63dd1906 100644 --- a/ambry-frontend/src/main/java/com/github/ambry/frontend/NamedBlobRetirementHandler.java +++ b/ambry-frontend/src/main/java/com/github/ambry/frontend/NamedBlobRetirementHandler.java @@ -13,6 +13,9 @@ */ package com.github.ambry.frontend; +import com.codahale.metrics.Counter; +import com.codahale.metrics.Histogram; +import com.codahale.metrics.MetricRegistry; import com.github.ambry.account.Account; import com.github.ambry.account.Container; import com.github.ambry.clustermap.ClusterMap; @@ -53,16 +56,32 @@ final class NamedBlobRetirementHandler implements AutoCloseable { private final Router router; private final BlobIdFactory keyFactory; private final QuotaManager quotaManager; + private final Counter successCount; + private final Counter busyCount; + private final Counter unsupportedCount; + private final Counter conflictCount; + private final Counter unreadableRootCount; + private final Counter childLimitCount; + private final Histogram processingTimeInMs; private final ThreadPoolExecutor worker = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new Utils.SchedulerThreadFactory("NamedBlobRetirement", true)); NamedBlobRetirementHandler(String namespace, NamedBlobDb namedBlobDb, Router router, ClusterMap clusterMap, - QuotaManager quotaManager) { + QuotaManager quotaManager, MetricRegistry registry) { this.namespace = namespace; this.namedBlobDb = namedBlobDb; this.router = router; this.keyFactory = new BlobIdFactory(clusterMap); this.quotaManager = quotaManager; + successCount = registry.counter(MetricRegistry.name(NamedBlobRetirementHandler.class, "SuccessCount")); + busyCount = registry.counter(MetricRegistry.name(NamedBlobRetirementHandler.class, "BusyCount")); + unsupportedCount = registry.counter(MetricRegistry.name(NamedBlobRetirementHandler.class, "UnsupportedCount")); + conflictCount = registry.counter(MetricRegistry.name(NamedBlobRetirementHandler.class, "ConflictCount")); + unreadableRootCount = + registry.counter(MetricRegistry.name(NamedBlobRetirementHandler.class, "UnreadableRootCount")); + childLimitCount = registry.counter(MetricRegistry.name(NamedBlobRetirementHandler.class, "ChildLimitCount")); + processingTimeInMs = + registry.histogram(MetricRegistry.name(NamedBlobRetirementHandler.class, "ProcessingTimeInMs")); } boolean matches(String account, String container) { @@ -84,6 +103,7 @@ void handle(RestRequest request, NamedBlobPath path, Callback callback) th if (request.getRestMethod() != RestMethod.DELETE || request.getArgs().containsKey(S3_BATCH_DELETE_SUBREQUEST) || request.getArgs().containsKey(DATASET_DELETE_ENABLED) || RestUtils.isDatasetVersionQueryEnabled(request.getArgs()) || (RestUtils.isS3Request(request) && request.getArgs().containsKey("versionId"))) { + unsupportedCount.inc(); throw new RestServiceException("Only single-object named DELETE is supported in the retirement namespace", RestServiceErrorCode.NotAllowed); } @@ -93,17 +113,26 @@ void handle(RestRequest request, NamedBlobPath path, Callback callback) th Container container = (Container) request.getArgs().get(TARGET_CONTAINER_KEY); try { worker.execute(() -> { + long startTime = System.nanoTime(); Exception failure = null; try { QuotaChargeCallback charge = QuotaUtils.buildQuotaChargeCallback(request, quotaManager, false); namedBlobDb.retire(container, path.getBlobName(), keyFactory, (root, limit) -> loadChildren(root, limit, request, charge)); + successCount.inc(); } catch (Exception e) { failure = e; + if (e instanceof RestServiceException + && ((RestServiceException) e).getErrorCode() == RestServiceErrorCode.Conflict) { + conflictCount.inc(); + } + } finally { + processingTimeInMs.update(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)); } callback.onCompletion(null, failure); }); } catch (RejectedExecutionException e) { + busyCount.inc(); throw new RestServiceException("Named retirement worker is busy or stopped", e, RestServiceErrorCode.ServiceUnavailable); } @@ -128,6 +157,7 @@ private List loadChildren(StoreKey root, int limit, RestRequest reques if (failure instanceof RouterException) { RouterErrorCode code = ((RouterException) failure).getErrorCode(); if (code == RouterErrorCode.BlobTooLarge) { + childLimitCount.inc(); throw new RestServiceException("Named retirement exceeds its child limit", failure, RestServiceErrorCode.Conflict); } @@ -137,6 +167,7 @@ private List loadChildren(StoreKey root, int limit, RestRequest reques } } // Storage absence does not prove that the name is absent (S3 maps NotFound to success). + unreadableRootCount.inc(); throw new RestServiceException("Cannot read named retirement root", failure, RestServiceErrorCode.ServiceUnavailable); } catch (InterruptedException e) { diff --git a/ambry-frontend/src/test/java/com/github/ambry/frontend/NamedBlobDeleteHandlerTest.java b/ambry-frontend/src/test/java/com/github/ambry/frontend/NamedBlobDeleteHandlerTest.java index bbc5a43848..d54d35141f 100644 --- a/ambry-frontend/src/test/java/com/github/ambry/frontend/NamedBlobDeleteHandlerTest.java +++ b/ambry-frontend/src/test/java/com/github/ambry/frontend/NamedBlobDeleteHandlerTest.java @@ -259,8 +259,11 @@ public void testRetirementDoesNotTreatMissingStorageAsMissingName() throws Excep return null; }).when(db).retire(eq(REF_CONTAINER), eq(BLOBNAME), any(), any()); try (NamedBlobRetirementHandler retirement = retirement(db, exactRouter)) { + String name = MetricRegistry.name(NamedBlobRetirementHandler.class, "UnreadableRootCount"); + long before = metrics.getMetricRegistry().counter(name).getCount(); assertDeleteError(RestServiceErrorCode.ServiceUnavailable, delete(withRetirement(retirement, exactRouter), getDeleteRestRequest(new JSONObject(), request_path), new MockRestResponseChannel())); + assertEquals(before + 1, metrics.getMetricRegistry().counter(name).getCount()); verify(exactRouter).getBlob(eq("missing-root"), any(GetBlobOptions.class), isNull(), any(QuotaChargeCallback.class)); verifyNoMoreInteractions(exactRouter); @@ -269,7 +272,7 @@ public void testRetirementDoesNotTreatMissingStorageAsMissingName() throws Excep private NamedBlobRetirementHandler retirement(NamedBlobDb db, Router retirementRouter) { return new NamedBlobRetirementHandler(REF_ACCOUNT.getName() + "/" + REF_CONTAINER.getName(), db, - retirementRouter, CLUSTER_MAP, QuotaTestUtils.createDummyQuotaManager()); + retirementRouter, CLUSTER_MAP, QuotaTestUtils.createDummyQuotaManager(), metrics.getMetricRegistry()); } private DeleteBlobHandler withRetirement(NamedBlobRetirementHandler retirement, Router retirementRouter) { diff --git a/ambry-frontend/src/test/java/com/github/ambry/frontend/S3BatchDeleteHandlerTest.java b/ambry-frontend/src/test/java/com/github/ambry/frontend/S3BatchDeleteHandlerTest.java index c9e0918148..5bf17bb831 100644 --- a/ambry-frontend/src/test/java/com/github/ambry/frontend/S3BatchDeleteHandlerTest.java +++ b/ambry-frontend/src/test/java/com/github/ambry/frontend/S3BatchDeleteHandlerTest.java @@ -154,7 +154,7 @@ public void testBatchDeleteDoesNotRetireOrDeleteSelectedNamespace() throws Excep SecurityService security = new FrontendTestSecurityServiceFactory().getSecurityService(); try (NamedBlobRetirementHandler retirement = new NamedBlobRetirementHandler( account.getName() + "/" + container.getName(), db, router, clusterMap, - QuotaTestUtils.createDummyQuotaManager())) { + QuotaTestUtils.createDummyQuotaManager(), metrics.getMetricRegistry())) { DeleteBlobHandler delete = new DeleteBlobHandler(router, security, null, injector, metrics, clusterMap, QuotaTestUtils.createDummyQuotaManager(), ACCOUNT_SERVICE, null, retirement); S3BatchDeleteHandler batch = new S3BatchDeleteHandler(delete, metrics); diff --git a/ambry-named-mysql/README.md b/ambry-named-mysql/README.md index 78cba59127..ab07144741 100644 --- a/ambry-named-mysql/README.md +++ b/ambry-named-mysql/README.md @@ -139,14 +139,25 @@ before retrying `ALTER TABLE ... ADD INDEX`; each retry rebuilds the index. Afte `frontend.named.blob.retirement.namespace` defaults to empty. If set to one `account/container`, authorized native and S3 single-object named DELETEs for that namespace use retirement instead of the legacy named and router DELETEs. The -writer refuses publication unless `mysql.named.blob.honor.retirement.fence` is enabled. Batch, dataset, and S3 -`versionId` DELETEs are rejected for the selected namespace; multipart aborts and raw-ID DELETEs do not use this path. +frontend checks one local writer connection at startup when the namespace is set, and fails startup if the writer +does not support fence-aware soft delete or the session is incompatible. The same session checks still run on +every retirement checkout. The probe does not validate migration, permissions for publication, or failover targets. +Batch, dataset, and S3 `versionId` DELETEs are rejected for the selected namespace; multipart aborts and raw-ID DELETEs +do not use this path. The frontend uses one worker with no queue. Under the DB's admission permit, it selects exact live versions from the local writer, closes the selection transaction, and fetches only their root metadata by ID. The router bypasses its negative cache and checks the remaining child budget before allocating the decoded list. Publication rechecks the full -name range under lock. If the commit reply is lost, the same request checks only its exact receipt. A missing or -unreadable receipt returns an error, not success. +name range under lock. A known history conflict with a successful rollback returns `409`. If the commit reply is +lost, the same request checks only its exact receipt. A missing or unreadable receipt returns `503`, not success. +An unreadable raw root returns `503` without fencing or creating an empty manifest; missing root metadata does not +establish that the children are absent. Simple roots and live `IN_PROGRESS` versions return `409` without falling +back to physical DELETE. Verify those restrictions are compatible with the selected namespace before enabling it. + +Monitor `NamedBlobRetirementHandler` success, processing latency, busy rejections, unsupported request shapes, +conflicts, unreadable roots and descriptor-read child limits. The MySQL metrics distinguish recovery by receipt, +an unconfirmed publication, and child-budget exhaustion between roots. Before raising concurrency, measure busy +rejections and retry behavior with representative bursts alongside heap, descriptor latency and writer load. ## Before enabling publication 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 abc8603da7..a30a70fb8e 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 @@ -211,7 +211,7 @@ public void testWiredRetirementRejectsReplacementAndUnsupportedRootsWithoutMutat }); fail("The original intent did not represent the replacement"); } catch (RestServiceException failure) { - assertEquals(RestServiceErrorCode.ServiceUnavailable, failure.getErrorCode()); + assertEquals(RestServiceErrorCode.Conflict, failure.getErrorCode()); } try { named.retire(container, NAME, keyFactory, (selected, limit) -> { @@ -234,6 +234,60 @@ private static MySqlNamedBlobDb fenceAwareWriter(DataSource writer) throws Excep return namedDb(writer, properties, SystemTime.getInstance()); } + @Test + public void testWiredRetirementDoesNotTreatJdbcDataExceptionDuringCommitAsConflict() throws Exception { + withDatabase((db, unused) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + StoreKeyFactory keyFactory = mock(StoreKeyFactory.class); + when(keyFactory.getStoreKey(root.getID())).thenReturn(root); + Container container = fixtureAccounts().getAccountById(ACCOUNT).getContainerById(CONTAINER); + try (Connection physical = db.getConnection()) { + Connection failingCommit = mock(Connection.class, delegatesTo(physical)); + SQLException jdbcFailure = new SQLDataException("JDBC commit failure"); + doThrow(jdbcFailure).when(failingCommit).commit(); + DataSource writer = mock(DataSource.class); + when(writer.getConnection()).thenAnswer(call -> db.getConnection()).thenReturn(failingCommit) + .thenAnswer(call -> db.getConnection()); + try (MySqlNamedBlobDb named = fenceAwareWriter(writer)) { + try { + named.retire(container, NAME, keyFactory, (selected, limit) -> Collections.singletonList(child)); + fail("A missing receipt must not confirm publication"); + } catch (RestServiceException failure) { + assertEquals(RestServiceErrorCode.ServiceUnavailable, failure.getErrorCode()); + assertSame(jdbcFailure, failure.getCause()); + } + } + verify(writer, times(3)).getConnection(); + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + }); + } + + @Test + public void testRetirementWriterPreflightRejectsIncompatibleWriter() throws Exception { + withDatabase((db, disabled) -> { + try (MySqlNamedBlobDb ready = fenceAwareWriter(db)) { + ready.validateRetirementWriter(); + } + try (Connection connection = db.getConnection(); Statement sql = connection.createStatement()) { + sql.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED"); + DataSource writer = mock(DataSource.class); + when(writer.getConnection()).thenReturn(connection); + try (MySqlNamedBlobDb notReady = fenceAwareWriter(writer)) { + try { + notReady.validateRetirementWriter(); + fail("Startup validation accepted a non-REPEATABLE READ session"); + } catch (SQLException failure) { + assertTrue(failure.getMessage(), failure.getMessage().contains("idle autocommit REPEATABLE READ")); + } + } + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + }); + } + @Test public void testFenceAwareGetWithSlowFrontend() throws Exception { withDatabase((db, writer) -> { @@ -1455,7 +1509,7 @@ public void testRetirementRejectsConnectorJReconnectOptions() throws Exception { BlobId child = blob(BlobId.BlobDataType.DATACHUNK); insertNamed(db, 1, root, NamedBlobState.READY); for (String option : Arrays.asList("autoReconnect", "autoReconnectForPools", "reconnectAtTxEnd")) { - MysqlDataSource unsafeSource = source(db.unwrap(MysqlDataSource.class).getDatabaseName()); + MysqlDataSource unsafeSource = source(((MysqlDataSource) db).getDatabaseName()); unsafeSource.setUrl(unsafeSource.getUrl() + "?" + option + "=true"); try (MySqlNamedBlobDb unsafe = namedDb(unsafeSource); MySqlNamedBlobDb.Retirement retirement = unsafe.prepareRetirement("account", "container", NAME, diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java index 8471c18168..29b4db385b 100644 --- a/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java @@ -68,6 +68,9 @@ public class Metrics { final Counter connectionCloseErrorCount; final Counter retirementConnectionFailureCount; final Counter retirementWriterBusyCount; + final Counter retirementReceiptRecoveredCount; + final Counter retirementUnconfirmedCount; + final Counter retirementChildBudgetExhaustedCount; /** * Constructor to create the Metrics. @@ -147,6 +150,12 @@ public Metrics(MetricRegistry metricRegistry, String prefix) { metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "RetirementConnectionFailureCount")); retirementWriterBusyCount = metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "RetirementWriterBusyCount")); + retirementReceiptRecoveredCount = + metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "RetirementReceiptRecoveredCount")); + retirementUnconfirmedCount = + metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "RetirementUnconfirmedCount")); + retirementChildBudgetExhaustedCount = metricRegistry.counter( + MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "RetirementChildBudgetExhaustedCount")); } /** 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 e7596035f0..f85c6cb423 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 @@ -529,13 +529,27 @@ private Retirement prepareRetirement(Container container, } } - @Override - public void retire(Container container, String blobName, StoreKeyFactory keyFactory, RetirementLoader loader) - throws Exception { + private void requireRetirementEnabled() throws RestServiceException { if (!config.honorRetirementFence || config.enableHardDelete) { throw new RestServiceException("Named retirement requires fence-aware soft delete", RestServiceErrorCode.ServiceUnavailable); } + } + + @Override + public void validateRetirementWriter() throws Exception { + requireRetirementEnabled(); + TransactionExecutor writer = transactionExecutors.get(localDatacenter); + if (writer == null || writer.executor.isShutdown()) { + throw new IllegalStateException("Named retirement writer is unavailable"); + } + writer.runRetirementTransaction(connection -> null); + } + + @Override + public void retire(Container container, String blobName, StoreKeyFactory keyFactory, RetirementLoader loader) + throws Exception { + requireRetirementEnabled(); short accountId = container.getParentAccountId(); short containerId = container.getId(); try (Retirement retirement = prepareRetirement(container, blobName, writer -> { @@ -548,11 +562,12 @@ public void retire(Container container, String blobName, StoreKeyFactory keyFact int remaining = NamedBlobManifestStore.MAX_CHILDREN; for (Map.Entry entry : roots.entrySet()) { if (remaining == 0) { - throw new SQLDataException("Too many children for named retirement"); + metricsRecoder.retirementChildBudgetExhaustedCount.inc(); + throw new RestServiceException("Named retirement exceeds its child limit", RestServiceErrorCode.Conflict); } List children = loader.load(entry.getValue(), remaining); if (children == null || children.isEmpty() || children.size() > remaining) { - throw new SQLDataException("Invalid child list for named retirement"); + throw new RestServiceException("Invalid child list for named retirement", RestServiceErrorCode.Conflict); } remaining -= children.size(); pending.put(entry.getKey(), @@ -562,10 +577,14 @@ public void retire(Container container, String blobName, StoreKeyFactory keyFact })) { try { retirement.publish(); + } catch (RolledBackRetirementConflict refusal) { + throw new RestServiceException("Named blob history changed before retirement", refusal, + RestServiceErrorCode.Conflict); } catch (Exception publishFailure) { // Never rediscover the name after a failed publish: it could already point to a replacement. try { if (retirement.isPublished()) { + metricsRecoder.retirementReceiptRecoveredCount.inc(); return; } } catch (Exception confirmationFailure) { @@ -573,14 +592,21 @@ public void retire(Container container, String blobName, StoreKeyFactory keyFact publishFailure.addSuppressed(confirmationFailure); } } + metricsRecoder.retirementUnconfirmedCount.inc(); throw new RestServiceException("Named retirement was not confirmed", publishFailure, RestServiceErrorCode.ServiceUnavailable); } - } catch (SQLDataException unsupported) { + } catch (RolledBackRetirementConflict unsupported) { throw new RestServiceException("Named blob history cannot be retired", unsupported, RestServiceErrorCode.Conflict); } } + private static final class RolledBackRetirementConflict extends SQLDataException { + RolledBackRetirementConflict(NamedBlobManifestStore.RetirementConflict cause) { + super(cause.getMessage(), cause); + } + } + /** Owns the admission slot and the encoded bytes until close. Never queues a payload. */ final class Retirement implements AutoCloseable { private final TransactionExecutor writer; @@ -1011,6 +1037,10 @@ private T runTransaction(TransactionMode mode, TransactionGeneric transac } } returnConnection(connection, mode, timeoutToRestore, failure); + if (retirement && failure instanceof NamedBlobManifestStore.RetirementConflict) { + // A domain refusal can only be reported after rollback succeeds. + throw new RolledBackRetirementConflict((NamedBlobManifestStore.RetirementConflict) failure); + } throw failure; } returnConnection(connection, mode, timeoutToRestore, null); 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 e61788af75..a0d0ebf0bc 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 @@ -77,19 +77,19 @@ static Map selectRoots(Connection c, short account, short containe int rows = 0; while (r.next()) { if (++rows > MAX_VERSIONS || !name.equals(r.getString(1))) { - throw new SQLDataException("Unsupported named version range"); + throw new RetirementConflict("Unsupported named version range"); } if (r.getBoolean(5)) { continue; } byte[] bytes = r.getBytes(3); if (r.getInt(4) != NamedBlobState.READY.ordinal() || bytes == null || bytes.length == 0) { - throw new SQLDataException("Ineligible named version"); + throw new RetirementConflict("Ineligible named version"); } StoreKey key = keyFactory.getStoreKey(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)); if (!(key instanceof BlobId) || !Arrays.equals(bytes, key.toBytes()) || !isCompositeRoot((BlobId) key, account, container)) { - throw new SQLDataException("Unsupported named composite capture"); + throw new RetirementConflict("Unsupported named composite capture"); } roots.put(r.getLong(2), (BlobId) key); } @@ -276,7 +276,7 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { int rows = 0; while (r.next()) { if (++rows > MAX_VERSIONS || !p.name.equals(r.getString(1))) { - throw new SQLDataException("Unsupported named version range"); + throw new RetirementConflict("Unsupported named version range"); } long version = r.getLong(2); PreparedVersion expected = p.versions.get(version); @@ -321,7 +321,7 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { 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"); + throw new RetirementConflict("Unrepresented or ineligible named version"); } } catch (SQLIntegrityConstraintViolationException duplicate) { if (duplicate.getErrorCode() != 1062) { @@ -336,7 +336,7 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { return; } if (freshlyPublished.size() != p.versions.size()) { - throw new SQLDataException("Partial manifest set"); + throw new RetirementConflict("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); @@ -350,7 +350,7 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { 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"); + throw new RetirementConflict("Named version is no longer eligible"); } // Only the installed fence turns the explicit NULL into a delete timestamp. try (ResultSet r = fence.executeQuery()) { @@ -373,18 +373,25 @@ private static void confirmExistingMatches(Connection c, PreparedRetirement p, l 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"); + throw new RetirementConflict("Manifest belongs to a different publication"); } if (!MessageDigest.isEqual(r.getBytes(1), requested.hash)) { - throw new SQLDataException("Conflicting manifest for named version"); + throw new RetirementConflict("Conflicting manifest for named version"); } if (!MessageDigest.isEqual(r.getBytes(2), p.intentToken)) { - throw new SQLDataException("Manifest belongs to a different publication"); + throw new RetirementConflict("Manifest belongs to a different publication"); } } } } + /** A rejection raised by our transaction body, never by JDBC or commit. */ + static final class RetirementConflict extends SQLDataException { + RetirementConflict(String message) { + super(message); + } + } + /** * Match the exact receipt visible to the supplied transaction without locking or reading {@code named_blobs_v2}. * A transaction can see its own uncommitted writes, and an older snapshot can miss a committed receipt. From f774da354f5f0f8dc3d2efaa7f18f0fe50ca214f Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Thu, 3 Dec 2026 14:52:48 -0800 Subject: [PATCH 4/4] Keep descriptor validation failures distinct from database errors Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...NamedBlobManifestStoreIntegrationTest.java | 21 +++++++++++++++++++ .../github/ambry/named/MySqlNamedBlobDb.java | 13 +++++++++--- 2 files changed, 31 insertions(+), 3 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 a30a70fb8e..ce3e58e227 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 @@ -234,6 +234,27 @@ private static MySqlNamedBlobDb fenceAwareWriter(DataSource writer) throws Excep return namedDb(writer, properties, SystemTime.getInstance()); } + @Test + public void testWiredRetirementRejectsInvalidDescriptorsBeforePublication() throws Exception { + withDatabase((db, unused) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, 1, root, NamedBlobState.READY); + StoreKeyFactory keyFactory = mock(StoreKeyFactory.class); + when(keyFactory.getStoreKey(root.getID())).thenReturn(root); + Container container = fixtureAccounts().getAccountById(ACCOUNT).getContainerById(CONTAINER); + try (MySqlNamedBlobDb named = fenceAwareWriter(db)) { + try { + named.retire(container, NAME, keyFactory, (selected, limit) -> Collections.singletonList(selected)); + fail("A root must not be accepted as its own descriptor"); + } catch (RestServiceException failure) { + assertEquals(RestServiceErrorCode.Conflict, failure.getErrorCode()); + } + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE retirement_fenced")); + }); + } + @Test public void testWiredRetirementDoesNotTreatJdbcDataExceptionDuringCommitAsConflict() throws Exception { withDatabase((db, unused) -> { 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 f85c6cb423..70370bc2a2 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 @@ -517,9 +517,16 @@ private Retirement prepareRetirement(Container container, } boolean prepared = false; try { - Retirement retirement = new Retirement(writer, - NamedBlobManifestStore.prepare(container.getParentAccountId(), container.getId(), blobName, - input.load(writer))); + Map pending = input.load(writer); + Retirement retirement; + try { + retirement = new Retirement(writer, + NamedBlobManifestStore.prepare(container.getParentAccountId(), container.getId(), blobName, pending)); + } catch (SQLDataException invalidDescriptors) { + // Only preparation's own validation failures are conflicts; loader and JDBC failures are not. + throw new RestServiceException("Named blob descriptors cannot be retired", invalidDescriptors, + RestServiceErrorCode.Conflict); + } prepared = true; return retirement; } finally {