fix(ecs): serialize create, update and delete of one service (#5845)

* fix(ecs): serialize create, update and delete of one service

DeleteService removed a service's deployment and revision records after
stopping its tasks, so an UpdateService that had passed its status check
could record a new deployment afterwards, and a CreateService landing in
that window had its first deployment removed by the delete's cleanup.

Take one lock per service key (region, cluster, name) in CreateService,
UpdateService and DeleteService, from the status check to the last write.

* fix(ecs): take no service lock for a service that does not exist; make race tests fail on worker errors

* style(ecs): order imports in EcsServiceDeleteDeploymentsTest

* fix(ecs): drop the service locks on a state reset

* refactor(ecs): share the existing-service lock lookup in update and delete

updateService and deleteService each repeated the check that a service
exists before taking its per-key lock. Move it into lockForExisting so the
no-lock-for-unknown-names rule lives in one place.

* fix(ecs): serialize service writes on fixed lock stripes

The per-key lock map grew with every failed CreateService name and was
cleared on reset, so a delete still holding the old lock could run beside
a recreate on a new one and remove the recreated service's deployment.
A fixed, never-cleared stripe array removes both: nothing grows, and
lock identity survives a reset.

Race tests now release parked workers in finally, use daemon threads,
interrupt stragglers, and fail when a worker neither blocks nor finishes.

* test(ecs): use ThreadStates.awaitBlockedOrDone for the delete-race waits

Adds a Thread overload to ThreadStates sharing the Future overload's poll
loop, and drops the ECS test's local copy.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-10-16 22:19:36 -04:00
1 parent d988a137c5
commit f031e4052d
3 files changed
+409 -219

No files matched your search

@@ -16,11 +16,20 @@ import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
@@ -84,6 +93,137 @@ class EcsServiceDeleteDeploymentsTest {
"the new deployment does not roll from the deleted service's revision");
}
@Test
void anUpdateThatPassedItsStatusCheckCannotRestoreRecordsAfterDelete() throws Exception {
EcsService service = spy(newMockModeService());
service.createCluster(CLUSTER, REGION);
registerTaskDef(service);
service.createService(CLUSTER, "racy", "del-fam", 0, LaunchType.FARGATE, List.of(), null, REGION);
CountDownLatch passedCheck = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicReference<Thread> updater = new AtomicReference<>();
doAnswer(inv -> {
if (Thread.currentThread() == updater.get()) {
passedCheck.countDown();
release.await();
}
return inv.callRealMethod();
}).when(service).currentServiceDeployment(any());
Thread update = worker(() -> service.updateService(CLUSTER, "racy", null, null, null, null, true, REGION));
Thread delete = worker(() -> service.deleteService(CLUSTER, "racy", true, REGION));
updater.set(update);
try {
update.start();
assertTrue(passedCheck.await(10, TimeUnit.SECONDS));
delete.start();
awaitBlockedOrDone(delete);
} finally {
release.countDown();
joinAll(update, delete);
}
assertEquals(List.of(), service.listServiceDeployments("racy", CLUSTER, null, REGION),
"an update racing a delete leaves no deployment behind");
assertEquals("INACTIVE",
service.describeServices(CLUSTER, List.of("racy"), REGION).getFirst().getStatus());
}
@Test
void aCreateRacingADeleteKeepsItsOwnDeployment() throws Exception {
EcsService service = newMockModeService();
service.createCluster(CLUSTER, REGION);
registerTaskDef(service);
service.createService(CLUSTER, "swap", "del-fam", 1, LaunchType.FARGATE, List.of(), null, REGION);
service.reconcileServices();
Thread delete = worker(() -> service.deleteService(CLUSTER, "swap", true, REGION));
Thread create = worker(() ->
service.createService(CLUSTER, "swap", "del-fam", 0, LaunchType.FARGATE, List.of(), null, REGION));
// Runs while the delete is between marking the service INACTIVE and cleaning up its records.
doAnswer(inv -> {
if (Thread.currentThread() == delete && create.getState() == Thread.State.NEW) {
create.start();
awaitBlockedOrDone(create);
}
return null;
}).when(containerManager).releaseTaskNetwork(any(), any());
delete.start();
joinAll(delete, create);
assertEquals("ACTIVE", service.describeServices(CLUSTER, List.of("swap"), REGION).getFirst().getStatus());
assertEquals(1, service.listServiceDeployments("swap", CLUSTER, null, REGION).size(),
"the recreated service keeps the deployment it recorded");
}
@Test
void aResetDuringADeleteDoesNotLetARecreateLoseItsDeployment() throws Exception {
EcsService service = newMockModeService();
service.createCluster(CLUSTER, REGION);
registerTaskDef(service);
service.createService(CLUSTER, "reset", "del-fam", 1, LaunchType.FARGATE, List.of(), null, REGION);
service.reconcileServices();
CountDownLatch stopping = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
Thread delete = worker(() -> service.deleteService(CLUSTER, "reset", true, REGION));
Thread create = worker(() ->
service.createService(CLUSTER, "reset", "del-fam", 0, LaunchType.FARGATE, List.of(), null, REGION));
// Parks the delete between marking the service INACTIVE and cleaning up its records.
doAnswer(inv -> {
if (Thread.currentThread() == delete) {
stopping.countDown();
release.await();
}
return null;
}).when(containerManager).releaseTaskNetwork(any(), any());
try {
delete.start();
assertTrue(stopping.await(10, TimeUnit.SECONDS), "delete reached task stop");
service.clear();
create.start();
awaitBlockedOrDone(create);
} finally {
release.countDown();
joinAll(delete, create);
}
assertEquals("ACTIVE", service.describeServices(CLUSTER, List.of("reset"), REGION).getFirst().getStatus());
assertEquals(1, service.listServiceDeployments("reset", CLUSTER, null, REGION).size(),
"a service recreated after a reset keeps its deployment when the older delete resumes");
}
private final ConcurrentLinkedQueue<Throwable> workerFailures = new ConcurrentLinkedQueue<>();
/** A thread that records what it throws, so a failed worker cannot leave a passing test behind. */
private Thread worker(Runnable body) {
Thread t = new Thread(() -> {
try {
body.run();
} catch (Throwable e) {
workerFailures.add(e);
}
});
t.setDaemon(true);
return t;
}
private void joinAll(Thread... threads) throws InterruptedException {
for (Thread t : threads) {
t.join(10_000);
}
for (Thread t : threads) {
if (t.isAlive()) {
t.interrupt();
}
}
for (Thread t : threads) {
assertTrue(!t.isAlive(), "worker thread finished");
}
assertTrue(workerFailures.isEmpty(), "workers threw: " + workerFailures);
}
private static ServiceDeployment onlyDeployment(EcsService service, String serviceName) {
List<ServiceDeployment> deployments =
service.listServiceDeploymentsDetailed(serviceName, CLUSTER, null, REGION);
@@ -98,13 +238,15 @@ class EcsServiceDeleteDeploymentsTest {
service.registerTaskDefinition("del-fam", List.of(cd), null, null, null, null, null, List.of(), REGION);
}
private static EcsService newMockModeService() {
private final EcsContainerManager containerManager = mock(EcsContainerManager.class);
private EcsService newMockModeService() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(true);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsService service = new EcsService(
new RegionResolver(REGION, "000000000000"),
mock(EcsContainerManager.class),
containerManager,
config,
mock(EcsLoadBalancerRegistrar.class),
new InMemoryStorageFactory(),
@@ -3,6 +3,10 @@ package io.github.hectorvent.floci.testing;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Waiting for a thread to reach a lock, for tests that force two requests to overlap. */
public final class ThreadStates {
@@ -17,13 +21,33 @@ public final class ThreadStates {
*/
public static void awaitBlockedOrDone(AtomicReference<Thread> thread, Future<?> task)
throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (System.nanoTime() < deadline && !task.isDone()) {
Thread current = thread.get();
if (current != null && current.getState() == Thread.State.BLOCKED) {
return;
awaitBlockedOrDone(thread::get, task::isDone, 5);
}
/**
* Returns once {@code thread} is blocked entering a monitor or is no longer alive. Same wait as
* the {@link Future} overload, for a test that owns the {@link Thread} directly; gives up after
* ten seconds and fails, since a thread still running unblocked by then is not overlapping the
* way the test needs.
*/
public static void awaitBlockedOrDone(Thread thread) throws InterruptedException {
assertTrue(awaitBlockedOrDone(() -> thread, () -> !thread.isAlive(), 10),
"worker blocked or finished before timeout");
}
private static boolean awaitBlockedOrDone(Supplier<Thread> thread, BooleanSupplier done, long timeoutSeconds)
throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds);
while (System.nanoTime() < deadline && !done.getAsBoolean()) {
if (isBlocked(thread.get())) {
return true;
}
Thread.sleep(5);
}
return done.getAsBoolean() || isBlocked(thread.get());
}
private static boolean isBlocked(Thread thread) {
return thread != null && thread.getState() == Thread.State.BLOCKED;
}
}