fix(lifecycle): keep SageMaker and ECS background work running after a state reset (#3797)

A state reset and nuke run every container teardown (#3718), a hook written
for process shutdown. The SageMaker training runner and endpoint manager shut
their worker pools down there and never created new ones, so after one reset
every CreateTrainingJob, CreateEndpoint and UpdateEndpoint returned 500 with
RejectedExecutionException until Floci restarted. The ECS service stopped its
reconciler the same way, so services were never reconciled again.

The three services now implement Resettable and restore the pool or the
reconciler in clear(), which a reset runs after the teardown and the storage
wipe and shutdown never runs. Teardown itself is unchanged, so the ECS
reconciler still stops before the final flush on shutdown.

A reset also interrupts in-flight training runs, and an interrupted run wrote
its failure back unconditionally, which could bring a wiped job back.
updateTrainingJob now writes only while the stored job is the same one, by
ARN and creation time, as finalizeEndpointStart already does for endpoints.

CI only showed this when EmulatorInfoControllerIntegrationTest and
SageMakerDockerIntegrationTest shared a shard, which the deterministic
partitioner does for some class lists, so it failed every rerun on those PRs.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-16 23:09:57 -05:00
1 parent bdabb16fd4
commit 08656347c7
10 files changed
+397 -22

No files matched your search

@@ -19,6 +19,7 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -76,6 +77,33 @@ class EcsServiceTeardownTest {
verify(containerManager, times(1)).stopTask(handle);
}
@Test
void clearRestartsTheReconcilerThatAResetTeardownStopped() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(false); // docker mode
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsService service = new EcsService(
new RegionResolver(REGION, "000000000000"),
mock(EcsContainerManager.class),
config,
mock(EcsLoadBalancerRegistrar.class),
new SingleUseStorageFactory(),
null);
service.initializeStorage();
// A reset runs the teardown and then clear(); shutdown runs only the teardown.
service.stopManagedContainers();
assertTrue(service.isReconcilerShutdown());
service.clear();
assertFalse(service.isReconcilerShutdown());
service.clear();
assertFalse(service.isReconcilerShutdown());
service.stopManagedContainers();
assertTrue(service.isReconcilerShutdown());
}
@Test
void stoppedTaskRetriesTeardownUntilItsRemainingLogStreamIsReleased() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
@@ -0,0 +1,71 @@
package io.github.hectorvent.floci.services.sagemaker;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.sagemaker.model.SageMakerEntities.EndpointResource;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
/**
* A state reset runs the container teardown, which shuts the worker pool down, and then
* {@code clear()}. Shutdown runs only the teardown.
*/
class SageMakerEndpointManagerTest {
@Test
void teardownStopsThePoolAndClearRestoresIt() {
SageMakerEndpointManager manager = manager();
assertTrue(manager.acceptsWork());
manager.stopManagedContainers();
assertFalse(manager.acceptsWork());
manager.clear();
assertTrue(manager.acceptsWork());
manager.clear();
assertTrue(manager.acceptsWork());
manager.stopManagedContainers();
}
@Test
void endpointStartsSubmittedAfterAResetStillRun() throws InterruptedException {
SageMakerEndpointManager manager = manager();
manager.stopManagedContainers();
manager.clear();
SageMakerService service = mock(SageMakerService.class);
CountDownLatch published = new CountDownLatch(1);
EndpointResource endpoint = new EndpointResource();
endpoint.endpointName = "after-reset";
endpoint.region = "us-east-1";
// A latch rather than verify(timeout): finalizeEndpointStart is synchronized, and a timed
// verify holds the mock's monitor while it polls, blocking the very call it waits for.
doAnswer(invocation -> {
published.countDown();
return true;
}).when(service).finalizeEndpointStart(endpoint);
manager.startEndpointAsync(endpoint, service);
// The mocked service has no model for the endpoint, so the start fails at once, and every
// start that executes publishes its outcome: the publish proves the new pool ran the work.
assertTrue(published.await(5, TimeUnit.SECONDS));
manager.stopManagedContainers();
}
private static SageMakerEndpointManager manager() {
return new SageMakerEndpointManager(mock(ContainerBuilder.class), mock(ContainerLifecycleManager.class),
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), mock(ContainerDetector.class), mock(S3Service.class));
}
}
@@ -0,0 +1,70 @@
package io.github.hectorvent.floci.services.sagemaker;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.notNullValue;
/**
* A state reset runs every container teardown, and the SageMaker training runner and endpoint
* manager shut their worker pools down there. Without restoring them afterwards, every later
* CreateTrainingJob, CreateEndpoint and UpdateEndpoint failed with a 500 until the emulator
* restarted. The requests submit their work before touching Docker, so no daemon is needed.
*/
@QuarkusTest
class SageMakerResetIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/sagemaker/aws4_request";
private static final String UNPULLABLE_IMAGE = "floci.invalid/none:latest";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void trainingJobsAndEndpointsCanStillBeCreatedAfterAStateReset() {
given().when().post("/_floci/state/reset").then().statusCode(200);
try {
String suffix = Long.toString(System.nanoTime(), 36);
post("SageMaker.CreateTrainingJob", """
{"TrainingJobName":"sm-reset-%s",
"AlgorithmSpecification":{"TrainingImage":"%s","TrainingInputMode":"File"},
"OutputDataConfig":{"S3OutputPath":"s3://sm-reset-%s/output"},
"ResourceConfig":{"InstanceType":"ml.m5.large","InstanceCount":1,"VolumeSizeInGB":1},
"StoppingCondition":{"MaxRuntimeInSeconds":60}}
""".formatted(suffix, UNPULLABLE_IMAGE, suffix))
.then().statusCode(200).body("TrainingJobArn", notNullValue());
String model = "sm-reset-model-" + suffix;
post("SageMaker.CreateModel", """
{"ModelName":"%s","PrimaryContainer":{"Image":"%s"}}
""".formatted(model, UNPULLABLE_IMAGE))
.then().statusCode(200);
String config = "sm-reset-cfg-" + suffix;
post("SageMaker.CreateEndpointConfig", """
{"EndpointConfigName":"%s","ProductionVariants":[{"VariantName":"AllTraffic","ModelName":"%s","InitialInstanceCount":1,"InstanceType":"ml.t2.medium"}]}
""".formatted(config, model))
.then().statusCode(200);
post("SageMaker.CreateEndpoint", """
{"EndpointName":"sm-reset-ep-%s","EndpointConfigName":"%s"}
""".formatted(suffix, config))
.then().statusCode(200).body("EndpointArn", notNullValue());
} finally {
// Floci has no DeleteTrainingJob, so a second reset is what leaves nothing behind.
given().when().post("/_floci/state/reset").then().statusCode(200);
}
}
private Response post(String target, String body) {
return given().header("Authorization", AUTH)
.header("X-Amz-Target", target)
.contentType("application/x-amz-json-1.1")
.body(body)
.when().post("/");
}
}
@@ -14,6 +14,7 @@ import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
@@ -160,11 +161,51 @@ class SageMakerServiceTest {
assertThrows(IllegalArgumentException.class, () -> S3Uri.parse("http://bucket/key"));
}
@Test
void trainingRunUpdatesApplyOnlyWhileTheirJobIsStillStored() throws Exception {
InMemoryStorage<String, TrainingJobResource> jobs = new InMemoryStorage<>();
SageMakerService service = service(jobs);
String request = """
{"TrainingJobName":"reset-job",
"AlgorithmSpecification":{"TrainingImage":"busybox:stable"},
"OutputDataConfig":{"S3OutputPath":"s3://bucket/out"}}
""";
service.createTrainingJob(mapper.readTree(request), "us-east-1");
TrainingJobResource run = jobs.scan(key -> true).get(0);
run.trainingJobStatus = "Completed";
assertTrue(service.updateTrainingJob(run));
assertEquals("Completed", describeStatus(service, "reset-job"));
// A state reset wipes the store while the run is still finishing.
jobs.clear();
run.trainingJobStatus = "Failed";
assertFalse(service.updateTrainingJob(run));
assertTrue(jobs.scan(key -> true).isEmpty());
assertThrows(AwsException.class, () -> describeStatus(service, "reset-job"));
// A same-named job created after the reset is not overwritten by the old run.
service.createTrainingJob(mapper.readTree(request), "us-east-1");
TrainingJobResource recreated = jobs.scan(key -> true).get(0);
run.creationTime = recreated.creationTime - 1;
assertFalse(service.updateTrainingJob(run));
assertEquals("InProgress", describeStatus(service, "reset-job"));
}
private String describeStatus(SageMakerService service, String name) throws Exception {
return service.describeTrainingJob(mapper.readTree("{\"TrainingJobName\":\"" + name + "\"}"), "us-east-1")
.path("TrainingJobStatus").asText();
}
private SageMakerService service() {
return service(new InMemoryStorage<String, TrainingJobResource>());
}
private SageMakerService service(InMemoryStorage<String, TrainingJobResource> trainingJobs) {
return new SageMakerService(new InMemoryStorage<String, ModelResource>(),
new InMemoryStorage<String, EndpointConfigResource>(),
new InMemoryStorage<String, EndpointResource>(),
new InMemoryStorage<String, TrainingJobResource>(),
trainingJobs,
new RegionResolver("us-east-1", "000000000000"), mapper,
mock(SageMakerEndpointManager.class), mock(SageMakerTrainingRunner.class));
}
@@ -0,0 +1,76 @@
package io.github.hectorvent.floci.services.sagemaker;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.sagemaker.model.SageMakerEntities.TrainingJobResource;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
/**
* A state reset runs the container teardown, which shuts the worker pool down, and then
* {@code clear()}. Shutdown runs only the teardown.
*/
class SageMakerTrainingRunnerTest {
@Test
void teardownStopsThePoolAndClearRestoresIt() {
SageMakerTrainingRunner runner = runner();
assertTrue(runner.acceptsWork());
runner.stopManagedContainers();
assertFalse(runner.acceptsWork());
runner.clear();
assertTrue(runner.acceptsWork());
runner.clear();
assertTrue(runner.acceptsWork());
runner.stopManagedContainers();
}
@Test
void trainingJobsSubmittedAfterAResetStillRun() throws InterruptedException {
SageMakerTrainingRunner runner = runner();
runner.stopManagedContainers();
runner.clear();
SageMakerService service = mock(SageMakerService.class);
CountDownLatch reported = new CountDownLatch(1);
TrainingJobResource job = new TrainingJobResource();
job.trainingJobName = "after-reset";
job.region = "us-east-1";
job.algorithmSpecification = Map.of("TrainingImage", "busybox:stable");
// A latch rather than verify(timeout): updateTrainingJob is synchronized, and a timed
// verify holds the mock's monitor while it polls, blocking the very call it waits for.
doAnswer(invocation -> {
reported.countDown();
return true;
}).when(service).updateTrainingJob(job);
runner.runAsync(job, service);
// The mocked Docker helpers fail the run at once, and every run that executes reports its
// outcome, so the report proves the new pool accepted and ran the work.
assertTrue(reported.await(5, TimeUnit.SECONDS));
runner.stopManagedContainers();
}
private static SageMakerTrainingRunner runner() {
return new SageMakerTrainingRunner(mock(ContainerBuilder.class), mock(ContainerLifecycleManager.class),
mock(ContainerLogStreamer.class), mock(EmulatorConfig.class, RETURNS_DEEP_STUBS),
mock(ContainerDetector.class), mock(S3Service.class), new ObjectMapper());
}
}