feat: persistent volumes with TTL for container/worktree storage (archie-core-j7v)

Add [containers].volume_ttl (default 72h). Persistent-storage repos get a
per-repo bare Git cache (--reference-if-able --dissociate) so task
worktrees clone fast without repeated full network clones, while staying
fully independent of the cache's lifecycle — cache expiry can never
corrupt an active or parked task's worktree. Docker repo volumes are
labeled as Archie-owned and swept non-forced (a volume still attached to a
running container survives and retries next cycle); the repo cache
directory is swept by mtime. Both cleanups run at daemon startup and each
poll cycle.

Filed archie-core-756 (repo-wide golangci-lint baseline) and archie-core-340
(intermittent JetStream TempDir teardown flake) as separate follow-ups
rather than scope-creeping them into this change.
This commit is contained in:
sam committed 2026-07-24 10:22:11 +10:00
1 parent 827c108401
commit e4368f70af
15 files changed
+562 -29

No files matched your search

+61 -3
View File
@@ -30,9 +30,11 @@ package storage
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/moby/moby/api/types/mount"
"github.com/moby/moby/client"
@@ -76,6 +78,9 @@ type Backend interface {
Setup(ctx context.Context, task TaskRef) ([]Mount, error)
// Teardown cleans up ephemeral storage. Cache volumes survive.
Teardown(ctx context.Context, task TaskRef) error
// CleanupExpired removes persistent per-repo storage older than ttl.
// Shared ecosystem caches and storage not owned by Archie survive.
CleanupExpired(ctx context.Context, ttl time.Duration) (int, error)
}
// ── cache mounts per ecosystem ─────────────────────────────────────────
@@ -155,8 +160,15 @@ func (e *ErrVolumeCreate) Unwrap() error { return e.Cause }
// DockerBackend implements Backend for Docker via the moby client.
type DockerBackend struct {
cli *client.Client
now func() time.Time
}
const (
storageLabel = "com.samcharles93.archie.storage"
storageKindRepo = "repo"
storageKindCache = "cache"
)
// NewDockerBackend creates a Docker storage backend.
func NewDockerBackend(cli *client.Client) *DockerBackend {
return &DockerBackend{cli: cli}
@@ -170,7 +182,7 @@ func NewDockerBackend(cli *client.Client) *DockerBackend {
// creating a volume. The returned mounts will fail at container create
// time if Docker cannot find the volume. Production code always sets
// cli via NewDockerBackend.
func (d *DockerBackend) ensureVolume(ctx context.Context, name string) error {
func (d *DockerBackend) ensureVolume(ctx context.Context, name string, labels map[string]string) error {
if d.cli == nil {
return nil // nil client for testing — volumes must be pre-created
}
@@ -183,6 +195,7 @@ func (d *DockerBackend) ensureVolume(ctx context.Context, name string) error {
_, err = d.cli.VolumeCreate(ctx, client.VolumeCreateOptions{
Name: name,
Driver: "local",
Labels: labels,
})
if err != nil {
// TOCTOU: a concurrent caller may have created the volume between
@@ -217,7 +230,7 @@ func (d *DockerBackend) Setup(ctx context.Context, task TaskRef) ([]Mount, error
// Per-repo persistent volume.
if task.PersistentStorage && task.Owner != "" && task.Repo != "" {
volName := repoVolumeName(task.Owner, task.Repo)
if err := d.ensureVolume(ctx, volName); err != nil {
if err := d.ensureVolume(ctx, volName, map[string]string{storageLabel: storageKindRepo}); err != nil {
return nil, err
}
mounts = append(mounts, Mount{
@@ -229,7 +242,7 @@ func (d *DockerBackend) Setup(ctx context.Context, task TaskRef) ([]Mount, error
caches := cacheMounts(task.Ecosystem)
for _, m := range caches {
if err := d.ensureVolume(ctx, m.Source); err != nil {
if err := d.ensureVolume(ctx, m.Source, map[string]string{storageLabel: storageKindCache}); err != nil {
return nil, err
}
}
@@ -244,6 +257,51 @@ func (d *DockerBackend) Teardown(ctx context.Context, task TaskRef) error {
return nil
}
// CleanupExpired removes Archie-owned per-repo volumes whose creation time is
// at least ttl old. Docker volume labels are immutable, so the TTL is a hard
// maximum age rather than an idle lease. Removal is non-forced: a volume still
// attached to a running container is retained and retried on the next sweep.
func (d *DockerBackend) CleanupExpired(ctx context.Context, ttl time.Duration) (int, error) {
if d.cli == nil || ttl <= 0 {
return 0, nil
}
result, err := d.cli.VolumeList(ctx, client.VolumeListOptions{
Filters: client.Filters{}.Add("label", storageLabel+"="+storageKindRepo),
})
if err != nil {
return 0, fmt.Errorf("list persistent volumes: %w", err)
}
now := time.Now()
if d.now != nil {
now = d.now()
}
var (
removed int
errs []error
)
for _, vol := range result.Items {
// Defend against Docker implementations that ignore label filters.
if vol.Labels[storageLabel] != storageKindRepo {
continue
}
created, err := time.Parse(time.RFC3339Nano, vol.CreatedAt)
if err != nil {
errs = append(errs, fmt.Errorf("persistent volume %s created_at %q: %w", vol.Name, vol.CreatedAt, err))
continue
}
if now.Sub(created) < ttl {
continue
}
if _, err := d.cli.VolumeRemove(ctx, vol.Name, client.VolumeRemoveOptions{}); err != nil {
errs = append(errs, fmt.Errorf("remove persistent volume %s: %w", vol.Name, err))
continue
}
removed++
}
return removed, errors.Join(errs...)
}
// ConvertMounts converts []Mount to moby mount.Mount for container creation.
func ConvertMounts(mounts []Mount) []mount.Mount {
out := make([]mount.Mount, len(mounts))
+150 -1
View File
@@ -2,10 +2,19 @@ package storage
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"slices"
"sort"
"strings"
"testing"
"time"
"github.com/moby/moby/api/types/volume"
"github.com/moby/moby/client"
)
// ── interface contract ───────────────────────────────────────────────
@@ -370,6 +379,98 @@ func TestRepoVolumeName(t *testing.T) {
}
}
func TestDockerBackendLabelsPersistentRepoVolumes(t *testing.T) {
var createBody string
cli := dockerTestClient(t, func(req *http.Request) (*http.Response, error) {
path := dockerAPIPath(req.URL.Path)
switch {
case req.Method == http.MethodGet:
return dockerResponse(http.StatusNotFound, `{"message":"not found"}`), nil
case req.Method == http.MethodPost && path == "/volumes/create":
data, readErr := io.ReadAll(req.Body)
if readErr != nil {
return nil, readErr
}
createBody = string(data)
return dockerResponse(http.StatusCreated, `{"Name":"archie-repo-alice-demo","Driver":"local","Labels":{}}`), nil
default:
return dockerResponse(http.StatusNotFound, `{"message":"unexpected request"}`), nil
}
})
backend := NewDockerBackend(cli)
if _, err := backend.Setup(context.Background(), TaskRef{
WorktreeDir: t.TempDir(),
Ecosystem: "custom",
PersistentStorage: true,
Owner: "alice",
Repo: "demo",
}); err != nil {
t.Fatal(err)
}
if !strings.Contains(createBody, `"com.samcharles93.archie.storage":"repo"`) {
t.Fatalf("persistent volume create body lacks Archie repo label: %s", createBody)
}
}
func TestDockerBackendCleanupExpiredOnlyRemovesOwnedRepoVolumes(t *testing.T) {
now := time.Date(2026, 7, 24, 12, 0, 0, 0, time.UTC)
listBody, err := json.Marshal(volume.ListResponse{Volumes: []volume.Volume{
{
Name: "archie-repo-old",
CreatedAt: now.Add(-25 * time.Hour).Format(time.RFC3339Nano),
Labels: map[string]string{"com.samcharles93.archie.storage": "repo"},
},
{
Name: "archie-repo-fresh",
CreatedAt: now.Add(-23 * time.Hour).Format(time.RFC3339Nano),
Labels: map[string]string{"com.samcharles93.archie.storage": "repo"},
},
{
Name: "archie-cache-old",
CreatedAt: now.Add(-100 * time.Hour).Format(time.RFC3339Nano),
Labels: map[string]string{"com.samcharles93.archie.storage": "cache"},
},
{
Name: "operator-volume",
CreatedAt: now.Add(-100 * time.Hour).Format(time.RFC3339Nano),
},
}})
if err != nil {
t.Fatal(err)
}
var removed []string
cli := dockerTestClient(t, func(req *http.Request) (*http.Response, error) {
path := dockerAPIPath(req.URL.Path)
switch req.Method {
case http.MethodGet:
if !strings.Contains(req.URL.Query().Get("filters"), "com.samcharles93.archie.storage") {
t.Errorf("volume list did not filter by Archie ownership: %s", req.URL.RawQuery)
}
return dockerResponse(http.StatusOK, string(listBody)), nil
case http.MethodDelete:
removed = append(removed, strings.TrimPrefix(path, "/volumes/"))
return dockerResponse(http.StatusNoContent, ""), nil
default:
return dockerResponse(http.StatusNotFound, `{"message":"unexpected request"}`), nil
}
})
backend := NewDockerBackend(cli)
backend.now = func() time.Time { return now }
count, err := backend.CleanupExpired(context.Background(), 24*time.Hour)
if err != nil {
t.Fatal(err)
}
if count != 1 {
t.Fatalf("CleanupExpired count = %d, want 1", count)
}
if !slices.Equal(removed, []string{"archie-repo-old"}) {
t.Fatalf("removed volumes = %v, want only expired owned repo volume", removed)
}
}
func TestCacheMountsForTypeScript(t *testing.T) {
// S4: typescript ecosystem must share node + pnpm cache volumes.
mounts := cacheMounts("typescript")
@@ -419,7 +520,7 @@ func TestEnsureVolumeAlreadyExistsIsNotError(t *testing.T) {
// something OTHER than "already exists". For now, verify that
// ensureVolume with nil client returns nil (existing behavior).
backend := &DockerBackend{}
err := backend.ensureVolume(context.Background(), "test-volume")
err := backend.ensureVolume(context.Background(), "test-volume", nil)
if err != nil {
t.Error("ensureVolume with nil client should not error:", err)
}
@@ -438,3 +539,51 @@ func mountDestinations(mounts []Mount) []string {
func contains(slice []string, s string) bool {
return slices.Contains(slice, s)
}
func dockerResponse(status int, body string) *http.Response {
return &http.Response{
StatusCode: status,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(body)),
}
}
func dockerTestClient(t *testing.T, roundTrip func(*http.Request) (*http.Response, error)) *client.Client {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
resp, err := roundTrip(req)
if err != nil {
t.Errorf("Docker test handler: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for key, values := range resp.Header {
for _, value := range values {
w.Header().Add(key, value)
}
}
w.WriteHeader(resp.StatusCode)
if _, err := io.Copy(w, resp.Body); err != nil {
t.Errorf("Docker test response write: %v", err)
}
}))
t.Cleanup(srv.Close)
cli, err := client.New(
client.WithHost(srv.URL),
client.WithHTTPClient(srv.Client()),
client.WithAPIVersion("1.55"),
)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = cli.Close() })
return cli
}
func dockerAPIPath(path string) string {
if strings.HasPrefix(path, "/v1.55/") {
return strings.TrimPrefix(path, "/v1.55")
}
return path
}