From a345a8519721a9ba33eaaa326a8a206a296d8823 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Fri, 18 Sep 2026 23:59:40 +1000 Subject: [PATCH 1/4] fix(webui): retry event pump priming until the state store answers archie-ui binds before archie-state-store is guaranteed to be listening, so the first prime is routinely refused. PumpEvents returned on that error, which left the activity feed history-only for the life of the process. Prime now retries with capped backoff and gives up only when the context ends. Orders archie-ui.service after archie-state-store.service as well, which narrows the window without closing it: After= sequences the start, it does not wait for the listener. --- deployments/systemd-user-service.md | 8 ++++- internal/webui/event_pump.go | 40 ++++++++++++++++++++- internal/webui/event_pump_test.go | 55 +++++++++++++++++++++++++++++ 3 files changed, 101 insertions(+), 2 deletions(-) diff --git a/deployments/systemd-user-service.md b/deployments/systemd-user-service.md index e8e94515b..9e78729ba 100644 --- a/deployments/systemd-user-service.md +++ b/deployments/systemd-user-service.md @@ -97,7 +97,8 @@ the dashboard's health endpoint behind the token. A watchdog can curl ```ini [Unit] Description=Archie UI Service -After=network.target +After=network.target archie-state-store.service +Wants=archie-state-store.service [Service] Type=simple @@ -121,6 +122,11 @@ GATEWAY_TOKEN=... # presented to archie-gateway STATE_STORE_TOKEN=... # presented to archie-state-store ``` +`After=` orders the start, it does not wait for the store to bind. The UI +process closes that gap itself: its event pump retries priming with backoff +until the State Store answers, so the activity feed goes live once the store +is up rather than staying history-only until the next restart. + ```ini ExecStart=%h/.local/bin/archie-ui -config %h/.config/archie/config.toml -token-file %h/.local/share/archie/web-token ``` diff --git a/internal/webui/event_pump.go b/internal/webui/event_pump.go index 3f7d46658..ce3d35600 100644 --- a/internal/webui/event_pump.go +++ b/internal/webui/event_pump.go @@ -22,6 +22,14 @@ const ( eventPumpPageSize = 200 ) +// Backoff bounds for priming. The UI process and the State Store are separate +// units with no ordering between them, so a refused dial at startup is +// ordinary rather than fatal and the pump waits the store out. +const ( + eventPumpPrimeRetryMin = 250 * time.Millisecond + eventPumpPrimeRetryMax = 30 * time.Second +) + // eventPump is the UI process's substitute for the daemon's in-process event // bus. The daemon hands persisted events to Server.Broadcast from its own bus // subscription (internal/app/archied/main.go's persistAndBroadcastEvents); a @@ -42,6 +50,36 @@ type eventPump struct { // watermark is the highest event id already handed to broadcast. It only // ever moves forward, and only past an event that was delivered. watermark int64 + // primeRetryMin is the first backoff between priming attempts. Zero + // means eventPumpPrimeRetryMin; a test sets it small. + primeRetryMin time.Duration +} + +// primeWithRetry primes, retrying with capped exponential backoff until it +// succeeds or ctx ends. Returning on the first error instead left the +// activity feed history-only for the life of the process whenever the UI won +// the startup race against the State Store. +func (p *eventPump) primeWithRetry(ctx context.Context) error { + delay := p.primeRetryMin + if delay <= 0 { + delay = eventPumpPrimeRetryMin + } + for attempt := 1; ; attempt++ { + err := p.prime(ctx) + if err == nil { + return nil + } + if ctx.Err() != nil { + return err + } + p.log("event pump priming failed; retrying", "attempt", attempt, "retry_in", delay, "err", err) + select { + case <-ctx.Done(): + return err + case <-time.After(delay): + } + delay = min(delay*2, eventPumpPrimeRetryMax) + } } // eventReader is the one method the pump needs, so a test can drive it @@ -65,7 +103,7 @@ func (s *Server) PumpEvents(ctx context.Context, interval time.Duration) error { interval = DefaultEventPollInterval } pump := s.newEventPump() - if err := pump.prime(ctx); err != nil { + if err := pump.primeWithRetry(ctx); err != nil { return fmt.Errorf("prime event pump: %w", err) } pump.run(ctx, interval) diff --git a/internal/webui/event_pump_test.go b/internal/webui/event_pump_test.go index 181d01a1d..fcf9812ac 100644 --- a/internal/webui/event_pump_test.go +++ b/internal/webui/event_pump_test.go @@ -3,6 +3,7 @@ package webui import ( "bufio" "context" + "errors" "net/http" "net/http/httptest" "strings" @@ -162,3 +163,57 @@ func openSSEStream(t *testing.T, ctx context.Context, ts *httptest.Server) <-cha }() return lines } + +// flakyEventReader fails its first failures calls, then answers an empty +// table. It stands in for the State Store during the window where the UI +// process is up and the store has not bound its listener yet. +type flakyEventReader struct { + failures int + calls int +} + +func (f *flakyEventReader) EventsSince(context.Context, int64, int) ([]events.Event, error) { + f.calls++ + if f.calls <= f.failures { + return nil, errors.New("connection refused") + } + return nil, nil +} + +// archie-ui binds before archie-state-store is guaranteed to be listening, so +// the first prime is routinely refused. Returning on that error left the +// activity feed history-only until the process was restarted by hand. +func TestPumpPrimingRetriesUntilTheStoreAnswers(t *testing.T) { + reader := &flakyEventReader{failures: 3} + pump := &eventPump{ + store: reader, + log: func(string, ...any) {}, + broadcast: func(events.Event) {}, + primeRetryMin: time.Millisecond, + } + + if err := pump.primeWithRetry(t.Context()); err != nil { + t.Fatalf("primeWithRetry: %v", err) + } + if reader.calls != 4 { + t.Fatalf("EventsSince called %d times, want 4 (3 refusals then success)", reader.calls) + } +} + +// A shutdown during the retry wait must end the pump, not hold the process +// open until the store appears. +func TestPumpPrimingStopsRetryingWhenTheContextEnds(t *testing.T) { + reader := &flakyEventReader{failures: 1 << 30} + pump := &eventPump{ + store: reader, + log: func(string, ...any) {}, + broadcast: func(events.Event) {}, + primeRetryMin: time.Millisecond, + } + + ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond) + defer cancel() + if err := pump.primeWithRetry(ctx); err == nil { + t.Fatal("primeWithRetry returned no error after the context ended") + } +} From 4a566217f96d3db6dc495b5bdddd5bd961f9c21b Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Fri, 18 Sep 2026 23:59:40 +1000 Subject: [PATCH 2/4] fix(container): cancel a container's max-uptime reaper on release The timer stayed armed after Release removed the container, so an hour later it stopped and removed an ID Docker had already forgotten and logged two warnings that read like a failed teardown. --- internal/container/pool.go | 41 +++++++++++++++++++++--- internal/container/pool_test.go | 55 +++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 5 deletions(-) diff --git a/internal/container/pool.go b/internal/container/pool.go index 18d3e583f..3e8ce9b0f 100644 --- a/internal/container/pool.go +++ b/internal/container/pool.go @@ -88,6 +88,9 @@ type Pool struct { mu sync.Mutex active int + // reapers holds the armed max-uptime timer for each live container, + // keyed by ID, so Release can cancel the one it is tearing down. + reapers map[string]*time.Timer } // Config is the subset of daemon container configuration the pool needs. @@ -238,12 +241,13 @@ func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string } // armMaxUptime schedules a hard stop and remove for a container once its -// lifetime cap elapses. The timer is keyed to the container ID and never -// touches p.active: Release (or Close) remains the only owner of the active -// slot. Docker stop and remove are idempotent, so a timer that fires after -// Release has already removed the container only logs a warning. +// lifetime cap elapses. The timer never touches p.active: Release (or Close) +// remains the only owner of the active slot. Release cancels the timer, so a +// container that finished normally is not reaped a second time against an ID +// Docker has already forgotten. func (p *Pool) armMaxUptime(ctx context.Context, id string) { - time.AfterFunc(p.cfg.MaxUptime, func() { + timer := time.AfterFunc(p.cfg.MaxUptime, func() { + p.forgetReaper(id) zero := 0 stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) defer cancel() @@ -254,6 +258,32 @@ func (p *Pool) armMaxUptime(ctx context.Context, id string) { p.log.Warn("max uptime remove failed", "id", id[:12], "err", err) } }) + + p.mu.Lock() + defer p.mu.Unlock() + if p.reapers == nil { + p.reapers = make(map[string]*time.Timer) + } + p.reapers[id] = timer +} + +// cancelMaxUptime disarms a container's reaper, if it has not already fired. +func (p *Pool) cancelMaxUptime(id string) { + p.mu.Lock() + timer := p.reapers[id] + delete(p.reapers, id) + p.mu.Unlock() + if timer != nil { + timer.Stop() + } +} + +// forgetReaper drops a timer's own map entry as it fires, so the map does not +// grow for the life of the pool. +func (p *Pool) forgetReaper(id string) { + p.mu.Lock() + delete(p.reapers, id) + p.mu.Unlock() } // releaseDecision reports how Release should tear a container down: whether @@ -284,6 +314,7 @@ func (p *Pool) Release(ctx context.Context, c *Container) { if c == nil { return } + p.cancelMaxUptime(c.ID) honorGrace, stopTimeout := releaseDecision(ctx, p.cfg.GracePeriod) if honorGrace { p.log.Info("container keeping alive for grace period", "id", c.ID[:12], "grace", p.cfg.GracePeriod) diff --git a/internal/container/pool_test.go b/internal/container/pool_test.go index 645d21114..e31bbb67c 100644 --- a/internal/container/pool_test.go +++ b/internal/container/pool_test.go @@ -367,3 +367,58 @@ func TestAcquireEnforcesMaxUptime(t *testing.T) { t.Fatalf("expected at least one stop and remove, got stop=%d remove=%d", stopCalls.Load(), removeCalls.Load()) } } + +// A released container is already gone, so its max-uptime reaper has nothing +// left to reap. Leaving the timer armed made it fire an hour later against a +// dead ID, logging "max uptime stop failed ... No such container" as though +// teardown had gone wrong. +func TestReleaseCancelsTheMaxUptimeTimer(t *testing.T) { + const containerID = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210" + + var stopCalls, removeCalls atomic.Int32 + dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/containers/create"): + writeDockerJSON(t, w, map[string]any{"Id": containerID, "Warnings": []string{}}) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID+"/start"): + w.WriteHeader(http.StatusNoContent) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID+"/stop"): + stopCalls.Add(1) + w.WriteHeader(http.StatusNoContent) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID): + removeCalls.Add(1) + w.WriteHeader(http.StatusNoContent) + default: + http.Error(w, "unexpected Docker API path "+r.URL.Path, http.StatusNotFound) + } + })) + t.Cleanup(dockerAPI.Close) + + dockerClient, err := client.New(client.WithHost(dockerAPI.URL), client.WithAPIVersion("1.55")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dockerClient.Close() }) + + pool := &Pool{ + cli: dockerClient, + cfg: Config{Image: "test/image", MaxUptime: 60 * time.Millisecond}, + log: discardLogger(), + } + + c, err := pool.Acquire(context.Background(), nil, nil) + if err != nil { + t.Fatalf("Acquire: %v", err) + } + pool.Release(context.Background(), c) + + stopAfterRelease, removeAfterRelease := stopCalls.Load(), removeCalls.Load() + time.Sleep(200 * time.Millisecond) + + if got := stopCalls.Load(); got != stopAfterRelease { + t.Errorf("stop called %d times after Release, want %d: the max uptime timer still fired", got, stopAfterRelease) + } + if got := removeCalls.Load(); got != removeAfterRelease { + t.Errorf("remove called %d times after Release, want %d: the max uptime timer still fired", got, removeAfterRelease) + } +} From fed5bec709bc5237cb61376d6cc5c47e943b2555 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 19 Sep 2026 00:06:26 +1000 Subject: [PATCH 3/4] fix(container): keep the max-uptime cap active during the grace period The reaper was cancelled at the top of Release, before the grace-period sleep, which let a container outlive MaxUptime by GracePeriod. MaxUptime is documented as a cap from creation enforced regardless of task state, and a grace period is task state, so the cancel belongs after the sleep. Also asserts the disarmed reaper directly rather than only inferring it from the absence of later Docker calls. --- internal/container/pool.go | 6 ++- internal/container/pool_test.go | 73 +++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/internal/container/pool.go b/internal/container/pool.go index 3e8ce9b0f..018602bbd 100644 --- a/internal/container/pool.go +++ b/internal/container/pool.go @@ -314,13 +314,17 @@ func (p *Pool) Release(ctx context.Context, c *Container) { if c == nil { return } - p.cancelMaxUptime(c.ID) honorGrace, stopTimeout := releaseDecision(ctx, p.cfg.GracePeriod) if honorGrace { p.log.Info("container keeping alive for grace period", "id", c.ID[:12], "grace", p.cfg.GracePeriod) time.Sleep(p.cfg.GracePeriod) } + // Disarm only now. MaxUptime is a cap from creation enforced regardless of + // task state, so it must still bite during the grace period above; + // cancelling before the sleep would quietly extend the cap by GracePeriod. + p.cancelMaxUptime(c.ID) + // Detach from ctx before stopping. Release runs on the way out of a // task, and the most important reason a task is on its way out is // that it was cancelled -- at which point ctx is already dead, the diff --git a/internal/container/pool_test.go b/internal/container/pool_test.go index e31bbb67c..4bf4f2a27 100644 --- a/internal/container/pool_test.go +++ b/internal/container/pool_test.go @@ -412,6 +412,16 @@ func TestReleaseCancelsTheMaxUptimeTimer(t *testing.T) { } pool.Release(context.Background(), c) + // Deterministic half: the reaper is disarmed and its bookkeeping dropped, + // so nothing is left that could fire. The wait below is the observable + // consequence, not the proof. + pool.mu.Lock() + remaining := len(pool.reapers) + pool.mu.Unlock() + if remaining != 0 { + t.Errorf("pool still holds %d armed reaper(s) after Release, want 0", remaining) + } + stopAfterRelease, removeAfterRelease := stopCalls.Load(), removeCalls.Load() time.Sleep(200 * time.Millisecond) @@ -422,3 +432,66 @@ func TestReleaseCancelsTheMaxUptimeTimer(t *testing.T) { t.Errorf("remove called %d times after Release, want %d: the max uptime timer still fired", got, removeAfterRelease) } } + +// MaxUptime is a hard lifetime cap from creation, enforced "regardless of +// task state" (Config.MaxUptime). A grace period is task state, so a +// container that outlives the cap while waiting out its grace window is still +// reaped: cancelling the reaper before the grace sleep would extend the cap +// by GracePeriod. +func TestGracePeriodDoesNotExtendTheMaxUptimeCap(t *testing.T) { + const containerID = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789" + + stopped := make(chan struct{}, 4) + dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/containers/create"): + writeDockerJSON(t, w, map[string]any{"Id": containerID, "Warnings": []string{}}) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID+"/start"): + w.WriteHeader(http.StatusNoContent) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID+"/stop"): + select { + case stopped <- struct{}{}: + default: + } + w.WriteHeader(http.StatusNoContent) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID): + w.WriteHeader(http.StatusNoContent) + default: + http.Error(w, "unexpected Docker API path "+r.URL.Path, http.StatusNotFound) + } + })) + t.Cleanup(dockerAPI.Close) + + dockerClient, err := client.New(client.WithHost(dockerAPI.URL), client.WithAPIVersion("1.55")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dockerClient.Close() }) + + pool := &Pool{ + cli: dockerClient, + cfg: Config{Image: "test/image", MaxUptime: 30 * time.Millisecond, GracePeriod: 2 * time.Second}, + log: discardLogger(), + } + + c, err := pool.Acquire(context.Background(), nil, nil) + if err != nil { + t.Fatalf("Acquire: %v", err) + } + + released := make(chan struct{}) + go func() { + defer close(released) + pool.Release(context.Background(), c) + }() + + // The cap must bite while Release is still sleeping out the grace period. + select { + case <-stopped: + case <-released: + t.Fatal("Release returned before the max uptime cap fired; the grace period extended the cap") + case <-time.After(time.Second): + t.Fatal("max uptime cap never fired during the grace period") + } + <-released +} From ab8ba79966f4d5e6bd1c54c61362cde4429c4821 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 19 Sep 2026 00:13:36 +1000 Subject: [PATCH 4/4] fix(container): claim container teardown once instead of cancelling a timer Timer.Stop cannot unwind a max-uptime callback that has already begun, so cancelling still let the reaper and Release both stop and remove the same container, which is the duplicate teardown and the misleading 'No such container' warnings this was meant to remove. Teardown is now claimed once per container: whichever of the two gets there first talks to Docker and the loser skips to its own bookkeeping. Release still claims after the grace period, so MaxUptime keeps biting during it. Also table-drives the event pump priming cases, per the repo's test directive. --- internal/container/pool.go | 116 +++++++++++++++++++----------- internal/container/pool_test.go | 67 ++++++++++++++++- internal/webui/event_pump_test.go | 79 ++++++++++++-------- 3 files changed, 191 insertions(+), 71 deletions(-) diff --git a/internal/container/pool.go b/internal/container/pool.go index 018602bbd..0006c58a9 100644 --- a/internal/container/pool.go +++ b/internal/container/pool.go @@ -88,9 +88,9 @@ type Pool struct { mu sync.Mutex active int - // reapers holds the armed max-uptime timer for each live container, - // keyed by ID, so Release can cancel the one it is tearing down. - reapers map[string]*time.Timer + // teardowns holds the one-shot teardown state for each live container, + // keyed by ID. See containerTeardown. + teardowns map[string]*containerTeardown } // Config is the subset of daemon container configuration the pool needs. @@ -240,14 +240,28 @@ func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string return &Container{ID: resp.ID}, nil } +// containerTeardown is the one-shot teardown state for a live container: its +// armed max-uptime reaper, and whether Docker stop/remove has been claimed. +// +// Both the reaper and Release tear a container down, and Timer.Stop cannot +// unwind a callback that has already begun, so cancelling the timer is not +// enough to keep them from overlapping. Claiming decides the winner instead: +// exactly one path talks to Docker, and the loser skips straight to its own +// bookkeeping. +type containerTeardown struct { + timer *time.Timer + closed bool +} + // armMaxUptime schedules a hard stop and remove for a container once its // lifetime cap elapses. The timer never touches p.active: Release (or Close) -// remains the only owner of the active slot. Release cancels the timer, so a -// container that finished normally is not reaped a second time against an ID -// Docker has already forgotten. +// remains the only owner of the active slot. func (p *Pool) armMaxUptime(ctx context.Context, id string) { timer := time.AfterFunc(p.cfg.MaxUptime, func() { - p.forgetReaper(id) + if !p.claimTeardown(id) { + return + } + defer p.forgetTeardown(id) zero := 0 stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) defer cancel() @@ -261,29 +275,46 @@ func (p *Pool) armMaxUptime(ctx context.Context, id string) { p.mu.Lock() defer p.mu.Unlock() - if p.reapers == nil { - p.reapers = make(map[string]*time.Timer) - } - p.reapers[id] = timer + p.teardownLocked(id).timer = timer } -// cancelMaxUptime disarms a container's reaper, if it has not already fired. -func (p *Pool) cancelMaxUptime(id string) { +// claimTeardown reports whether the caller owns this container's Docker +// teardown. The first caller wins; every later one is told to stay out. +func (p *Pool) claimTeardown(id string) bool { p.mu.Lock() - timer := p.reapers[id] - delete(p.reapers, id) + defer p.mu.Unlock() + t := p.teardownLocked(id) + if t.closed { + return false + } + t.closed = true + return true +} + +// forgetTeardown disarms the reaper and drops the container's bookkeeping, so +// the map does not grow for the life of the pool. +func (p *Pool) forgetTeardown(id string) { + p.mu.Lock() + t := p.teardowns[id] + delete(p.teardowns, id) p.mu.Unlock() - if timer != nil { - timer.Stop() + if t != nil && t.timer != nil { + t.timer.Stop() } } -// forgetReaper drops a timer's own map entry as it fires, so the map does not -// grow for the life of the pool. -func (p *Pool) forgetReaper(id string) { - p.mu.Lock() - delete(p.reapers, id) - p.mu.Unlock() +// teardownLocked returns the container's teardown state, creating it on first +// use. Callers must hold p.mu. +func (p *Pool) teardownLocked(id string) *containerTeardown { + if p.teardowns == nil { + p.teardowns = make(map[string]*containerTeardown) + } + t := p.teardowns[id] + if t == nil { + t = &containerTeardown{} + p.teardowns[id] = t + } + return t } // releaseDecision reports how Release should tear a container down: whether @@ -320,26 +351,29 @@ func (p *Pool) Release(ctx context.Context, c *Container) { time.Sleep(p.cfg.GracePeriod) } - // Disarm only now. MaxUptime is a cap from creation enforced regardless of - // task state, so it must still bite during the grace period above; - // cancelling before the sleep would quietly extend the cap by GracePeriod. - p.cancelMaxUptime(c.ID) + // Claim only now. MaxUptime is a cap from creation enforced regardless of + // task state, so the reaper must still be free to bite during the grace + // period above; claiming before the sleep would quietly extend the cap by + // GracePeriod. Losing the claim means the reaper already removed this + // container, so there is nothing left to stop. + if p.claimTeardown(c.ID) { + // Detach from ctx before stopping. Release runs on the way out of a + // task, and the most important reason a task is on its way out is + // that it was cancelled -- at which point ctx is already dead, the + // graceful stop fails immediately, and the container is left to the + // forced remove below. Teardown is cleanup, so it gets its own + // deadline rather than inheriting the caller's cancellation. + stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) + defer cancel() - // Detach from ctx before stopping. Release runs on the way out of a - // task, and the most important reason a task is on its way out is - // that it was cancelled -- at which point ctx is already dead, the - // graceful stop fails immediately, and the container is left to the - // forced remove below. Teardown is cleanup, so it gets its own - // deadline rather than inheriting the caller's cancellation. - stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) - defer cancel() - - if _, err := p.cli.ContainerStop(stopCtx, c.ID, client.ContainerStopOptions{Timeout: stopTimeout}); err != nil { - p.log.Warn("container stop failed", "id", c.ID[:12], "err", err) - } - if _, err := p.cli.ContainerRemove(context.WithoutCancel(ctx), c.ID, client.ContainerRemoveOptions{Force: true}); err != nil { - p.log.Warn("container remove failed", "id", c.ID[:12], "err", err) + if _, err := p.cli.ContainerStop(stopCtx, c.ID, client.ContainerStopOptions{Timeout: stopTimeout}); err != nil { + p.log.Warn("container stop failed", "id", c.ID[:12], "err", err) + } + if _, err := p.cli.ContainerRemove(context.WithoutCancel(ctx), c.ID, client.ContainerRemoveOptions{Force: true}); err != nil { + p.log.Warn("container remove failed", "id", c.ID[:12], "err", err) + } } + p.forgetTeardown(c.ID) p.mu.Lock() p.active-- diff --git a/internal/container/pool_test.go b/internal/container/pool_test.go index 4bf4f2a27..9f4561b12 100644 --- a/internal/container/pool_test.go +++ b/internal/container/pool_test.go @@ -416,10 +416,10 @@ func TestReleaseCancelsTheMaxUptimeTimer(t *testing.T) { // so nothing is left that could fire. The wait below is the observable // consequence, not the proof. pool.mu.Lock() - remaining := len(pool.reapers) + remaining := len(pool.teardowns) pool.mu.Unlock() if remaining != 0 { - t.Errorf("pool still holds %d armed reaper(s) after Release, want 0", remaining) + t.Errorf("pool still holds %d armed teardown entr(ies) after Release, want 0", remaining) } stopAfterRelease, removeAfterRelease := stopCalls.Load(), removeCalls.Load() @@ -495,3 +495,66 @@ func TestGracePeriodDoesNotExtendTheMaxUptimeCap(t *testing.T) { } <-released } + +// Timer.Stop cannot unwind a callback that has already begun, so cancelling +// is not enough on its own: teardown has to be claimed once, by whichever of +// the reaper and Release gets there first. Firing the reaper before Release +// is the deterministic stand-in for the two overlapping. +func TestReleaseAfterTheReaperFiredDoesNotTearDownTwice(t *testing.T) { + const containerID = "0f1e2d3c4b5a69780f1e2d3c4b5a69780f1e2d3c4b5a69780f1e2d3c4b5a6978" + + var stopCalls, removeCalls atomic.Int32 + reaped := make(chan struct{}, 1) + dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/containers/create"): + writeDockerJSON(t, w, map[string]any{"Id": containerID, "Warnings": []string{}}) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID+"/start"): + w.WriteHeader(http.StatusNoContent) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID+"/stop"): + stopCalls.Add(1) + w.WriteHeader(http.StatusNoContent) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID): + removeCalls.Add(1) + select { + case reaped <- struct{}{}: + default: + } + w.WriteHeader(http.StatusNoContent) + default: + http.Error(w, "unexpected Docker API path "+r.URL.Path, http.StatusNotFound) + } + })) + t.Cleanup(dockerAPI.Close) + + dockerClient, err := client.New(client.WithHost(dockerAPI.URL), client.WithAPIVersion("1.55")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dockerClient.Close() }) + + pool := &Pool{ + cli: dockerClient, + cfg: Config{Image: "test/image", MaxUptime: 20 * time.Millisecond}, + log: discardLogger(), + } + + c, err := pool.Acquire(context.Background(), nil, nil) + if err != nil { + t.Fatalf("Acquire: %v", err) + } + + select { + case <-reaped: + case <-time.After(2 * time.Second): + t.Fatal("max uptime reaper never ran") + } + pool.Release(context.Background(), c) + + if got := stopCalls.Load(); got != 1 { + t.Errorf("stop called %d times, want 1: the reaper and Release both tore the container down", got) + } + if got := removeCalls.Load(); got != 1 { + t.Errorf("remove called %d times, want 1: the reaper and Release both tore the container down", got) + } +} diff --git a/internal/webui/event_pump_test.go b/internal/webui/event_pump_test.go index fcf9812ac..29f2d4712 100644 --- a/internal/webui/event_pump_test.go +++ b/internal/webui/event_pump_test.go @@ -183,37 +183,60 @@ func (f *flakyEventReader) EventsSince(context.Context, int64, int) ([]events.Ev // archie-ui binds before archie-state-store is guaranteed to be listening, so // the first prime is routinely refused. Returning on that error left the // activity feed history-only until the process was restarted by hand. -func TestPumpPrimingRetriesUntilTheStoreAnswers(t *testing.T) { - reader := &flakyEventReader{failures: 3} - pump := &eventPump{ - store: reader, - log: func(string, ...any) {}, - broadcast: func(events.Event) {}, - primeRetryMin: time.Millisecond, +func TestPumpPriming(t *testing.T) { + forever := 1 << 30 + + tests := []struct { + name string + // failures is how many EventsSince calls are refused before the + // store starts answering. + failures int + // deadline bounds the prime; zero means the test's own context, so + // priming runs until it succeeds. + deadline time.Duration + wantErr bool + wantCalls int // 0 means "unbounded, do not assert" + }{ + { + name: "retries until the store answers", + failures: 3, + wantCalls: 4, + }, + { + name: "gives up when the context ends", + failures: forever, + deadline: 20 * time.Millisecond, + wantErr: true, + }, } - if err := pump.primeWithRetry(t.Context()); err != nil { - t.Fatalf("primeWithRetry: %v", err) - } - if reader.calls != 4 { - t.Fatalf("EventsSince called %d times, want 4 (3 refusals then success)", reader.calls) - } -} + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + reader := &flakyEventReader{failures: tc.failures} + pump := &eventPump{ + store: reader, + log: func(string, ...any) {}, + broadcast: func(events.Event) {}, + primeRetryMin: time.Millisecond, + } -// A shutdown during the retry wait must end the pump, not hold the process -// open until the store appears. -func TestPumpPrimingStopsRetryingWhenTheContextEnds(t *testing.T) { - reader := &flakyEventReader{failures: 1 << 30} - pump := &eventPump{ - store: reader, - log: func(string, ...any) {}, - broadcast: func(events.Event) {}, - primeRetryMin: time.Millisecond, - } + ctx := t.Context() + if tc.deadline > 0 { + timed, cancel := context.WithTimeout(ctx, tc.deadline) + defer cancel() + ctx = timed + } - ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond) - defer cancel() - if err := pump.primeWithRetry(ctx); err == nil { - t.Fatal("primeWithRetry returned no error after the context ended") + err := pump.primeWithRetry(ctx) + if tc.wantErr && err == nil { + t.Fatal("primeWithRetry returned no error") + } + if !tc.wantErr && err != nil { + t.Fatalf("primeWithRetry: %v", err) + } + if tc.wantCalls > 0 && reader.calls != tc.wantCalls { + t.Fatalf("EventsSince called %d times, want %d", reader.calls, tc.wantCalls) + } + }) } }