carlos / platform Public

edge: sweep the static cache while running, not only at start

claude pushed by paul@keymail.dev 00910e3f4ba77455db91fd9023d87ad04c239154 parent 326d467
7 files changed, +706 −99
  • internal/edge/edge.go +15 −3
  • internal/edge/static.go +19 −0
  • internal/edge/static_periodic_sweep_test.go +239 −0
  • internal/edge/static_sweep_other.go +13 −3
  • internal/edge/static_sweep_test.go +18 −10
  • internal/edge/static_sweep_unix.go +160 −83
  • internal/edge/static_trees.go +242 −0
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 127dac2c5..218b7d576 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -206,8 +206,10 @@ type Edge struct {
// routes are served from instead of staticStore. See localstatic.go.
localStaticRoot string
// staticLock is this process's shared hold on the static cache
- // (sweepStaticCache): a starting edge sweeps only when it is alone.
+ // (sweepStaticCache): an edge sweeps only when it is alone. staticTrees
+ // is the process's record of that cache (static_trees.go).
staticLock *os.File
+ staticTrees *staticTrees
staticRecheck time.Duration
// staticRatchet is #253's ratchet for static pointer reads: marks under
// <dataDir>/pointer-digests, root's under /opt read too.
@@ -624,8 +626,11 @@ func (e *Edge) EnableStatic(store release.Store, pub ed25519.PublicKey, cacheDir
// Before any static handler exists: old extracted trees go if this is
// the only edge using the cache (static_sweep_unix.go). The lock is
// held, shared, for the process's life.
- if cacheDir != "" && e.staticLock == nil {
- e.staticLock, _ = sweepStaticCache(cacheDir)
+ if cacheDir != "" && e.staticTrees == nil {
+ e.staticTrees, _ = openStaticTrees(cacheDir)
+ e.staticLock = e.staticTrees.lock
+ // Then again after every swap and every hour, for the process's life.
+ go e.staticTrees.run(staticSweepEvery, staticSweepSettle)
}
e.armStoreDoor()
}
@@ -806,6 +811,11 @@ func (e *Edge) fleetAccount(fleet string) (string, bool) {
// EnableStatic and before Reload; handlers built on the next reload use it.
func (e *Edge) SetStaticRecheck(d time.Duration) { e.staticRecheck = d }
+// LargestStaticTree is the byte count of the largest extracted static tree
+// this edge keeps on disk, 0 when it serves none. The disk alert leaves
+// room for two more above the cold-wake floor (internal/host).
+func (e *Edge) LargestStaticTree() int64 { return e.staticTrees.Largest() }
+
// staticHandlerFor builds the handler for one static route: the real serving
// class when EnableStatic has configured it, else the pre-config 404 (the
// route exists — and its cert can be minted — before the bytes can flow).
@@ -824,6 +834,8 @@ func (e *Edge) staticHandlerFor(rt registry.Route) http.Handler {
if ss, ok := h.(*staticSite); ok {
ss.recheck = e.staticRecheck
ss.ratchet = e.staticRatchet
+ ss.trees = e.staticTrees
+ e.staticTrees.register(ss)
}
return h
}
diff --git a/internal/edge/static.go b/internal/edge/static.go
index 13ff63fbf..221c54b28 100644
--- a/internal/edge/static.go
+++ b/internal/edge/static.go
@@ -153,6 +153,12 @@ type staticSite struct {
// ratchet is #253's per-box ratchet for this process's pointer reads
// (Edge.staticRatchet); nil admits every verified pointer.
ratchet *release.DigestRatchet
+
+ // trees is the edge's record of the static cache (static_trees.go): a
+ // sweep keeps the tree serving names, and leaves the app directory alone
+ // while this handler chooses a tree there. nil records nothing.
+ trees *staticTrees
+ serving atomic.Pointer[string]
}
// newStaticHandler builds the serving handler for one static route. The
@@ -268,14 +274,22 @@ func (s *staticSite) currentDir(ctx context.Context) (servedTree, error) {
return s.stale(err)
}
if want := cp.Digest; cp.Version != s.version || (want != "" && want != s.digest) {
+ // From the check of what is on disk to the record of what is served,
+ // no sweep touches this app's directory.
+ done := s.trees.begin(s.appDir())
name, digest, err := s.ensureExtracted(ctx, cp.Version, want)
if err != nil {
+ done()
return s.stale(fmt.Errorf("stage %s: %w", cp.Version, err))
}
if err := s.pointCurrent(name); err != nil {
+ done()
return s.stale(fmt.Errorf("swap current -> %s: %w", name, err))
}
s.version, s.digest, s.name = cp.Version, digest, name
+ s.serving.Store(&name)
+ done()
+ s.trees.swapped()
s.redirects = s.loadRedirects(s.dir(name), cp.Version)
s.headers = s.loadHeaders(s.dir(name), cp.Version)
}
@@ -485,7 +499,12 @@ func (s *staticSite) ensureExtracted(ctx context.Context, version, want string)
// pointCurrent atomically swaps the app's `current` symlink to the tree named name
// (temp symlink + rename — the same swap versions.go's PointLive uses), so
// anything looking at the cache dir sees the version flip as one atomic step.
+//
+// The tree's mtime is set to now first: it records when the tree last
+// became current, which is how the sweep tells the previous tree.
func (s *staticSite) pointCurrent(name string) error {
+ now := time.Now()
+ _ = os.Chtimes(s.dir(name), now, now)
link := filepath.Join(s.appDir(), "current")
tmp := link + ".tmp"
_ = os.Remove(tmp) // a leftover from a crashed swap
diff --git a/internal/edge/static_periodic_sweep_test.go b/internal/edge/static_periodic_sweep_test.go
new file mode 100644
index 000000000..7e667ec00
--- /dev/null
+++ b/internal/edge/static_periodic_sweep_test.go
@@ -0,0 +1,239 @@
+//go:build unix
+
+package edge
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// madeCurrentAt dates a tree the way pointCurrent does: its mtime is when it
+// last became an app's current tree.
+func madeCurrentAt(t *testing.T, cache, acct, app, name string, at time.Time) {
+ t.Helper()
+ if err := os.Chtimes(filepath.Join(cache, acct, app, name), at, at); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// openTrees is a started edge's view of cache: the startup sweep has run
+// (the lock file existed, so this start was allowed to sweep).
+func openTrees(t *testing.T, cache string) *staticTrees {
+ t.Helper()
+ seenLock(t, cache)
+ tr, done := openStaticTrees(cache)
+ <-done
+ if tr.lock == nil {
+ t.Fatal("no serving lock")
+ }
+ t.Cleanup(func() { tr.lock.Close() })
+ return tr
+}
+
+func joined(t *testing.T, dir string) string { return strings.Join(entries(t, dir), "|") }
+
+// The 2026-11-08 annie outage: the edge ran for a day while eight apt
+// releases shipped, and only a restart swept. A running edge now sweeps by
+// itself, keeping each app's current tree, the one current before it, and
+// any tree a live handler still serves (another channel of the same app
+// shares the app directory and its one current link).
+func TestStaticPeriodicSweepKeepsCurrentPreviousAndServed(t *testing.T) {
+ cache := t.TempDir()
+ tr := openTrees(t, cache)
+ base := time.Now().Add(-time.Hour)
+ for i, v := range []string{"v1", "v2", "v3", "v4", "v5"} {
+ cacheTree(t, cache, "bab", "apt", tree(v))
+ madeCurrentAt(t, cache, "bab", "apt", tree(v), base.Add(time.Duration(i)*time.Minute))
+ }
+ pointAt(t, cache, "bab", "apt", tree("v5"))
+ beta := &staticSite{acct: "bab", app: "apt", cacheDir: cache}
+ beta.serving.Store(new(tree("v2")))
+ tr.register(beta)
+
+ tr.sweepOnce()
+
+ if got, want := joined(t, filepath.Join(cache, "bab", "apt")), strings.Join([]string{"current", tree("v2"), tree("v4"), tree("v5")}, "|"); got != want {
+ t.Errorf("bab/apt = %v, want %v (current, previous, and the tree a live handler serves)", got, want)
+ }
+ runtime.KeepAlive(beta)
+}
+
+// A handler choosing a tree (resolving, extracting, swapping current) holds
+// its app directory out of the sweep, so a tree it found on disk cannot be
+// set aside between its check and its swap, and its temp extraction is not
+// taken for debris.
+func TestStaticPeriodicSweepSkipsAnAppMidResolve(t *testing.T) {
+ cache := t.TempDir()
+ tr := openTrees(t, cache)
+ for _, v := range []string{"v1", "v2", "v3"} {
+ cacheTree(t, cache, "bab", "apt", tree(v))
+ }
+ cacheTree(t, cache, "bab", "apt", ".extract-42")
+ pointAt(t, cache, "bab", "apt", tree("v3"))
+ appDir := filepath.Join(cache, "bab", "apt")
+
+ done := tr.begin(appDir)
+ tr.sweepOnce()
+ if got := entries(t, appDir); len(got) != 5 {
+ t.Errorf("bab/apt = %v, want nothing swept while a handler resolves there", got)
+ }
+ done()
+ tr.sweepOnce()
+ if got := entries(t, appDir); len(got) != 3 {
+ t.Errorf("bab/apt = %v, want current + previous once the resolve is done", got)
+ }
+}
+
+// Another edge process using the cache holds its shared lock: the running
+// edge sweeps nothing. flock(2) drops a shared lock whose conversion to
+// exclusive fails, so the sweep must take it back: once the other process
+// lets go, no third process may take the cache exclusively.
+func TestStaticPeriodicSweepSkipsWhileAnotherEdgeServesAndKeepsItsLock(t *testing.T) {
+ cache := t.TempDir()
+ tr := openTrees(t, cache)
+ for _, v := range []string{"v1", "v2", "v3"} {
+ cacheTree(t, cache, "bab", "apt", tree(v))
+ }
+ pointAt(t, cache, "bab", "apt", tree("v3"))
+ other, err := os.OpenFile(filepath.Join(cache, staticLockName), os.O_RDWR, 0o600)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer other.Close()
+ if err := syscall.Flock(int(other.Fd()), syscall.LOCK_SH); err != nil {
+ t.Fatal(err)
+ }
+
+ tr.sweepOnce()
+
+ if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 4 {
+ t.Errorf("bab/apt = %v, want everything kept while another edge serves", got)
+ }
+ if err := syscall.Flock(int(other.Fd()), syscall.LOCK_UN); err != nil {
+ t.Fatal(err)
+ }
+ probe, err := os.OpenFile(filepath.Join(cache, staticLockName), os.O_RDWR, 0o600)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer probe.Close()
+ if err := syscall.Flock(int(probe.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil {
+ t.Fatal("the running edge lost its shared lock after a refused sweep")
+ }
+}
+
+// The first lock-aware start may share the cache with an edge that takes no
+// lock, for the whole of its life: it never sweeps, at start or later.
+func TestStaticPeriodicSweepNeverOnTheFirstLockAwareStart(t *testing.T) {
+ cache := t.TempDir()
+ tr, done := openStaticTrees(cache)
+ <-done
+ defer tr.lock.Close()
+ for _, v := range []string{"v1", "v2", "v3"} {
+ cacheTree(t, cache, "bab", "apt", tree(v))
+ }
+ pointAt(t, cache, "bab", "apt", tree("v3"))
+ tr.sweepOnce()
+ if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 4 {
+ t.Errorf("bab/apt = %v, want nothing swept by the first lock-aware edge", got)
+ }
+}
+
+// The edge knows the size of the largest tree it keeps: the disk alert
+// leaves room for two of them above the cold-wake floor.
+func TestStaticTreesMeasureTheLargestKeptTree(t *testing.T) {
+ cache := t.TempDir()
+ tr := openTrees(t, cache)
+ if got := tr.Largest(); got != 0 {
+ t.Fatalf("empty cache: largest = %d", got)
+ }
+ for _, v := range []string{"v1", "v2"} {
+ cacheTree(t, cache, "bab", "apt", tree(v))
+ }
+ big := filepath.Join(cache, "bab", "apt", tree("v1"), "pool.deb")
+ if err := os.WriteFile(big, make([]byte, 5000), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ pointAt(t, cache, "bab", "apt", tree("v2"))
+ cacheTree(t, cache, "bac", "docs", tree("v9"))
+ pointAt(t, cache, "bac", "docs", tree("v9"))
+
+ tr.sweepOnce()
+
+ // v1 = index.html (its own name, 66 bytes) + 5000.
+ if got, want := tr.Largest(), int64(len(tree("v1"))+5000); got != want {
+ t.Errorf("largest = %d, want %d", got, want)
+ }
+}
+
+// End to end through the serving handler: four releases promoted one after
+// another leave the two newest on disk after a sweep, the site keeps
+// serving, every swap asks for a sweep, and a rollback to a swept release
+// extracts it again.
+func TestStaticPeriodicSweepThroughTheHandler(t *testing.T) {
+ storeRoot := filepath.Join(t.TempDir(), "store")
+ store := release.NewDirStore(storeRoot)
+ priv, pub := testKeys(t)
+ cache := filepath.Join(t.TempDir(), "cache")
+ if err := os.MkdirAll(cache, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ tr := openTrees(t, cache)
+
+ rt := registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "stable", Status: "ready"}
+ h := newStaticHandler(rt, store, pub, cache).(*staticSite)
+ h.recheck = 0
+ h.trees = tr
+ tr.register(h)
+ srv := httptest.NewServer(h)
+ defer srv.Close()
+
+ for _, v := range []string{"v1", "v2", "v3", "v4"} {
+ shipSite(t, store, "site", v, map[string]string{"index.html": "home " + v})
+ if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "stable", v); err != nil {
+ t.Fatalf("Promote %s: %v", v, err)
+ }
+ if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != http.StatusOK || body != "home "+v {
+ t.Fatalf("GET / after %s = %d %q", v, code, body)
+ }
+ select {
+ case <-tr.kick:
+ default:
+ t.Fatalf("the swap to %s asked for no sweep", v)
+ }
+ time.Sleep(20 * time.Millisecond) // mtimes order the trees
+ }
+
+ tr.sweepOnce()
+
+ appDir := filepath.Join(cache, h.acct, "site")
+ var trees []string
+ for _, n := range entries(t, appDir) {
+ if m := siteTreeName.FindStringSubmatch(n); m != nil {
+ trees = append(trees, m[1])
+ }
+ }
+ if got := strings.Join(trees, ","); got != "v3,v4" {
+ t.Errorf("trees after the sweep = %s, want v3,v4", got)
+ }
+ if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != http.StatusOK || body != "home v4" {
+ t.Fatalf("GET / after the sweep = %d %q", code, body)
+ }
+ if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "stable", "v1"); err != nil {
+ t.Fatalf("Promote v1 again: %v", err)
+ }
+ if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != http.StatusOK || body != "home v1" {
+ t.Fatalf("GET / after rolling back to a swept release = %d %q", code, body)
+ }
+}
diff --git a/internal/edge/static_sweep_other.go b/internal/edge/static_sweep_other.go
index 2be635b30..62860fb41 100644
--- a/internal/edge/static_sweep_other.go
+++ b/internal/edge/static_sweep_other.go
@@ -6,8 +6,18 @@ import "os"
// sweepStaticCache needs flock to know no other edge serves the cache; with
// none here, nothing is swept (static_sweep_unix.go).
-func sweepStaticCache(string) (*os.File, <-chan struct{}) {
+func sweepStaticCache(cacheDir string) (*os.File, <-chan struct{}) {
+ t, done := openStaticTrees(cacheDir)
+ return t.lock, done
+}
+
+// openStaticTrees holds no lock and sweeps nothing here; it still measures
+// the trees for the disk alert.
+func openStaticTrees(cacheDir string) (*staticTrees, <-chan struct{}) {
+ t := newStaticTrees(cacheDir)
done := make(chan struct{})
- close(done)
- return nil, done
+ go func() { defer close(done); t.measure() }()
+ return t, done
}
+
+func (t *staticTrees) sweepCache() int { return 0 }
diff --git a/internal/edge/static_sweep_test.go b/internal/edge/static_sweep_test.go
index df7b1c712..d980597e7 100644
--- a/internal/edge/static_sweep_test.go
+++ b/internal/edge/static_sweep_test.go
@@ -9,6 +9,7 @@ import (
"strings"
"syscall"
"testing"
+ "time"
)
// tree is a cache entry name as ensureExtracted makes it.
@@ -67,15 +68,16 @@ func sweep(t *testing.T, cache string) {
}
// With no other edge holding the cache, every release tree but each app's
-// current one goes, and so does the edge's own debris (a temp extraction,
+// current one and the one current before it (the newest other by mtime) goes, and so does the edge's own debris (a temp extraction,
// an earlier sweep's leftovers) and pre-#253 bare-version trees. Anything
// the sweep does not recognise as its own (an operator's directory, a
// file, a link) is left alone.
-func TestStaticStartupSweepKeepsOnlyEachAppsCurrentTree(t *testing.T) {
+func TestStaticStartupSweepKeepsEachAppsCurrentAndPreviousTree(t *testing.T) {
cache := t.TempDir()
seenLock(t, cache)
- for _, v := range []string{"v1", "v2", "v3"} {
+ for i, v := range []string{"v1", "v2", "v3"} {
cacheTree(t, cache, "bab", "apt", tree(v))
+ madeCurrentAt(t, cache, "bab", "apt", tree(v), time.Now().Add(time.Duration(i-10)*time.Minute))
}
pointAt(t, cache, "bab", "apt", tree("v3"))
cacheTree(t, cache, "bab", "apt", ".extract-123")
@@ -88,18 +90,20 @@ func TestStaticStartupSweepKeepsOnlyEachAppsCurrentTree(t *testing.T) {
}
cacheTree(t, cache, "bac", "docs", tree("v7"))
pointAt(t, cache, "bac", "docs", tree("v7"))
- cacheTree(t, cache, "bac", "nolink", tree("v1")) // no current link: no tree is kept
+ cacheTree(t, cache, "bac", "nolink", tree("v1")) // no current link: the newest tree is the previous one
+ cacheTree(t, cache, "bac", "nolink", tree("v0"))
+ madeCurrentAt(t, cache, "bac", "nolink", tree("v0"), time.Now().Add(-time.Hour))
sweep(t, cache)
- if got, want := entries(t, filepath.Join(cache, "bab", "apt")), []string{"backup 2026", "current", "note.txt", "v0.5.0-1", tree("v3")}; strings.Join(got, "|") != strings.Join(want, "|") {
+ if got, want := entries(t, filepath.Join(cache, "bab", "apt")), []string{"backup 2026", "current", "note.txt", "v0.5.0-1", tree("v2"), tree("v3")}; strings.Join(got, "|") != strings.Join(want, "|") {
t.Errorf("bab/apt = %v, want %v", got, want)
}
if got, want := entries(t, filepath.Join(cache, "bac", "docs")), []string{"current", tree("v7")}; strings.Join(got, "|") != strings.Join(want, "|") {
t.Errorf("bac/docs = %v, want %v", got, want)
}
- if got := entries(t, filepath.Join(cache, "bac", "nolink")); len(got) != 0 {
- t.Errorf("bac/nolink = %v, want empty", got)
+ if got := joined(t, filepath.Join(cache, "bac", "nolink")); got != tree("v1") {
+ t.Errorf("bac/nolink = %v, want only the newest tree", got)
}
if got := entries(t, filepath.Join(cache, "Not An Account", "apt")); len(got) != 1 {
t.Errorf("an invalid account's directory was entered: %v", got)
@@ -116,6 +120,8 @@ func TestStaticStartupSweepNeverTakesAReleaseForDebris(t *testing.T) {
cacheTree(t, cache, "bab", "a", tree(".sweep-x-1"))
pointAt(t, cache, "bab", "a", tree(".sweep-x-1"))
cacheTree(t, cache, "bab", "b", tree(".extract-9"))
+ madeCurrentAt(t, cache, "bab", "b", tree(".extract-9"), time.Now().Add(-time.Hour))
+ cacheTree(t, cache, "bab", "b", tree("v1")) // the previous tree
cacheTree(t, cache, "bab", "b", tree("v2"))
pointAt(t, cache, "bab", "b", tree("v2"))
@@ -130,7 +136,7 @@ func TestStaticStartupSweepNeverTakesAReleaseForDebris(t *testing.T) {
if got := entries(t, filepath.Join(cache, "bab", "a")); strings.Join(got, "|") != tree(".sweep-x-1")+"|current" {
t.Errorf("bab/a = %v, want the current release kept", got)
}
- if got := entries(t, filepath.Join(cache, "bab", "b")); strings.Join(got, "|") != "current|"+tree("v2") {
+ if got := entries(t, filepath.Join(cache, "bab", "b")); strings.Join(got, "|") != "current|"+tree("v1")+"|"+tree("v2") {
t.Errorf("bab/b = %v", got)
}
}
@@ -141,11 +147,12 @@ func TestStaticStartupSweepNeverTakesAReleaseForDebris(t *testing.T) {
// cache is known to take it.
func TestStaticStartupSweepFirstStartOnlyCreatesTheLock(t *testing.T) {
cache := t.TempDir()
+ cacheTree(t, cache, "bab", "apt", tree("v0"))
cacheTree(t, cache, "bab", "apt", tree("v1"))
cacheTree(t, cache, "bab", "apt", tree("v2"))
pointAt(t, cache, "bab", "apt", tree("v2"))
sweep(t, cache)
- if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 3 {
+ if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 4 {
t.Errorf("bab/apt = %v, want nothing swept on the first lock-aware start", got)
}
if _, err := os.Stat(filepath.Join(cache, staticLockName)); err != nil {
@@ -157,6 +164,7 @@ func TestStaticStartupSweepFirstStartOnlyCreatesTheLock(t *testing.T) {
// sweep does nothing, and still returns a shared lock for this process.
func TestStaticStartupSweepSkipsWhileAnotherEdgeServes(t *testing.T) {
cache := t.TempDir()
+ cacheTree(t, cache, "bab", "apt", tree("v0"))
cacheTree(t, cache, "bab", "apt", tree("v1"))
cacheTree(t, cache, "bab", "apt", tree("v2"))
pointAt(t, cache, "bab", "apt", tree("v2"))
@@ -170,7 +178,7 @@ func TestStaticStartupSweepSkipsWhileAnotherEdgeServes(t *testing.T) {
t.Fatal(err)
}
sweep(t, cache)
- if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 3 {
+ if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 4 {
t.Errorf("bab/apt = %v, want everything kept while another edge serves", got)
}
}
diff --git a/internal/edge/static_sweep_unix.go b/internal/edge/static_sweep_unix.go
index fbf15e743..814804670 100644
--- a/internal/edge/static_sweep_unix.go
+++ b/internal/edge/static_sweep_unix.go
@@ -17,34 +17,41 @@ import (
// Every version of a static site a box served stayed extracted under
// <cacheDir>/<acct>/<app>/ forever: annie-welding held 51 copies of the apt
-// site, 20 GB of 59 (2026-10-25). Sweeping on the serving path races the
-// handlers that pick trees (Astra review of static-sweep), so the sweep
-// runs once, at startup, before any handler exists, and only when no other
-// edge process can be serving from this cache:
+// site, 20 GB of 59 (2026-10-25). The sweep that fixed that ran only at
+// startup, before any handler existed, and annie filled to the cold-wake
+// floor again on 2026-11-08 between two restarts. A running edge now sweeps
+// too (staticTrees.run). Who may sweep is decided across processes by a
+// lock:
// - Every running edge holds a shared flock on staticLockName for its
-// life. A starting edge sweeps only if it can take it exclusively.
-// - An edge from before this change takes no lock, so the first edge to
-// create the lock file sweeps nothing: from its next start on, every
-// edge using the cache is known to take the lock. That rests on the
+// life. An edge sweeps only while it can hold it exclusively: at start,
+// and on each later sweep by converting its own shared hold, which it
+// takes back straight after.
+// - An edge from before the lock takes none, so the first edge to create
+// the lock file never sweeps, at start or later: from the next start on,
+// every edge using the cache is known to take the lock. That rests on the
// edge only running as carlos-edge.service, which systemd stops before
// it starts the next (Paul's ruling, 2026-10-25, on Astra round 3).
// - An edge that cannot hold the lock serves anyway and raises an ALERT
// (Paul's ruling, same day): a lock-file fault must not take static
// sites down, and the exposure needs a second edge starting beside it.
//
+// Inside the process, staticTrees says what the handlers need: a sweep
+// keeps every tree a live handler serves and leaves alone an app directory
+// a handler is choosing a tree in (begin). In each app it also keeps the
+// tree current names and the previous one, the newest other tree by mtime,
+// which pointCurrent sets when a tree becomes current.
+//
// Only entries the edge itself made are touched, recognised by name:
// release trees (<version>@<digest>, siteDirName), temp extractions
// (.extract-<n>, os.MkdirTemp's) and an earlier sweep's leftovers
// (.sweep-<name>-<n>), under account and app directories whose names are
-// valid ones. Each app keeps the tree
-// its current link names. Every other release tree is renamed to a .sweep-
-// name before the sweep returns, so no handler built after it can select
-// it (ensureExtracted then extracts a fresh, verified copy if a pointer
-// names that version), and is removed in the background with the debris.
+// valid ones. Every release tree the sweep does not keep is renamed to a
+// .sweep- name while the sweep holds the app directory, so no handler can
+// select it afterwards (ensureExtracted then extracts a fresh, verified copy
+// if a pointer names that version), and is removed with the debris.
const staticLockName = ".edge.lock"
var (
- siteTreeName = regexp.MustCompile(`^(.+)@[0-9a-f]{64}$`)
extractTmpName = regexp.MustCompile(`^\.extract-[0-9]+$`)
sweptName = regexp.MustCompile(`^\.sweep-.+-[0-9]+$`)
)
@@ -70,21 +77,29 @@ func classifyStaticEntry(name string) staticEntry {
return entryUnknown
}
-// sweepStaticCache sweeps cacheDir if no other edge can be using it, and
-// returns this process's lock on it, held shared until the process exits
-// (nil when no lock could be held), and a channel closed once the
-// background removal is done. A lock it cannot hold is an ALERT, not a
-// refusal to serve: static sites stay up, and the only exposure is a second
-// edge starting beside this one while it serves.
+// sweepStaticCache is openStaticTrees for callers that want only the lock.
func sweepStaticCache(cacheDir string) (*os.File, <-chan struct{}) {
+ t, done := openStaticTrees(cacheDir)
+ return t.lock, done
+}
+
+// openStaticTrees takes this process's lock on cacheDir, sweeps it if no
+// other edge can be using it, and returns the process's staticTrees (its
+// lock held shared until the process exits, nil when none could be held)
+// and a channel closed once the startup removal is done and the trees left
+// are measured. A lock it cannot hold is an ALERT, not a refusal to serve:
+// static sites stay up, and the only exposure is a second edge starting
+// beside this one while it serves.
+func openStaticTrees(cacheDir string) (*staticTrees, <-chan struct{}) {
+ t := newStaticTrees(cacheDir)
done := make(chan struct{})
- fail := func(f *os.File, err error) (*os.File, <-chan struct{}) {
+ fail := func(f *os.File, err error) (*staticTrees, <-chan struct{}) {
log.Printf("ALERT: edge: static cache %s: no lock held (%v): not swept, and a second edge starting beside this one could sweep trees it serves", cacheDir, err)
if f != nil {
f.Close()
}
- close(done)
- return nil, done
+ go func() { defer close(done); t.measure() }()
+ return t, done
}
if err := os.MkdirAll(cacheDir, 0o755); err != nil {
return fail(nil, err)
@@ -101,59 +116,98 @@ func sweepStaticCache(cacheDir string) (*os.File, <-chan struct{}) {
return fail(nil, err)
}
fd := int(lock.Fd())
- shared := func() error {
- var err error
- for range 5 {
- if err = syscall.Flock(fd, syscall.LOCK_SH); err == nil {
- return nil
- }
- time.Sleep(200 * time.Millisecond)
- }
- return err
+ measured := func() (*staticTrees, <-chan struct{}) {
+ t.lock = lock
+ go func() { defer close(done); t.measure() }()
+ return t, done
}
if first {
log.Printf("edge: static cache %s: first start with the lock; sweeping from the next start", cacheDir)
- if err := shared(); err != nil {
+ if err := reshare(fd); err != nil {
return fail(lock, err)
}
- close(done)
- return lock, done
+ return measured()
}
+ t.periodic = true
if err := syscall.Flock(fd, syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
log.Printf("edge: static cache %s: another edge process serves from it; not swept this start", cacheDir)
- if err := shared(); err != nil {
+ if err := reshare(fd); err != nil {
return fail(lock, err)
}
- close(done)
- return lock, done
+ return measured()
}
- doomed := setAside(cacheDir)
- if err := shared(); err != nil {
+ doomed := t.setAside()
+ if err := reshare(fd); err != nil {
return fail(lock, err)
}
+ t.lock = lock
go func() {
defer close(done)
- removed := 0
- for _, p := range doomed {
- if err := os.RemoveAll(p); err != nil {
- log.Printf("edge: static cache: remove %s: %v", p, err)
- continue
- }
- removed++
- }
- if removed > 0 {
- log.Printf("edge: static cache %s: swept %d entr(ies) no app's current link names", cacheDir, removed)
+ if removed := removeAll(doomed); removed > 0 {
+ log.Printf("edge: static cache %s: swept %d entr(ies) at start", cacheDir, removed)
}
+ t.measure()
}()
- return lock, done
+ return t, done
+}
+
+// reshare takes (or takes back) the process's shared hold on the lock.
+func reshare(fd int) error {
+ var err error
+ for range 5 {
+ if err = syscall.Flock(fd, syscall.LOCK_SH); err == nil {
+ return nil
+ }
+ time.Sleep(200 * time.Millisecond)
+ }
+ return err
+}
+
+func removeAll(doomed []string) int {
+ removed := 0
+ for _, p := range doomed {
+ if err := os.RemoveAll(p); err != nil {
+ log.Printf("edge: static cache: remove %s: %v", p, err)
+ continue
+ }
+ removed++
+ }
+ return removed
+}
+
+// sweepCache is a running edge's sweep: only while no other edge process
+// holds the lock, and never on the first lock-aware start. It reports how
+// many entries it removed.
+func (t *staticTrees) sweepCache() int {
+ if t.lock == nil || !t.periodic {
+ return 0
+ }
+ fd := int(t.lock.Fd())
+ if err := syscall.Flock(fd, syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
+ // A refused conversion has dropped the shared hold (flock(2)):
+ // take it back before anything else.
+ log.Printf("edge: static cache %s: another edge process serves from it; not swept", t.cacheDir)
+ if err := reshare(fd); err != nil {
+ log.Printf("ALERT: edge: static cache %s: shared lock not taken back (%v): a second edge starting beside this one could sweep trees it serves", t.cacheDir, err)
+ }
+ return 0
+ }
+ doomed := t.setAside()
+ if err := reshare(fd); err != nil {
+ log.Printf("ALERT: edge: static cache %s: shared lock not taken back (%v): a second edge starting beside this one could sweep trees it serves", t.cacheDir, err)
+ }
+ return removeAll(doomed)
}
// setAside renames, in every <acct>/<app> directory, each release tree the
-// current link does not name to a .sweep- name, and returns those paths and
-// the edge's debris for removal. It touches nothing it does not recognise.
-func setAside(cacheDir string) []string {
+// sweep does not keep to a .sweep- name, and returns those paths and the
+// edge's debris for removal. It holds mu for each app directory, so no
+// handler can begin choosing a tree there meanwhile, and skips a directory
+// a handler is already choosing in. It touches nothing it does not
+// recognise.
+func (t *staticTrees) setAside() []string {
var doomed []string
- accts, err := os.ReadDir(cacheDir)
+ accts, err := os.ReadDir(t.cacheDir)
if err != nil {
return nil
}
@@ -162,7 +216,7 @@ func setAside(cacheDir string) []string {
if !a.IsDir() || !release.ValidAccount(a.Name()) {
continue
}
- apps, err := os.ReadDir(filepath.Join(cacheDir, a.Name()))
+ apps, err := os.ReadDir(filepath.Join(t.cacheDir, a.Name()))
if err != nil {
continue
}
@@ -170,35 +224,58 @@ func setAside(cacheDir string) []string {
if !ap.IsDir() || !release.ValidApp(ap.Name()) {
continue
}
- appDir := filepath.Join(cacheDir, a.Name(), ap.Name())
- cur, _ := os.Readlink(filepath.Join(appDir, "current"))
- names, err := os.ReadDir(appDir)
- if err != nil {
- continue
- }
- for _, n := range names {
- name := n.Name()
- path := filepath.Join(appDir, name)
- if name == cur {
- continue
- }
- fi, err := os.Lstat(path)
- if err != nil || !fi.IsDir() {
- continue
- }
- switch classifyStaticEntry(name) {
- case entryDebris:
- doomed = append(doomed, path)
- case entryTree:
- to := filepath.Join(appDir, fmt.Sprintf(".sweep-%s-%d", name, stamp))
- if err := os.Rename(path, to); err != nil {
- log.Printf("edge: static cache: set aside %s: %v", path, err)
- continue
- }
- doomed = append(doomed, to)
- }
+ appDir := filepath.Join(t.cacheDir, a.Name(), ap.Name())
+ t.mu.Lock()
+ doomed = append(doomed, t.setAsideAppLocked(appDir, stamp)...)
+ t.mu.Unlock()
+ }
+ }
+ return doomed
+}
+
+func (t *staticTrees) setAsideAppLocked(appDir string, stamp int64) []string {
+ keep, busy := t.keepLocked(appDir)
+ if busy {
+ return nil
+ }
+ if cur, err := os.Readlink(filepath.Join(appDir, "current")); err == nil {
+ keep[cur] = true
+ }
+ names, err := os.ReadDir(appDir)
+ if err != nil {
+ return nil
+ }
+ var trees, doomed []string
+ var prev string
+ var prevAt time.Time
+ for _, n := range names {
+ name := n.Name()
+ path := filepath.Join(appDir, name)
+ fi, err := os.Lstat(path)
+ if err != nil || !fi.IsDir() || keep[name] {
+ continue
+ }
+ switch classifyStaticEntry(name) {
+ case entryDebris:
+ doomed = append(doomed, path)
+ case entryTree:
+ trees = append(trees, name)
+ if prev == "" || fi.ModTime().After(prevAt) {
+ prev, prevAt = name, fi.ModTime()
}
}
}
+ for _, name := range trees {
+ if name == prev {
+ continue
+ }
+ path := filepath.Join(appDir, name)
+ to := filepath.Join(appDir, fmt.Sprintf(".sweep-%s-%d", name, stamp))
+ if err := os.Rename(path, to); err != nil {
+ log.Printf("edge: static cache: set aside %s: %v", path, err)
+ continue
+ }
+ doomed = append(doomed, to)
+ }
return doomed
}
diff --git a/internal/edge/static_trees.go b/internal/edge/static_trees.go
new file mode 100644
index 000000000..10699f6ab
--- /dev/null
+++ b/internal/edge/static_trees.go
@@ -0,0 +1,242 @@
+package edge
+
+import (
+ "io/fs"
+ "log"
+ "os"
+ "path/filepath"
+ "regexp"
+ "sync"
+ "sync/atomic"
+ "time"
+ "weak"
+)
+
+// siteTreeName is a release tree's directory name: siteDirName's
+// <version>@<digest>.
+var siteTreeName = regexp.MustCompile(`^(.+)@[0-9a-f]{64}$`)
+
+// staticTrees is one edge process's record of the extracted static trees
+// under its cache directory: which ones its handlers serve, which app
+// directories a handler is choosing a tree in right now, and how big the
+// trees it keeps are. The sweep (static_sweep_unix.go) reads it to know
+// what it must not touch; the disk alert reads Largest.
+//
+// The startup sweep alone let annie-welding fill to the cold-wake floor on
+// 2026-11-08: carlos-edge ran for a day while eight 2.6 GB apt releases
+// shipped. A running edge therefore sweeps again after every swap a handler
+// makes (a deploy or promote reaching this box) and every staticSweepEvery.
+type staticTrees struct {
+ cacheDir string
+ // lock is this process's shared hold on <cacheDir>/.edge.lock, nil when
+ // none could be held. periodic is whether this process may sweep after
+ // startup: only when the lock file was already there at start, so every
+ // edge that can be using the cache is known to take the lock.
+ lock *os.File
+ periodic bool
+
+ mu sync.Mutex
+ // sites are the handlers this edge has built. Weak: a handler the route
+ // table dropped, with no request still holding it, goes away by itself.
+ sites []weak.Pointer[staticSite]
+ // busy counts, per app directory, the handlers choosing a tree there
+ // (begin). The sweep leaves such a directory alone.
+ busy map[string]int
+ // sizes caches each kept tree's byte count by path: a tree never changes
+ // once extracted.
+ sizes map[string]int64
+ largest atomic.Int64
+
+ kick chan struct{}
+}
+
+// staticSweepEvery is how often a running edge sweeps without a swap to
+// prompt it, and staticSweepSettle how long it waits after a swap, so a
+// burst of deploys costs one sweep.
+const (
+ staticSweepEvery = time.Hour
+ staticSweepSettle = 30 * time.Second
+)
+
+func newStaticTrees(cacheDir string) *staticTrees {
+ return &staticTrees{
+ cacheDir: cacheDir,
+ busy: map[string]int{},
+ sizes: map[string]int64{},
+ kick: make(chan struct{}, 1),
+ }
+}
+
+// register records a handler this edge built.
+func (t *staticTrees) register(s *staticSite) {
+ if t == nil {
+ return
+ }
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if len(t.sites) >= 64 && len(t.sites)%64 == 0 {
+ t.pruneLocked()
+ }
+ t.sites = append(t.sites, weak.Make(s))
+}
+
+func (t *staticTrees) pruneLocked() {
+ live := t.sites[:0]
+ for _, w := range t.sites {
+ if w.Value() != nil {
+ live = append(live, w)
+ }
+ }
+ clear(t.sites[len(live):])
+ t.sites = live
+}
+
+// begin marks a handler choosing a tree in appDir: from its check of what is
+// on disk to its swap of current and the record of what it serves. The
+// returned func ends it.
+func (t *staticTrees) begin(appDir string) func() {
+ if t == nil {
+ return func() {}
+ }
+ t.mu.Lock()
+ t.busy[appDir]++
+ t.mu.Unlock()
+ return func() {
+ t.mu.Lock()
+ if t.busy[appDir]--; t.busy[appDir] <= 0 {
+ delete(t.busy, appDir)
+ }
+ t.mu.Unlock()
+ }
+}
+
+// swapped asks for a sweep: a handler has just moved to another tree.
+func (t *staticTrees) swapped() {
+ if t == nil {
+ return
+ }
+ select {
+ case t.kick <- struct{}{}:
+ default:
+ }
+}
+
+// keepLocked is what the sweep must leave in appDir besides current and
+// previous: every tree a live handler serves there. The caller holds mu, and
+// a busy directory is not swept at all.
+func (t *staticTrees) keepLocked(appDir string) (keep map[string]bool, busy bool) {
+ if t.busy[appDir] > 0 {
+ return nil, true
+ }
+ keep = map[string]bool{}
+ for _, w := range t.sites {
+ s := w.Value()
+ if s == nil || s.appDir() != appDir {
+ continue
+ }
+ if name := s.serving.Load(); name != nil {
+ keep[*name] = true
+ }
+ }
+ return keep, false
+}
+
+// Largest is the byte count of the largest tree the last sweep kept, 0
+// before one has measured.
+func (t *staticTrees) Largest() int64 {
+ if t == nil {
+ return 0
+ }
+ return t.largest.Load()
+}
+
+// measure sizes every release tree left in the cache, reusing the count of
+// a tree it has measured before.
+func (t *staticTrees) measure() {
+ seen := map[string]bool{}
+ var largest int64
+ accts, _ := os.ReadDir(t.cacheDir)
+ for _, a := range accts {
+ if !a.IsDir() {
+ continue
+ }
+ apps, _ := os.ReadDir(filepath.Join(t.cacheDir, a.Name()))
+ for _, ap := range apps {
+ if !ap.IsDir() {
+ continue
+ }
+ appDir := filepath.Join(t.cacheDir, a.Name(), ap.Name())
+ names, _ := os.ReadDir(appDir)
+ for _, n := range names {
+ if !n.IsDir() || !siteTreeName.MatchString(n.Name()) {
+ continue
+ }
+ p := filepath.Join(appDir, n.Name())
+ seen[p] = true
+ t.mu.Lock()
+ size, ok := t.sizes[p]
+ t.mu.Unlock()
+ if !ok {
+ size = treeBytes(p)
+ t.mu.Lock()
+ t.sizes[p] = size
+ t.mu.Unlock()
+ }
+ largest = max(largest, size)
+ }
+ }
+ }
+ t.mu.Lock()
+ for p := range t.sizes {
+ if !seen[p] {
+ delete(t.sizes, p)
+ }
+ }
+ t.mu.Unlock()
+ t.largest.Store(largest)
+}
+
+// treeBytes is the total size of the regular files under dir.
+func treeBytes(dir string) int64 {
+ var n int64
+ _ = filepath.WalkDir(dir, func(_ string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return nil
+ }
+ if d.Type().IsRegular() {
+ if fi, err := d.Info(); err == nil {
+ n += fi.Size()
+ }
+ }
+ return nil
+ })
+ return n
+}
+
+// run sweeps after each swap (once the burst settles) and every
+// staticSweepEvery, for the life of the process.
+func (t *staticTrees) run(every, settle time.Duration) {
+ tick := time.NewTicker(every)
+ defer tick.Stop()
+ for {
+ select {
+ case <-t.kick:
+ time.Sleep(settle)
+ select {
+ case <-t.kick:
+ default:
+ }
+ case <-tick.C:
+ }
+ t.sweepOnce()
+ }
+}
+
+// sweepOnce sets aside and removes what no handler needs (sweepCache, per
+// platform), then measures what is left.
+func (t *staticTrees) sweepOnce() {
+ if removed := t.sweepCache(); removed > 0 {
+ log.Printf("edge: static cache %s: swept %d entr(ies) no handler serves", t.cacheDir, removed)
+ }
+ t.measure()
+}