Skip to content

Fix Docker BuildKit "image already exists" error in dependency-installer tests #342

Closed

Description

@josecelano

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:

  1. Docker BuildKit may have stale tags or cache conflicts
  2. The image_exists() check might return false even though a partially-built or corrupt image is in the cache
  3. 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:

  1. Force remove any existing image before building: Add docker rmi -f <image> before the build command to ensure a clean slate
  2. Add --force-rm flag to docker build: Clean up intermediate containers even if the build fails
  3. 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_integration

All 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

  1. added
    bug
    on Feb 12, 2026
  2. self-assigned this
    on Feb 12, 2026
  3. added a commit that references this issue on Feb 12, 2026
  4. josecelano commented on Feb 13, 2026

    @josecelano
    MemberAuthor

    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:

    • Added docker rmi -f <image> before building to remove stale images
    • Added --force-rm flag to clean up intermediate containers
    • Applied to both dependency-installer and E2E image builders

    Result: ❌ Still failing in CI with timeout errors

    Attempt 2: Remove Fully-Qualified Image Names (Commit c719c92)

    What we did:

    • Extended the fix to remove both short and fully-qualified image names:
      • dependency-installer-test:ubuntu-24.04
      • docker.io/library/dependency-installer-test:ubuntu-24.04

    Reasoning: 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:

    • Added structured logging with error!() macro
    • Captured both stdout and stderr in error messages
    • Added exit codes and output length metrics

    Result: 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:

    Test A (parallel)           Test B (parallel)
    ─────────────────          ─────────────────
    Check: no image exists  →  Check: no image exists
    Start building          →  Start building  
    docker rmi -f (removes!)→  docker rmi -f (removes A's build!)
    Build completes         →  Build completes
    Try to tag              →  Try to tag
                               ❌ ERROR: timeouts/conflicts
    

    Why this happened:

    1. Multiple tests check image_exists() simultaneously → all return false
    2. Multiple tests start building the same image in parallel
    3. Multiple tests execute docker rmi -f which can delete each other's partial builds
    4. Build failures, timeouts, and "already exists" conflicts occur

    The Solution (Commit d3c42aa)

    Removed the docker rmi -f commands entirely. Docker BuildKit already handles concurrent builds to the same tag atomically with internal locking. The image_exists() check at the start is sufficient for the common case.

    Final changes:

    - // Remove stale images before building
    - drop(Command::new("docker").args(["rmi", "-f", &image_tag]).output());
    
    + // Docker BuildKit handles concurrent builds to the same tag atomically.
    + // We don't need to manually remove existing images - this would create race
    + // conditions when multiple tests build the same image in parallel.

    Kept from original proposal:

    • ✅ --force-rm flag (cleans up intermediate containers)
    • ✅ Better error reporting (stdout + stderr + structured logging)

    Key Insights

    1. Docker BuildKit is smarter than we thought: It has internal locking to handle concurrent builds safely
    2. The original error was likely transient: A one-time CI hiccup that the proposed "fix" made much worse
    3. Race conditions are hard to debug: They manifest differently each time (timeouts, conflicts, partial builds)
    4. Trust the existing image_exists() check: It works correctly - don't try to work around it

    Testing 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

    • ⚠️ Be cautious with "solutions" that involve manual cache invalidation - they often create more problems than they solve
    • ⚠️ Test parallelism matters - what works sequentially can break in parallel
    • ✅ Trust well-tested tools - Docker BuildKit's concurrency handling is battle-tested
    • ✅ Better observability helps - improved error logging revealed the real issue
  5. added a commit that references this issue on Feb 13, 2026
  6. josecelano commented on Feb 13, 2026

    @josecelano
    MemberAuthor

    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 test runs multiple integration tests in parallel, each test calls build_if_missing() to ensure the Docker image exists. The race unfolds as:

    1. Test A and Test B both call build_if_missing() simultaneously
    2. Both call image_exists() → both get false (no image yet)
    3. Both start docker build in parallel (~60s each)
    4. Test A's build finishes first, tags dependency-installer-test:ubuntu-24.04 → success
    5. Test B's build finishes, all Docker steps complete successfully (Roadmap #1 through feat: add independent format control for file and stderr logging with automatic ANSI code removal #7), but the final export/tagging step (EPIC: Destroy Command Implementation #8) fails with:
      #8 ERROR: image "docker.io/library/dependency-installer-test:ubuntu-24.04": already exists
      

    The 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

    Attempt Approach Result
    1 docker rmi -f before building ❌ Created worse race conditions (removing image while another test uses it)
    2 Extended docker rmi for fully-qualified names ❌ Same problem
    3 Remove all docker rmi, trust BuildKit atomicity ❌ BuildKit does NOT handle this silently — it errors out
    4 (final) Treat "already exists" as success ✅ CI passes

    The fix

    In both image builders (packages/dependency-installer/tests/containers/image_builder.rs and src/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 return Ok(()) instead of propagating the error:

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
    
        // Concurrent build race: another test already tagged this image.
        // The image is available for use — this is not a real failure.
        if stderr.contains("already exists") {
            info!(
                image = full_image_name,
                "Docker image was built by a concurrent process, treating as success"
            );
            return Ok(());
        }
    
        // ... real errors propagated as before
    }

    Why this is correct

    • The "already exists" error only occurs at the export/tagging step, after all build steps complete successfully
    • It means the exact same image (same Dockerfile, same tag) was already built and tagged by a concurrent process
    • The image is immediately available for Docker container creation
    • No data is lost, no corruption possible — Docker tags are atomic pointers

    CI Results

    All checks passing on PR #344 after this fix.

  7. added 2 commits that reference this issue on Feb 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugcidependenciestesting

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions