From 1c28620b65d4d1cd599537f7d3572fb6e57adba3 Mon Sep 17 00:00:00 2001 From: Ameya Lokare Date: Thu, 27 Aug 2026 13:16:48 -0700 Subject: [PATCH] Re-use ACI / clear account queues under a pessimistic ACI lock --- .../storage/AccountsManager.java | 10 +++- ...learOrphanedFoundationDbQueuesCommand.java | 47 ++++++++++++---- .../workers/CommandDependencies.java | 7 ++- ...xpiredFoundationDbMessagesCommandTest.java | 4 +- ...OrphanedFoundationDbQueuesCommandTest.java | 55 +++++++++++++++++-- ...PushNotificationExperimentCommandTest.java | 1 + .../workers/NotifyIdleDevicesCommandTest.java | 2 +- ...SecondaryDynamoDbTableDataCommandTest.java | 1 + ...PushNotificationExperimentCommandTest.java | 2 +- ...dFoundationDbMessageQueuesCommandTest.java | 3 +- 10 files changed, 107 insertions(+), 25 deletions(-) diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java index 4880535e8..6b7e4759a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java @@ -522,7 +522,15 @@ public class AccountsManager extends RedisPubSubAdapter implemen additionalWriteItems.add(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, phoneNumberRecoveryPassword)))); if (maybeNumber.isPresent()) { - accounts.create(account, additionalWriteItems); + if (maybeRecentlyDeletedAccountIdentifier.isPresent()) { + // If we are re-using a recently deleted ACI, also obtain a lock for it so that clearing queues for the ACI synchronize against it + accountLockManager.withLock(Set.of(maybeRecentlyDeletedAccountIdentifier.get()), () -> { + accounts.create(account, additionalWriteItems); + return null; + }, accountLockExecutor); + } else { + accounts.create(account, additionalWriteItems); + } } else { assert accountAttributes.recoveryPassword().isPresent(); accounts.create(account, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java index 6624af409..ffcb908bd 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java @@ -25,7 +25,10 @@ import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.Set; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; @@ -37,8 +40,10 @@ import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.WhisperServerConfiguration; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; import org.whispersystems.textsecuregcm.metrics.MetricsUtil; +import org.whispersystems.textsecuregcm.storage.AccountLockManager; import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore; +import org.whispersystems.textsecuregcm.util.ManagedExecutors; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.util.retry.Retry; @@ -132,26 +137,32 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD throw new UncheckedIOException(e); } }); + final ExecutorService executorService = ManagedExecutors.newVirtualThreadPerTaskExecutor("clearOrphanedQueues", + configuration.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(), environment); clearOrphanedQueues(databases, commandDependencies.accountsManager(), concurrency, dryRun, maxAcisPerTransaction, configuration.getFoundationDbMessagesConfiguration().batchPriorityTransactionRetryLimit(), configuration.getFoundationDbMessagesConfiguration().batchPriorityTransactionTimeout(), - chunksPerShard); + chunksPerShard, + commandDependencies.accountLockManager(), + executorService); } @VisibleForTesting void clearOrphanedQueues(final Stream databases, final AccountsManager accountsManager, final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit, - final Duration transactionTimeout, final int numChunks) { + final Duration transactionTimeout, final int numChunks, final AccountLockManager accountLockManager, + final Executor executor) { Flux.fromStream(databases) .flatMap(database -> crawlAcisInShard(database, accountsManager, concurrency, dryRun, maxAcisPerTransaction, - transactionRetryLimit, transactionTimeout, numChunks)) + transactionRetryLimit, transactionTimeout, numChunks, accountLockManager, executor)) .then() .block(); } private Mono crawlAcisInShard(final Database database, final AccountsManager accountsManager, final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit, - final Duration transactionTimeout, final int numChunks) { + final Duration transactionTimeout, final int numChunks, final AccountLockManager accountLockManager, + final Executor executor) { return getAcisInShard(database, maxAcisPerTransaction, transactionRetryLimit, transactionTimeout, numChunks) .doOnNext(_ -> Metrics.counter(ACCOUNTS_CRAWLED_COUNTER, "dryRun", String.valueOf(dryRun)).increment()) .flatMap(aci -> Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(aci.uuid())) @@ -172,7 +183,8 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD logger.info("Would have cleared queue for ACI: {}", aci.uuid()); return Mono.just(true); } - return clearQueue(database, aci, transactionRetryLimit, transactionTimeout) + return clearQueueWithAciLock(database, aci, transactionRetryLimit, transactionTimeout, accountsManager, + accountLockManager, executor) .thenReturn(true) .onErrorResume(t -> { logger.error("Failed to clear orphaned queue for ACI: {}", aci.uuid(), t); @@ -185,15 +197,30 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD .then(); } - private Mono clearQueue(final Database database, final AciServiceIdentifier aci, - final long transactionRetryLimit, final Duration transactionTimeout) { - return Mono.fromFuture(() -> database.runAsync(transaction -> { + private Mono clearQueueWithAciLock(final Database database, final AciServiceIdentifier aci, + final long transactionRetryLimit, final Duration transactionTimeout, final AccountsManager accountsManager, + final AccountLockManager accountLockManager, + final Executor executor) { + return Mono.fromFuture( + () -> CompletableFuture.runAsync(() -> accountLockManager.withLock(Set.of(aci.uuid()), () -> { + if (accountsManager.getByAccountIdentifier(aci.uuid()).isPresent()) { + logger.info("ACI re-used after we checked for existence, not clearing its queues: {}", aci.uuid()); + return null; + } + clearQueue(database, aci, transactionRetryLimit, transactionTimeout); + return null; + }, executor), executor)); + } + + private void clearQueue(final Database database, final AciServiceIdentifier aci, final long transactionRetryLimit, + final Duration transactionTimeout) { + database.run(transaction -> { transaction.options().setPriorityBatch(); transaction.options().setRetryLimit(transactionRetryLimit); transaction.options().setTimeout(transactionTimeout.toMillis()); transaction.clear(getAccountSubspace(messagesSubspace, aci).range()); - return CompletableFuture.completedFuture(null); - })); + return null; + }); } @VisibleForTesting diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java index 060647faa..0d15d3dff 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java @@ -126,7 +126,8 @@ public record CommandDependencies( DynamoDbClient dynamoDbClient, PhoneNumberIdentifiers phoneNumberIdentifiers, DynamoDbRecoveryManager dynamoDbRecoveryManager, - FDB fdb) { + FDB fdb, + AccountLockManager accountLockManager) { static CommandDependencies build( final String name, @@ -460,8 +461,8 @@ public record CommandDependencies( dynamoDbClient, phoneNumberIdentifiers, dynamoDbRecoveryManager, - fdb - ); + fdb, + accountLockManager); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java index fcfcfe279..162a18ef1 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java @@ -22,7 +22,6 @@ import net.sourceforge.argparse4j.inf.Namespace; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.Device; import org.whispersystems.textsecuregcm.storage.MessagesManager; @@ -45,7 +44,8 @@ class ClearExpiredFoundationDbMessagesCommandTest { super(clock); - this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); + this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, + null); this.dryRun = dryRun; } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommandTest.java index 9b9a21df5..b57953bca 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommandTest.java @@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.workers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -38,12 +39,14 @@ import org.junit.jupiter.api.extension.RegisterExtension; import org.whispersystems.textsecuregcm.entities.MessageProtos; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; import org.whispersystems.textsecuregcm.storage.Account; +import org.whispersystems.textsecuregcm.storage.AccountLockManager; import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.Device; import org.whispersystems.textsecuregcm.storage.FoundationDbClusterExtension; import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore; import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher; import org.whispersystems.textsecuregcm.util.TestClock; +import org.whispersystems.textsecuregcm.util.ThrowingSupplier; class ClearOrphanedFoundationDbQueuesCommandTest { @@ -54,6 +57,9 @@ class ClearOrphanedFoundationDbQueuesCommandTest { private FoundationDbMessageStore foundationDbMessageStore; + private AccountsManager accountsManager; + private AccountLockManager accountLockManager; + @BeforeEach void setup() { final byte[] versionstampCipherKey = new byte[16]; @@ -61,6 +67,15 @@ class ClearOrphanedFoundationDbQueuesCommandTest { final List databases = Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases()); + accountsManager = mock(AccountsManager.class); + accountLockManager = mock(AccountLockManager.class); + + when(accountLockManager.withLock(any(), any(), any())).thenAnswer(invocation -> { + //noinspection rawtypes + final ThrowingSupplier supplier = invocation.getArgument(1); + return supplier.get(); + }); + foundationDbMessageStore = new FoundationDbMessageStore( Map.of(0, databases), 0, @@ -85,7 +100,6 @@ class ClearOrphanedFoundationDbQueuesCommandTest { // Assume that a subset of accounts are deleted final Set deletedAccounts = new HashSet<>(accounts.subList(0, 3)); - final AccountsManager accountsManager = mock(AccountsManager.class); when(accountsManager.getByAccountIdentifierAsync(any())) .thenReturn(CompletableFuture.completedFuture(Optional.of(mock(Account.class)))); for (final AciServiceIdentifier deletedAccount : deletedAccounts) { @@ -98,7 +112,10 @@ class ClearOrphanedFoundationDbQueuesCommandTest { Arrays.stream(FOUNDATION_DB_EXTENSION.getDatabases()), accountsManager, 16, false, 8, 3, Duration.ofSeconds(2), - 2); + 2, + accountLockManager, + Executors.newVirtualThreadPerTaskExecutor() + ); for (final AciServiceIdentifier aci : accounts) { assertEquals(!deletedAccounts.contains(aci), queueExists(FoundationDbMessageStore.getAccountSubspace(aci))); @@ -110,15 +127,18 @@ class ClearOrphanedFoundationDbQueuesCommandTest { // create accounts in a test subspace that doesn't conflict with the main messages subspace final Subspace testMessagesSubspace = new Subspace( Tuple.from("MT")); - final ClearOrphanedFoundationDbQueuesCommand command = new ClearOrphanedFoundationDbQueuesCommand(testMessagesSubspace); + final ClearOrphanedFoundationDbQueuesCommand command = new ClearOrphanedFoundationDbQueuesCommand( + testMessagesSubspace); final List acis = IntStream.range(0, 128) .mapToObj(_ -> new AciServiceIdentifier(UUID.randomUUID())) .toList(); final Database database = FOUNDATION_DB_EXTENSION.getDatabases()[0]; database.run(transaction -> { acis.forEach(aci -> { - transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("foo")), new byte[]{42}); - transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("bar")), new byte[]{43}); + transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("foo")), + new byte[]{42}); + transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("bar")), + new byte[]{43}); }); return null; }); @@ -129,6 +149,31 @@ class ClearOrphanedFoundationDbQueuesCommandTest { assertEquals(new HashSet<>(acis), new HashSet<>(fetchedAcis)); } + @Test + void aciReusedAfterExistenceCheck() { + final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID()); + foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage())).join(); + foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage())).join(); + + // Stub that the initial existence check returns empty, but the second check under the ACI lock returns present i.e the ACI has been re-used + // since the initial check + when(accountsManager.getByAccountIdentifierAsync(aci.uuid())) + .thenReturn(CompletableFuture.completedFuture(Optional.empty())); + when(accountsManager.getByAccountIdentifier(aci.uuid())).thenReturn(Optional.of(mock(Account.class))); + + final ClearOrphanedFoundationDbQueuesCommand command = new ClearOrphanedFoundationDbQueuesCommand(); + command.clearOrphanedQueues( + Arrays.stream(FOUNDATION_DB_EXTENSION.getDatabases()), accountsManager, 16, false, 8, + 3, + Duration.ofSeconds(2), + 2, + accountLockManager, + Executors.newVirtualThreadPerTaskExecutor() + ); + + assertTrue(queueExists(FoundationDbMessageStore.getAccountSubspace(aci))); + } + /// Returns whether any key exists under the account's prefix in any shard private boolean queueExists(final Subspace accountSpace) { final Range accountRange = accountSpace.range(); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/FinishPushNotificationExperimentCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/FinishPushNotificationExperimentCommandTest.java index 827557c8b..f00867e07 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/FinishPushNotificationExperimentCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/FinishPushNotificationExperimentCommandTest.java @@ -88,6 +88,7 @@ class FinishPushNotificationExperimentCommandTest { null, null, null, + null, null); //noinspection unchecked diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java index bb7d17027..3501f7cdf 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java @@ -18,7 +18,6 @@ import net.sourceforge.argparse4j.inf.Namespace; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.push.IdleDeviceNotificationScheduler; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.Device; @@ -69,6 +68,7 @@ class NotifyIdleDevicesCommandTest { null, null, null, + null, null); this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/RegenerateSecondaryDynamoDbTableDataCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/RegenerateSecondaryDynamoDbTableDataCommandTest.java index 175c9b43d..95f7fd117 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/RegenerateSecondaryDynamoDbTableDataCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/RegenerateSecondaryDynamoDbTableDataCommandTest.java @@ -55,6 +55,7 @@ class RegenerateSecondaryDynamoDbTableDataCommandTest { null, null, dynamoDbRecoveryManager, + null, null); namespace = new Namespace(Map.of( diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommandTest.java index 4857760e5..d1de0c423 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommandTest.java @@ -22,7 +22,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment; import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.Device; import reactor.core.publisher.Flux; @@ -77,6 +76,7 @@ class StartPushNotificationExperimentCommandTest { null, null, null, + null, null); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java index 2c9eaa14d..821a3a0b2 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java @@ -20,7 +20,6 @@ import net.sourceforge.argparse4j.inf.Namespace; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.Device; import org.whispersystems.textsecuregcm.storage.MessagesManager; @@ -40,7 +39,7 @@ public class TrimOversizedFoundationDbMessageQueuesCommandTest { final boolean dryRun) { super(); - this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); + this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); this.dryRun = dryRun; }