Repository navigation
Description
Problem
The dependency-installer Docker integration test it_should_report_missing_dependencies_when_checking_all_in_fresh_ubuntu_container is failing in GitHub Actions with a Docker BuildKit export error:
ERROR: image "docker.io/library/dependency-installer-test:ubuntu-24.04": already exists
The image builds successfully (all 38 seconds of layers complete), but Docker BuildKit fails when trying to export/tag the final image because an image with that name already exists from a previous test run.
Root Cause
The current ImageBuilder::build_if_missing() method in packages/dependency-installer/tests/containers/image_builder.rs checks if an image exists using docker image inspect. However, in CI environments:
- Docker BuildKit may have stale tags or cache conflicts
- The
image_exists()check might return false even though a partially-built or corrupt image is in the cache - When the build completes, Docker BuildKit refuses to overwrite the existing image
This is a known issue in containerized CI environments where Docker state can be inconsistent between runs.
Solution
Update ImageBuilder::build_if_missing() to:
- Force remove any existing image before building: Add
docker rmi -f <image>before the build command to ensure a clean slate - Add
--force-rmflag to docker build: Clean up intermediate containers even if the build fails - Use absolute paths from
CARGO_MANIFEST_DIR: Already fixed - ensures paths work from workspace root (as GitHub Actions runs tests)
Implementation
File: packages/dependency-installer/tests/containers/image_builder.rs
Changes needed in build_if_missing() method:
pub fn build_if_missing(&self) -> Result<(), ImageBuildError> {
let full_image_name = format!("{}:{}", self.image_name, self.tag);
// Check if image already exists
if Self::image_exists(&full_image_name) {
info!(
image = full_image_name,
"Docker image already exists, skipping build"
);
return Ok(());
}
info!(image = full_image_name, "Building Docker image...");
// Remove any stale/corrupt image that might exist but wasn't detected
// This fixes CI issues where Docker BuildKit reports "already exists" during export
drop(
Command::new("docker")
.arg("rmi")
.arg("-f")
.arg(&full_image_name)
.output(), // Ignore errors - image might not exist
);
// Build the image with --force-rm to clean up intermediate containers
let output = Command::new("docker")
.arg("build")
.arg("--force-rm") // Remove intermediate containers after build
.arg("-f")
.arg(&self.dockerfile_path)
.arg("-t")
.arg(&full_image_name)
.arg(&self.context_path)
.output()?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(ImageBuildError::BuildFailed(stderr.to_string()));
}
info!(image = full_image_name, "Successfully built Docker image");
Ok(())
}Also update the doc comment to explain the CI fix.
Testing
Local Testing
cargo test -p torrust-dependency-installer --test check_command_docker_integrationAll 10 tests should pass.
CI Testing
Push to a branch and verify the Testing workflow completes successfully with no Docker BuildKit errors.
Expected Outcome
- ✅ All dependency-installer tests pass in GitHub Actions
- ✅ No "image already exists" errors from Docker BuildKit
- ✅ Clean image builds on every test run
- ✅ Tests remain fast (image build is skipped if already exists and valid)
Related
This is a pre-existing issue unrelated to PR #341 (SSH validation fix). The test failure blocks #341 from being merged, but the fix should be in a separate PR to maintain clean separation of concerns.
References
- Test file:
packages/dependency-installer/tests/check_command_docker_integration.rs - Image builder:
packages/dependency-installer/tests/containers/image_builder.rs - Dockerfile:
packages/dependency-installer/docker/ubuntu-24.04.Dockerfile
Activity
fix: [#342] resolve Docker BuildKit 'image already exists' error in CI
josecelano commentedon Feb 13, 2026
Investigation Summary
After implementing the proposed solution and extensive testing, we discovered that the original diagnosis was incorrect. The issue was much more subtle than initially thought.
Timeline of Investigation
Attempt 1: Implement Proposed Solution (Commits 74f2151, 3b506dd)
What we did:
docker rmi -f <image>before building to remove stale images--force-rmflag to clean up intermediate containersdependency-installerand E2E image buildersResult: ❌ Still failing in CI with timeout errors
Attempt 2: Remove Fully-Qualified Image Names (Commit c719c92)
What we did:
dependency-installer-test:ubuntu-24.04docker.io/library/dependency-installer-test:ubuntu-24.04Reasoning: BuildKit uses fully-qualified names during export phase
Result: ❌ Still failing - tests timing out after 60+ seconds during Docker builds
Attempt 3: Improve Error Reporting (Commit 2dbd31c)
What we did:
error!()macroResult: Revealed the real problem - race conditions!
The Actual Root Cause: Race Conditions 🎯
The
docker rmi -f"fix" introduced a race condition when multiple tests run in parallel:Why this happened:
image_exists()simultaneously → all return falsedocker rmi -fwhich can delete each other's partial buildsThe Solution (Commit d3c42aa)
Removed the
docker rmi -fcommands entirely. Docker BuildKit already handles concurrent builds to the same tag atomically with internal locking. Theimage_exists()check at the start is sufficient for the common case.Final changes:
Kept from original proposal:
--force-rmflag (cleans up intermediate containers)Key Insights
image_exists()check: It works correctly - don't try to work around itTesting Status
The fix is now in PR #344 and awaiting CI verification. The changes are minimal and restore the original behavior while keeping the improvements (--force-rm, better logging).
Lessons Learned
fix: [#342] treat 'already exists' build error as success in concurre…
josecelano commentedon Feb 13, 2026
Final Fix — CI Now Passing ✅
The fix that resolved this issue was commit 5582ea0: treat "already exists" build error as success in concurrent tests.
Root Cause (confirmed)
The error is a race condition during parallel test execution. When
cargo testruns multiple integration tests in parallel, each test callsbuild_if_missing()to ensure the Docker image exists. The race unfolds as:build_if_missing()simultaneouslyimage_exists()→ both getfalse(no image yet)docker buildin parallel (~60s each)dependency-installer-test:ubuntu-24.04→ successThe image itself is perfectly valid and available — it was built and tagged by Test A. Test B's build did redundant work but the resulting image is identical.
Why previous attempts failed
docker rmi -fbefore buildingdocker rmifor fully-qualified namesdocker rmi, trust BuildKit atomicityThe fix
In both image builders (
packages/dependency-installer/tests/containers/image_builder.rsandsrc/testing/e2e/containers/image_builder.rs), when a build fails, we now check if the error message contains"already exists". If so, we log it and returnOk(())instead of propagating the error:Why this is correct
CI Results
All checks passing on PR #344 after this fix.
docs: [#342] add ADR for concurrent Docker image builds in tests
docs: [#342] add skill for creating ADRs