testcontainers-go icon indicating copy to clipboard operation
testcontainers-go copied to clipboard

[Bug]: reaper reuse finds an exited ryuk container and times out instead of creating a new one

Open skartikey opened this issue 3 months ago • 11 comments

Testcontainers version

v0.44.0

Using the latest Testcontainers version?

Yes

Host OS

Linux (Ubuntu 22.04.5 LTS, CircleCI machine executor)

Host arch

amd64

Go version

1.26.0

Docker version

The failure occurs on CircleCI (Linux amd64, machine executor), where the ephemeral VM was destroyed before full output could be captured. From the testcontainers-go banner on the failing host: Server Version 28.4.0, API Version 1.51. The output below is from my local dev machine, not the failing host:

Client:
 Version:           28.3.2
 API version:       1.51
 Go version:        go1.24.5
 Git commit:        578ccf6
 Built:             Wed Jul  9 16:12:57 2025
 OS/Arch:           darwin/arm64
 Context:           default

Server: Docker Desktop 4.43.2 (199162)
 Engine:
  Version:          28.3.2
  API version:      1.51 (minimum version 1.24)
  Go version:       go1.24.5
  Git commit:       e77ff99
  Built:            Wed Jul  9 16:13:56 2025
  OS/Arch:          linux/arm64
  Experimental:     false
 containerd:
  Version:          1.7.27
  GitCommit:        05044ec0a9a75232cad458027ca83437aae3f4da
 runc:
  Version:          1.2.5
  GitCommit:        v1.2.5-0-g59923ef
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

Docker info

Not captured on the failing CI host (ephemeral VM). From the testcontainers-go banner: Ubuntu 22.04.5 LTS, Total Memory 15706 MB, docker host unix:///var/run/docker.sock, ryuk image testcontainers/ryuk:0.14.0. The output below is from my local dev machine:

Client:
 Version:    28.3.2
 Context:    default
 Debug Mode: false
 Plugins:
  ai: Docker AI Agent - Ask Gordon (Docker Inc.)
    Version:  v1.6.0
    Path:     /Users/sunilkartikey/.docker/cli-plugins/docker-ai
  buildx: Docker Buildx (Docker Inc.)
    Version:  v0.25.0-desktop.1
    Path:     /Users/sunilkartikey/.docker/cli-plugins/docker-buildx
  cloud: Docker Cloud (Docker Inc.)
    Version:  v0.4.2
    Path:     /Users/sunilkartikey/.docker/cli-plugins/docker-cloud
  compose: Docker Compose (Docker Inc.)
    Version:  v2.38.2-desktop.1
    Path:     /Users/sunilkartikey/.docker/cli-plugins/docker-compose
  debug: Get a shell into any image or container (Docker Inc.)
    Version:  0.0.41
    Path:     /Users/sunilkartikey/.docker/cli-plugins/docker-debug
  desktop: Docker Desktop commands (Docker Inc.)
    Version:  v0.1.11
    Path:     /Users/sunilkartikey/.docker/cli-plugins/docker-desktop
  extension: Manages Docker extensions (Docker Inc.)
    Version:  v0.2.29
    Path:     /Users/sunilkartikey/.docker/cli-plugins/docker-extension
  init: Creates Docker-related starter files for your project (Docker Inc.)
    Version:  v1.4.0
    Path:     /Users/sunilkartikey/.docker/cli-plugins/docker-init
  mcp: Docker MCP Plugin (Docker Inc.)
    Version:  v0.9.9
    Path:     /Users/sunilkartikey/.docker/cli-plugins/docker-mcp
  model: Docker Model Runner (EXPERIMENTAL) (Docker Inc.)
    Version:  v0.1.33
    Path:     /Users/sunilkartikey/.docker/cli-plugins/docker-model
  sbom: View the packaged-based Software Bill Of Materials (SBOM) for an image (Anchore Inc.)
    Version:  0.6.0
    Path:     /Users/sunilkartikey/.docker/cli-plugins/docker-sbom
  scout: Docker Scout (Docker Inc.)
    Version:  v1.18.1
    Path:     /Users/sunilkartikey/.docker/cli-plugins/docker-scout
WARNING: Plugin "/Users/sunilkartikey/.docker/cli-plugins/docker-dev" is not valid: failed to fetch metadata: fork/exec /Users/sunilkartikey/.docker/cli-plugins/docker-dev: no such file or directory
WARNING: Plugin "/Users/sunilkartikey/.docker/cli-plugins/docker-feedback" is not valid: failed to fetch metadata: fork/exec /Users/sunilkartikey/.docker/cli-plugins/docker-feedback: no such file or directory

Server:
 Containers: 4
  Running: 0
  Paused: 0
  Stopped: 4
 Images: 108
 Server Version: 28.3.2
 Storage Driver: overlayfs
  driver-type: io.containerd.snapshotter.v1
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Cgroup Version: 2
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local splunk syslog
 CDI spec directories:
  /etc/cdi
  /var/run/cdi
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 05044ec0a9a75232cad458027ca83437aae3f4da
 runc version: v1.2.5-0-g59923ef
 init version: de40ad0
 Security Options:
  seccomp
   Profile: builtin
  cgroupns
 Kernel Version: 6.10.14-linuxkit
 Operating System: Docker Desktop
 OSType: linux
 Architecture: aarch64
 CPUs: 14
 Total Memory: 7.653GiB
 Name: docker-desktop
 ID: 18b3abd9-fc10-4562-8b54-6a32dae2e3f9
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 HTTP Proxy: http.docker.internal:3128
 HTTPS Proxy: http.docker.internal:3128
 No Proxy: hubproxy.docker.internal
 Labels:
  com.docker.desktop.address=unix:///Users/sunilkartikey/Library/Containers/com.docker.docker/Data/docker-cli.sock
 Experimental: false
 Insecure Registries:
  hubproxy.docker.internal:5555
  ::1/128
  127.0.0.0/8
 Live Restore Enabled: false

WARNING: DOCKER_INSECURE_NO_IPTABLES_RAW is set

What happened?

We run go test -run Integration ./... over a large repo (influxdata/telegraf, several hundred packages, a few dozen of which start containers). All package test processes of one go test ./... invocation share a session ID, so they share a single ryuk container. Ryuk exits 10 seconds after its last client disconnects (RYUK_RECONNECTION_TIMEOUT default), and a full ./... run has natural gaps where no package currently holds a ryuk connection, so ryuk legitimately exits mid-run.

When the next package needs a container, reaperSpawner.lookupContainer lists containers with All: true and no running-state filter, and the health-status switch accepts an empty health status, so the exited ryuk container is returned as reusable. fromContainer then waits for wait.ForLog("Started") plus wait.ForExposedPort() on a container that is not running, until the default 60s startup timeout expires. The whole container request fails with:

container failed to start: create container: reaper: from container "8ed2e2fc": wait for reaper 8ed2e2fc: context deadline exceeded

The test that hit the window never gets to start its own container. retryError does treat context.DeadlineExceeded as retryable, but by then the 60 seconds are gone and in our CI the retry hits the same dead container again.

This fails a handful of CI runs per week for us. Because package scheduling on a fixed-size runner is roughly deterministic, the same package keeps landing in the idle window, so it looks like one flaky test but is actually the reaper lifecycle race.

Expected behavior: an exited reaper container found during lookup should be treated like errReaperNotFound (create a fresh reaper), not waited on. Either lookupContainer should filter on the running state (the doc comment on it already says "in the case it's found in the running state", which the All: true listing contradicts), or fromContainer should check State().Running before entering the wait, and fall back to newReaper. The name-conflict retry for a dying AutoRemove container already exists in retryError (createContainerFailDueToNameConflictRegex), so the create-new path handles the corpse disappearing underneath it.

Relevant log output

2026/08/31 22:17:25 github.com/testcontainers/testcontainers-go - Connected to docker:
  Server Version: 28.4.0
  API Version: 1.51
  Operating System: Ubuntu 22.04.5 LTS
  Total Memory: 15706 MB
  Testcontainers for Go Version: v0.44.0
  Resolved Docker Host: unix:///var/run/docker.sock
  Resolved Docker Socket Path: /var/run/docker.sock
2026/08/31 22:17:29 🐳 Creating container for image apache/activemq-artemis
2026/08/31 22:17:32 ⏳ Waiting for Reaper "8ed2e2fc" to be ready
--- FAIL: TestIntegrationArtemis (67.44s)
    jolokia2_agent_test.go:699:
        Error: container failed to start: create container: reaper: from container "8ed2e2fc": wait for reaper 8ed2e2fc: context deadline exceeded

Additional information

Looks related to #764 (reaper not re-initialized after termination), but this is specifically the reuse path racing a ryuk that exited normally after its reconnection timeout. Our workaround is TESTCONTAINERS_RYUK_DISABLED=true in CI (the VM is ephemeral), which sidesteps the reaper entirely, but the race is reachable for anyone running go test ./... across many packages with ryuk enabled. Happy to send a PR for the state check in fromContainer if that is the preferred shape.

skartikey avatar Sep 01 '26 13:09 skartikey

Independent reproduction of this on GitHub Actions (ubuntu-latest, 4 vCPU, Docker 28.0.4, testcontainers-go v0.44.0, ryuk 0.14.0), plus two details that may help shape the fix.

Same mechanism, same signature. Our go test ./... -race run has 37 packages that start containers through one shared Postgres helper, and the compile-only stretch between two groups of them is 11–13s in every run we timed. Ryuk's reconnection timer fires, and the next package to call lookupContainer gets:

create container: reaper: from container "0a284fa3": wait for reaper 0a284fa3: context deadline exceeded

exactly 60s after ⏳ Waiting for Reaper "0a284fa3" to be ready. Red or green depends only on when the next package arrives relative to Ryuk's exit: arrivals ~1.5–3s after the timer failed, an arrival ~3.5s after (the container already gone) took the newReaper path and passed.

Why it is a bare 60s context deadline exceeded and not a fast "container exited". In fromContainer, wait.ForLog("Started") runs first. LogStrategy.WaitUntilReady calls checkTarget but then, when target.Logs(ctx) returns an error, it continues without consulting that state error (wait/log.go, the // TODO: fix as this will wait for timeout if the logs are not available branch). A reaper container that has exited but is still present has readable logs, so that case would pass ForLog (it already logged Started) and fail fast in ForExposedPort via checkTarget. The 60s bare deadline is the AutoRemove window: Docker lists the container while it is dead / marked for removal, inspect still works (so lookupContainer returns it), but ContainerLogs errors for the rest of its life, so ForLog polls until its startup timeout and returns errors.Join(nil, ctx.Err()). A stub StrategyTarget whose Logs() returns the daemon's "dead or marked for removal" error reproduces this without Docker. So besides the running-state check in lookupContainer/fromContainer proposed above, LogStrategy returning checkTarget's error when Logs() fails on a non-running container would make any future variant fail in one poll instead of eating the whole timeout.

A workaround that keeps Ryuk enabled. TESTCONTAINERS_RYUK_RECONNECTION_TIMEOUT (→ RYUK_RECONNECTION_TIMEOUT on the reaper) sized to outlive the job removes the gap entirely; we use 30m on ephemeral runners. TESTCONTAINERS_RYUK_CONNECTION_TIMEOUT does not help here: it only covers the reaper's first client. Note the library reads the bare RYUK_RECONNECTION_TIMEOUT before the prefixed spelling, so a stray bare entry silently wins.

+1 to treating a non-running reaper as errReaperNotFound; happy to test a PR against our workload.

topcoder1 avatar Sep 16 '26 19:09 topcoder1

Thanks, that explains why we always saw the full 60s rather than a fast failure. I checked v0.44.0 and LogStrategy.WaitUntilReady does skip checkTarget's error whenever Logs() fails, so a reaper in the AutoRemove window can only end in a bare deadline.

#3868 already covers the lookup side. lookupContainer only reuses a running reaper, removes one that is exited, dead or being removed and creates a new one, and fromContainer checks the state again right before the wait. It would be great if you could try it against your workload. The LogStrategy change is useful on its own, since it affects every log wait and not just the reaper, so I'd keep it as a separate PR.

skartikey avatar Sep 17 '26 07:09 skartikey

@topcoder1 I've opened #3898 for the LogStrategy change, so a container that stops during a log wait now fails right away instead of running out the timeout.

#3868 also picked up two more fixes. A reaper that exits during the readiness wait is now retried and recreated, and one still being auto-removed no longer stalls the lookup. If you can run your workload against #3868, that would be the most useful check, since it's the one that fixes this issue.

skartikey avatar Sep 17 '26 07:09 skartikey

A third independent reproduction occurred in golusoris/golusoris run 35457421096 on 2026-09-19 with testcontainers-go v0.44.0 and Ryuk 0.14.0. At 23:05:08 the next package logged Waiting for Reaper "4b66ec5c" to be ready; exactly 60 seconds later it failed with reaper: from container "4b66ec5c": wait for reaper 4b66ec5c: context deadline exceeded. The following call immediately created fresh Ryuk b888c3ef4fc2, which became ready in about five seconds, and its TimescaleDB test passed. The two package tests share the same session ID. This is the stopped/AutoRemove reuse sequence described here, not a dependency-update regression. We can validate #3868 against the same hosted matrix once its workflow is approved or a release containing it is available.

lusoris avatar Sep 20 '26 05:09 lusoris

@lusoris thanks, that's exactly the case #3868 fixes. Its workflows are green now (the minio failure is an unrelated Docker Hub pull denial), so you can test it before a release with:

go mod edit -replace github.com/testcontainers/testcontainers-go=github.com/skartikey/testcontainers-go@4153ad13227e358bcfb2fe1e093b2c2065ad29bf && go mod tidy

skartikey avatar Sep 28 '26 17:09 skartikey

Sorry for going quiet on this, @skartikey, and thank you for the replace line.

I haven't run #3868 yet. The branch has moved since your comment, so I'll test the current head (72158f4e, which includes the retry and in-progress-removal fixes) rather than 4153ad13. I'll run it against the same hosted workflow as the failing run and post the result here with the run link.

lusoris avatar Oct 07 '26 10:10 lusoris

@skartikey, #3868 at 72158f4e fixes our case. A forced reproduction that fails every time on v0.44.0 passes every time with it, both locally and on the runner set that ran run 35457421096, and three runs of that workflow with the replace applied were green.

Forced reproduction (harness): package A starts a container and exits; package B waits for the session's Ryuk die event, then starts a container. Ryuk's writable layer is padded with 150,000 small files so its AutoRemove takes seconds instead of milliseconds.

  • v0.44.0: 7 of 7 failed locally (Docker 29.8.2) and 6 of 6 on the hosted runner (Docker 29.8.2, dind). Each failure is the reported one: ⏳ Waiting for Reaper "<id>" on the exited container, then wait for reaper <id>: context deadline exceeded about 60 s later.
  • 72158f4e: 8 of 8 passed locally (1.7–9.4 s) and 6 of 6 on the hosted runner (6.1–15.5 s). The exited reaper was never waited on; a fresh Ryuk came up as soon as the old one's removal finished, after several create attempts that hit the name conflict.

Hosted workflow: the same Test job (go test -race -p 4 ./..., default reconnection timeout) in run 37609615670 and run 37613636683 (attempt 1, attempt 2).

  • 3 runs, 0 failures, 0 reaper errors.
  • 11 Ryuk exits mid-run, each followed by a package that started a fresh Ryuk.
  • Closest arrival: in attempt 1, outbox logged 🐳 Creating container for image testcontainers/ryuk:0.14.0 0.24 s after Ryuk f149f4f1 exited, and passed.

What the natural runs don't show: on this runner an unpadded Ryuk is gone 23–111 ms after it exits, so I can't tell whether that outbox lookup saw the stopped container. The fix path itself is covered by the forced reproduction above.

One limit worth knowing: the new code waits out an in-progress removal through the create retries, which give up after 20 s. A removal slower than that would still fail. On our runners real removals take about 0.1 s, so we don't expect to hit it.

lusoris avatar Oct 07 '26 12:10 lusoris

@lusoris thank you, that's a really thorough validation. The padded writable layer is a nice way to force the AutoRemove window, and seeing the exited reaper never waited on in 14 of 14 forced runs is exactly the behaviour #3868 is meant to pin.

On the 20 s limit: that's the existing backoff for reaper creation (MaxElapsedTime in reaperSpawner), which already bounded the name-conflict retries before this PR. The fix reuses it rather than adding a second timer, so a removal slower than 20 s would have failed on v0.44.0 too, just with a different error. If someone does hit that in practice it would be easy to make the bound configurable, but as you say real removals are two orders of magnitude below it.

I'll link your results from the PR so the maintainers have them when they get to it.

skartikey avatar Oct 07 '26 13:10 skartikey

Additional reproduction on v0.44.1-0.20261029064637-ff84c26717f1 with Go 1.27.3, Docker 29.5.2/API 1.54 under Colima on macOS arm64, and Ryuk 0.14.0.

During one go test -p 2 ./... invocation, the shared reaper had worked for several earlier package binaries. The later sequence was:

  • 12:33:40: package A started waiting for existing reaper cf2c1cae.
  • 12:33:43–44: package B created and successfully started replacement reaper f59c23a0 under the same session ID.
  • Package A still failed after 61.79 seconds with create container: reaper: from container "cf2c1cae": wait for reaper cf2c1cae: context deadline exceeded, before its requested service container was created.

The original reaper was already gone when inspected, so I did not capture its terminal state. This sequence is consistent with the AutoRemove window described above; it does not independently establish why that reaper exited.

The swallowed-state-error behavior is independently reproducible through the public wait.StrategyTarget interface. Save the following as main.go in an empty directory, then run:

go mod init example.com/reaper-log-repro
go get github.com/testcontainers/[email protected]
go mod tidy
go run .
package main

import (
 "context"
 "errors"
 "fmt"
 "io"
 "time"

 "github.com/moby/moby/api/types/container"
 "github.com/testcontainers/testcontainers-go/wait"
)

type stoppedTarget struct { wait.StrategyTarget }
func (stoppedTarget) State(context.Context) (*container.State,error) {
 return &container.State{Status:container.StateExited,Running:false,ExitCode:0},nil
}
func (stoppedTarget) Logs(context.Context) (io.ReadCloser,error) {
 return nil,errors.New("container is dead or marked for removal")
}
func main() {
 start:=time.Now()
 err:=wait.ForLog("Started").WithStartupTimeout(200*time.Millisecond).WithPollInterval(time.Millisecond).WaitUntilReady(context.Background(),stoppedTarget{})
 fmt.Printf("elapsed=%s deadline=%t error=%v\n",time.Since(start).Round(time.Millisecond),errors.Is(err,context.DeadlineExceeded),err)
}

Actual output: elapsed=200ms deadline=true error=context deadline exceeded. Expected: fail promptly with the stopped-container error rather than exhaust the log-wait timeout. This component reproduction stubs the daemon's stopped state and unavailable logs; it does not simulate the whole reaper race.

The affected branch remains in LogStrategy.WaitUntilReady at this revision: a logs error bypasses the state error. This supports the separate log-wait fix in #3898 as well as the reaper reuse fix in #3868.

CaliLuke avatar Oct 29 '26 19:10 CaliLuke

The timeout still reproduces on ff84c26717f1, the pre-release in the report above. On the same forced reproduction, #3868 removes it, and #3898 alone turns it into a fast failure.

I used the harness from my 2026-10-07 comment, with 150,000 padded files and TESTCONTAINERS_RYUK_RECONNECTION_TIMEOUT=30s. I ran it three times per commit on Docker 29.9.2, Go 1.27.3 and Ryuk 0.14.0. Elapsed is the testcontainers.Run call made while the exited Ryuk was still being removed.

Commit Passed Elapsed Outcome
ff84c267 0 of 3 61.3–61.7 s wait for reaper <id>: context deadline exceeded
#3868 at 72158f4e 3 of 3 3.4–6.5 s Exited reaper not waited on; new reaper created
#3898 at 04c949ab 0 of 3 1.1–1.7 s wait for reaper <id>: unexpected container status "removing"
ff84c267 with both merged 3 of 3 3.1–3.8 s Exited reaper not waited on; new reaper created

The two PR heads are 42 and 50 commits behind ff84c267, and both merged onto it without conflicts.

I also ran the stopped-target stub from the report above with the default 60 s startup timeout. ff84c267 and #3868 returned context deadline exceeded after 60.0 s. #3898 and the merged tree returned container exited with code 0 plus the logs error in under 1 ms.

lusoris avatar Oct 30 '26 14:10 lusoris

@CaliLuke @lusoris thanks both, that's a fourth reproduction and a clean matrix showing the two fixes are complementary.

Update: #3898 is merged and stevenh has picked up #3868, which now sits on top of it. CI is rerunning after an unrelated proxy failure.

skartikey avatar Nov 04 '26 17:11 skartikey