carlos / platform Public

edge: a static site's version swap sweeps the trees nothing serves

Every version of a static site a box served stayed extracted forever:
annie-welding held 51 copies of the apt site, 20 GB of 59 (2026-10-25),
and each apt version carries the whole pool, so each was bigger. A swap
now sweeps the app's cache directory, keeping the current link's tree,
every tree a handler in this process serves (channels of one app share
the directory), the tree just replaced (requests in flight), anything
changed in the last hour (another process may have just extracted it),
and dot-named extractions in progress. It runs off the request. Nothing
it removes is lost: a handler whose served tree has gone from disk
extracts it again at its next check (ensureExtracted verifies and
re-extracts from the signed release).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 86655c500920ca5041fe16b9d37768061ebb6de1 parent 9623e47
3 files changed, +268 −1
  • internal/edge/static.go +8 −1
  • internal/edge/static_sweep.go +105 −0
  • internal/edge/static_sweep_test.go +155 −0
diff --git a/internal/edge/static.go b/internal/edge/static.go
index 2f2fd0907..5350a7462 100644
--- a/internal/edge/static.go
+++ b/internal/edge/static.go
@@ -252,7 +252,9 @@ func (s *staticSite) currentDir(ctx context.Context) (servedTree, error) {
if err := s.ratchet.Admit(s.acct, cp); err != nil {
return s.stale(err)
}
- if want := cp.Digest; cp.Version != s.version || (want != "" && want != s.digest) {
+ if want := cp.Digest; cp.Version != s.version || (want != "" && want != s.digest) || s.treeMissing() {
+ // treeMissing: the served tree went from disk (another process's
+ // sweep, a hand cleanup); ensureExtracted brings it back.
name, digest, err := s.ensureExtracted(ctx, cp.Version, want)
if err != nil {
return s.stale(fmt.Errorf("stage %s: %w", cp.Version, err))
@@ -260,8 +262,13 @@ func (s *staticSite) currentDir(ctx context.Context) (servedTree, error) {
if err := s.pointCurrent(name); err != nil {
return s.stale(fmt.Errorf("swap current -> %s: %w", name, err))
}
+ replaced := s.name
s.version, s.digest, s.name = cp.Version, digest, name
s.redirects = s.loadRedirects(s.dir(name), cp.Version)
+ s.noteServing(name)
+ if replaced != name {
+ s.sweepTrees(replaced)
+ }
}
s.checkedAt = time.Now()
return s.served(), nil
diff --git a/internal/edge/static_sweep.go b/internal/edge/static_sweep.go
new file mode 100644
index 000000000..8b19321c5
--- /dev/null
+++ b/internal/edge/static_sweep.go
@@ -0,0 +1,105 @@
+package edge
+
+import (
+ "log"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Every version of a static site a box ever served used to stay extracted
+// under its app's cache directory: annie-welding held 51 copies of the apt
+// site, 20 GB of a 59 GB disk (2026-10-25), and each apt version carries the
+// whole package pool, so each new one was bigger. A version swap now sweeps
+// the app's directory (sweepTrees). Nothing it removes is lost: a tree is a
+// cache of a signed release, and ensureExtracted fetches, verifies and
+// extracts it again if a pointer ever names it.
+
+// staticSweepGrace keeps any tree changed this recently: another process
+// (an edge restarting beside this one) may have just extracted it.
+var staticSweepGrace = time.Hour
+
+// staticSweepSync runs the sweep inline (tests only); in production it runs
+// off the request, since removing a large tree takes seconds.
+var staticSweepSync bool
+
+// staticServing is every tree a handler in this process serves, by app
+// directory and handler: handlers for different channels of one app share
+// the directory, and one channel's sweep must not remove another's tree. A
+// handler that is dropped keeps its entry, which only keeps a tree longer.
+var staticServing = struct {
+ sync.Mutex
+ m map[string]map[*staticSite]string
+}{m: map[string]map[*staticSite]string{}}
+
+func (s *staticSite) noteServing(name string) {
+ staticServing.Lock()
+ defer staticServing.Unlock()
+ dir := s.appDir()
+ if staticServing.m[dir] == nil {
+ staticServing.m[dir] = map[*staticSite]string{}
+ }
+ staticServing.m[dir][s] = name
+}
+
+// sweepTrees removes the trees in this app's directory that nothing needs:
+// every tree is kept that the current link names, that any handler here
+// serves, that this handler just replaced (requests may still be reading
+// it), or that changed within staticSweepGrace. Dot-named entries are
+// extractions in progress and are never touched, nor is anything that is
+// not a plain directory.
+func (s *staticSite) sweepTrees(replaced string) {
+ dir := s.appDir()
+ keep := map[string]bool{replaced: true}
+ if cur, err := os.Readlink(filepath.Join(dir, "current")); err == nil {
+ keep[cur] = true
+ }
+ staticServing.Lock()
+ for _, name := range staticServing.m[dir] {
+ keep[name] = true
+ }
+ staticServing.Unlock()
+ sweep := func() {
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return
+ }
+ removed := 0
+ for _, e := range entries {
+ name := e.Name()
+ if keep[name] || strings.HasPrefix(name, ".") || name == "current" {
+ continue
+ }
+ path := filepath.Join(dir, name)
+ fi, err := os.Lstat(path)
+ if err != nil || !fi.IsDir() || time.Since(fi.ModTime()) < staticSweepGrace {
+ continue
+ }
+ if err := os.RemoveAll(path); err != nil {
+ log.Printf("edge: static %s/%s: sweep %s: %v", s.app, s.channel, name, err)
+ continue
+ }
+ removed++
+ }
+ if removed > 0 {
+ log.Printf("edge: static %s/%s: swept %d tree(s) nothing serves", s.app, s.channel, removed)
+ }
+ }
+ if staticSweepSync {
+ sweep()
+ return
+ }
+ go sweep()
+}
+
+// treeMissing reports whether the tree this handler serves has gone from
+// disk (swept by another process, or removed by hand).
+func (s *staticSite) treeMissing() bool {
+ if s.name == "" {
+ return false
+ }
+ _, err := os.Stat(s.dir(s.name))
+ return os.IsNotExist(err)
+}
diff --git a/internal/edge/static_sweep_test.go b/internal/edge/static_sweep_test.go
new file mode 100644
index 000000000..d451b1406
--- /dev/null
+++ b/internal/edge/static_sweep_test.go
@@ -0,0 +1,155 @@
+package edge
+
+import (
+ "context"
+ "crypto/ed25519"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// noGrace makes every extracted tree old enough to sweep, and waits for a
+// swap's sweep to finish before a test looks at the disk.
+func noGrace(t *testing.T) {
+ t.Helper()
+ old := staticSweepGrace
+ staticSweepGrace = 0
+ staticSweepSync = true
+ t.Cleanup(func() { staticSweepGrace, staticSweepSync = old, false })
+}
+
+func treesIn(t *testing.T, appDir string) []string {
+ t.Helper()
+ entries, err := os.ReadDir(appDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var names []string
+ for _, e := range entries {
+ if e.IsDir() {
+ names = append(names, strings.SplitN(e.Name(), "@", 2)[0])
+ }
+ }
+ sort.Strings(names)
+ return names
+}
+
+func sweepFixture(t *testing.T) (release.Store, func(string), *staticSite, *httptest.Server) {
+ store, promote, h, srv, _, _ := sweepFixtureKeys(t)
+ return store, promote, h, srv
+}
+
+func sweepFixtureKeys(t *testing.T) (release.Store, func(string), *staticSite, *httptest.Server, ed25519.PrivateKey, ed25519.PublicKey) {
+ t.Helper()
+ store := release.NewDirStore(filepath.Join(t.TempDir(), "store"))
+ priv, pub := testKeys(t)
+ promote := func(v string) {
+ shipSite(t, store, "site", v, map[string]string{"index.html": "home " + v})
+ if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "canary/x", v); err != nil {
+ t.Fatal(err)
+ }
+ }
+ promote("v1")
+ rt := registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"}
+ h := newStaticHandler(rt, store, pub, filepath.Join(t.TempDir(), "cache")).(*staticSite)
+ h.recheck = 0
+ srv := httptest.NewServer(h)
+ t.Cleanup(srv.Close)
+ return store, promote, h, srv, priv, pub
+}
+
+// Extracted versions used to stay on the box forever: annie-welding held 51
+// copies of the apt site, 20 GB (2026-10-25). A swap now removes the trees
+// nothing serves, keeping the new one and the one it replaced (requests
+// still in flight on it).
+func TestStaticSwapSweepsTreesNothingServes(t *testing.T) {
+ noGrace(t)
+ _, promote, h, srv := sweepFixture(t)
+ for _, v := range []string{"v1", "v2", "v3", "v4"} {
+ if v != "v1" {
+ promote(v)
+ }
+ if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != 200 || body != "home "+v {
+ t.Fatalf("GET / on %s = %d %q", v, code, body)
+ }
+ }
+ if got := treesIn(t, h.appDir()); strings.Join(got, ",") != "v3,v4" {
+ t.Fatalf("trees = %v, want the served v4 and the replaced v3", got)
+ }
+}
+
+// Two channels of one app share the app's directory: one channel's swap
+// never removes the tree the other is serving.
+func TestStaticSweepKeepsWhatAnotherChannelServes(t *testing.T) {
+ noGrace(t)
+ store, promote, h, srv, priv, pub := sweepFixtureKeys(t)
+ // A second handler, another channel, the same app and cache dir, serving v1.
+ if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "stable", "v1"); err != nil {
+ t.Fatal(err)
+ }
+ rt2 := registry.Route{Host: "stable.example.com", Kind: "static", App: "site", Channel: "stable", Status: "ready"}
+ h2 := newStaticHandler(rt2, store, pub, h.cacheDir).(*staticSite)
+ h2.recheck = 0
+ srv2 := httptest.NewServer(h2)
+ t.Cleanup(srv2.Close)
+ if code, body := getPath(t, srv2.URL, "stable.example.com", "/"); code != 200 || body != "home v1" {
+ t.Fatalf("stable GET / = %d %q", code, body)
+ }
+ for _, v := range []string{"v2", "v3", "v4"} {
+ promote(v)
+ getPath(t, srv.URL, "site.example.com", "/")
+ }
+ if code, body := getPath(t, srv2.URL, "stable.example.com", "/"); code != 200 || body != "home v1" {
+ t.Fatalf("stable GET / after canary's sweeps = %d %q, want its v1 still served", code, body)
+ }
+ if got := strings.Join(treesIn(t, h.appDir()), ","); !strings.Contains(got, "v1") {
+ t.Fatalf("trees = %s: the other channel's v1 was swept", got)
+ }
+}
+
+// A tree that went missing (swept by another process, removed by hand) is
+// extracted again at the next check, never served as a 404.
+func TestStaticServedTreeThatWentMissingIsExtractedAgain(t *testing.T) {
+ _, _, h, srv := sweepFixture(t)
+ if code, _ := getPath(t, srv.URL, "site.example.com", "/"); code != 200 {
+ t.Fatalf("first GET / = %d", code)
+ }
+ if err := os.RemoveAll(h.dir(h.name)); err != nil {
+ t.Fatal(err)
+ }
+ if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != 200 || body != "home v1" {
+ t.Fatalf("GET / after its tree went = %d %q, want it extracted again", code, body)
+ }
+}
+
+// Within the grace a tree is kept: another process may have just
+// extracted it. A temp extraction (dot-named) and the current link are
+// never touched.
+func TestStaticSweepKeepsRecentTreesAndTemps(t *testing.T) {
+ staticSweepSync = true
+ t.Cleanup(func() { staticSweepSync = false })
+ _, promote, h, srv := sweepFixture(t)
+ getPath(t, srv.URL, "site.example.com", "/")
+ tmp := filepath.Join(h.appDir(), ".extract-123")
+ if err := os.MkdirAll(tmp, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ old := time.Now().Add(-48 * time.Hour)
+ if err := os.Chtimes(tmp, old, old); err != nil {
+ t.Fatal(err)
+ }
+ promote("v2")
+ getPath(t, srv.URL, "site.example.com", "/")
+ promote("v3")
+ getPath(t, srv.URL, "site.example.com", "/")
+ if got := strings.Join(treesIn(t, h.appDir()), ","); got != ".extract-123,v1,v2,v3" {
+ t.Fatalf("trees = %s, want every tree kept inside the grace, and the temp", got)
+ }
+}