Repository navigation
Prevent duplicate reusable containers on concurrent starts #12126
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kiview
wants to merge
3
commits into
main
Choose a base branch
from
claude/project-thread-uxjf2l
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
116 changes: 116 additions & 0 deletions
116
core/src/test/java/org/testcontainers/containers/ReusableContainerConcurrencyTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| package org.testcontainers.containers; | ||
|
|
||
| import com.github.dockerjava.api.DockerClient; | ||
| import org.junit.jupiter.api.AfterEach; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.junit.jupiter.api.extension.ExtendWith; | ||
| import org.mockito.Mockito; | ||
| import org.testcontainers.DockerClientFactory; | ||
| import org.testcontainers.TestImages; | ||
| import org.testcontainers.utility.MockTestcontainersConfigurationExtension; | ||
| import org.testcontainers.utility.TestcontainersConfiguration; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Collections; | ||
| import java.util.List; | ||
| import java.util.Set; | ||
| import java.util.UUID; | ||
| import java.util.concurrent.CompletableFuture; | ||
| import java.util.concurrent.CountDownLatch; | ||
| import java.util.concurrent.ExecutorService; | ||
| import java.util.concurrent.Executors; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
|
|
||
| @ExtendWith(MockTestcontainersConfigurationExtension.class) | ||
| class ReusableContainerConcurrencyTest { | ||
|
|
||
| private final DockerClient dockerClient = DockerClientFactory.instance().client(); | ||
|
|
||
| // Makes the hash unique per test run, so containers from earlier runs are not reused | ||
| private final String runId = UUID.randomUUID().toString(); | ||
|
|
||
| @BeforeEach | ||
| void enableReuse() { | ||
| Mockito.doReturn(true).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse(); | ||
| } | ||
|
|
||
| @AfterEach | ||
| void removeContainers() { | ||
| dockerClient | ||
| .listContainersCmd() | ||
| .withShowAll(true) | ||
| .withLabelFilter(Collections.singletonMap("test-run-id", runId)) | ||
| .exec() | ||
| .forEach(it -> dockerClient.removeContainerCmd(it.getId()).withForce(true).exec()); | ||
| } | ||
|
|
||
| @Test | ||
| void concurrentStartsShareOneContainer() throws Exception { | ||
| int starts = 8; | ||
| ExecutorService executor = Executors.newFixedThreadPool(starts); | ||
| CountDownLatch go = new CountDownLatch(1); | ||
| List<CompletableFuture<String>> futures = new ArrayList<>(); | ||
| try { | ||
| for (int i = 0; i < starts; i++) { | ||
| futures.add( | ||
| CompletableFuture.supplyAsync( | ||
| () -> { | ||
| GenericContainer<?> container = reusableContainer(); | ||
| try { | ||
| go.await(); | ||
| } catch (InterruptedException e) { | ||
| throw new RuntimeException(e); | ||
| } | ||
| container.start(); | ||
| return container.getContainerId(); | ||
| }, | ||
| executor | ||
| ) | ||
| ); | ||
| } | ||
| go.countDown(); | ||
|
|
||
| Set<String> containerIds = futures.stream().map(CompletableFuture::join).collect(Collectors.toSet()); | ||
|
|
||
| assertThat(containerIds).hasSize(1); | ||
| assertThat(containersOfThisRun()).hasSize(1); | ||
| } finally { | ||
| executor.shutdownNow(); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void replacesStoppedContainer() { | ||
| GenericContainer<?> first = reusableContainer(); | ||
| first.start(); | ||
| dockerClient.stopContainerCmd(first.getContainerId()).withTimeout(0).exec(); | ||
|
|
||
| GenericContainer<?> second = reusableContainer(); | ||
| second.start(); | ||
|
|
||
| assertThat(second.getContainerId()).isNotEqualTo(first.getContainerId()); | ||
| assertThat(second.isRunning()).isTrue(); | ||
| assertThat(containersOfThisRun()).hasSize(1); | ||
| } | ||
|
|
||
| private GenericContainer<?> reusableContainer() { | ||
| return new GenericContainer<>(TestImages.TINY_IMAGE) | ||
| .withCommand("sleep", "infinity") | ||
| .withLabel("test-run-id", runId) | ||
| .withReuse(true); | ||
| } | ||
|
|
||
| private List<String> containersOfThisRun() { | ||
| return dockerClient | ||
| .listContainersCmd() | ||
| .withShowAll(true) | ||
| .withLabelFilter(Collections.singletonMap("test-run-id", runId)) | ||
| .exec() | ||
| .stream() | ||
| .map(it -> it.getId()) | ||
| .collect(Collectors.toList()); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
Repository: testcontainers/testcontainers-java
Length of output: 8409
🏁 Script executed:
Repository: testcontainers/testcontainers-java
Length of output: 38003
🏁 Script executed:
Repository: testcontainers/testcontainers-java
Length of output: 17318
Reclaim orphaned reusable containers without deleting active creators.
If the JVM terminates after
createCommand.exec()and beforestartContainerCmd, the reusable container is not registered withResourceReaper. A later start receives a name conflict, ignores thecreatedcontainer, and waits for a running container until the one-minute timeout. The failure is then reported asContainerLaunchException.A same-hash container in the
pausedstate has the same timeout path because the lookup accepts onlyrunning, and cleanup removes onlyexitedordeadcontainers.Do not reclaim
createdcontainers by age alone. The winning starter performs file copies, network setup, andcontainerIsCreatedbetween creation andstartContainerCmd. If that work exceeds the threshold, a concurrent starter can remove the active winner and cause its start to fail. Use an ownership or lease mechanism that distinguishes an active creator from an orphan before reclaiming stalecreatedcontainers. Apply an explicit lifecycle policy topausedcontainers as well.🤖 Prompt for AI Agents
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Agreed that a start killed between create and start can leave the container orphaned. Commit 780994e (pushing next) fixes that:
createdcontainer with a matching hash that is older than one minute counts as orphaned. It is removed by ID and recreated. Losers now wait up to two minutes, so a start that begins right after the orphan was left behind still recovers.pausedcontainer fails fast with a clear error and is not removed, because pausing it is a deliberate user action.I didn't add a lease or ownership mechanism. The point of this PR is to replace #11980's locking with Docker's name uniqueness, and a lease would bring that machinery back. The age check can only remove an active winner if that winner spends more than a minute between create and start, i.e. copying files into the container. If that happens, the winner's start fails, and the next attempt joins the recreated container. A new unit test covers the orphan path.
Generated by Claude Code
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@kiview Thanks for explaining the design constraint. Docker name uniqueness should remain the coordination mechanism; I am not insisting on a lease.
The proposed orphan cleanup and fail-fast policy for
pausedcontainers address those cases. The age check remains a heuristic: it can remove an active creator during a file copy that takes more than one minute.One clarification:
startupAttemptsdefaults to1. After removal causes the active creator to fail, that caller does not automatically retry unless retries are configured. A later start can join the replacement container.I accept this as an explicit trade-off, rather than a guarantee that active creators cannot be removed. The pending commit and its tests remain unverified, so this finding stays open pending verification.
✏️ Learnings added
You are interacting with an AI system.