fix(docker): recover named containers after a lost create response (#9916)

Docker can finish creating a named container after the client stops
waiting for its ID. Floci already adopted that container when a
replayed create hit a name conflict, but a read timeout or other
transient I/O failure surfaced directly and left it untracked. A named
create now looks the name up after either failure and adopts only the
container carrying this call's attempt label; an answered HTTP error
other than 409 is returned at once, and a lookup that finds nothing
within one Docker API timeout returns the original error.

Co-authored-by: Hai Yan <8153134+oeyh@users.noreply.github.com>
This commit is contained in:
Jackson PriceandHai Yan authored and GitHub committed 2026-12-01 15:33:37 -04:00
1 parent 46252ae13e
commit dea4bc889e
3 files changed
+118 -71

No files matched your search

@@ -73,7 +73,7 @@ public class ContainerLifecycleManager {
/**
* Label carrying a fresh id per {@code create()} invocation, used to tell this call's own
* replayed create apart from a genuinely concurrent caller's, see
* {@link #createWithConflictRecovery}.
* {@link #createWithRecovery}.
*/
static final String CREATE_ATTEMPT_LABEL = "floci_create_attempt_id";
@@ -449,7 +449,7 @@ public class ContainerLifecycleManager {
// A fresh id per create() call, not per spec: two calls can carry identical image, name,
// and labels (a second, genuinely concurrent caller racing on the same fixed name), and
// matchesSpec must be able to tell that apart from a replay of THIS call's own create
// hitting a lost-response conflict, see createWithConflictRecovery.
// hitting a lost-response conflict, see createWithRecovery.
String createAttemptId = UUID.randomUUID().toString();
Map<String, String> labels = mergedLabels(spec.labels());
labels.put(CREATE_ATTEMPT_LABEL, createAttemptId);
@@ -461,7 +461,7 @@ public class ContainerLifecycleManager {
}
String containerId;
try {
containerId = createWithConflictRecovery(createCmd, spec, createAttemptId);
containerId = createWithRecovery(createCmd, spec, createAttemptId);
DockerContainerServices.record(containerId, spec.name(), labels);
} catch (DockerException e) {
if (ContainerRejectedException.isRejection(e)) {
@@ -491,35 +491,19 @@ public class ContainerLifecycleManager {
}
/**
* Executes the create, recovering the container when a replay of it lost the race with its own
* earlier attempt.
* Docker may have accepted a named create even when the response is lost. The transport
* can surface the I/O failure directly or replay the request and receive a name conflict.
* In either case, look up the name and adopt only the container with this call's attempt label.
*
* <p>{@link RetryingDockerHttpClient} replays {@code POST /containers/create}, it has a
* {@code bodyBytes} body, no hijacked input, and no {@code /exec} in its path, so it is
* replayable by that decorator's rules. That replay is what makes this recovery necessary: a
* create is not idempotent, so if the daemon accepts a named create but the response is lost to
* a transient socket drop, the replay hits a 409 name conflict instead of the transient error
* the retry exists to absorb. {@code DockerRetry} correctly classifies that 409 as
* non-transient and rethrows it immediately, so without this it surfaces as a spurious build
* failure, and leaks the container the first attempt actually created, untracked.
*
* <p>Docker can reserve the name before the original create becomes visible to list or inspect.
* Successful empty lookups may be retried for one additional configured Docker API timeout,
* using monotonic elapsed time. Each lookup retains the transport's own timeout and retries;
* this budget bounds polling, not an already running lookup.
*
* <p>Recovery only fires for a named spec, and only adopts a candidate whose labels and
* this exact call's {@link #CREATE_ATTEMPT_LABEL} all match. Image and spec labels alone cannot tell
* this call's own lost-response replay apart from a second, genuinely concurrent
* {@code create()} racing on the same fixed name/image/labels, which would otherwise be adopted
* as if it were this invocation's container.
* <p>The container may take time to appear in the list. Poll for up to one configured Docker
* API timeout using monotonic elapsed time. Each lookup retains its own transport timeout.
*/
private String createWithConflictRecovery(CreateContainerCmd createCmd, ContainerSpec spec,
String createAttemptId) {
private String createWithRecovery(CreateContainerCmd createCmd, ContainerSpec spec,
String createAttemptId) {
try {
return createCmd.exec().getId();
} catch (ConflictException e) {
if (spec.name() == null) {
} catch (RuntimeException e) {
if (spec.name() == null || !mayHaveCreatedContainer(e)) {
throw e;
}
long started = nanoTime.getAsLong();
@@ -542,9 +526,8 @@ public class ContainerLifecycleManager {
}
if (existing.isPresent()) {
if (matchesSpec(existing.get(), spec, createAttemptId)) {
LOG.infov("Create for {0} hit a name conflict; an earlier attempt''s response "
+ "was lost but the container exists, adopting {1}",
spec.name(), existing.get().getId());
LOG.infov("Recovered container {0} after losing the create response for {1}",
existing.get().getId(), spec.name());
return existing.get().getId();
}
break;
@@ -554,7 +537,7 @@ public class ContainerLifecycleManager {
break;
}
if (attempt == 0) {
LOG.infov("Reconciling reserved name {0} while its container creation finishes", spec.name());
LOG.infov("Waiting for container {0} after losing its create response", spec.name());
}
attempt++;
long delay = TimeUnit.MILLISECONDS.toNanos(DockerRetry.backoffDelay(
@@ -571,6 +554,13 @@ public class ContainerLifecycleManager {
}
}
private static boolean mayHaveCreatedContainer(RuntimeException failure) {
if (failure instanceof DockerException response && response.getHttpStatus() > 0) {
return response instanceof ConflictException;
}
return DockerRetry.isTransientIo(failure);
}
/**
* Applies endpoint IPAM while the container is still in CREATED state. docker-java does not
* expose Docker's {@code NetworkingConfig} on create, but it does expose the equivalent
@@ -16,6 +16,7 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -80,7 +81,7 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd);
// The container that actually got created on the daemon carries exactly the labels this
// create() call applied (including the per-call attempt-id), captured here rather than
// hardcoded, since createWithConflictRecovery only adopts a container proven to be THIS
// hardcoded, since createWithRecovery only adopts a container proven to be THIS
// call's own lost-response attempt, not merely one with matching image/spec labels.
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, String>> labelsCaptor =
@@ -259,7 +260,7 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
@Test
void createAdoptsOriginalAttemptAfterMinutesOfDelayedVisibility() {
ConflictScenario scenario = conflictScenario();
CreateScenario scenario = conflictScenario();
AtomicLong now = new AtomicLong(TimeUnit.HOURS.toNanos(2));
long started = now.get();
when(scenario.listCmd().exec()).thenAnswer(inv ->
@@ -276,14 +277,14 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
@Test
void createPreservesOriginalConflictWhenVisibilityBudgetExpires() {
ConflictScenario scenario = conflictScenario();
CreateScenario scenario = conflictScenario();
AtomicLong now = new AtomicLong();
when(scenario.listCmd().exec()).thenReturn(List.of());
ConflictException failure = assertThrows(ConflictException.class,
() -> manager(now, now::addAndGet).create(scenario.spec()));
assertSame(scenario.conflict(), failure);
assertSame(scenario.failure(), failure);
assertEquals(TimeUnit.SECONDS.toNanos(300), now.get());
verifyOnlyOriginalCreate(scenario);
}
@@ -291,11 +292,11 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
@ParameterizedTest
@ValueSource(longs = {300, 301})
void createDoesNotPollAgainWhenWaitReachesOrExceedsDeadline(long elapsedSeconds) {
ConflictScenario scenario = conflictScenario();
CreateScenario scenario = conflictScenario();
AtomicLong now = new AtomicLong();
when(scenario.listCmd().exec()).thenReturn(List.of(), List.of(scenario.owned()));
assertSame(scenario.conflict(), assertThrows(ConflictException.class,
assertSame(scenario.failure(), assertThrows(ConflictException.class,
() -> manager(now, nanos -> now.set(TimeUnit.SECONDS.toNanos(elapsedSeconds)))
.create(scenario.spec())));
@@ -305,7 +306,7 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
@Test
void createChargesLookupTimeToVisibilityBudget() {
ConflictScenario scenario = conflictScenario();
CreateScenario scenario = conflictScenario();
AtomicLong now = new AtomicLong();
when(scenario.listCmd().exec()).thenAnswer(inv -> {
now.addAndGet(TimeUnit.SECONDS.toNanos(301));
@@ -313,7 +314,7 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
});
AtomicLong sleeps = new AtomicLong();
assertSame(scenario.conflict(), assertThrows(ConflictException.class,
assertSame(scenario.failure(), assertThrows(ConflictException.class,
() -> manager(now, nanos -> sleeps.incrementAndGet()).create(scenario.spec())));
assertEquals(0, sleeps.get());
@@ -324,22 +325,12 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void createRejectsForeignContainerThatAppearsWhileWaiting(boolean missingAttemptLabel) {
ConflictScenario scenario = conflictScenario();
CreateScenario scenario = conflictScenario();
AtomicLong now = new AtomicLong();
Container foreign = mock(Container.class);
when(foreign.getNames()).thenReturn(new String[] {"/emulator-fixed-name"});
when(foreign.getLabels()).thenAnswer(inv -> {
Map<String, String> labels = new HashMap<>(scenario.owned().getLabels());
if (missingAttemptLabel) {
labels.remove(ContainerLifecycleManager.CREATE_ATTEMPT_LABEL);
} else {
labels.put(ContainerLifecycleManager.CREATE_ATTEMPT_LABEL, "different-create-attempt");
}
return labels;
});
Container foreign = containerFromAnotherCreate(scenario, missingAttemptLabel);
when(scenario.listCmd().exec()).thenReturn(List.of(), List.of(foreign), List.of(scenario.owned()));
assertSame(scenario.conflict(), assertThrows(ConflictException.class,
assertSame(scenario.failure(), assertThrows(ConflictException.class,
() -> manager(now, now::addAndGet).create(scenario.spec())));
verify(scenario.listCmd(), times(2)).exec();
@@ -348,7 +339,7 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
@Test
void createPreservesLookupFailureInsteadOfTreatingItAsPendingCreation() {
ConflictScenario scenario = conflictScenario();
CreateScenario scenario = conflictScenario();
AtomicLong now = new AtomicLong();
IllegalStateException lookupFailure = new IllegalStateException("Docker inventory unavailable");
when(scenario.listCmd().exec()).thenThrow(lookupFailure);
@@ -356,7 +347,7 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
ConflictException failure = assertThrows(ConflictException.class,
() -> manager(now, now::addAndGet).create(scenario.spec()));
assertSame(scenario.conflict(), failure);
assertSame(scenario.failure(), failure);
assertEquals(1, failure.getSuppressed().length);
assertSame(lookupFailure, failure.getSuppressed()[0]);
assertEquals(0, now.get());
@@ -366,7 +357,7 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
@Test
void createPreservesInterruptedSleepAndOriginalConflict() {
ConflictScenario scenario = conflictScenario();
CreateScenario scenario = conflictScenario();
AtomicLong now = new AtomicLong();
InterruptedException interruption = new InterruptedException("caller cancelled");
when(scenario.listCmd().exec()).thenReturn(List.of());
@@ -377,7 +368,7 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
throw interruption;
}).create(scenario.spec()));
assertSame(scenario.conflict(), failure);
assertSame(scenario.failure(), failure);
assertTrue(Thread.currentThread().isInterrupted());
assertEquals(1, failure.getSuppressed().length);
assertSame(interruption, failure.getSuppressed()[0]);
@@ -390,12 +381,12 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
@Test
void createDoesNotPollWhenConflictRecoveryIsAlreadyInterrupted() {
ConflictScenario scenario = conflictScenario();
CreateScenario scenario = conflictScenario();
AtomicLong now = new AtomicLong();
try {
Thread.currentThread().interrupt();
assertSame(scenario.conflict(), assertThrows(ConflictException.class,
assertSame(scenario.failure(), assertThrows(ConflictException.class,
() -> manager(now, now::addAndGet).create(scenario.spec())));
assertTrue(Thread.currentThread().isInterrupted());
@@ -408,7 +399,7 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
@Test
void createDoesNotAdoptWhenInterruptedDuringLookup() {
ConflictScenario scenario = conflictScenario();
CreateScenario scenario = conflictScenario();
AtomicLong now = new AtomicLong();
when(scenario.listCmd().exec()).thenAnswer(inv -> {
Thread.currentThread().interrupt();
@@ -416,7 +407,7 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
});
try {
assertSame(scenario.conflict(), assertThrows(ConflictException.class,
assertSame(scenario.failure(), assertThrows(ConflictException.class,
() -> manager(now, now::addAndGet).create(scenario.spec())));
assertTrue(Thread.currentThread().isInterrupted());
@@ -427,14 +418,76 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
}
}
private ConflictScenario conflictScenario() {
@Test
void createRecoversOwnContainerThatAppearsAfterReadTimeoutWithoutAnotherCreate() {
RuntimeException timeout = new RuntimeException(new SocketTimeoutException("Read timed out"));
CreateScenario scenario = createScenario(timeout);
AtomicLong now = new AtomicLong();
when(scenario.listCmd().exec()).thenAnswer(inv ->
now.get() < TimeUnit.SECONDS.toNanos(42) ? List.of() : List.of(scenario.owned()));
assertEquals("original-container-id", manager(now, now::addAndGet).create(scenario.spec()));
assertTrue(now.get() >= TimeUnit.SECONDS.toNanos(42));
assertTrue(now.get() < TimeUnit.SECONDS.toNanos(300));
verifyOnlyOriginalCreate(scenario);
}
@Test
void createPreservesReadTimeoutWhenAnotherCallerOwnsTheName() {
RuntimeException timeout = new RuntimeException(new SocketTimeoutException("Read timed out"));
CreateScenario scenario = createScenario(timeout);
Container foreign = containerFromAnotherCreate(scenario, false);
when(scenario.listCmd().exec()).thenReturn(List.of(foreign));
AtomicLong now = new AtomicLong();
assertSame(timeout, assertThrows(RuntimeException.class,
() -> manager(now, now::addAndGet).create(scenario.spec())));
assertEquals(0, now.get());
verifyOnlyOriginalCreate(scenario);
}
@Test
void createPreservesReadTimeoutWhenItsContainerNeverAppearsWithinRecoveryBudget() {
RuntimeException timeout = new RuntimeException(new SocketTimeoutException("Read timed out"));
CreateScenario scenario = createScenario(timeout);
when(scenario.listCmd().exec()).thenReturn(List.of());
AtomicLong now = new AtomicLong();
assertSame(timeout, assertThrows(RuntimeException.class,
() -> manager(now, now::addAndGet).create(scenario.spec())));
assertEquals(TimeUnit.SECONDS.toNanos(300), now.get());
verifyOnlyOriginalCreate(scenario);
}
private Container containerFromAnotherCreate(CreateScenario scenario, boolean missingAttemptLabel) {
Container foreign = mock(Container.class);
when(foreign.getNames()).thenReturn(new String[] {"/emulator-fixed-name"});
when(foreign.getLabels()).thenAnswer(inv -> {
Map<String, String> labels = new HashMap<>(scenario.owned().getLabels());
if (missingAttemptLabel) {
labels.remove(ContainerLifecycleManager.CREATE_ATTEMPT_LABEL);
} else {
labels.put(ContainerLifecycleManager.CREATE_ATTEMPT_LABEL, "different-create-attempt");
}
return labels;
});
return foreign;
}
private CreateScenario conflictScenario() {
return createScenario(new ConflictException("named container already exists"));
}
private CreateScenario createScenario(RuntimeException failure) {
CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF);
when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd);
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, String>> labelsCaptor = ArgumentCaptor.forClass(Map.class);
when(createCmd.withLabels(labelsCaptor.capture())).thenReturn(createCmd);
ConflictException conflict = new ConflictException("named container already exists");
when(createCmd.exec()).thenThrow(conflict);
when(createCmd.exec()).thenThrow(failure);
when(dockerConfig.apiTimeoutSeconds()).thenReturn(300);
Container owned = mock(Container.class);
@@ -447,10 +500,10 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
"busybox:stable", "emulator-fixed-name", List.of(), null, null, null, Map.of(),
List.of(), null, List.of(), List.of(), List.of(), Map.of("resource_owner", "caller-a"),
null, false, null, List.of(), null, null, List.of());
return new ConflictScenario(createCmd, listCmd, owned, spec, conflict);
return new CreateScenario(createCmd, listCmd, owned, spec, failure);
}
private void verifyOnlyOriginalCreate(ConflictScenario scenario) {
private void verifyOnlyOriginalCreate(CreateScenario scenario) {
verify(dockerClient).createContainerCmd("busybox:stable");
verify(scenario.createCmd()).exec();
verify(dockerClient, never()).startContainerCmd(anyString());
@@ -462,8 +515,8 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
0, now::get, wait);
}
private record ConflictScenario(CreateContainerCmd createCmd, ListContainersCmd listCmd, Container owned,
ContainerSpec spec, ConflictException conflict) {
private record CreateScenario(CreateContainerCmd createCmd, ListContainersCmd listCmd, Container owned,
ContainerSpec spec, RuntimeException failure) {
}
private ContainerLifecycleManager manager() {
@@ -25,6 +25,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
@@ -74,11 +76,13 @@ class ContainerLifecycleManagerCreateRejectionTest {
assertTrue(rejected.getMessage().contains("--mounts is not allowed"), rejected.getMessage());
}
@Test
void createReportsABadRequestAsARejection() {
failCreateWith(new BadRequestException("invalid mount config"));
@ParameterizedTest
@ValueSource(strings = {"invalid mount config", "network setup failed: connection reset by peer"})
void createReportsABadRequestAsARejection(String message) {
failCreateWith(new BadRequestException(message));
assertThrows(ContainerRejectedException.class, () -> manager().create(spec()));
verify(dockerClient, never()).listContainersCmd();
}
@ParameterizedTest