fix(container): enforce MaxUptime lifetime cap with a timer

WIRE: Config.MaxUptime and Acquire documented a hard container lifetime cap
(PRD section 4), but the code only wrapped ContainerCreate/ContainerStart in
a MaxUptime deadline that was cancelled when Acquire returned, so no running
container was ever killed. Wire the documented cap with a per-container
timer that stops and removes the container once the cap elapses.
This commit is contained in:
sam committed 2026-09-15 13:33:48 +10:00
1 parent a0dd21273b
commit 7c5b81fd53
2 files changed
+103 -9

No files matched your search

+26 -9
View File
@@ -174,8 +174,9 @@ func NewPool(ctx context.Context, cfg Config, log *slog.Logger) (*Pool, error) {
// Acquire creates and starts a container with the given mounts and
// environment variables. Mounts are provided by the caller (typically
// from a storage.Backend). If MaxUptime is set, the container is
// created with a deadline -- Docker kills it when the time elapses.
// from a storage.Backend). If MaxUptime is set, the pool schedules a hard
// stop and remove of the container once that lifetime cap elapses,
// regardless of task state.
func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string) (*Container, error) {
p.mu.Lock()
if p.cfg.MaxConcurrency > 0 && p.active >= p.cfg.MaxConcurrency {
@@ -185,13 +186,6 @@ func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string
p.active++
p.mu.Unlock()
// Enforce MaxUptime via container-level timeout.
if p.cfg.MaxUptime > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, p.cfg.MaxUptime)
defer cancel()
}
name := fmt.Sprintf("archie-agent-%d", time.Now().UnixNano())
hostConfig := &container.HostConfig{
@@ -235,10 +229,33 @@ func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string
return nil, fmt.Errorf("container start: %w", err)
}
if p.cfg.MaxUptime > 0 {
p.armMaxUptime(ctx, resp.ID)
}
p.log.Info("container started", "id", resp.ID[:12], "name", name)
return &Container{ID: resp.ID}, nil
}
// 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.
func (p *Pool) armMaxUptime(ctx context.Context, id string) {
time.AfterFunc(p.cfg.MaxUptime, func() {
zero := 0
stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
if _, err := p.cli.ContainerStop(stopCtx, id, client.ContainerStopOptions{Timeout: &zero}); err != nil {
p.log.Warn("max uptime stop failed", "id", id[:12], "err", err)
}
if _, err := p.cli.ContainerRemove(context.WithoutCancel(ctx), id, client.ContainerRemoveOptions{Force: true}); err != nil {
p.log.Warn("max uptime remove failed", "id", id[:12], "err", err)
}
})
}
// releaseDecision reports how Release should tear a container down: whether
// to honour the configured post-completion grace period, and what Docker
// stop timeout to request (nil means the container's configured timeout or
+77
View File
@@ -3,10 +3,16 @@ package container
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/moby/moby/client"
)
// ── regression: Gap 2 -- post-completion grace period ────────────────
@@ -290,3 +296,74 @@ func TestWriteTaskJSONMinimalPayload(t *testing.T) {
t.Error("minimal payload ID mismatch")
}
}
// TestAcquireEnforcesMaxUptime pins the MaxUptime lifetime cap: a container
// acquired with MaxUptime > 0 must be stopped and removed once that cap
// elapses, independent of any later Release call.
func TestAcquireEnforcesMaxUptime(t *testing.T) {
const containerID = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
var stopCalls, removeCalls atomic.Int32
stopped := make(chan struct{}, 1)
removed := 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)
select {
case stopped <- struct{}{}:
default:
}
w.WriteHeader(http.StatusNoContent)
case strings.HasSuffix(r.URL.Path, "/containers/"+containerID):
removeCalls.Add(1)
select {
case removed <- 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: 50 * time.Millisecond},
log: discardLogger(),
}
c, err := pool.Acquire(context.Background(), nil, nil)
if err != nil {
t.Fatalf("Acquire: %v", err)
}
if c.ID != containerID {
t.Fatalf("Acquire returned container ID %q, want %q", c.ID, containerID)
}
select {
case <-stopped:
case <-time.After(2 * time.Second):
t.Fatal("max uptime timer did not stop the container")
}
select {
case <-removed:
case <-time.After(2 * time.Second):
t.Fatal("max uptime timer did not remove the container")
}
if stopCalls.Load() == 0 || removeCalls.Load() == 0 {
t.Fatalf("expected at least one stop and remove, got stop=%d remove=%d", stopCalls.Load(), removeCalls.Load())
}
}