keploy icon indicating copy to clipboard operation
keploy copied to clipboard

compose replay: a bring-up retry orphans the agent's mocks, and the next up can reuse a container that is still stopping

Open slayerjain opened this issue 2 months ago • 7 comments

Two defects on the docker-compose replay path, found from one CI run. They compound: the first turns a transient dependency crash into a run that verifies nothing, and the second is one way to produce that crash. Line numbers are main (v3.6.67); the behaviour is the same in v3.6.58, where it was observed.

1. The compose bring-up retry replaces the agent and orphans the session's mocks

pkg/client/app/app.go:1457 retries docker compose up when a dependency container crashes before the app starts. The retry calls a.ComposeDown() (:1468), which tears down the injected keploy-agent service along with the stack — the retry's own comment says so — and then re-issues up.

All replay state lives in the agent process:

  • the mock corpus, in Agent.clientMocks (pkg/service/agent/agent.go:51), published by finalizeClientMocks (:752);
  • the proxy's MockManager, created by MockOutgoing.

The replacement agent boots empty. Nothing re-arms it: in RunTestSet (pkg/service/replay/replay.go:1285) the sequence AgentHealthTicker → MockOutgoing → GetMocks/StoreMocks → SendMockFilterParamsToAgent → MakeAgentReadyForDockerCompose (:1338–:1488) is straight-line code that has already run, and AgentHealthTicker returns on the first healthy observation (pkg/util.go:2790), so the agent going away is never observed.

What the run then produces:

failed to get consumed mocks ... mock manager not found
failed to update mock parameters on agent ... no mocks stored for client ID
app accepted TCP but never completed an HTTP round-trip within the ceiling; firing tests anyway
found no test results for test set with id: test-set-0

The stack itself recovered — the retry's second attempt came up clean — so the run looked healthy from the outside and reported Total tests: 4, passed 0, failed 0, replay completed successfully, exit 0.

Any transient dependency crash during a compose bring-up reproduces this.

Fix shape (a maintainer's call): after the retry replaces the agent, re-register the session's mocks with the replacement before any test fires — or fail the test-set loudly rather than proceeding mockless. Whatever the mechanism, a zero-test run should not be reachable silently. keploy/keploy#4613 makes such a run report APP_FAULT instead of PASSED, but it is a reporting fix, not this.

2. The next up can start while the previous stack is still coming down

ComposeDown runs docker compose down --timeout 1 bounded by composeDownCmdBudget (8s), then a reap barrier that waits on two names — the agent and the app container (app.go:694). A user service that the down did not reach, or that is still stopping, is not waited for at all.

The next up then finds it present and reuses it, with its state. In the run above that container was a zookeeper: every other service printed Creating on the replay's bring-up, zookeeper printed Starting. It came back with its data directory, restored the previous broker's session and ephemeral node from its snapshot, and the new kafka could not claim its own id:

ERROR Error while creating ephemeral at /brokers/ids/1, node already exists and
owner '0x1001bf47ecd0001' does not match current session '0x1001bf56ee30001'
Fatal error during KafkaServer startup

kafka exited 1 and --abort-on-container-exit took the bring-up down — which is what triggered the retry in defect 1.

I tried the obvious fix (capture the project's containers before the down, wait for them before the next up) and withdrew it, because review showed it does not work here and is not safe as written:

  • the capture lived on App, and AgentClient.Setup builds a new App per call — so at the record→auto-replay boundary, the exact sequence above, the capture is empty and the guard is a no-op;
  • with test.mocking on, composeReuse means one run() per App, so the capture/consume pair never completes at all;
  • it waits for a removal nobody issued: when the down is killed at its budget, nothing is in flight, so waiting changes nothing — a force-remove has to come first, as removeStaleComposeAgentWithin already does;
  • and it added a 90s context.Background() wait on the SIGINT drain path, which the surrounding code explicitly avoids (app.go:1567).

Recording that here so the next attempt starts past those four traps rather than into them.

Reproducing

Any compose stack with a service that survives a killed down and carries identity in its data directory — zookeeper is the clean example — recorded with keploy record -c "docker compose up" --auto-replay-delay <n>, with a dependency made to crash once during the replay's bring-up.

slayerjain avatar Sep 20 '26 18:09 slayerjain

Thank you and congratulations 🎉 for opening your very first issue in keploy

github-actions[bot] avatar Sep 20 '26 18:09 github-actions[bot]

Taking this one.

Defect 1 trace matches what I see in the code: everything the replay session puts on the agent — the stored corpus (Agent.clientMocks), the proxy's mock manager, the filter params, and the /tmp/agent.ready file the compose healthchecks watch — lives in the agent container that the retry's ComposeDown() replaces, and the straight-line setup in RunTestSet has already run, so nothing re-registers it. Tests then fire against an empty agent and the run reports zero executed tests.

Plan for defect 1 (the part #4613's reporting fix sits behind): before the first test fires, have the replayer verify the agent still holds what setup stored, using the non-draining GET /agent/mock/stats loaded count — a replacement agent reports 0 while setup stored a non-empty corpus, and unlike GetConsumedMocks polling it steals nothing. When the agent no longer holds the session, re-register against the replacement in the same order setup uses (MockOutgoing → StoreMocks → SendMockFilterParamsToAgent → MakeAgentReadyForDockerCompose), then confirm via stats; if the state still cannot be confirmed, the test-set fails loudly instead of proceeding mockless.

For defect 2 I will start past the four traps you recorded (keyed on a surface that actually survives the App-per-call boundary, force-remove before waiting, no background-context wait on the drain path). I'll bring defect 1 first with the full gate, then defect 2 on top — happy to fold them into one branch if you'd prefer.

Branch up shortly with the exact commands and tests.

ayam04 avatar Sep 21 '26 02:09 ayam04

Thanks for picking this up. Everything below is checked against origin/main (cf9c6dc5) before posting; where I was wrong in the issue, I say so.

Going through your plan in the order that would change your code.

A detector already exists and already fires — but it does not cover the case that argues for yours

You don't need a new probe to detect a replacement. UpdateMockParams bails on exactly that condition:

// pkg/service/agent/agent.go:1079-1082
storageInterface, exists := a.clientMocks.Load(uint64(0))
if !exists {
    return fmt.Errorf("no mocks stored for client ID")
}

→ 500 (pkg/agent/routes/replay.go:157-161) → SendMockFilterParamsToAgent error → the test loop breaks:

// pkg/service/replay/replay.go:2045-2053
err = r.SendMockFilterParamsToAgent(runTestSetCtx, expectedNames, reqTime, respTime, ...)
if err != nil {
    ...
    utils.LogError(r.logger, err, "failed to update mock parameters on agent")
    break
}

That is the run in the issue: failed to update mock parameters on agent ... no mocks stored for client ID, then found no test results for test set, then Total tests: 4, passed 0, failed 0. The replacement was detected on the first test and both loops stopped — the break exits for idx, testCase := range testsToRun (replay.go:1953), and a set with deferred streaming tests breaks the same way in Phase 2 (replay.go:2767, :2838-2843). What it did not do is change the verdict: resolveTestSetStatus (replay.go:114-127) returns ("", false) — testSetStatus is Passed (:1257), getErrStatus() is still Running (:1258), and the error text matches none of isDockerComposeReplayShutdown's substrings (:129-144) — so control falls to the LogError branch and the set stays PASSED.

Where that leaves your gate, and this is the part I had wrong when I filed: #4613 only fixes the all-or-nothing case. scoredNothing (replay.go:207-210) requires success == 0 && failure == 0 && ignored == 0 && obsolete == 0. If the agent is replaced part-way through a set in which no test has failed, currentFailures is still 0 (a failure would have taken the default arm at replay.go:2446), scoredNothing is false — and the set reports PASSED with a partial run. All-passing and all-obsolete both qualify; one real failure first, and you get FAILED honestly.

The report makes it visible and still calls it green. Total is testCasesCount — every test the set intended to run, the loaded count or the selected count when test.selectedTests is set (replay.go:1741, :1743-1744), used at :3280 — while Success counts only those that passed (:2437), and failure is assigned in exactly one place, failure += currentFailures at :2734. So a 4-test set that loses its agent after two prints Total tests: 4, Total test passed: 2, Total test failed: 0 (replay.go:3510-3516) under status PASSED, with nothing saying why the other two never ran.

So the honest summary is: detection exists but is late and partial, and the verdict is only fixed at one end. A pre-flight gate of the kind you're proposing is the right instinct. Two limits on the existing signal worth designing around: it fires only when the CLI next calls UpdateMockParams — the first test after the replacement, never before any test — and only for a restarted agent. A wedged-but-alive agent never trips it.

But loaded == 0 is also a perfectly healthy empty test-set

A test-set with no recorded mocks is supported and non-fatal, and the compose branch stores the empty corpus anyway:

// pkg/service/replay/replay.go:1485-1487, then :1499 unconditionally
if filteredMocks == nil && unfilteredMocks == nil {
    r.logger.Debug("no mocks found for test set", zap.String("testSetID", testSetID))
}
...
err = r.instrumentation.StoreMocks(ctx, filteredMocks, unfilteredMocks)

The client always POSTs the stream, and finalizeClientMocks runs on the zero-length one (pkg/service/agent/agent.go:874; the loop at :833 is skipped when total == 0), so the pool entry is stored and loadedMocks = 0 — on a completely healthy agent, indistinguishable from a fresh process. "The test-set fails loudly" would turn a currently-passing configuration into a hard failure.

The information that would rescue it exists in the agent (a.clientMocks has an entry) but never reaches the wire: MockStats carries counts only — Loaded/Consumed/Missed (pkg/models/agent.go:147-151), of which the service fills Loaded alone (pkg/service/agent/scope.go:168-172) — with no "pool present" bit. Your wording says "while setup stored a non-empty corpus", which dodges the false positive, but then the gate is blind on exactly the zero-mock sets, where a replacement still costs you the filter params and the readiness file.

By contrast the pool check distinguishes "replaced" from "stored empty" for free. It's sharper on the false-positive axis — though not strictly better: the loaded count is pollable at any moment with no side effects, while the pool check only surfaces as a side effect of a call you were making anyway.

A cleaner signal exists and is cheap. There is no process identity on any agent endpoint — /agent/health returns the bare string "OK" (pkg/agent/routes/record.go:237-241). (/agent/scope/begin and /scope/windows do carry a Pid, pkg/models/agent.go:114-135, but that's the client worker's, not the agent's.) A per-process nonce set in agent.New and returned by /agent/health, compared against the value captured at setup, detects replacement directly, with no empty-corpus false positive. The good news: nothing parses that body — isAgentHealthy checks only the status code (pkg/util.go:2813-2836) and the compose healthcheck reads /tmp/agent.ready (pkg/platform/docker/docker.go:35-38) — so changing its shape is safe. It isn't free, though: it needs the field, the handler change, and the same missing client method + Instrumentation entry noted below, and an agent predating it returns "OK" with no nonce — the same 404-tolerance problem I flag against the stats route. It just doesn't have the empty-corpus one.

What the four calls don't restore

The order is right (replay.go:1402 → :1499 → :1510 → :1515 is the compose branch verbatim; the native branch is inverted and has no ready call, so a shared helper must be branch-aware). There is no client-id hazard: the agent hardcodes the pool key uint64(0) (pkg/service/agent/agent.go:754, :759, :1079) and the CLI never sends a client id at all — so a replacement can't mis-key a re-registration, it just has an empty map. And the four are safe to re-run before the first test fires — though MockOutgoing is not a general no-op: Proxy.Mock calls setSession (pkg/agent/proxy/proxy.go:3619), mm.ResetForReplaySession() (:3653) and ClearAllWorkerScopes() (:3659), so anywhere later it drops connection-scoped mock state and worker scopes.

But the sequence as written can't run, and if it did it would restore a different session:

  1. The corpus is out of scope. filteredMocks, unfilteredMocks are :=-declared inside the compose block (replay.go:1467; the native branch has its own at :1590, no outer declaration) and last used at :1499. At "before the first test fires" they're gone — StoreMocks has nothing to store. Either hoist them or re-run GetMocks, which re-pays the decode that pkg/platform/docker/docker.go:61-72 documents as the dominant cost (~60s for an ~80 MB / ~1.1k-mock set on a contended runner).
  2. Two corpus transforms sit between GetMocks and StoreMocks — AfterGetMocks + rebalanceReusableMocks (replay.go:1489-1497), when a MockMutator is registered — no OSS type implements it today, and the in-repo comment points at "the mongo/v2 stable-metadata promotion" (replay.go:1493-1494). Skip them and retagged mocks stay in the per-test pool, where SetMocksWithWindow filters them out: the recovered run serves a strictly smaller corpus than setup did.
  3. BeforeTestSetCompose (replay.go:1387) is agent-side state in the same setup run. On a replacement, any non-default agent.AgentHooks implementation never gets its BeforeTestSetCompose (pkg/service/agent/hooks.go:12-26, invoked at pkg/agent/routes/record.go:168), and — when KEPLOY_DEBUG_FILE is set (record.go:153-166) — the per-test-set debug log never rotates, losing the artifact you'd most want for diagnosing the replacement.
  4. The re-sent UpdateMockParams must carry the setup window — models.BaseTime, time.Now() and firstRecordedTestStart(testCases) (replay.go:1510) — not the per-test time.Time{} used at :2045. A zero FirstRecordedTestStart skips SeedStartupCutoff (pkg/service/agent/agent.go:1035-1038), and the startup cutoff falls back to whichever test fires first.
  5. GetConsumedMocks right after setup (replay.go:1783) returns empty on a replacement, so mappings.yaml's STARTUP section comes out empty for that set — the boot mocks were consumed by the dead agent. Next run, they have no mapping entry.
  6. Under KEPLOY_AGENT_OWNS_CONSUMED (replay.go:3647-3658) the sequence rebuilds nothing — the agent owns consumption history and the CLI sends nil. A recovered run then re-serves already-consumed mocks: a silently wrong pass, worse than the vacuous one. Worth forcing that off on a recovery path, or refusing to recover under it.

The question I'd settle before writing any of it

The app service is wired into the agent container's namespaces — and not just for Java; it's under if isTargetService { (pkg/platform/docker/docker.go:1389):

// pkg/platform/docker/docker.go:1418, :1421
idc.addServiceProperty(serviceContentNode, "pid", fmt.Sprintf("service:%s", "keploy-agent"))
idc.addServiceProperty(serviceContentNode, "network_mode", fmt.Sprintf("service:%s", "keploy-agent"))

condition: service_healthy only gates the app's start. So "the agent container was replaced" and "the app can still reach it" are not independent. In the retry path both are recreated together — the retry tears the whole stack down deliberately (pkg/client/app/app.go:1457 loop → a.ComposeDown() at :1468, "so the retry's up re-creates every service fresh"), which is also why --abort-on-container-exit doesn't narrow this: the agent isn't replaced because it died, it's replaced because the retry removed it. So re-registration is coherent there. But a gate that keys on the mock pool can't tell that case from one where only the agent was replaced, and in the latter, re-arming mocks produces a healthy-looking agent in front of an app that has lost its netns owner — worse than the loud failure. A process nonce plus a container-identity check distinguishes them; a mock count can't.

Related, and I think it's your natural insertion point: the readiness gate that would otherwise notice is skipped for test-sets 2..N under compose reuse — if !serveTest || r.isFirstTestSet at replay.go:1357 guards the AgentHealthTicker at :1365. Whatever you add should not sit inside that condition, or it won't fire on the long-lived-stack runs where a replacement is likeliest.

Three things that will bite during implementation

  • There is no client method for GET /agent/mock/stats. The route exists (pkg/agent/routes/record.go:94) and the service side exists (pkg/service/agent/scope.go:168-172), but nothing in pkg/platform/http/agent.go calls it and it's not on the replay Instrumentation interface. New method + interface entry first.
  • A zero body is ambiguous. HandleMockStats falls through to a 200 with a zero-valued MockStats when the service doesn't implement mockStatsReader (pkg/agent/routes/scope.go:135-146) — so {"loaded":0,"consumed":0,"missed":0} also means "this agent can't report it". Its sibling HandleServedMocks returns 501 for exactly this reason (pkg/agent/routes/scope.go:156-162), and an agent older than the route 404s. Failing a test-set on a bare 0 turns version skew into a red run; the repo's 404-tolerance pattern is at pkg/platform/http/agent.go:1984-1986.
  • The shared agent HTTP client has no timeout — client: http.Client{} (pkg/platform/http/agent.go:83). Several callers wrap their own (MakeAgentReadyForDockerCompose at :2043, the hook calls at :649–:795), but the two that matter here — StoreMocks (:907) and UpdateMockParams (:1005) — inherit only the test-set context. A pre-first-test gate on a wedged rather than dead replacement would hang as long as that context lives, which is worse than what it guards. pkg/service/mock/replay.go:694-699 bounds its poll for this exact reason.

A correction to my own issue

app.go:1567 does not exist — pkg/client/app/app.go is 1564 lines, both on main and at v3.6.67 where I observed it. The discipline I was pointing at is real but lives at app.go:1479-1497: the pre-up guards are ctx-short-circuited before and between each guard, because that goroutine drains under DrainErrGroup's 30s budget while the guards can each wait preRunRemoveBudget (90s). The rule isn't "no long waits" — it's "no wait that can't be cancelled on that path". Sorry for the bad line number.

Defect 2 — what I'd build on

removeStaleComposeAgentWithin (app.go:844-861) is already force-remove-then-wait, in that order, which is what my withdrawn attempt had backwards. Covering the whole project is mostly dropping one argument:

// pkg/client/app/app.go:876 and :880 — both branches identical
args = append(args, "ps", "-aq", keployAgentComposeService)

Two caveats: the force-removes are serial at forceRemoveBudget 2s each (app.go:854-856), and waitContainersRemoved gets the caller's whole budget for the entire list — so a six-service stack needs the app.go:1488-1497 ctx short-circuit or it recreates the drain timeout. Put it on the pre-up guard path (90s budget), not inside ComposeDown, which is already budgeted to ~22.5s of a 30s envelope (app.go:700-708).

On "a surface that survives the App-per-call boundary" — you may not need stored state at all. The compose project is already derivable from objects that outlive App: com.docker.compose.project off the app container (app.go:563, :577), where the container name comes from conf.ContainerName and the docker client hangs off AgentClient (pkg/platform/http/agent.go:52 dockerClient, :55 conf). Label-scoped listing is already done at app.go:519-523. Enumerating at the moment it matters sidesteps trap (a) rather than working around it. The boundary is also crossed more often than I said: pkg.RetryAgentSetup re-runs Setup up to 3 times in-process on ErrAgentNotReady (pkg/util.go:2740, :2752-2754), so a capture on App is wrong there too, not only at the record→auto-replay hop.

For reference, what ComposeDown actually guarantees free is two names — a.forceRemoveContainerByName on the agent and the app (app.go:684-685), reap-waited at :694. Everything else in the project is only ever reached by the 8s down whose errors are swallowed (app.go:627, :665), which is the mechanism in defect 2.

On branching

Your call, but I'd keep them separate and land defect 1 first. Defect 1's fix is worth having on its own — defect 2 is one way to produce the crash, not the only one, and any transient dependency crash during a compose bring-up reproduces defect 1.

Happy to review either branch, and to re-run the reproduction against it.

slayerjain avatar Sep 21 '26 04:09 slayerjain

Thanks - this is the kind of review that saves a week of wrong turns. I re-checked every reference against origin/main before posting: the !serveTest || r.isFirstTestSet guard (replay.go:1357), scoredNothing's all-zero requirement (:207-210), resolveTestSetStatus falling through to ("", false) (:112-127), and the no mocks stored for client ID bail (agent.go:1079-1082) all match.

On #4616 (defect 1): that PR is the retry-path fix exactly - the case your last section calls coherent, where the retry's ComposeDown recreates the whole stack together. Kartik has LGTM'd it; the heavier workflows (Go on Linux/Windows/macOS, golangci-lint, CodeQL, perf) all sit at action_required (fork gate), so a maintainer approval would start them - and I'll take you up on the re-run offer once they do.

On the general gate: agreed on all counts, loaded == 0 is out as the detector:

  • the empty-corpus case is real (:1485-1487 stores the empty pool, finalizeClientMocks on the zero-length stream), and "fail loudly" would turn a healthy configuration red;
  • the stats route needs a client method plus an Instrumentation entry anyway, its zero body is ambiguous against the 501 pattern of its sibling, and it is blind on exactly the zero-mock sets.

The per-process nonce on /agent/health is the right identity signal - nothing parses that body (isAgentHealthy is status-code only, the compose healthcheck reads /tmp/agent.ready), so the shape change is safe, and an agent without the nonce gets the same 404-tolerance handling as the stats route. I would fold in the container-identity check so the gate can tell whole-stack recreation from agent-only replacement, and keep it out of the isFirstTestSet condition so it fires on test-sets 2..N.

The six "don't restore" items are noted as design constraints, not details: corpus scope (:1467 vs :1490), the two corpus transforms, BeforeTestSetCompose and the debug-log rotation, the setup window on the re-sent UpdateMockParams, mappings.yaml's STARTUP section, and KEPLOY_AGENT_OWNS_CONSUMED (force it off on a recovery path or refuse to recover).

On the verdict gap you flagged: with #4613 merged, the no-failure partial run still reading PASSED looks like its own focused fix - a loop that breaks before every selected test ran should not resolve as passed, and the reason should surface. Happy to take that as a separate issue if you would rather keep it out of the #4614 scope.

On branching: agreed, separate and defect 1 first. Defect 2 starts from your notes - generalize removeStaleComposeAgentWithin to the whole project with the :1488-1497 ctx short-circuit on the pre-up guard path, and derive the compose project from the app container label rather than stored state (also because RetryAgentSetup re-runs Setup up to 3x in-process).

And noted on the app.go:1567 correction - the rule is cancellable waits on the drain path, not short waits.

ayam04 avatar Sep 21 '26 10:09 ayam04

Architectural Deep Dive & Two-Phase Solution

This bug is caused by two tightly coupled race conditions in the compose lifecycle on pkg/client/app/app.go:1457:

1. The Agent State Disconnect

When a.ComposeDown() is invoked during a dependency bring-up retry:

  • The keploy-agent container is destroyed along with all memory state (Agent.clientMocks in pkg/service/agent/agent.go:51 and the eBPF network mappings in MockManager).
  • When docker compose up re-spawns keploy-agent, RunTestSet assumes the session is already armed from the initial pre-flight check, so the app runs against an un-initialized proxy that forwards or drops all downstream calls.

2. Async Container Teardown Drain

ComposeDown sends SIGTERM to dependency containers. If a container takes longer than docker's grace timeout to terminate, docker compose up on the immediate retry re-attaches or attempts to bind to ports while the previous container process is still releasing socket descriptors (EADDRINUSE).


Proposed Resolution

// 1. In pkg/client/app/app.go: Refactor bring-up retry to use state-draining restarts
func (a *AppClient) RetryComposeUpWithDrain(ctx context.Context, testSetID string) error {
    // Phase 1: Wait for running/stopping containers to fully exit
    if err := a.waitForContainersToExit(ctx, 10*time.Second); err != nil {
        a.logger.Warn("timeout waiting for previous container descriptors to release", zap.Error(err))
    }

    // Phase 2: Re-issue compose up
    if err := a.ComposeUp(ctx); err != nil {
        return fmt.Errorf("failed to re-issue compose up: %w", err)
    }

    // Phase 3: Re-arm agent session mocks if agent container restarted
    if err := a.reArmSessionMocks(ctx, testSetID); err != nil {
        return fmt.Errorf("failed to re-populate agent mocks after compose retry: %w", err)
    }

    return nil
}

This ensures that:

  1. Sockets and virtual network bridges are completely drained before the retry starts.
  2. The newly booted keploy-agent container is explicitly re-armed with Agent.clientMocks for the current test set before the application is released to execute.

chilkotiKartik avatar Sep 21 '26 12:09 chilkotiKartik

The analysis of the two races matches what I found tracing this, and phase 3 is now redundant in a good way: #4616's guard already re-registers the session's mocks with a replacement agent before any test fires, and #4619 bounded it with the caller's context, re-runs BeforeTestSetCompose on the repair, and carries the consumption history forward. So the state-disconnect half is shipped; what remains of #4614 is the drain half.

For phases 1 and 2, the shape has to clear the four traps recorded in the issue, and a bare waitForContainersToExit does not:

  1. A wait needs a removal in flight. When docker compose down is killed at its budget, nothing is mid-removal for the service it never reached, so waiting for that service changes nothing. A force-remove has to come first, the way removeStaleComposeAgentWithin already does it for the agent name.
  2. The capture cannot live on App: AgentClient.Setup builds a new App per call, so at the record-to-auto-replay boundary the capture would be empty and the guard a no-op. The safe form re-derives the project's containers at the moment of use, through the same compose flags the up/down use (docker compose ... ps -aq, mirroring composeAgentContainerIDs).
  3. No context.Background() waits on the drain path: every call bounded on its own deadline, with ctx short-circuits between calls, exactly like the guards already in the retry loop.

Concretely, what I would ship for the drain: after the retry's ComposeDown, before the next up, force-remove whatever containers the project still has (bounded per call, project resolved the same way the up resolves it), wait until they are gone (bounded), then re-issue up. That gives the retry the clean slate its own comment already promises, without reintroducing the traps.

Happy to implement it in exactly that shape, or to fold in whatever you would change about it first.

ayam04 avatar Sep 22 '26 02:09 ayam04

Verified on current main: both defects from this issue are now shipped, so this one can be closed.

  • Defect 1 (the bring-up retry orphans the agent's mocks): #4616 re-registers the session's mocks with the replacement agent before any test fires, and #4619 bounded the repair with the caller's context and carried the consumption history forward.
  • Defect 2 (the next up reuses a still-stopping container): #4625 (merged 09-22) added sweepStragglingProjectContainers (pkg/client/app/app.go:882) and forceRemoveContainers (:923), and the sweep's ids feed the reap barrier at :799-802 — waitContainersRemoved(append([]string{a.keployContainer, a.container}, stragglers...), reapBarrierBudget). ComposeDown is the same teardown the replay loop calls on a per-test-set setup failure before a retry, so the drain fires on the dependency-retry path, not only at run end. Scoping the sweep to a.composeServices is what keeps a user's own orphan containers out of it.

The one gap left is the one documented in that function rather than fixed: a multi-file command (docker compose -f app.yml -f deps.yml up), where the sweep is exactly down's set and the deps-file containers survive every teardown. Happy to pick that up as a follow-up if you want it filed.

ayam04 avatar Oct 16 '26 03:10 ayam04