carlos / platform Public

rootfs: every activator-ownership reader asks Route.ActivatorOwned; the layout pass never moves a rootfs row

Instance sites that tested Kind instance && Hibernate (ActivatorManaged,
the serve gates, the edge's three, rollout.Managed, the status probe, the
advisory probe, scheduled delivery, release.BuildStateKept) take
ActivatorOwned. Sites with no kind check (box-wide litestream's exclusion,
HibernatingHosts, the socket advisory's owned test and its diagnostic,
replicationRail) take ActivatorLeased, so hibernating binary sidecars keep
today's answers. A wake whose row changed runtime is a changed route.
Retention needs a fresh, complete box report for a resident rootfs
record, as for a hibernating one, and deletes nothing without it. The
layout pass keeps every row with a runtime ("kept"), in Converge,
restoreHold, recheck and under the fence, and the leg logs kept as
quietly as unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev d14743165347ad0ee88962e3ee218abeebd6b65f parent f2a5819
37 files changed, +1,242 −48
  • cli.go +6 −3
  • internal/activator/activator.go +8 −5
  • internal/activator/layout.go +6 −4
  • internal/activator/rootfs_predicates_test.go +198 −0
  • internal/activator/wakeidentity.go +4 −0
  • internal/appconfig/sync.go +1 −1
  • internal/caps/converge.go +2 −0
  • internal/console/instances.go +1 −0
  • internal/console/overview.go +1 −1
  • internal/console/view.go +1 −1
  • internal/domains/export_test.go +6 −0
  • internal/domains/rootfs_apex_test.go +93 −0
  • internal/edge/edge.go +9 −7
  • internal/edge/rootfs_reload_test.go +113 −0
  • internal/host/agent.go +2 −0
  • internal/host/layoutleg.go +3 −1
  • internal/host/probes.go +1 −1
  • internal/host/restart.go +2 −0
  • internal/host/restartscope.go +2 −0
  • internal/host/retention.go +6 −2
  • internal/host/rootfs_advice_test.go +334 −0
  • internal/host/schedule_wiring.go +1 −1
  • internal/host/socket_advice.go +18 −7
  • internal/layout/pass.go +34 −2
  • internal/layout/rootfs_pass_test.go +120 −0
  • internal/ops/hibernate_verify.go +3 −1
  • internal/ops/litestream.go +6 −1
  • internal/ops/rootfs_litestream_test.go +114 −0
  • internal/provision/seedswap.go +1 −1
  • internal/release/adopt.go +3 −0
  • internal/release/pins.go +7 −5
  • internal/release/rootfs_pins_test.go +51 −0
  • internal/rollout/policy.go +4 −3
  • internal/rollout/rootfs_managed_test.go +39 −0
  • internal/schedule/converge.go +2 −0
  • internal/status/snapshot.go +1 −1
  • rootfs_replication_test.go +39 −0
diff --git a/cli.go b/cli.go
index 573b48261..8701cf506 100644
--- a/cli.go
+++ b/cli.go
@@ -1837,7 +1837,8 @@ func unitWord(unit string) string {
// is read in exactly one place — the activator's wake path — and
// /etc/litestream.yml covers everything box-wide litestream is NOT told to
// leave alone, at its own interval. What it is told to leave alone is
-// `r.Hibernate && r.DBPath != ""` (internal/ops/litestream.go), so BOTH
+// `r.ActivatorLeased() && r.DBPath != ""` (internal/ops/litestream.go:
+// hibernating rows, and every instance with a runtime), so BOTH
// halves are required: a non-hibernating route, and a hibernating route
// whose row names no database, are each swept into the box-wide config and
// each would have the column written, reported as set, and read by nothing —
@@ -1878,12 +1879,14 @@ func runRouteReplication(r *registry.Registry, rt registry.Route, class string,
// pure function for the reason unitRail and backingRail are: a rail nobody
// can exercise without running the process is a rail nobody tests.
func replicationRail(rt registry.Route) error {
- if !rt.Hibernate {
+ // ActivatorLeased, the box-wide exclusion's own test: a resident rootfs
+ // instance never hibernates, but the activator replicates it.
+ if !rt.ActivatorLeased() {
return fmt.Errorf("route does not hibernate — the replication class is read only where the activator replicates, on wake, and /etc/litestream.yml (which covers every NON-hibernating database on this box) has its own interval. "+
"Setting a rung here would write a column nothing reads. Use `carlos route --host %s --hibernate` first if this route should be activator-managed", rt.Host)
}
// Hibernation alone was never the premise — the exclusion it stands on
- // is `r.Hibernate && r.DBPath != ""` (ops.FleetDBsWithSkipped), and
+ // is `r.ActivatorLeased() && r.DBPath != ""` (ops.FleetDBsWithSkipped), and
// provision.routeFor's comment already records this trap from the other
// side. A hibernating route whose row names no database is NOT excluded
// from box-wide litestream: the dataDir glob claims its file anyway and
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 05609da8a..a3001f822 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -5010,6 +5010,8 @@ func (a *Service) sweepOnce() {
// flip-off's release re-records one after the flag is already clear).
// The registry's DueInstances is deliberately broader (no hibernate
// filter), so the gate lives here, with the machine it protects.
+ // Left on Hibernate: a resident is never due-woken; the rootfs tick
+ // starts it.
if !rt.Hibernate || rt.Status != "ready" {
continue
}
@@ -5392,7 +5394,7 @@ func (a *Service) ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.
// write behind the move's final mirror round. The move worker's fence closes
// the race in-process; this gate is the half that survives an agent restart.
func (a *Service) ServeScheduled(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler) bool {
- if rt.Kind == "instance" && rt.Hibernate && rt.Status != "" && rt.Status != "ready" {
+ if rt.ActivatorOwned() && rt.Status != "" && rt.Status != "ready" {
maintenanceResponse(w, r)
return true
}
@@ -5404,7 +5406,7 @@ func (a *Service) ServeScheduled(w http.ResponseWriter, r *http.Request, rt regi
}
func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler, stamp bool) bool {
- if rt.Kind == "instance" && rt.Hibernate && a.Startup != nil {
+ if rt.ActivatorOwned() && a.Startup != nil {
deadline := time.NewTimer(wakeWaitBound)
err := a.awaitStartup(r.Context(), deadline.C)
deadline.Stop()
@@ -5433,11 +5435,12 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout
maintenanceResponse(w, r)
return true
}
- // Per-host gating: only a hibernate-flagged instance is activator-managed;
- // unflagged instances and sibling services are the edge's to proxy
+ // Per-host gating: only an instance the activator owns (a hibernate-flagged
+ // one, or one with a runtime: Route.ActivatorOwned) is activator-managed;
+ // unflagged binary instances and sibling services are the edge's to proxy
// straight — the deploy-safety property that lets the bucket env ship
// fleet-wide as a no-op before any host is flagged.
- if rt.Kind != "instance" || !rt.Hibernate {
+ if !rt.ActivatorOwned() {
return false
}
diff --git a/internal/activator/layout.go b/internal/activator/layout.go
index 61f9ddd85..f743512f4 100644
--- a/internal/activator/layout.go
+++ b/internal/activator/layout.go
@@ -57,11 +57,13 @@ func (in LayoutInputs) sockets(host string) (flat, nested string) {
// ActivatorManaged is the activator's own predicate for a route it owns
// (activator.go's per-host gate and edge.go's proxy decision): an instance
-// route, hibernate-flagged, with a socket, not unit-backed, not
-// tunnel-served. An unflagged socket route is an externally supervised
-// process and is nobody's to migrate or isolate (design §8.2 step 1).
+// route the activator owns (registry.Route.ActivatorOwned: hibernate-flagged,
+// or with a runtime, a resident rootfs instance included), with a socket,
+// not unit-backed, not tunnel-served. An unflagged binary socket route is an
+// externally supervised process and is nobody's to migrate or isolate
+// (design §8.2 step 1).
func ActivatorManaged(rt registry.Route) bool {
- return rt.Kind == "instance" && rt.Hibernate && rt.Socket != "" && rt.Backing == "" && rt.Tunnel == ""
+ return rt.ActivatorOwned() && rt.Socket != "" && rt.Backing == "" && rt.Tunnel == ""
}
// Classifier lets doWake ask a backend for a route's layout before it does
diff --git a/internal/activator/rootfs_predicates_test.go b/internal/activator/rootfs_predicates_test.go
new file mode 100644
index 000000000..053f95578
--- /dev/null
+++ b/internal/activator/rootfs_predicates_test.go
@@ -0,0 +1,198 @@
+package activator
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// predicateRoutes are the rows every Task 5 reader is asked about: a binary
+// instance asleep and awake, a binary sidecar asleep, a resident rootfs
+// instance (Hibernate false, nested socket and database) and an unknown
+// runtime, which is fixed and inert and so the activator's (Task 2).
+func predicateRoutes() map[string]registry.Route {
+ nested := func(host string) registry.Route {
+ return registry.Route{Host: host, Kind: "instance", App: "shop", Account: "bab", Status: "ready",
+ Socket: "/run/carlos/instances/" + host + "/app.sock", DBPath: "/data/instances/" + host + "/" + host + ".db"}
+ }
+ binaryAsleep := nested("asleep.example.com")
+ binaryAsleep.Hibernate = true
+ binaryAwake := nested("awake.example.com")
+ resident := nested("shop.example.com")
+ resident.Runtime = registry.RuntimeRootfsV1
+ unknown := nested("later.example.com")
+ unknown.Runtime = "rootfs-v9"
+ sidecar := registry.Route{Host: "jobs.example.com", Kind: "sidecar", App: "shop", Account: "bab", Status: "ready",
+ Hibernate: true, Socket: "/run/carlos/jobs.example.com.sock", DBPath: "/data/jobs.example.com.db"}
+ return map[string]registry.Route{
+ "binary hibernating": binaryAsleep,
+ "binary awake": binaryAwake,
+ "binary sidecar": sidecar,
+ "resident rootfs": resident,
+ "unknown runtime": unknown,
+ }
+}
+
+// TestActivatorManagedIncludesResidentRootfs: ActivatorManaged asks
+// Route.ActivatorOwned, so a resident rootfs instance is the activator's
+// although it never hibernates. Binary rows answer as on main, and the
+// socket, backing and tunnel conditions still hold for a resident.
+func TestActivatorManagedIncludesResidentRootfs(t *testing.T) {
+ routes := predicateRoutes()
+ want := map[string]bool{
+ "binary hibernating": true,
+ "binary awake": false,
+ "binary sidecar": false,
+ "resident rootfs": true,
+ "unknown runtime": true,
+ }
+ for name, rt := range routes {
+ if got := ActivatorManaged(rt); got != want[name] {
+ t.Errorf("ActivatorManaged(%s) = %v, want %v", name, got, want[name])
+ }
+ }
+ resident := routes["resident rootfs"]
+ for name, edit := range map[string]func(*registry.Route){
+ "no socket": func(r *registry.Route) { r.Socket = "" },
+ "unit-backed": func(r *registry.Route) { r.Backing = registry.BackingUnit },
+ "tunnelled": func(r *registry.Route) { r.Tunnel = "far" },
+ } {
+ rt := resident
+ edit(&rt)
+ if ActivatorManaged(rt) {
+ t.Errorf("ActivatorManaged(resident, %s) = true, want false", name)
+ }
+ }
+}
+
+// TestWakeRouteChangedOnRuntime: a wake that began on a binary row and
+// finds a rootfs row (or the reverse) is a changed route, even where both
+// are ActivatorManaged: the process it would start is another kind.
+func TestWakeRouteChangedOnRuntime(t *testing.T) {
+ routes := predicateRoutes()
+ binary := routes["binary hibernating"]
+ rootfs := binary
+ rootfs.Runtime, rootfs.Hibernate = registry.RuntimeRootfsV1, false
+ if !ActivatorManaged(binary) || !ActivatorManaged(rootfs) {
+ t.Fatal("both rows must be ActivatorManaged, or this test proves nothing about the runtime")
+ }
+ if err := wakeRouteChanged(binary, rootfs, false); err == nil {
+ t.Error("wakeRouteChanged(began binary, now rootfs) = nil, want a changed route")
+ }
+ if err := wakeRouteChanged(rootfs, binary, false); err == nil {
+ t.Error("wakeRouteChanged(began rootfs, now binary) = nil, want a changed route")
+ }
+ unknown := rootfs
+ unknown.Runtime = "rootfs-v9"
+ if err := wakeRouteChanged(rootfs, unknown, false); err == nil {
+ t.Error("wakeRouteChanged(began rootfs-v1, now an unknown runtime) = nil, want a changed route")
+ }
+ if err := wakeRouteChanged(rootfs, rootfs, false); err != nil {
+ t.Errorf("wakeRouteChanged(rootfs, rootfs) = %v, want nil", err)
+ }
+ if err := wakeRouteChanged(binary, binary, false); err != nil {
+ t.Errorf("wakeRouteChanged(binary, binary) = %v, want nil", err)
+ }
+}
+
+// TestServeGatesFollowActivatorOwned: ServeScheduled's status gate, serve's
+// startup wait and serve's per-host gate each ask ActivatorOwned. A
+// resident is the activator's at all three; a binary awake row and a
+// sidecar are proxied straight, as on main.
+func TestServeGatesFollowActivatorOwned(t *testing.T) {
+ routes := predicateRoutes()
+ owned := map[string]bool{
+ "binary hibernating": true,
+ "binary awake": false,
+ "binary sidecar": false,
+ "resident rootfs": true,
+ "unknown runtime": true,
+ }
+ proxied := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ t.Errorf("%s: the proxy was reached", r.Host)
+ })
+ // woke reports whether a went near a wake for host: a lease taken or
+ // an entry made.
+ woke := func(a *Service, b *fakeBackend, host string) bool {
+ b.mu.Lock()
+ acquires := b.acquires
+ b.mu.Unlock()
+ a.mu.Lock()
+ _, entry := a.entries[host]
+ a.mu.Unlock()
+ return acquires != 0 || entry
+ }
+ for name, rt := range routes {
+ // ServeScheduled: a managed row this box has stopped serving gets
+ // the maintenance answer, never a wake.
+ a, b, _, _ := testActivator(t, 0)
+ moving := rt
+ moving.Status = "moving"
+ w := httptest.NewRecorder()
+ got := a.ServeScheduled(w, httptest.NewRequest(http.MethodGet, "http://"+rt.Host+"/", nil), moving, http.NotFoundHandler())
+ if got != owned[name] {
+ t.Errorf("ServeScheduled(%s, moving) handled = %v, want %v", name, got, owned[name])
+ }
+ if owned[name] && (w.Code != http.StatusServiceUnavailable || woke(a, b, rt.Host)) {
+ t.Errorf("ServeScheduled(%s, moving) = %d, woke %v; want the maintenance 503 and no wake", name, w.Code, woke(a, b, rt.Host))
+ }
+
+ // serve's startup wait: an owned row waits for recovery and, its
+ // request gone before recovery finished, is answered without a wake.
+ a, b, _, _ = testActivator(t, 0)
+ a.Startup = make(chan struct{})
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ req := httptest.NewRequest(http.MethodGet, "http://"+rt.Host+"/", nil).WithContext(ctx)
+ got = a.ServeHTTP(httptest.NewRecorder(), req, rt, proxied)
+ cancel()
+ if got != owned[name] {
+ t.Errorf("ServeHTTP(%s, startup pending) handled = %v, want %v", name, got, owned[name])
+ }
+ if woke(a, b, rt.Host) {
+ t.Errorf("ServeHTTP(%s, startup pending) went near a wake before recovery finished", name)
+ }
+
+ // Just after recovery, an owned row whose upstream recovery moved
+ // is answered as a wake in progress, so the edge routes the retry
+ // afresh: the proxy it chose names the old socket.
+ a, b, _, reg := testActivator(t, 0)
+ a.Routes = reg
+ moved := rt
+ moved.Socket += ".moved"
+ if err := reg.Upsert(moved); err != nil {
+ t.Fatal(err)
+ }
+ recovered := make(chan struct{})
+ close(recovered)
+ a.Startup = recovered
+ w = httptest.NewRecorder()
+ got = a.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "http://"+rt.Host+"/", nil), rt, proxied)
+ if got != owned[name] {
+ t.Errorf("ServeHTTP(%s, upstream moved at startup) handled = %v, want %v", name, got, owned[name])
+ }
+ if owned[name] && (w.Code != http.StatusServiceUnavailable || woke(a, b, rt.Host)) {
+ t.Errorf("ServeHTTP(%s, upstream moved at startup) = %d, woke %v; want a 503 and no wake", name, w.Code, woke(a, b, rt.Host))
+ }
+
+ // serve's per-host gate: sidecar-marked traffic to an owned row that
+ // is not awake is refused here and never wakes it.
+ a, b, _, _ = testActivator(t, 0)
+ req = httptest.NewRequest(http.MethodGet, "http://"+rt.Host+"/", nil)
+ req.Header.Set(SidecarHeader, "1")
+ w = httptest.NewRecorder()
+ got = a.ServeHTTP(w, req, rt, proxied)
+ if got != owned[name] {
+ t.Errorf("ServeHTTP(%s, sidecar-marked) handled = %v, want %v", name, got, owned[name])
+ }
+ if got && w.Code != http.StatusServiceUnavailable {
+ t.Errorf("ServeHTTP(%s, sidecar-marked) = %d, want 503", name, w.Code)
+ }
+ if woke(a, b, rt.Host) {
+ t.Errorf("ServeHTTP(%s, sidecar-marked) went near a wake", name)
+ }
+ }
+}
diff --git a/internal/activator/wakeidentity.go b/internal/activator/wakeidentity.go
index e0313cf16..7d2f5db7b 100644
--- a/internal/activator/wakeidentity.go
+++ b/internal/activator/wakeidentity.go
@@ -39,6 +39,10 @@ func wakeRouteChanged(began, now registry.Route, worker bool) error {
return fmt.Errorf("%s: the route changed before the wake: it is no longer a sidecar", now.Host)
case !worker && !stillWoken(began, now):
return fmt.Errorf("%s: the route changed before the wake: the activator no longer manages it", now.Host)
+ case began.Runtime != now.Runtime:
+ // A binary and a rootfs row can both be ActivatorManaged, but the
+ // process a wake starts for one is not the other's.
+ return fmt.Errorf("%s: the route changed before the wake: its runtime is %q now, not %q", now.Host, now.Runtime, began.Runtime)
case began.Account != now.Account || began.App != now.App:
return fmt.Errorf("%s: the route changed before the wake: it belongs to %s/%s now, not %s/%s", now.Host, now.Account, now.App, began.Account, began.App)
case began.Addr != now.Addr:
diff --git a/internal/appconfig/sync.go b/internal/appconfig/sync.go
index a6915f16f..ad92e8dc6 100644
--- a/internal/appconfig/sync.go
+++ b/internal/appconfig/sync.go
@@ -638,7 +638,7 @@ func syncHostClaimed(ctx context.Context, work hostwrite.Work, rt registry.Route
case err != nil:
fmt.Printf(" %s: config updated but restart failed: %v\n", rt.Host, err)
a.RestartError = err.Error()
- case rt.Hibernate:
+ case rt.Hibernate: // left on Hibernate: a resident's config change is a bounce, and the rootfs tick restarts it
a.Hibernating = true
fmt.Printf(" %s: config updated, hibernating — delivered on wake\n", rt.Host)
default:
diff --git a/internal/caps/converge.go b/internal/caps/converge.go
index 73ef5ec5c..177d95bcd 100644
--- a/internal/caps/converge.go
+++ b/internal/caps/converge.go
@@ -229,6 +229,8 @@ func Converge(o Ops, p Plan) (Result, error) {
// A daemon the platform is asked to keep running and to stop when idle is
// a contradiction, and hibernation for these apps means an MX that sleeps.
+ // Left on Hibernate: exec rows, a resident rootfs instance included,
+ // never materialize capabilities (host/caps_pass.go).
if p.Set.Daemon && p.Hibernate {
err := fmt.Errorf("capability daemon and hibernation contradict")
o.logf(" %s: %v — nothing written and no unit state changed; fix it with: carlos route --host %s --hibernate=false", p.Host, err, p.Host)
diff --git a/internal/console/instances.go b/internal/console/instances.go
index bf6989223..876ceac06 100644
--- a/internal/console/instances.go
+++ b/internal/console/instances.go
@@ -99,6 +99,7 @@ func (s *Server) newInstanceFetcher(client *http.Client, scheme string) *instanc
// renders the same as "not reporting".
func (f *instanceFetcher) Report(ctx context.Context, routes []RouteView) *InstanceReport {
for _, rt := range routes {
+ // Left on Hibernate: display, and a resident reads as running, which is true.
if rt.Host == "" || rt.Kind == "static" || rt.Kind == "sidecar" || rt.Status != "ready" || rt.Hibernate {
continue
}
diff --git a/internal/console/overview.go b/internal/console/overview.go
index fc1b260fc..f209f329b 100644
--- a/internal/console/overview.go
+++ b/internal/console/overview.go
@@ -171,7 +171,7 @@ func assembleOverview(view *AppView, acct string, metrics []InstanceMetrics, ver
// health. Counted, and neither reporting nor asleep.
} else if reporting[rt.Host] || rt.boxAwake {
st.InstanceReporting++
- } else if rt.Hibernate && rt.Status != "failed" {
+ } else if rt.Hibernate && rt.Status != "failed" { // display: a resident reads as running, which is true
// A failed instance (one held down after a failed build) is
// not sleeping: it will not wake, so it is not counted here.
st.InstanceAsleep++
diff --git a/internal/console/view.go b/internal/console/view.go
index 90544da62..3825bbe28 100644
--- a/internal/console/view.go
+++ b/internal/console/view.go
@@ -630,7 +630,7 @@ func Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519.
// appends apart breaks that join silently.
byApp[rt.App] = append(byApp[rt.App], RouteView{
Host: rt.Host, Kind: rt.Kind, Status: rt.Status,
- Version: rt.Version, Channel: ch, Hibernate: rt.Hibernate,
+ Version: rt.Version, Channel: ch, Hibernate: rt.Hibernate, // display: a resident reads as running, which is true
Platform: rt.Platform,
Account: rtAcct,
Environment: rt.Environment,
diff --git a/internal/domains/export_test.go b/internal/domains/export_test.go
new file mode 100644
index 000000000..13c251e84
--- /dev/null
+++ b/internal/domains/export_test.go
@@ -0,0 +1,6 @@
+package domains
+
+// MintedRoute is mintedRoute, for the external tests that drive a minted
+// row through the edge (rootfs_apex_test.go): package edge imports this one,
+// so only an external test package can import both.
+var MintedRoute = mintedRoute
diff --git a/internal/domains/rootfs_apex_test.go b/internal/domains/rootfs_apex_test.go
new file mode 100644
index 000000000..88a45e155
--- /dev/null
+++ b/internal/domains/rootfs_apex_test.go
@@ -0,0 +1,93 @@
+package domains_test
+
+import (
+ "errors"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// apexActivator is an instant wake that proxies straight through, and
+// records which hosts it was asked to serve.
+type apexActivator struct{ served []string }
+
+func (a *apexActivator) ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler) bool {
+ a.served = append(a.served, rt.Host)
+ proxy.ServeHTTP(w, r)
+ return true
+}
+
+func (a *apexActivator) RetireExcept(map[string]bool) {}
+
+// TestPlatformApexOfRootfsIsAnAlias: the platform apex minted from a
+// resident rootfs instance copies its upstream and nothing of its runtime,
+// so it is a plain socket route, not ActivatorOwned: the edge proxies it to
+// the resident's socket and never hands it to the activator, which would
+// otherwise own one process under two hosts.
+func TestPlatformApexOfRootfsIsAnAlias(t *testing.T) {
+ dir, err := os.MkdirTemp("", "ap")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(dir) })
+ sock := filepath.Join(dir, "app.sock")
+ ln, err := net.Listen("unix", sock)
+ if err != nil {
+ if errors.Is(err, syscall.EPERM) || strings.Contains(err.Error(), "operation not permitted") {
+ t.Skipf("unix-socket listeners not permitted in this environment: %v", err)
+ }
+ t.Fatal(err)
+ }
+ srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "resident")
+ })}
+ go srv.Serve(ln)
+ t.Cleanup(func() { srv.Close() })
+
+ src := registry.Route{Host: "shop.example.com", Kind: "instance", App: "shop", Account: "bab", Status: "ready",
+ Runtime: registry.RuntimeRootfsV1, Socket: sock, DBPath: filepath.Join(dir, "shop.example.com.db"), Provisioned: true}
+ if !src.ActivatorOwned() {
+ t.Fatal("the resident source is not ActivatorOwned")
+ }
+ apex := domains.MintedRoute("shop.bab.example.com", "shop", "bab", src)
+ if apex.Runtime != "" || apex.Hibernate || apex.ActivatorOwned() {
+ t.Fatalf("apex = runtime %q hibernate %v owned %v, want a plain alias of the resident's socket", apex.Runtime, apex.Hibernate, apex.ActivatorOwned())
+ }
+ if apex.Socket != src.Socket {
+ t.Fatalf("apex socket %q, want the resident's %q", apex.Socket, src.Socket)
+ }
+
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ for _, rt := range []registry.Route{src, apex} {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatalf("upsert %s: %v", rt.Host, err)
+ }
+ }
+ act := &apexActivator{}
+ e, err := edge.New(reg, act)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "http://"+apex.Host+"/", nil))
+ if rec.Body.String() != "resident" {
+ t.Fatalf("apex answered %d %q, want the resident's socket", rec.Code, rec.Body.String())
+ }
+ if len(act.served) != 0 {
+ t.Fatalf("the activator was handed %v for the apex", act.served)
+ }
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index f63a693b5..5aa23a843 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -799,10 +799,10 @@ func (e *Edge) Reload() error {
// An activator-managed instance's process binds a generation
// socket, not t.Socket, once generations are on (spec §7.1):
// every new connection asks the activator for the current one.
- // t.Kind/t.Hibernate are the activator-managed test below
+ // t.ActivatorOwned() is the activator-managed test below
// (hib); viaTunnel is false in this arm by construction.
var p *httputil.ReverseProxy
- if e.gens != nil && t.Kind == "instance" && t.Hibernate {
+ if e.gens != nil && t.ActivatorOwned() {
p, genManaged = appSocketProxy(t.Host, e.gens, e.genPools), true
} else {
p = unixProxy(t.Socket)
@@ -903,9 +903,11 @@ func (e *Edge) Reload() error {
if t.Version != "" && t.Kind != "static" && t.Kind != "status" && !genManaged {
proxy = versionHeader(t.Version, proxy)
}
- // Hibernation is per-host: only an instance whose route carries the
- // hibernate flag is activator-managed; unflagged instances and sibling
- // services are proxied straight. With an activator wired but no route
+ // Hibernation is per-host: only an instance the activator owns (its
+ // route carries the hibernate flag, or a runtime: a resident rootfs
+ // instance never sleeps but is the activator's all the same,
+ // registry.Route.ActivatorOwned) is activator-managed; unflagged
+ // binary instances and sibling services are proxied straight. With an activator wired but no route
// flagged, the edge therefore behaves exactly as it does without one —
// so the binary + env can ship fleet-wide first, and the flag flips
// one instance at a time.
@@ -923,7 +925,7 @@ func (e *Edge) Reload() error {
// this platform edge must never manage it either. The lease race is
// the backstop if the fallback rule (fleetProxy) ever routes two
// requests to two different boxes for the same route in a gap.
- hib := e.act != nil && t.Kind == "instance" && t.Hibernate && !viaTunnel
+ hib := e.act != nil && t.ActivatorOwned() && !viaTunnel
if hib {
managed[t.Host] = true
}
@@ -956,7 +958,7 @@ func (e *Edge) Reload() error {
// a value the box itself controls, per logThrottled's rule. Not a
// refusal to serve: dropping the route would only trade a 502 for a
// 404, and the row may yet be served once an activator arms.
- if e.act == nil && t.Kind == "instance" && t.Hibernate && !viaTunnel {
+ if e.act == nil && t.ActivatorOwned() && !viaTunnel {
e.logThrottled("no-activator "+t.Host, fmt.Sprintf(
"route %s is a hibernating instance but this box has no activator, so nothing here will create %s or start its process. If this box runs `carlos agent`, set CARLOS_HIBERNATE_BUCKET in /etc/carlos/host.env and restart carlos-edge; `carlos edge` on its own never runs instances.",
t.Host, t.Socket))
diff --git a/internal/edge/rootfs_reload_test.go b/internal/edge/rootfs_reload_test.go
new file mode 100644
index 000000000..0ef06ce9a
--- /dev/null
+++ b/internal/edge/rootfs_reload_test.go
@@ -0,0 +1,113 @@
+package edge
+
+import (
+ "bytes"
+ "log"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// reloadRows are the rows the edge's three activator tests are asked
+// about: a binary instance asleep and awake, a hibernating binary sidecar,
+// a resident rootfs instance and an unknown runtime (fixed and inert, so
+// the activator's: registry.Route.ActivatorOwned).
+func reloadRows() []registry.Route {
+ row := func(host string) registry.Route {
+ return registry.Route{Host: host, Kind: "instance", App: "shop", Account: "bab", Status: "ready",
+ Socket: "/run/carlos/instances/" + host + "/app.sock", DBPath: "/data/instances/" + host + "/" + host + ".db"}
+ }
+ asleep := row("asleep.example.com")
+ asleep.Hibernate = true
+ awake := row("awake.example.com")
+ resident := row("shop.example.com")
+ resident.Runtime = registry.RuntimeRootfsV1
+ unknown := row("later.example.com")
+ unknown.Runtime = "rootfs-v9"
+ sidecar := registry.Route{Host: "jobs.example.com", Kind: "sidecar", App: "shop", Account: "bab", Status: "ready",
+ Hibernate: true, DBPath: "/data/jobs.example.com.db"}
+ return []registry.Route{asleep, awake, resident, unknown, sidecar}
+}
+
+// reloadOwned is which of reloadRows the activator manages after a reload.
+var reloadOwned = map[string]bool{
+ "asleep.example.com": true,
+ "awake.example.com": false,
+ "shop.example.com": true,
+ "later.example.com": true,
+ "jobs.example.com": false, // the edge serves no sidecar, as on main
+}
+
+func reloadRegistry(t *testing.T) *registry.Registry {
+ t.Helper()
+ reg := openReg(t)
+ for _, rt := range reloadRows() {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatalf("upsert %s: %v", rt.Host, err)
+ }
+ }
+ return reg
+}
+
+// TestReloadManagesResidentRootfs: the edge's activator test is
+// ActivatorOwned at all three sites. A resident rootfs instance is handed
+// to the activator (upstream.hibernating), is in the managed set
+// RetireExcept keeps, and with generations on is reached through its
+// current generation. Binary rows and the hibernating sidecar answer as on
+// main.
+func TestReloadManagesResidentRootfs(t *testing.T) {
+ act := &fakeActivator{}
+ e, err := New(reloadRegistry(t), act)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ if len(act.retired) == 0 {
+ t.Fatal("Reload handed no managed set to RetireExcept")
+ }
+ keep := act.retired[len(act.retired)-1]
+ cur := e.current()
+ for host, want := range reloadOwned {
+ if up, ok := cur[host]; ok && up.hibernating != want {
+ t.Errorf("%s: upstream.hibernating = %v, want %v", host, up.hibernating, want)
+ } else if !ok && want {
+ t.Errorf("%s: no upstream", host)
+ }
+ if keep[host] != want {
+ t.Errorf("%s: in RetireExcept's managed set = %v, want %v", host, keep[host], want)
+ }
+ }
+
+ // Generations on: the owned rows dial their current generation.
+ gact := &genActivator{fakeGens: newFakeGens(true)}
+ e, err = New(reloadRegistry(t), gact)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ cur = e.current()
+ for host, want := range reloadOwned {
+ if up, ok := cur[host]; ok && up.genManaged != want {
+ t.Errorf("%s: upstream.genManaged = %v, want %v", host, up.genManaged, want)
+ }
+ }
+}
+
+// TestNoActivatorAdviceNamesResidentRootfs: on a box with no activator, the
+// edge's diagnostic names every row only an activator would start, a
+// resident rootfs instance included, and no binary awake row.
+func TestNoActivatorAdviceNamesResidentRootfs(t *testing.T) {
+ var buf bytes.Buffer
+ prev := log.Writer()
+ log.SetOutput(&buf)
+ defer log.SetOutput(prev)
+ if _, err := New(reloadRegistry(t), nil); err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ out := buf.String()
+ for host, want := range reloadOwned {
+ got := strings.Contains(out, "route "+host+" is a hibernating instance but this box has no activator")
+ if got != want {
+ t.Errorf("%s: no-activator advice logged = %v, want %v\n%s", host, got, want, out)
+ }
+ }
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 3245308c3..d624f2464 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -4471,6 +4471,8 @@ func makeRestartRoute(reg *registry.Registry, tryRestart func(host string), tryR
func makeStartRoute(reg *registry.Registry, startUnit func(unit string) error) func(host string) error {
return func(host string) error {
rt, err := reg.Get(host)
+ // Left on Hibernate: unit-only (rt.Unit == "" returns first for an
+ // exec row, a resident rootfs instance included).
if err != nil || rt == nil || rt.Hibernate || rt.Unit == "" {
return nil
}
diff --git a/internal/host/layoutleg.go b/internal/host/layoutleg.go
index 37d3b88b5..740486151 100644
--- a/internal/host/layoutleg.go
+++ b/internal/host/layoutleg.go
@@ -686,7 +686,9 @@ func logLayoutResults(rs []layout.Result) (retry bool) {
var awake []string
for _, r := range rs {
switch {
- case r.Outcome == "unchanged":
+ case r.Outcome == "unchanged", r.Outcome == "kept":
+ // kept is a rootfs row's standing answer (always nested), said
+ // on every pass: as quiet as unchanged.
case r.Outcome == "held":
retry = true
log.Printf("layout: %s: %s -> %s", r.Host, r.Outcome, r.Reason)
diff --git a/internal/host/probes.go b/internal/host/probes.go
index dc42fd9ac..ff65b5c4a 100644
--- a/internal/host/probes.go
+++ b/internal/host/probes.go
@@ -307,7 +307,7 @@ func wrapListeningProbe(unitBacked map[string]bool, probe func(string) *bool) fu
func currentSocketProbe(routes []registry.Route, appSocket func(host string) (string, bool), probe func(string) *bool) func(string) *bool {
hostOf := map[string]string{}
for _, r := range routes {
- if r.Kind == "instance" && r.Hibernate && r.Socket != "" && r.Backing != registry.BackingUnit {
+ if r.ActivatorOwned() && r.Socket != "" && r.Backing != registry.BackingUnit {
hostOf[r.Socket] = r.Host
}
}
diff --git a/internal/host/restart.go b/internal/host/restart.go
index 8f5d28afe..aa068d862 100644
--- a/internal/host/restart.go
+++ b/internal/host/restart.go
@@ -762,6 +762,8 @@ func restartPass(ctx context.Context, routes []registry.Route, store release.Sto
if !release.Adoptable(rt) || rt.App != k[1] || release.RouteAccount(rt) != k[0] {
continue
}
+ // Left on Hibernate: a unit-only path; an exec row, a resident
+ // rootfs instance included, is bounced by the agent.
if rt.Hibernate {
log.Printf("adopt: restart requested for %s/%s: %s is hibernating — left asleep (it execs fresh on its next wake)",
k[0], k[1], rt.Host)
diff --git a/internal/host/restartscope.go b/internal/host/restartscope.go
index 5863a738b..0256d01bb 100644
--- a/internal/host/restartscope.go
+++ b/internal/host/restartscope.go
@@ -493,6 +493,8 @@ func restartScopeLeg(ctx context.Context, routes []registry.Route, store release
if !ok {
continue
}
+ // Left on Hibernate: a resident is not asleep, so it goes to the
+ // restart callback, a no-op for an exec row; the scheduler moves it.
if rt.Hibernate {
log.Printf("adopt: narrowed restart for %s/%s: %s is hibernating — left asleep (it execs fresh on its next wake)", k[0], k[1], host)
continue
diff --git a/internal/host/retention.go b/internal/host/retention.go
index e6b1c7248..51aaacd29 100644
--- a/internal/host/retention.go
+++ b/internal/host/retention.go
@@ -391,9 +391,13 @@ func settingsProtected(ctx context.Context, store release.Store, boxes []status.
// never "nothing to protect". For a valid record this is
// keepsBuildState's instance rule (activator.ActivatorManaged): an
// instance with no unit that hibernates has no addr (the record door
- // refuses addr with hibernate), so reconcile mints it a socket.
+ // refuses addr with hibernate), so reconcile mints it a socket. A
+ // rootfs record is the same whether or not it hibernates: a resident
+ // never sleeps but the activator owns it, reconcile mints it nested
+ // (no addr: validateRuntime), and its box reports its build state like
+ // a hibernating one's [Astra R3 2].
for _, r := range recs {
- if r.KindOrDefault() != "instance" || r.Unit != "" || !r.HibernateOrDefault() {
+ if r.KindOrDefault() != "instance" || r.Unit != "" || (!r.HibernateOrDefault() && r.Runtime != provision.RuntimeRootfsV1) {
continue
}
if _, ok := byHost[r.Host]; !ok {
diff --git a/internal/host/rootfs_advice_test.go b/internal/host/rootfs_advice_test.go
new file mode 100644
index 000000000..e079be04a
--- /dev/null
+++ b/internal/host/rootfs_advice_test.go
@@ -0,0 +1,334 @@
+package host
+
+import (
+ "context"
+ "log"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/layout"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// rootfsHostRows are the rows each host reader is asked about: a binary
+// instance asleep and awake, a hibernating binary sidecar with a socket and
+// database (the shape no reader may newly take), a resident rootfs
+// instance and an unknown runtime (fixed and inert: the activator's).
+func rootfsHostRows() map[string]registry.Route {
+ row := func(host string) registry.Route {
+ return registry.Route{Host: host, Kind: "instance", App: "shop", Account: "bab", Status: "ready",
+ Socket: "/run/carlos/instances/" + host + "/app.sock", DBPath: "/data/instances/" + host + "/" + host + ".db"}
+ }
+ asleep := row("asleep.example.com")
+ asleep.Hibernate = true
+ resident := row("shop.example.com")
+ resident.Runtime = registry.RuntimeRootfsV1
+ unknown := row("later.example.com")
+ unknown.Runtime = "rootfs-v9"
+ sidecar := row("jobs.example.com")
+ sidecar.Kind, sidecar.Hibernate = "sidecar", true
+ return map[string]registry.Route{
+ "binary hibernating": asleep,
+ "binary awake": row("awake.example.com"),
+ "hibernating sidecar": sidecar,
+ "resident rootfs": resident,
+ "unknown runtime": unknown,
+ }
+}
+
+// TestSocketAdvisoryLeavesOwnedResident: a resident's live socket, owned by
+// the activator, is not a stray; not owned, it is, and the line logged is
+// the activator-managed one, never the "set hibernate=1" advice it could
+// not take. A binary awake row warns with that advice whoever owns it, and
+// a hibernating sidecar with a socket is out of the advisory's scope, both
+// as on main.
+func TestSocketAdvisoryLeavesOwnedResident(t *testing.T) {
+ t.Parallel()
+ const strayLine = "is activator-managed (hibernate=1) but its socket"
+ const flagLine = "set hibernate=1 once the app speaks the activation contract"
+ for name, c := range map[string]struct {
+ ownedWarns, unownedWarns bool
+ line string
+ }{
+ "binary hibernating": {false, true, strayLine},
+ "binary awake": {true, true, flagLine},
+ "hibernating sidecar": {false, false, ""},
+ "resident rootfs": {false, true, strayLine},
+ "unknown runtime": {false, true, strayLine},
+ } {
+ rt := rootfsHostRows()[name]
+ serving := func(string) bool { return true }
+ for owned, want := range map[bool]bool{true: c.ownedWarns, false: c.unownedWarns} {
+ got := warnExternalSockets([]registry.Route{rt}, serving, func(string) bool { return owned })
+ if (len(got) == 1) != want {
+ t.Errorf("%s, owned %v: warned %v, want %v", name, owned, len(got) == 1, want)
+ }
+ }
+ if c.line != "" {
+ if got := socketAdvice(rt); !strings.Contains(got, c.line) {
+ t.Errorf("%s: advice %q, want the line containing %q", name, got, c.line)
+ }
+ }
+ }
+
+ // With generations on, a resident's canonical path is the activator's
+ // symlink to its current generation, and is not probed as a stray.
+ dir := t.TempDir()
+ routes := []registry.Route{}
+ links := map[string]string{}
+ for name, rt := range rootfsHostRows() {
+ rt.Socket = filepath.Join(dir, rt.Host+".sock")
+ cur := filepath.Join(dir, rt.Host+".1.sock")
+ if err := os.Symlink(cur, rt.Socket); err != nil {
+ t.Fatal(err)
+ }
+ links[name] = rt.Socket
+ routes = append(routes, rt)
+ }
+ appSocket := func(host string) (string, bool) { return filepath.Join(dir, host+".1.sock"), true }
+ probe := advisorySocketServing(routes, appSocket, func(string) bool { return true })
+ for name, want := range map[string]bool{
+ "binary hibernating": false,
+ "binary awake": true,
+ "hibernating sidecar": true,
+ "resident rootfs": false,
+ "unknown runtime": false,
+ } {
+ if got := probe(links[name]); got != want {
+ t.Errorf("advisorySocketServing(%s) = %v, want %v", name, got, want)
+ }
+ }
+}
+
+// TestCurrentSocketProbeFollowsResident: with generations on, the status
+// probe asks about a resident's current generation, as it does for a
+// hibernating binary instance; a binary awake row and a sidecar are probed
+// at their own socket, as on main.
+func TestCurrentSocketProbeFollowsResident(t *testing.T) {
+ t.Parallel()
+ rows := rootfsHostRows()
+ var routes []registry.Route
+ for _, rt := range rows {
+ routes = append(routes, rt)
+ }
+ gen := func(host string) string { return "/run/carlos/g/" + host + ".4.sock" }
+ appSocket := func(host string) (string, bool) { return gen(host), true }
+ var asked string
+ probe := currentSocketProbe(routes, appSocket, func(sock string) *bool {
+ asked = sock
+ v := true
+ return &v
+ })
+ for name, followsGen := range map[string]bool{
+ "binary hibernating": true,
+ "binary awake": false,
+ "hibernating sidecar": false,
+ "resident rootfs": true,
+ "unknown runtime": true,
+ } {
+ rt := rows[name]
+ probe(rt.Socket)
+ want := rt.Socket
+ if followsGen {
+ want = gen(rt.Host)
+ }
+ if asked != want {
+ t.Errorf("%s: probed %s, want %s", name, asked, want)
+ }
+ }
+}
+
+// TestScheduledTicksFollowResidentGenerations: with generations on, a
+// resident's ticks go through its current generation, as a hibernating
+// binary instance's do. Not parallel: genDeliveryFixture sets the
+// activator's generations switch.
+func TestScheduledTicksFollowResidentGenerations(t *testing.T) {
+ svc, _, _ := genDeliveryFixture(t, true)
+ d := &activatorDeliverer{svc: svc}
+ for name, want := range map[string]bool{
+ "binary hibernating": true,
+ "binary awake": false,
+ "hibernating sidecar": false,
+ "resident rootfs": true,
+ "unknown runtime": true,
+ } {
+ if got := d.managedByGenerations(rootfsHostRows()[name]); got != want {
+ t.Errorf("managedByGenerations(%s) = %v, want %v", name, got, want)
+ }
+ }
+}
+
+// deleteRecorder is a directory store that records every key deleted
+// through it. It embeds the DirStore itself, not release.Store, so its
+// optional interfaces (ModLister, which pruning needs to rank versions)
+// still answer.
+type deleteRecorder struct {
+ *release.DirStore
+ mu sync.Mutex
+ deleted []string
+}
+
+func (d *deleteRecorder) Delete(ctx context.Context, key string) error {
+ d.mu.Lock()
+ d.deleted = append(d.deleted, key)
+ d.mu.Unlock()
+ return d.DirStore.Delete(ctx, key)
+}
+
+func residentRecord(host string) provision.Record {
+ no := false
+ return provision.Record{Schema: 1, Host: host, App: "km", Account: "bab", Channel: "stable",
+ Runtime: provision.RuntimeRootfsV1, Hibernate: &no}
+}
+
+// TestRetentionRefusesWithoutAResidentReport [Astra R3 2]: a resident
+// rootfs record keeps a build state like a hibernating one, so retention
+// needs a fresh, complete report naming it. Absent, older than
+// buildStateReportMaxAge, or not Complete, settingsProtected refuses, and
+// retentionPass deletes nothing. A binary always-on record and a unit
+// record are still not required, as on main.
+func TestRetentionRefusesWithoutAResidentReport(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ const host = "r.example.com"
+ s := recordsStore(t, residentRecord(host))
+ fresh := now0.Add(-time.Minute)
+ stale := now0.Add(-buildStateReportMaxAge - time.Minute)
+ incomplete := kmPins("v1")
+ incomplete.Complete = false
+ for name, boxes := range map[string][]status.Box{
+ "absent": {report("uk-1", fresh, map[string]status.BuildStatePins{})},
+ "stale": {report("uk-1", stale, map[string]status.BuildStatePins{host: kmPins("v1")})},
+ "incomplete": {report("uk-1", fresh, map[string]status.BuildStatePins{host: incomplete})},
+ } {
+ if _, err := settingsProtected(ctx, s, boxes, true, now0, "bab", "km"); err == nil {
+ t.Errorf("%s report: settingsProtected = nil error, want a refusal", name)
+ }
+ }
+ got, err := settingsProtected(ctx, s, []status.Box{report("uk-1", fresh, map[string]status.BuildStatePins{host: kmPins("v1")})}, true, now0, "bab", "km")
+ if err != nil || !got["v1"] {
+ t.Errorf("a fresh, complete report: %v, %v; want v1 protected", got, err)
+ }
+
+ no := false
+ notRequired := recordsStore(t,
+ provision.Record{Schema: 1, Host: "a.example.com", App: "km", Account: "bab", Channel: "stable", Hibernate: &no},
+ provision.Record{Schema: 1, Host: "u.example.com", App: "km", Account: "bab", Channel: "stable", Unit: "carlos-app@u"})
+ if _, err := settingsProtected(ctx, notRequired, nil, true, now0, "bab", "km"); err != nil {
+ t.Errorf("a binary always-on and a unit record with no report: %v, want no refusal (as on main)", err)
+ }
+
+ // Through the pass: an eligible build named only by the resident's
+ // build state, whose report is absent. Nothing is deleted.
+ dir := t.TempDir()
+ ds := release.NewDirStore(dir)
+ if err := provision.CreateRecord(ctx, ds, residentRecord(host)); err != nil {
+ t.Fatal(err)
+ }
+ base := time.Now().Add(-30 * 24 * time.Hour)
+ vname := func(i int) string { return "v" + string(rune('0'+i/10)) + string(rune('0'+i%10)) }
+ for i := 1; i <= 25; i++ {
+ stampKey(t, ds, dir, release.ManifestKey("bab", "km", vname(i)), base.Add(time.Duration(i)*time.Hour))
+ stampKey(t, ds, dir, release.ArtifactKey("bab", "km", vname(i), "linux-arm64"), base.Add(time.Duration(i)*time.Hour))
+ }
+ _, pub := retentionKeys(t)
+ // keep-20 protects v06..v25; the row pins v25. v01..v05 are eligible
+ // unless the resident's build state names them, which only its
+ // (absent) report could say.
+ if err := release.SetRetention(ctx, ds, "bab", "km", 20, "test", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ if err := reg.Upsert(registry.Route{Host: host, Kind: "instance", App: "km", Account: "bab", Status: "ready",
+ Runtime: registry.RuntimeRootfsV1, Version: "v25", Socket: provision.NestedSocket(host), DBPath: provision.NestedDBPath(dir, host)}); err != nil {
+ t.Fatal(err)
+ }
+ rec := &deleteRecorder{DirStore: ds}
+ if err := retentionPass(ctx, rec, &boxReports{status: release.NewDirStore(t.TempDir())}, pub, reg); err != nil {
+ t.Fatal(err)
+ }
+ for _, k := range rec.deleted {
+ if strings.Contains(k, "/releases/") {
+ t.Errorf("retention deleted %s with the resident's report absent", k)
+ }
+ }
+ for _, v := range []string{"v01", "v02", "v03", "v04", "v05"} {
+ if _, _, err := ds.Get(ctx, release.ManifestKey("bab", "km", v)); err != nil {
+ t.Errorf("%s pruned with the resident's report absent: %v", v, err)
+ }
+ }
+
+ // The control: once a fresh, complete report names the resident, the
+ // same pass prunes, so the zero above is the refusal and nothing else.
+ local := func() (map[string]status.BuildStatePins, error) {
+ return map[string]status.BuildStatePins{host: kmPins("v03")}, nil
+ }
+ if err := retentionPass(ctx, rec, &boxReports{local: local}, pub, reg); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := ds.Get(ctx, release.ManifestKey("bab", "km", "v01")); err == nil {
+ t.Error("v01 kept with a fresh, complete report naming the resident: the control pruned nothing")
+ }
+ if _, _, err := ds.Get(ctx, release.ManifestKey("bab", "km", "v03")); err != nil {
+ t.Errorf("v03, named by the resident's build state, was pruned: %v", err)
+ }
+}
+
+// TestResidentSettingsRefsWaitForBuildState [pf 1.13]: a held resident's
+// settings refs are incomplete while its build state is unread, so the
+// staged-version sweep deletes nothing before keepsBuildState's read could
+// name its last_executed. release.BuildStateKept and keepsBuildState agree
+// on every instance row.
+func TestResidentSettingsRefsWaitForBuildState(t *testing.T) {
+ t.Parallel()
+ held := release.UpdateSettings{Updates: release.UpdatesManual, Channel: "stable", Pin: "v1"}.Column()
+ for name, rt := range rootfsHostRows() {
+ if rt.Kind == "instance" {
+ if kept, keeps := release.BuildStateKept(rt), keepsBuildState(rt, false); kept != keeps {
+ t.Errorf("%s: release.BuildStateKept = %v, keepsBuildState = %v; want them equal", name, kept, keeps)
+ }
+ }
+ }
+ resident := rootfsHostRows()["resident rootfs"]
+ resident.UpdateSettings = held
+ if _, err := settingsPins([]registry.Route{resident}); err == nil {
+ t.Error("settingsPins(held resident, build state unread) = nil error, want incomplete: the sweep would read its refs as complete")
+ }
+ resident.BuildState = release.BuildStateCopy{Known: true, State: &release.BuildState{Schema: 1, Host: resident.Host, LastExecuted: "v0"}}.Column()
+ pins, err := settingsPins([]registry.Route{resident})
+ if err != nil || !pins["v0"] || !pins["v1"] {
+ t.Errorf("settingsPins(held resident, build state read) = %v, %v; want v0 and v1", pins, err)
+ }
+ awake := rootfsHostRows()["binary awake"]
+ awake.UpdateSettings = held
+ if _, err := settingsPins([]registry.Route{awake}); err != nil {
+ t.Errorf("settingsPins(held binary awake row) = %v, want nil as on main (the agent never refreshes it)", err)
+ }
+}
+
+// TestLayoutLegIsQuietAboutKeptRootfsRows: the layout pass says kept for
+// every rootfs row on every pass; the leg neither logs it nor retries for
+// it, as for unchanged. Not parallel: it captures the log.
+func TestLayoutLegIsQuietAboutKeptRootfsRows(t *testing.T) {
+ var buf strings.Builder
+ prev := log.Writer()
+ log.SetOutput(&buf)
+ defer log.SetOutput(prev)
+ if logLayoutResults([]layout.Result{{Host: "shop.example.com", Outcome: "kept", Reason: "rootfs instances are always nested"}}) {
+ t.Error("a kept rootfs row asked the leg to run again")
+ }
+ if buf.Len() != 0 {
+ t.Errorf("a kept rootfs row was logged: %q", buf.String())
+ }
+}
diff --git a/internal/host/schedule_wiring.go b/internal/host/schedule_wiring.go
index 8bcd4dcd3..b81a3543a 100644
--- a/internal/host/schedule_wiring.go
+++ b/internal/host/schedule_wiring.go
@@ -339,7 +339,7 @@ type activatorDeliverer struct {
// managedByGenerations reports whether rt's ticks go through the current
// generation: generations on, and an activator-managed instance.
func (d *activatorDeliverer) managedByGenerations(rt registry.Route) bool {
- return d.svc != nil && d.svc.GenerationsOn() && rt.Kind == "instance" && rt.Hibernate
+ return d.svc != nil && d.svc.GenerationsOn() && rt.ActivatorOwned()
}
// genProxyFor is the AppSocket proxy for host over the leg's own pools.
diff --git a/internal/host/socket_advice.go b/internal/host/socket_advice.go
index 366be32e0..be10767d0 100644
--- a/internal/host/socket_advice.go
+++ b/internal/host/socket_advice.go
@@ -9,6 +9,7 @@ package host
import (
"context"
"errors"
+ "fmt"
"log"
"math/rand/v2"
"net"
@@ -39,7 +40,9 @@ func warnExternalSockets(routes []registry.Route, serving func(socket string) bo
if !serving(rt.Socket) {
continue
}
- if rt.Hibernate && owns(rt.Host) {
+ // ActivatorLeased, not Hibernate: a resident rootfs instance never
+ // hibernates, and its live socket is the activator's own child.
+ if rt.ActivatorLeased() && owns(rt.Host) {
continue // the activator's own child, in whatever state
}
warned = append(warned, rt)
@@ -80,7 +83,7 @@ func socketServing(socket string) bool {
func advisorySocketServing(routes []registry.Route, appSocket func(host string) (string, bool), serving func(string) bool) func(string) bool {
hostOf := map[string]string{}
for _, r := range routes {
- if r.Kind == "instance" && r.Hibernate && r.Socket != "" && r.Backing != registry.BackingUnit {
+ if r.ActivatorOwned() && r.Socket != "" && r.Backing != registry.BackingUnit {
hostOf[r.Socket] = r.Host
}
}
@@ -118,11 +121,19 @@ func socketAdvisoryLoop(reg *registry.Registry, svc *activator.Service) {
serving = advisorySocketServing(routes, svc.AppSocket, socketServing)
}
for _, rt := range warnExternalSockets(routes, serving, owns) {
- if rt.Hibernate {
- log.Printf("agent: route %s is activator-managed (hibernate=1) but its socket %s is served by a process the activator did not spawn — a stray supervisor is squatting the socket and will fight the wake path; find and retire it (see platform issue #17)", rt.Host, rt.Socket)
- } else {
- log.Printf("agent: route %s is exec-shaped with hibernate=0 and its socket %s is live — an external process serves it, the activator never engages, and spawn-time config delivery (/data/%s.config.env) never reaches it; retire the external supervisor and set hibernate=1 once the app speaks the activation contract (see platform issue #17)", rt.Host, rt.Socket, rt.Host)
- }
+ log.Print(socketAdvice(rt))
}
}
}
+
+// socketAdvice is the advisory's line for a route warnExternalSockets
+// returned. An activator-managed route (Route.ActivatorLeased: hibernating,
+// or a resident rootfs instance, which never hibernates) gets the
+// stray-supervisor line; only a binary hibernate=0 route gets the "set
+// hibernate=1" advice, which a resident could never take [pf 1.13].
+func socketAdvice(rt registry.Route) string {
+ if rt.ActivatorLeased() {
+ return fmt.Sprintf("agent: route %s is activator-managed (hibernate=1) but its socket %s is served by a process the activator did not spawn — a stray supervisor is squatting the socket and will fight the wake path; find and retire it (see platform issue #17)", rt.Host, rt.Socket)
+ }
+ return fmt.Sprintf("agent: route %s is exec-shaped with hibernate=0 and its socket %s is live — an external process serves it, the activator never engages, and spawn-time config delivery (/data/%s.config.env) never reaches it; retire the external supervisor and set hibernate=1 once the app speaks the activation contract (see platform issue #17)", rt.Host, rt.Socket, rt.Host)
+}
diff --git a/internal/layout/pass.go b/internal/layout/pass.go
index 26a3870cd..af2b311d7 100644
--- a/internal/layout/pass.go
+++ b/internal/layout/pass.go
@@ -111,9 +111,10 @@ type Pass struct {
}
// Result is what the pass says about one host. Outcome is one of
-// migrated, reverted, recovered, unchanged, skipped, deferred, refused or
+// migrated, reverted, recovered, unchanged, skipped, deferred, refused,
// held (refused after the host was stopped for a nested move, and kept
-// fenced and down; see migrateHost). A Result with an empty Host is about
+// fenced and down; see migrateHost) or kept (a rootfs row, which the pass
+// never moves: keptRootfs). A Result with an empty Host is about
// the whole pass.
type Result struct {
Host string
@@ -223,6 +224,19 @@ func deadline(ctx context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, quiesceTimeout)
}
+// keptRootfs is the pass's answer for a row with a runtime: kept where it
+// is, in both modes. A rootfs instance is always nested (anti-goal §2;
+// reconcile mints it so on every box), and ActivatorManaged names a
+// resident, so without this the pass would fence it and move it flat. An
+// unknown runtime is fixed and inert, and is not the pass's to move
+// either.
+func keptRootfs(rt registry.Route) (Result, bool) {
+ if rt.Runtime == "" {
+ return Result{}, false
+ }
+ return Result{rt.Host, "kept", "rootfs instances are always nested"}, true
+}
+
// ready is the status a row must have for the pass to move it. Any other
// status belongs to an operation in flight on the row, the residence
// move's "moving" among them, and a row about to leave the box is not
@@ -264,6 +278,10 @@ func (p *Pass) Converge(ctx context.Context, mode Mode) []Result {
if !activator.ActivatorManaged(rt) || seen[rt.Host] {
continue
}
+ if r, kept := keptRootfs(rt); kept {
+ out = append(out, r)
+ continue
+ }
if ctx.Err() != nil {
break
}
@@ -530,6 +548,12 @@ func (p *Pass) restoreHold(ctx context.Context, host string) Result {
removeHoldMarker(p.DataDir, host)
return Result{host, "released", "hold marker dropped: the row is gone or no longer managed"}
}
+ if r, kept := keptRootfs(*rt); kept {
+ // The pass never holds a rootfs row (it never moves one), so a
+ // marker naming it is not the pass's and restores nothing.
+ removeHoldMarker(p.DataDir, host)
+ return r
+ }
if layout, _ := p.Classify(*rt, routes); layout != activator.LayoutFlat {
removeHoldMarker(p.DataDir, host)
return Result{host, "released", "hold marker dropped: the row is " + string(layout)}
@@ -557,6 +581,11 @@ func (p *Pass) restoreHold(ctx context.Context, host string) Result {
// (the same classes shift holds on). An empty reason means the move
// would go ahead.
func (p *Pass) recheck(host string, routes []registry.Route) (reason string, plantable bool) {
+ for _, rt := range routes {
+ if r, kept := keptRootfs(rt); kept && rt.Host == host {
+ return r.Reason, false
+ }
+ }
plan, err := PlanFor(p.DataDir, p.socketDir(), host, ModeNested)
if err != nil {
return err.Error(), false
@@ -747,6 +776,9 @@ func (p *Pass) shift(host string, mode Mode, prior *Journal) (res Result, h hand
if !activator.ActivatorManaged(*fresh) {
return Result{host, "refused", "no longer activator-managed under the fence"}, handoverNone, false
}
+ if r, kept := keptRootfs(*fresh); kept {
+ return r, handoverNone, false
+ }
routes, err := p.Registry.List()
if err != nil {
return Result{host, "refused", "list routes: " + err.Error()}, handoverNone, false
diff --git a/internal/layout/rootfs_pass_test.go b/internal/layout/rootfs_pass_test.go
new file mode 100644
index 000000000..b8844462e
--- /dev/null
+++ b/internal/layout/rootfs_pass_test.go
@@ -0,0 +1,120 @@
+//go:build linux
+
+package layout
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+const rootfsHost = "shop.example.com"
+
+// addRootfsRow adds a resident rootfs row at mode's endpoint, with a
+// database file there that the pass must leave as it is.
+func addRootfsRow(t *testing.T, p *Pass, h, runtime string, mode Mode) Endpoint {
+ t.Helper()
+ at := endpoints(t, p, h, mode)
+ if err := os.MkdirAll(filepath.Dir(at.DB), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(at.DB, []byte("db "+h), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := p.Registry.Upsert(registry.Route{Host: h, Kind: "instance", Status: "ready", Runtime: runtime,
+ Socket: at.Socket, DBPath: at.DB}); err != nil {
+ t.Fatal(err)
+ }
+ return at
+}
+
+func assertRootfsKept(t *testing.T, p *Pass, f *fakeFence, h string, at Endpoint, r Result) {
+ t.Helper()
+ if r.Outcome != "kept" || r.Reason != "rootfs instances are always nested" {
+ t.Errorf("%s: result %+v, want kept: rootfs instances are always nested", h, r)
+ }
+ if got := rowAt(t, p, h); got != at {
+ t.Errorf("%s row moved: %+v, want %+v", h, got, at)
+ }
+ if b, err := os.ReadFile(at.DB); err != nil || string(b) != "db "+h {
+ t.Errorf("%s db: %q %v", h, b, err)
+ }
+ if JournalPresent(p.DataDir, h) {
+ t.Errorf("%s has a journal", h)
+ }
+ if f.fences[h] != 0 {
+ t.Errorf("%s was fenced", h)
+ }
+}
+
+// TestPassNeverMovesRootfsRows: a rootfs instance is always nested
+// (anti-goal §2), and ActivatorManaged now names a resident, so the pass
+// keeps every rootfs row where it is, in both modes: no fence, no journal,
+// no file or row moved. An unknown runtime is fixed and inert and is kept
+// the same way. The binary rows beside it still converge.
+func TestPassNeverMovesRootfsRows(t *testing.T) {
+ p, f := box(t)
+ at := addRootfsRow(t, p, rootfsHost, registry.RuntimeRootfsV1, ModeNested)
+ unknownAt := addRootfsRow(t, p, "later.example.com", "rootfs-v9", ModeNested)
+
+ out := byHost(t, p.Converge(context.Background(), ModeFlat))
+ assertRootfsKept(t, p, f, rootfsHost, at, out[rootfsHost])
+ assertRootfsKept(t, p, f, "later.example.com", unknownAt, out["later.example.com"])
+ if out[host].Outcome != "unchanged" {
+ t.Errorf("binary row %s in flat mode: %+v, want unchanged", host, out[host])
+ }
+
+ out = byHost(t, p.Converge(context.Background(), ModeNested))
+ assertRootfsKept(t, p, f, rootfsHost, at, out[rootfsHost])
+ if out[host].Outcome != "migrated" {
+ t.Errorf("binary row %s in nested mode: %+v, want migrated", host, out[host])
+ }
+
+ // A rootfs row found at the flat paths (never minted so, but a row
+ // the pass is shown) is not moved to nested either.
+ p2, f2 := box(t)
+ flatAt := addRootfsRow(t, p2, rootfsHost, registry.RuntimeRootfsV1, ModeFlat)
+ out = byHost(t, p2.Converge(context.Background(), ModeNested))
+ assertRootfsKept(t, p2, f2, rootfsHost, flatAt, out[rootfsHost])
+}
+
+// TestRestoreHoldNeverHoldsARootfsRow: a hold marker naming a rootfs host
+// (the pass never writes one, but the marker is a file anyone with the
+// agent's uid can write) restores no hold: no fence, the marker dropped,
+// the result kept. recheck refuses the host the same way.
+func TestRestoreHoldNeverHoldsARootfsRow(t *testing.T) {
+ p, f := box(t)
+ addRootfsRow(t, p, rootfsHost, registry.RuntimeRootfsV1, ModeFlat)
+ if err := writeHoldMarker(p.DataDir, rootfsHost, "planted", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ r := byHost(t, p.RestoreHolds(context.Background(), ModeNested))[rootfsHost]
+ if r.Outcome != "kept" || r.Reason != "rootfs instances are always nested" {
+ t.Errorf("restore: %+v, want kept", r)
+ }
+ if f.fences[rootfsHost] != 0 {
+ t.Error("a hold marker fenced a rootfs row")
+ }
+ if _, held := p.Held(rootfsHost); held {
+ t.Error("a rootfs row is held")
+ }
+ if _, err := os.Lstat(filepath.Join(p.DataDir, "layout", rootfsHost+".hold")); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("the marker survived: %v", err)
+ }
+
+ routes, err := p.Registry.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if reason, plantable := p.recheck(rootfsHost, routes); reason != "rootfs instances are always nested" || plantable {
+ t.Errorf("recheck = %q, %v; want the rootfs refusal, not plantable", reason, plantable)
+ }
+ if _, err := os.Lstat(filepath.Dir(endpoints(t, p, rootfsHost, ModeNested).DB)); err == nil {
+ t.Error("recheck made the rootfs host's instance directory")
+ }
+}
diff --git a/internal/ops/hibernate_verify.go b/internal/ops/hibernate_verify.go
index 7073f3260..a1078e3db 100644
--- a/internal/ops/hibernate_verify.go
+++ b/internal/ops/hibernate_verify.go
@@ -55,7 +55,9 @@ func HibernatingHosts(reg *registry.Registry) ([]HibernatingRoute, error) {
if r.Backing == registry.BackingUnit {
continue
}
- if r.Hibernate && r.DBPath != "" {
+ // FleetDBsWithSkipped's exclusion, the same expression: a resident
+ // rootfs row is drilled here, never by box-wide litestream.
+ if r.ActivatorLeased() && r.DBPath != "" {
hosts = append(hosts, HibernatingRoute{Host: r.Host, DBPath: r.DBPath})
}
}
diff --git a/internal/ops/litestream.go b/internal/ops/litestream.go
index de6307f40..32d1eae4f 100644
--- a/internal/ops/litestream.go
+++ b/internal/ops/litestream.go
@@ -353,7 +353,12 @@ func FleetDBsWithSkipped(reg *registry.Registry, dataDir string, fenced func(hos
}
continue
}
- if r.Hibernate && r.DBPath != "" {
+ // The activator replicates every row it leases: hibernating rows,
+ // binary sidecars included, and every instance with a runtime,
+ // awake or asleep (Route.ActivatorLeased). Never ActivatorOwned,
+ // which is instance-only and would hand a hibernating sidecar's
+ // database to this pass beside the activator's [Astra R1 1].
+ if r.ActivatorLeased() && r.DBPath != "" {
hibernating[filepath.Clean(r.DBPath)] = true
}
}
diff --git a/internal/ops/rootfs_litestream_test.go b/internal/ops/rootfs_litestream_test.go
new file mode 100644
index 000000000..377d4f90b
--- /dev/null
+++ b/internal/ops/rootfs_litestream_test.go
@@ -0,0 +1,114 @@
+package ops
+
+import (
+ "os"
+ "path/filepath"
+ "slices"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// litestreamRow is one row of the box-wide replication partition tests: a
+// route, and whether its database belongs to the activator (skipped by
+// FleetDBsWithSkipped, listed by HibernatingHosts) or to box-wide
+// litestream (replicated, not listed).
+type litestreamRow struct {
+ name string
+ rt registry.Route
+ activator bool
+}
+
+// checkPartition writes each row's database, upserts the rows, and checks
+// that FleetDBsWithSkipped and HibernatingHosts split them as each row says.
+func checkPartition(t *testing.T, dir string, rows []litestreamRow) {
+ t.Helper()
+ reg, err := registry.Open(filepath.Join(dir, "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ for _, r := range rows {
+ if err := os.MkdirAll(filepath.Dir(r.rt.DBPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(r.rt.DBPath, []byte("x"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.Upsert(r.rt); err != nil {
+ t.Fatalf("%s: %v", r.name, err)
+ }
+ }
+ dbs, skipped, err := FleetDBsWithSkipped(reg, dir, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ hib, err := HibernatingHosts(reg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ listed := map[string]string{}
+ for _, h := range hib {
+ listed[h.Host] = h.DBPath
+ }
+ for _, r := range rows {
+ replicated := slices.Contains(dbs, r.rt.DBPath)
+ path, drilled := listed[r.rt.Host]
+ switch {
+ case r.activator && replicated:
+ t.Errorf("%s: %s is replicated box-wide beside the activator's replication: dbs %v", r.name, r.rt.DBPath, dbs)
+ case r.activator && (!drilled || path != r.rt.DBPath):
+ t.Errorf("%s: HibernatingHosts lists %v, want %s at %s (else no pass drills it)", r.name, hib, r.rt.Host, r.rt.DBPath)
+ case !r.activator && !replicated:
+ t.Errorf("%s: %s is not replicated box-wide: dbs %v, skipped %v", r.name, r.rt.DBPath, dbs, skipped)
+ case !r.activator && drilled:
+ t.Errorf("%s: HibernatingHosts lists %s, which box-wide litestream replicates", r.name, r.rt.Host)
+ }
+ }
+}
+
+// TestFleetDBsExcludesResidentRootfs: a resident rootfs instance never
+// sleeps, but the activator holds its lease and replicates its database
+// (Route.ActivatorLeased), so box-wide litestream must not claim it: two
+// writers on one replica. The restore drill lists it instead. A binary
+// hibernate=false row (as TestFleetDBsDiscoversNestedDatabases sets up) is
+// still box-wide litestream's, and an unknown runtime is fixed and inert,
+// the activator's like a resident.
+func TestFleetDBsExcludesResidentRootfs(t *testing.T) {
+ dir := t.TempDir()
+ nested := func(host string) registry.Route {
+ return registry.Route{Host: host, Kind: "instance", Socket: provision.NestedSocket(host), DBPath: provision.NestedDBPath(dir, host)}
+ }
+ resident := nested("shop.example.com")
+ resident.Runtime = registry.RuntimeRootfsV1
+ binaryAwake := nested("bab.example.com")
+ binaryAsleep := nested("asleep.example.com")
+ binaryAsleep.Hibernate = true
+ unknown := nested("later.example.com")
+ unknown.Runtime = "rootfs-v9"
+ checkPartition(t, dir, []litestreamRow{
+ {"resident rootfs", resident, true},
+ {"binary hibernate=false", binaryAwake, false},
+ {"binary hibernating", binaryAsleep, true},
+ {"unknown runtime", unknown, true},
+ })
+}
+
+// TestFleetDBsStillExcludesHibernatingSidecars [Astra R1 1]: a hibernating
+// binary sidecar, with the database path sidecarRouteFor mints, is the
+// activator's to replicate on main, so box-wide litestream skips it and the
+// restore drill lists it. An always-on sidecar's database is replicated
+// box-wide as on main. ActivatorOwned is instance-only: put in place of
+// ActivatorLeased it would hand the hibernating sidecar to box-wide
+// litestream as well.
+func TestFleetDBsStillExcludesHibernatingSidecars(t *testing.T) {
+ dir := t.TempDir()
+ sidecar := func(host string, hib bool) registry.Route {
+ return registry.Route{Host: host, Kind: provision.SidecarKind, App: "shop", DBPath: provision.DefaultDBPath(dir, host), Hibernate: hib, Status: "ready"}
+ }
+ checkPartition(t, dir, []litestreamRow{
+ {"hibernating sidecar", sidecar("jobs.example.com", true), true},
+ {"always-on sidecar", sidecar("mail.example.com", false), false},
+ })
+}
diff --git a/internal/provision/seedswap.go b/internal/provision/seedswap.go
index 2fc4dd352..3bbe79ce0 100644
--- a/internal/provision/seedswap.go
+++ b/internal/provision/seedswap.go
@@ -47,7 +47,7 @@ func importShape(rt registry.Route) string {
return "canary"
case rt.FleetBox != "":
return "fleet_box"
- case rt.Kind == "instance" && rt.Hibernate:
+ case rt.Kind == "instance" && rt.Hibernate: // left on Hibernate: a rootfs record carries no seed (D5)
return "hibernate"
case rt.ClaimOwnership != (registry.ClaimOwnership{}):
return "claim_owner"
diff --git a/internal/release/adopt.go b/internal/release/adopt.go
index 90e76816e..8849d2302 100644
--- a/internal/release/adopt.go
+++ b/internal/release/adopt.go
@@ -1238,6 +1238,9 @@ func PassFilter(ctx context.Context, reg *registry.Registry, s Store, pub ed2551
sidecars = append(sidecars, rt)
continue
}
+ // Left on Hibernate: a resident rootfs instance adopts in the awake
+ // group, whose restart is a no-op for an exec row
+ // (host/rootrestart.go); the scheduler moves it, through N1's swap.
if rt.Hibernate {
hibernating = append(hibernating, rt)
continue
diff --git a/internal/release/pins.go b/internal/release/pins.go
index a9927edf1..4519d7365 100644
--- a/internal/release/pins.go
+++ b/internal/release/pins.go
@@ -226,14 +226,16 @@ func SettingsRefs(rt registry.Route) ([]string, error) {
// BuildStateKept is a row update settings can hold whose build state the
// agent keeps and refreshes at every reconcile: an activator-managed exec
-// instance (Kind instance, hibernating, a socket, no Backing, no Tunnel), not
-// a named unit and not the platform's own row. It is the host's
+// instance (registry.Route.ActivatorOwned: an instance, hibernating or with
+// a runtime, a resident rootfs instance included; a socket, no Backing, no
+// Tunnel), not a named unit and not the platform's own row. It is the host's
// keepsBuildState less workers, which settings never apply to; this package
-// cannot import the activator, so the condition is spelled out here and the
+// cannot import the activator, so the condition is spelled out here (on the
+// registry's predicate, as the activator's ActivatorManaged is) and the
// host's sweep uses this one.
func BuildStateKept(rt registry.Route) bool {
- return rt.Kind == "instance" && rt.Unit == "" && !rt.Platform &&
- rt.Hibernate && rt.Socket != "" && rt.Backing == "" && rt.Tunnel == ""
+ return rt.ActivatorOwned() && rt.Unit == "" && !rt.Platform &&
+ rt.Socket != "" && rt.Backing == "" && rt.Tunnel == ""
}
// Generations is the generations file: for each host with a live or pending
diff --git a/internal/release/rootfs_pins_test.go b/internal/release/rootfs_pins_test.go
new file mode 100644
index 000000000..faeb738c6
--- /dev/null
+++ b/internal/release/rootfs_pins_test.go
@@ -0,0 +1,51 @@
+package release
+
+import (
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// TestBuildStateKeptCoversResident: BuildStateKept asks ActivatorOwned, so
+// a resident rootfs instance's build state is one the agent keeps, as the
+// host's keepsBuildState already says through ActivatorManaged [pf 1.13].
+// Binary rows and sidecars answer as on main.
+func TestBuildStateKeptCoversResident(t *testing.T) {
+ row := func(edit func(*registry.Route)) registry.Route {
+ rt := registry.Route{Host: "shop.example.com", Kind: "instance", App: "shop", Account: "bab", Status: "ready",
+ Socket: "/run/carlos/instances/shop/app.sock"}
+ edit(&rt)
+ return rt
+ }
+ for _, c := range []struct {
+ name string
+ rt registry.Route
+ want bool
+ }{
+ {"resident rootfs", row(func(r *registry.Route) { r.Runtime = registry.RuntimeRootfsV1 }), true},
+ {"unknown runtime", row(func(r *registry.Route) { r.Runtime = "rootfs-v9" }), true},
+ {"binary hibernating", row(func(r *registry.Route) { r.Hibernate = true }), true},
+ {"binary awake", row(func(*registry.Route) {}), false},
+ {"hibernating sidecar", row(func(r *registry.Route) { r.Kind, r.Socket, r.Hibernate = "sidecar", "", true }), false},
+ {"resident rootfs, no socket", row(func(r *registry.Route) { r.Runtime, r.Socket = registry.RuntimeRootfsV1, "" }), false},
+ {"resident rootfs, platform alias", row(func(r *registry.Route) { r.Runtime, r.Platform = registry.RuntimeRootfsV1, true }), false},
+ {"binary hibernating, named unit", row(func(r *registry.Route) { r.Hibernate, r.Unit = true, "carlos-app@shop" }), false},
+ } {
+ if got := BuildStateKept(c.rt); got != c.want {
+ t.Errorf("BuildStateKept(%s) = %v, want %v", c.name, got, c.want)
+ }
+ }
+
+ // The settings reading follows: a held resident whose build state is
+ // not read yet is incomplete, so no sweep reads its refs as all there
+ // are before keepsBuildState's read.
+ u := UpdateSettings{Updates: UpdatesManual, Channel: "stable", Pin: "v1"}
+ resident := row(func(r *registry.Route) { r.Runtime, r.UpdateSettings = registry.RuntimeRootfsV1, u.Column() })
+ if _, err := SettingsRefs(resident); err == nil {
+ t.Error("SettingsRefs(held resident, build state unread) = nil error, want incomplete")
+ }
+ awake := row(func(r *registry.Route) { r.UpdateSettings = u.Column() })
+ if _, err := SettingsRefs(awake); err != nil {
+ t.Errorf("SettingsRefs(held binary awake row) = %v, want nil as on main (the agent never refreshes it)", err)
+ }
+}
diff --git a/internal/rollout/policy.go b/internal/rollout/policy.go
index 54efe20ee..33e5fec65 100644
--- a/internal/rollout/policy.go
+++ b/internal/rollout/policy.go
@@ -154,8 +154,9 @@ func (e *policyEntry) lastOrHold() AppPolicy {
}
// Managed reports whether rt is an activator-managed exec route this
-// scheduler moves: a hibernating exec instance or a native sidecar of a known
-// app. Named-unit routes keep root's adoption and its privileged restart
+// scheduler moves: an exec instance the activator owns (hibernating, or with
+// a runtime: a resident rootfs instance, registry.Route.ActivatorOwned) or a
+// native sidecar of a known app. Named-unit routes keep root's adoption and its privileged restart
// (spec §13), unit-backed routes belong to systemd, and platform routes are
// never adopted.
func Managed(rt registry.Route) bool {
@@ -165,7 +166,7 @@ func Managed(rt registry.Route) bool {
if rt.IsSidecar() {
return release.SidecarAdoptable(rt)
}
- return release.Adoptable(rt) && rt.Hibernate
+ return release.Adoptable(rt) && rt.ActivatorOwned()
}
// Restrictable reports whether the failure book can restrict rt: Managed,
diff --git a/internal/rollout/rootfs_managed_test.go b/internal/rollout/rootfs_managed_test.go
new file mode 100644
index 000000000..30690d7a0
--- /dev/null
+++ b/internal/rollout/rootfs_managed_test.go
@@ -0,0 +1,39 @@
+package rollout
+
+import (
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// TestManagedIncludesResidentRootfs: Managed asks ActivatorOwned, so the
+// scheduler moves a resident rootfs instance although it never hibernates.
+// A binary instance asleep and awake, a hibernating and an always-on binary
+// sidecar, a named unit and a unit-backed row answer as on main.
+func TestManagedIncludesResidentRootfs(t *testing.T) {
+ row := func(edit func(*registry.Route)) registry.Route {
+ rt := registry.Route{Host: "shop.example.com", Kind: "instance", App: "shop", Account: "bab", Status: "ready",
+ Socket: "/run/carlos/instances/shop/app.sock"}
+ edit(&rt)
+ return rt
+ }
+ for _, c := range []struct {
+ name string
+ rt registry.Route
+ want bool
+ }{
+ {"resident rootfs", row(func(r *registry.Route) { r.Runtime = registry.RuntimeRootfsV1 }), true},
+ {"unknown runtime", row(func(r *registry.Route) { r.Runtime = "rootfs-v9" }), true},
+ {"binary hibernating", row(func(r *registry.Route) { r.Hibernate = true }), true},
+ {"binary awake", row(func(*registry.Route) {}), false},
+ {"hibernating sidecar", row(func(r *registry.Route) { r.Kind, r.Socket, r.Hibernate = "sidecar", "", true }), true},
+ {"always-on sidecar", row(func(r *registry.Route) { r.Kind, r.Socket = "sidecar", "" }), true},
+ {"resident rootfs, platform alias", row(func(r *registry.Route) { r.Runtime, r.Platform = registry.RuntimeRootfsV1, true }), false},
+ {"resident rootfs, unit-backed", row(func(r *registry.Route) { r.Runtime, r.Backing = registry.RuntimeRootfsV1, registry.BackingUnit }), false},
+ {"binary hibernating, named unit", row(func(r *registry.Route) { r.Hibernate, r.Unit = true, "carlos-app@shop" }), false},
+ } {
+ if got := Managed(c.rt); got != c.want {
+ t.Errorf("Managed(%s) = %v, want %v", c.name, got, c.want)
+ }
+ }
+}
diff --git a/internal/schedule/converge.go b/internal/schedule/converge.go
index 93cdd6c30..5f7f835e4 100644
--- a/internal/schedule/converge.go
+++ b/internal/schedule/converge.go
@@ -476,6 +476,8 @@ func StatusFor(reg *registry.Registry, rt registry.Route, box string, now time.T
st.Unsupported = UnsupportedUnit
return st, nil
}
+ // Left on Hibernate: a resident rootfs instance never sleeps, so no
+ // timer holds it awake and a zero idle window is right for it too.
if !rt.Hibernate {
idle = 0
}
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go
index 3d6b2258f..3d7377999 100644
--- a/internal/status/snapshot.go
+++ b/internal/status/snapshot.go
@@ -972,7 +972,7 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box {
sidecars++
case r.Kind == "static":
counts.Static++
- case r.Hibernate:
+ case r.Hibernate: // left on Hibernate: display, and a resident reads as running, which is true
counts.Hibernating++
if p.Listening == nil {
awakeKnown = false
diff --git a/rootfs_replication_test.go b/rootfs_replication_test.go
new file mode 100644
index 000000000..7fd0e96f6
--- /dev/null
+++ b/rootfs_replication_test.go
@@ -0,0 +1,39 @@
+package main
+
+import (
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// TestReplicationRailFollowsActivatorLeased: the rung is read where the
+// activator replicates, which box-wide litestream decides by
+// Route.ActivatorLeased (ops.FleetDBsWithSkipped). A resident rootfs
+// instance never hibernates, but the activator replicates it, so the rail
+// accepts a rung on it; an unknown runtime is the activator's too. Binary
+// rows and sidecars answer as on main.
+func TestReplicationRailFollowsActivatorLeased(t *testing.T) {
+ row := func(edit func(*registry.Route)) registry.Route {
+ rt := registry.Route{Host: "shop.example.com", Kind: "instance", App: "shop",
+ Socket: "/run/carlos/instances/shop/app.sock", DBPath: "/data/instances/shop/shop.example.com.db"}
+ edit(&rt)
+ return rt
+ }
+ for _, c := range []struct {
+ name string
+ rt registry.Route
+ accept bool
+ }{
+ {"resident rootfs", row(func(r *registry.Route) { r.Runtime = registry.RuntimeRootfsV1 }), true},
+ {"unknown runtime", row(func(r *registry.Route) { r.Runtime = "rootfs-v9" }), true},
+ {"resident rootfs, no db_path", row(func(r *registry.Route) { r.Runtime, r.DBPath = registry.RuntimeRootfsV1, "" }), false},
+ {"binary hibernating", row(func(r *registry.Route) { r.Hibernate = true }), true},
+ {"binary awake", row(func(*registry.Route) {}), false},
+ {"hibernating sidecar", row(func(r *registry.Route) { r.Kind, r.Socket, r.Hibernate = "sidecar", "", true }), true},
+ {"always-on sidecar", row(func(r *registry.Route) { r.Kind, r.Socket = "sidecar", "" }), false},
+ } {
+ if err := replicationRail(c.rt); (err == nil) != c.accept {
+ t.Errorf("replicationRail(%s) = %v, want accepted %v", c.name, err, c.accept)
+ }
+ }
+}